HomeController.cs 2.87 KB
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using CWA.CpoOnline.Models;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.AspNet.Identity.Owin;
using CWA.CpoOnline.Extensions;
using CWA.CpoOnline.Helpers;
using Omu.ValueInjecter;
using Microsoft.Owin.Security;

namespace CWA.CpoOnline.Controllers
{
    [Authorize]
    public class HomeController : Controller
    {

        private const int MinStatus = -1;
        private const int MaxStatus = 2;
        private const int MinTemp = 0;
        private const int MaxTemp = 5;

        private ApplicationUserManager _userManager;

        public ApplicationUserManager UserManager
        {
            get
            {
                return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
            }
            private set
            {
                _userManager = value;
            }
        }
        private IAuthenticationManager AuthenticationManager
        {
            get
            {
                return HttpContext.GetOwinContext().Authentication;
            }
        }

        public async Task<ActionResult> Index()
        {
            // Load all available sectors and symbols
            var allSectors = HardCode.AllSectors;
            var allSymbols = HardCode.AllSectors.SelectMany(sector => sector.Symbols).ToList();

            if (CurrentUser.AppUser == null)
            {
                AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
                return RedirectToAction("Index", "Home");
            }
            
            // Load user's current access claims
            var allClaims = await UserManager.GetClaimsAsync(CurrentUser.AppUser.Id);


            var symbolClaim = allClaims.Where(c => c.Type.Equals(CpoClaimTypes.Symbol, StringComparison.InvariantCultureIgnoreCase));
            var sectorsClaims = allClaims.Where(c => c.Type.Equals(CpoClaimTypes.Sector, StringComparison.InvariantCultureIgnoreCase));

            var symbolsFromSectorClaims = allSectors.Where((s) => sectorsClaims.Where((sc) => sc.Value == s.Id).Count() != 0).SelectMany(s => s.Symbols);
            var symbolsFromsymbolClaims = allSymbols.Where((s) => symbolClaim.Where((sc) => sc.Value == s.Id).Count() != 0);

            var results = symbolsFromSectorClaims.Union(symbolsFromsymbolClaims);

            var sectors = results.Select((s) => s.Sector).Distinct(new SectorViewModelComparer());

            ViewBag.UserSectors = sectors.ToList();
            ViewBag.UserSymbols = results.ToList();

            return View();
        }

        [Authorize(Roles = CpoRoles.Admin)]
        public ActionResult Admin()
        {
            return View();
        }
    }
}