Source

main-vinayFork / Source / WebClient / Web.Client / Controllers / AuthenticationController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using Microsoft.IdentityModel.Claims;
using Microsoft.IdentityModel.Web;
using DataUp.Web.BizLogic;
using DataUp.Web.BizLogic.Model;
using DataUp.Web.Client.Infrastructure;
using DataUp.Web.Client.ViewModel;
using BizLogicModel = DataUp.Web.BizLogic.Model;
using System.Web.Security;
using System.Threading;
using System.Net;

namespace DataUp.Web.Client.Controllers
{
    /// <summary>
    /// Controller used for Authentication.
    /// </summary>
    public class AuthenticationController : Controller
    {
        private IProfileService profileService;

        public AuthenticationController(IProfileService service)
        {
            this.profileService = service;
        }

        [OutputCache(Duration = 10)]
        [ChildActionOnly]
        public PartialViewResult GetLoginControl()
        {
            WSFederationAuthenticationModule fam = FederatedAuthentication.WSFederationAuthenticationModule;
            HrdRequest request = new HrdRequest(fam.Issuer, fam.Realm, context: Request.Url.AbsoluteUri);
            return PartialView("_SignIn", request);
        }

        [HttpPost]
        [Authorize]
        public ActionResult SignedIn(FormCollection forms)
        {
            return RedirectToAction("Register", "Authentication");
        }

        [Authorize]
        public ActionResult Register(string UrlReferrer)
        {
            var claimsPrincipal = HttpContext.User as IClaimsPrincipal;
            var claimsIdentity = claimsPrincipal.Identity as IClaimsIdentity;

            var nameIdentifier = claimsIdentity.Claims.Where(c => c.ClaimType.EndsWith("nameidentifier")).Single().Value;
            var identityProvider = claimsIdentity.Claims.Where(c => c.ClaimType.EndsWith("identityprovider")).Single().Value;
            var name = string.Empty;
            var emailId = string.Empty;

            if (identityProvider.StartsWith(IdentityProvider.Facebook.ToString()))
            {
                identityProvider = IdentityProvider.Facebook.ToString();
                name = claimsIdentity.Claims.Where(c => c.ClaimType.EndsWith("name")).Single().Value;
                emailId = claimsIdentity.Claims.Where(c => c.ClaimType.EndsWith("emailaddress")).Single().Value;
            }
            else if (identityProvider.Contains(IdentityProvider.WindowsLive.ToString()))
            {
                identityProvider = IdentityProvider.WindowsLive.ToString();
            }
            else
            {
                throw new Exception("Unrecognized identity provider.");
            }

            var user = profileService.GetUser(nameIdentifier, identityProvider);

            if (user == null)
            {
                user = new BizLogicModel.User();
                user.NameIdentifier = nameIdentifier;
                user.IdentityProvider = identityProvider;
                user.EmailId = emailId;

                int numberOfSpacebars = name.Where(c => c == ' ').Count();
                var indexOfFirstSpacebar = name.IndexOf(' ');
                if (numberOfSpacebars > 1)
                {
                    var indexOfSecondSpacebar = name.IndexOf(' ', indexOfFirstSpacebar + 1);

                    user.FirstName = name.Substring(0, indexOfFirstSpacebar);
                    user.LastName = name.Substring(indexOfSecondSpacebar + 1);
                }
                else if (numberOfSpacebars == 1)
                {
                    user.FirstName = name.Substring(0, indexOfFirstSpacebar);
                    user.LastName = name.Substring(indexOfFirstSpacebar + 1);
                }
                else
                {
                    user.FirstName = name;
                }

                RegistrationViewModel registration = new RegistrationViewModel();

                if (user != null)
                {
                    registration.NameIdentifier = user.NameIdentifier;
                    registration.IdentityProvider = user.IdentityProvider;
                    registration.FirstName = user.FirstName;
                    registration.LastName = user.LastName;
                    registration.MiddleName = user.MiddleName;
                    registration.EmailId = user.EmailId;
                    registration.UrlReferrer = UrlReferrer;
                }

                Session["User"] = user;
                return View(registration);
            }
            else
            {
                Session["User"] = user;
                Session["IsUserRegistered"] = true;
                return RedirectToAction("Index", "Document");
            }
        }

        [RegisteredUser]
        public ActionResult UpdateProfile(int userId)
        {
            RegistrationViewModel registration = new RegistrationViewModel();

            // TODO fill model with the 
            User user = Session["User"] as User;
            if (user != null)
            {
                registration.UserID = userId;
                registration.NameIdentifier = user.NameIdentifier;
                registration.IdentityProvider = user.IdentityProvider;
                registration.FirstName = user.FirstName;
                registration.Organization = user.Organization;
                registration.LastName = user.LastName;
                registration.MiddleName = user.MiddleName;
                registration.EmailId = user.EmailId;
            }

            return View("Register", registration);
        }

        [HttpPost]
        [Authorize]
        public ActionResult Register(RegistrationViewModel registration)
        {
            User user = new User()
            {
                Id = registration.UserID,
                NameIdentifier = registration.NameIdentifier,
                IdentityProvider = registration.IdentityProvider,
                FirstName = registration.FirstName,
                Organization = registration.Organization,
                LastName = registration.LastName,
                MiddleName = registration.MiddleName,
                EmailId = registration.EmailId
            };

            if (user.Id > 0)
            {
                profileService.UpdateUser(user);
            }
            else
            {
                profileService.AddUser(user);
                user = profileService.GetUser(user.NameIdentifier, user.IdentityProvider);
            }

            Session["User"] = user;
            Session["IsUserRegistered"] = true;

            return RedirectToAction("Index", "Document");
        }

        public ActionResult SignOut()
        {
            WSFederationAuthenticationModule wsfam = FederatedAuthentication.WSFederationAuthenticationModule;
            wsfam.SignOut(true);

            //FederatedAuthentication.WSFederationAuthenticationModule.SignOut(true);
            //FederatedAuthentication.SessionAuthenticationModule.SignOut();
            //if (Thread.CurrentPrincipal is IClaimsPrincipal)
            //{
            //    ClaimsIdentityCollection claims = ((IClaimsPrincipal)Thread.CurrentPrincipal).Identities;
            //    claims.Clear();
            //}

            //Session.Clear();
            //Session.Abandon();

            Session.Remove("IsUserRegistered");
            return RedirectToAction("Index", "Home");
        }
    }
}
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.