public virtual async Task<ActionResult> SignIn(LogOnViewModel model, string returnUrl, bool linkingAccount)
        {
            // I think it should be obvious why we don't want the current URL to be the return URL here ;)
            ViewData[Constants.ReturnUrlViewDataKey] = returnUrl;

            if (Request.IsAuthenticated)
            {
                TempData["Message"] = Strings.AlreadyLoggedIn;
                return SafeRedirect(returnUrl);
            }

            if (!ModelState.IsValid)
            {
                return LogOnView(model);
            }

            var user = await AuthService.Authenticate(model.SignIn.UserNameOrEmail, model.SignIn.Password);

            if (user == null)
            {
                ModelState.AddModelError(
                    "SignIn",
                    Strings.UsernameAndPasswordNotFound);

                return LogOnView(model);
            }
            
            if (linkingAccount)
            {
                // Link with an external account
                user = await AssociateCredential(user);
                if (user == null)
                {
                    return ExternalLinkExpired();
                }
            }

            // If we are an administrator and Gallery.EnforcedAuthProviderForAdmin is set
            // to require a specific authentication provider, challenge that provider if needed.
            ActionResult challenge;
            if (ShouldChallengeEnforcedProvider(
                NuGetContext.Config.Current.EnforcedAuthProviderForAdmin, user, returnUrl, out challenge))
            {
                return challenge;
            }

            // Create session
            AuthService.CreateSession(OwinContext, user.User);
            return SafeRedirect(returnUrl);
        }
        public virtual async Task<ActionResult> SignIn(LogOnViewModel model, string returnUrl, bool linkingAccount)
        {
            // I think it should be obvious why we don't want the current URL to be the return URL here ;)
            ViewData[Constants.ReturnUrlViewDataKey] = returnUrl;

            if (Request.IsAuthenticated)
            {
                TempData["Message"] = Strings.AlreadyLoggedIn;
                return SafeRedirect(returnUrl);
            }

            if (!ModelState.IsValid)
            {
                return LogOnView(model);
            }

            var user = await AuthService.Authenticate(model.SignIn.UserNameOrEmail, model.SignIn.Password);

            if (user == null)
            {
                ModelState.AddModelError(
                    "SignIn",
                    Strings.UsernameAndPasswordNotFound);

                return LogOnView(model);
            }

            if (linkingAccount)
            {
                // Link with an external account
                user = await AssociateCredential(user);
                if (user == null)
                {
                    return ExternalLinkExpired();
                }
            }

            // Now log in!
            AuthService.CreateSession(OwinContext, user.User);
            return SafeRedirect(returnUrl);
        }
        public async virtual Task<ActionResult> LinkExternalAccount(string returnUrl)
        {
            // Extract the external login info
            var result = await AuthService.AuthenticateExternalLogin(OwinContext);
            if (result.ExternalIdentity == null)
            {
                // User got here without an external login cookie (or an expired one)
                // Send them to the logon action
                return ExternalLinkExpired();
            }

            if (result.Authentication != null)
            {
                AuthService.CreateSession(OwinContext, result.Authentication.User);
                return SafeRedirect(returnUrl);
            }
            else
            {
                // Gather data for view model
                var authUI = result.Authenticator.GetUI();
                var email = result.ExternalIdentity.GetClaimOrDefault(ClaimTypes.Email);
                var name = result
                    .ExternalIdentity
                    .GetClaimOrDefault(ClaimTypes.Name);

                // Check for a user with this email address
                User existingUser = null;
                if (!string.IsNullOrEmpty(email))
                {
                    existingUser = UserService.FindByEmailAddress(email);
                }

                var external = new AssociateExternalAccountViewModel()
                {
                    ProviderAccountNoun = authUI.AccountNoun,
                    AccountName = name,
                    FoundExistingUser = existingUser != null
                };

                var model = new LogOnViewModel
                {
                    External = external,
                    SignIn = new SignInViewModel
                    {
                        UserNameOrEmail = email
                    },
                    Register = new RegisterViewModel
                    {
                        EmailAddress = email
                    }
                };

                return LogOnView(model);
            }
        }
        public async virtual Task<ActionResult> Register(LogOnViewModel model, string returnUrl, bool linkingAccount)
        {
            // I think it should be obvious why we don't want the current URL to be the return URL here ;)
            ViewData[Constants.ReturnUrlViewDataKey] = returnUrl;

            if (Request.IsAuthenticated)
            {
                TempData["Message"] = Strings.AlreadyLoggedIn;
                return SafeRedirect(returnUrl);
            }

            if (linkingAccount)
            {
                ModelState.Remove("Register.Password");
            }

            if (!ModelState.IsValid)
            {
                return LogOnView(model);
            }

            AuthenticatedUser user;
            try
            {

                if (linkingAccount)
                {
                    var result = await AuthService.ReadExternalLoginCredential(OwinContext);
                    if (result.ExternalIdentity == null)
                    {
                        return ExternalLinkExpired();
                    }

                    user = await AuthService.Register(
                        model.Register.Username,
                        model.Register.EmailAddress,
                        result.Credential);
                }
                else
                {
                    user = await AuthService.Register(
                        model.Register.Username,
                        model.Register.EmailAddress,
                        CredentialBuilder.CreatePbkdf2Password(model.Register.Password));
                }
            }
            catch (EntityException ex)
            {
                ModelState.AddModelError("Register", ex.Message);
                return LogOnView(model);
            }

            // Send a new account email
            if(NuGetContext.Config.Current.ConfirmEmailAddresses && !String.IsNullOrEmpty(user.User.UnconfirmedEmailAddress))
            {
                MessageService.SendNewAccountEmail(
                    new MailAddress(user.User.UnconfirmedEmailAddress, user.User.Username),
                    Url.ConfirmationUrl(
                        "Confirm",
                        "Users",
                        user.User.Username,
                        user.User.EmailConfirmationToken));
            }

            // We're logging in!
            AuthService.CreateSession(OwinContext, user.User);

            return RedirectFromRegister(returnUrl);
        }
        public virtual async Task <ActionResult> SignIn(LogOnViewModel model, string returnUrl, bool linkingAccount)
        {
            // I think it should be obvious why we don't want the current URL to be the return URL here ;)
            ViewData[Constants.ReturnUrlViewDataKey] = returnUrl;

            if (Request.IsAuthenticated)
            {
                TempData["Message"] = Strings.AlreadyLoggedIn;
                return(SafeRedirect(returnUrl));
            }

            if (!ModelState.IsValid)
            {
                return(SignInOrExternalLinkView(model, linkingAccount));
            }

            var authenticationResult = await _authService.Authenticate(model.SignIn.UserNameOrEmail, model.SignIn.Password);


            if (authenticationResult.Result != PasswordAuthenticationResult.AuthenticationResult.Success)
            {
                string modelErrorMessage = string.Empty;

                if (authenticationResult.Result == PasswordAuthenticationResult.AuthenticationResult.BadCredentials)
                {
                    modelErrorMessage = Strings.UsernameAndPasswordNotFound;
                }
                else if (authenticationResult.Result == PasswordAuthenticationResult.AuthenticationResult.AccountLocked)
                {
                    string timeRemaining =
                        authenticationResult.LockTimeRemainingMinutes == 1
                            ? Strings.AMinute
                            : string.Format(CultureInfo.CurrentCulture, Strings.Minutes,
                                            authenticationResult.LockTimeRemainingMinutes);

                    modelErrorMessage = string.Format(CultureInfo.CurrentCulture, Strings.UserAccountLocked, timeRemaining);
                }

                ModelState.AddModelError("SignIn", modelErrorMessage);

                return(SignInOrExternalLinkView(model, linkingAccount));
            }

            var user = authenticationResult.AuthenticatedUser;

            if (linkingAccount)
            {
                // Link with an external account
                user = await AssociateCredential(user);

                if (user == null)
                {
                    return(ExternalLinkExpired());
                }
            }

            // If we are an administrator and Gallery.EnforcedAuthProviderForAdmin is set
            // to require a specific authentication provider, challenge that provider if needed.
            ActionResult challenge;

            if (ShouldChallengeEnforcedProvider(
                    NuGetContext.Config.Current.EnforcedAuthProviderForAdmin, user, returnUrl, out challenge))
            {
                return(challenge);
            }

            // Create session
            await _authService.CreateSessionAsync(OwinContext, user);

            return(SafeRedirect(returnUrl));
        }
Ejemplo n.º 6
0
 private ActionResult LinkExternalView(LogOnViewModel existingModel)
 {
     return(AuthenticationView("LinkExternal", existingModel));
 }
Ejemplo n.º 7
0
        public virtual async Task <ActionResult> LinkExternalAccount(string returnUrl)
        {
            // Extract the external login info
            var result = await _authService.AuthenticateExternalLogin(OwinContext);

            if (result.ExternalIdentity == null)
            {
                // User got here without an external login cookie (or an expired one)
                // Send them to the logon action
                return(ExternalLinkExpired());
            }

            if (result.Authentication != null)
            {
                // If we are an administrator and Gallery.EnforcedAuthProviderForAdmin is set
                // to require a specific authentication provider, challenge that provider if needed.
                ActionResult challenge;
                if (ShouldChallengeEnforcedProvider(
                        NuGetContext.Config.Current.EnforcedAuthProviderForAdmin, result.Authentication, returnUrl, out challenge))
                {
                    return(challenge);
                }

                if (ShouldEnforceMultiFactorAuthentication(result))
                {
                    // Invoke the authentication again enforcing multi-factor authentication for the same provider.
                    return(ChallengeAuthentication(
                               Url.LinkExternalAccount(returnUrl),
                               result.Authenticator.Name,
                               new AuthenticationPolicy()
                    {
                        Email = result.LoginDetails.EmailUsed, EnforceMultiFactorAuthentication = true
                    }));
                }

                // Remove the password login if the password logins are deprecated and enforced discontinuation.
                if (NuGetContext.Config.Current.DeprecateNuGetPasswordLogins &&
                    _contentObjectService.LoginDiscontinuationConfiguration.IsPasswordLoginDiscontinuedForAll() &&
                    result.Authentication.CredentialUsed.IsExternal() &&
                    result.Authentication.User.HasPasswordCredential())
                {
                    // Remove password logins when a user signs in with an external login.
                    TempData["Message"] = string.Format(Strings.DiscontinuedLogin_PasswordRemoved, NuGetContext.Config.Current.Brand);
                    await RemovePasswordCredential(result.Authentication.User);
                }

                // Create session
                await _authService.CreateSessionAsync(OwinContext,
                                                      result.Authentication,
                                                      wasMultiFactorAuthenticated : result?.LoginDetails?.WasMultiFactorAuthenticated ?? false);

                // Update the 2FA if used during login but user does not have it set on their account. Only for personal microsoft accounts.
                if (result?.LoginDetails != null &&
                    result.LoginDetails.WasMultiFactorAuthenticated &&
                    !result.Authentication.User.EnableMultiFactorAuthentication &&
                    CredentialTypes.IsMicrosoftAccount(result.Credential.Type))
                {
                    await _userService.ChangeMultiFactorAuthentication(result.Authentication.User, enableMultiFactor : true);

                    OwinContext.AddClaim(NuGetClaims.EnabledMultiFactorAuthentication);
                    TempData["Message"] = Strings.MultiFactorAuth_LoginUpdate;
                }

                return(SafeRedirect(returnUrl));
            }
            else
            {
                // Gather data for view model
                string name   = null;
                string email  = null;
                var    authUI = result.Authenticator.GetUI();
                try
                {
                    var userInfo = result.Authenticator.GetIdentityInformation(result.ExternalIdentity);
                    name  = userInfo.Name;
                    email = userInfo.Email;
                }
                catch (Exception)
                {
                    // Consume the exception for now, for backwards compatibility to previous MSA provider.
                    email = result.ExternalIdentity.GetClaimOrDefault(ClaimTypes.Email);
                    name  = result.ExternalIdentity.GetClaimOrDefault(ClaimTypes.Name);
                }

                // Check for a user with this email address
                User existingUser = null;
                if (!string.IsNullOrEmpty(email))
                {
                    existingUser = _userService.FindByEmailAddress(email);
                }

                var foundExistingUser        = existingUser != null;
                var existingUserLinkingError = AssociateExternalAccountViewModel.ExistingUserLinkingErrorType.None;

                if (foundExistingUser)
                {
                    if (existingUser is Organization)
                    {
                        existingUserLinkingError = AssociateExternalAccountViewModel.ExistingUserLinkingErrorType.AccountIsOrganization;
                    }
                    else if (existingUser.Credentials.Any(c => c.IsExternal()) && !existingUser.IsAdministrator)
                    {
                        existingUserLinkingError = AssociateExternalAccountViewModel.ExistingUserLinkingErrorType.AccountIsAlreadyLinked;
                    }
                }

                var external = new AssociateExternalAccountViewModel()
                {
                    ProviderAccountNoun      = authUI.AccountNoun,
                    AccountName              = name,
                    FoundExistingUser        = foundExistingUser,
                    ExistingUserLinkingError = existingUserLinkingError
                };

                var model = new LogOnViewModel
                {
                    External = external,
                    SignIn   = new SignInViewModel
                    {
                        UserNameOrEmail = email
                    },
                    Register = new RegisterViewModel
                    {
                        EmailAddress = email
                    }
                };

                return(LinkExternalView(model));
            }
        }
Ejemplo n.º 8
0
        private ActionResult LogOnView(LogOnViewModel existingModel)
        {
            // Fill the providers list
            existingModel.Providers = GetProviders();

            // Reinitialize any nulled-out sub models
            existingModel.SignIn = existingModel.SignIn ?? new SignInViewModel();
            existingModel.Register = existingModel.Register ?? new RegisterViewModel();

            return View("LogOn", existingModel);
        }
Ejemplo n.º 9
0
        private ActionResult SignInFailure(LogOnViewModel model, bool linkingAccount, string modelErrorMessage)
        {
            ModelState.AddModelError("SignIn", modelErrorMessage);

            return(SignInOrExternalLinkView(model, linkingAccount));
        }
Ejemplo n.º 10
0
        public virtual async Task <ActionResult> Register(LogOnViewModel model, string returnUrl, bool linkingAccount)
        {
            // I think it should be obvious why we don't want the current URL to be the return URL here ;)
            ViewData[Constants.ReturnUrlViewDataKey] = returnUrl;

            if (Request.IsAuthenticated)
            {
                TempData["Message"] = Strings.AlreadyLoggedIn;
                return(SafeRedirect(returnUrl));
            }

            if (linkingAccount)
            {
                ModelState.Remove("Register.Password");
            }

            if (!ModelState.IsValid)
            {
                return(RegisterOrExternalLinkView(model, linkingAccount));
            }

            AuthenticatedUser user;
            var usedMultiFactorAuthentication = false;

            try
            {
                if (linkingAccount)
                {
                    var result = await _authService.ReadExternalLoginCredential(OwinContext);

                    if (result.ExternalIdentity == null)
                    {
                        return(ExternalLinkExpired());
                    }

                    usedMultiFactorAuthentication = result.LoginDetails?.WasMultiFactorAuthenticated ?? false;
                    user = await _authService.Register(
                        model.Register.Username,
                        model.Register.EmailAddress,
                        result.Credential,
                        (result.Credential.IsExternal() && string.Equals(result.UserInfo?.Email, model.Register.EmailAddress))
                        );
                }
                else
                {
                    user = await _authService.Register(
                        model.Register.Username,
                        model.Register.EmailAddress,
                        _credentialBuilder.CreatePasswordCredential(model.Register.Password));
                }
            }
            catch (EntityException ex)
            {
                ModelState.AddModelError("Register", ex.Message);

                return(RegisterOrExternalLinkView(model, linkingAccount));
            }

            // Send a new account email
            if (NuGetContext.Config.Current.ConfirmEmailAddresses && !string.IsNullOrEmpty(user.User.UnconfirmedEmailAddress))
            {
                var message = new NewAccountMessage(
                    _messageServiceConfiguration,
                    user.User,
                    Url.ConfirmEmail(
                        user.User.Username,
                        user.User.EmailConfirmationToken,
                        relativeUrl: false));

                await _messageService.SendMessageAsync(message);
            }

            // If we are an administrator and Gallery.EnforcedAuthProviderForAdmin is set
            // to require a specific authentication provider, challenge that provider if needed.
            ActionResult challenge;

            if (ShouldChallengeEnforcedProvider(
                    NuGetContext.Config.Current.EnforcedAuthProviderForAdmin, user, returnUrl, out challenge))
            {
                return(challenge);
            }

            // Create session
            await _authService.CreateSessionAsync(OwinContext, user, usedMultiFactorAuthentication);

            return(RedirectFromRegister(returnUrl));
        }
Ejemplo n.º 11
0
        public virtual async Task <ActionResult> SignIn(LogOnViewModel model, string returnUrl, bool linkingAccount)
        {
            // I think it should be obvious why we don't want the current URL to be the return URL here ;)
            ViewData[Constants.ReturnUrlViewDataKey] = returnUrl;

            if (Request.IsAuthenticated)
            {
                return(LoggedInRedirect(returnUrl));
            }

            if (!ModelState.IsValid)
            {
                return(SignInOrExternalLinkView(model, linkingAccount));
            }

            var authenticationResult = await _authService.Authenticate(model.SignIn.UserNameOrEmail, model.SignIn.Password);

            if (authenticationResult.Result != PasswordAuthenticationResult.AuthenticationResult.Success)
            {
                string modelErrorMessage = string.Empty;

                if (authenticationResult.Result == PasswordAuthenticationResult.AuthenticationResult.BadCredentials)
                {
                    modelErrorMessage = Strings.UsernameAndPasswordNotFound;
                }
                else if (authenticationResult.Result == PasswordAuthenticationResult.AuthenticationResult.AccountLocked)
                {
                    string timeRemaining =
                        authenticationResult.LockTimeRemainingMinutes == 1
                            ? Strings.AMinute
                            : string.Format(CultureInfo.CurrentCulture, Strings.Minutes,
                                            authenticationResult.LockTimeRemainingMinutes);

                    modelErrorMessage = string.Format(CultureInfo.CurrentCulture, Strings.UserAccountLocked, timeRemaining);
                }

                return(SignInFailure(model, linkingAccount, modelErrorMessage));
            }

            var  authenticatedUser             = authenticationResult.AuthenticatedUser;
            bool usedMultiFactorAuthentication = false;

            if (linkingAccount)
            {
                // Verify account has no other external accounts
                if (authenticatedUser.User.Credentials.Any(c => c.IsExternal()) && !authenticatedUser.User.IsAdministrator)
                {
                    var message = string.Format(
                        CultureInfo.CurrentCulture,
                        Strings.AccountIsLinkedToAnotherExternalAccount,
                        authenticatedUser.User.EmailAddress);
                    return(SignInFailure(model, linkingAccount, message));
                }

                // Link with an external account
                var loginUserDetails = await AssociateCredential(authenticatedUser);

                authenticatedUser = loginUserDetails?.AuthenticatedUser;
                if (authenticatedUser == null)
                {
                    return(ExternalLinkExpired());
                }

                usedMultiFactorAuthentication = loginUserDetails.UsedMultiFactorAuthentication;
            }

            // If we are an administrator and Gallery.EnforcedAuthProviderForAdmin is set
            // to require a specific authentication provider, challenge that provider if needed.
            ActionResult challenge;

            if (ShouldChallengeEnforcedProvider(
                    NuGetContext.Config.Current.EnforcedAuthProviderForAdmin, authenticatedUser, returnUrl, out challenge))
            {
                return(challenge);
            }

            // Create session
            await _authService.CreateSessionAsync(OwinContext, authenticatedUser, usedMultiFactorAuthentication);

            TempData["ShowPasswordDeprecationWarning"] = true;
            return(SafeRedirect(returnUrl));
        }
        public async virtual Task <ActionResult> LinkExternalAccount(string returnUrl)
        {
            // Extract the external login info
            var result = await AuthService.AuthenticateExternalLogin(OwinContext);

            if (result.ExternalIdentity == null)
            {
                // User got here without an external login cookie (or an expired one)
                // Send them to the logon action
                return(ExternalLinkExpired());
            }

            if (result.Authentication != null)
            {
                // If we are an administrator and Gallery.EnforcedAuthProviderForAdmin is set
                // to require a specific authentication provider, challenge that provider if needed.
                ActionResult challenge;
                if (ShouldChallengeEnforcedProvider(
                        NuGetContext.Config.Current.EnforcedAuthProviderForAdmin, result.Authentication, returnUrl, out challenge))
                {
                    return(challenge);
                }

                // Create session
                await AuthService.CreateSessionAsync(OwinContext, result.Authentication);

                return(SafeRedirect(returnUrl));
            }
            else
            {
                // Gather data for view model
                var authUI = result.Authenticator.GetUI();
                var email  = result.ExternalIdentity.GetClaimOrDefault(ClaimTypes.Email);
                var name   = result
                             .ExternalIdentity
                             .GetClaimOrDefault(ClaimTypes.Name);

                // Check for a user with this email address
                User existingUser = null;
                if (!string.IsNullOrEmpty(email))
                {
                    existingUser = UserService.FindByEmailAddress(email);
                }

                var external = new AssociateExternalAccountViewModel()
                {
                    ProviderAccountNoun = authUI.AccountNoun,
                    AccountName         = name,
                    FoundExistingUser   = existingUser != null
                };

                var model = new LogOnViewModel
                {
                    External = external,
                    SignIn   = new SignInViewModel
                    {
                        UserNameOrEmail = email
                    },
                    Register = new RegisterViewModel
                    {
                        EmailAddress = email
                    }
                };

                return(LogOnView(model));
            }
        }
        public async virtual Task <ActionResult> Register(LogOnViewModel model, string returnUrl, bool linkingAccount)
        {
            // I think it should be obvious why we don't want the current URL to be the return URL here ;)
            ViewData[Constants.ReturnUrlViewDataKey] = returnUrl;

            if (Request.IsAuthenticated)
            {
                TempData["Message"] = Strings.AlreadyLoggedIn;
                return(SafeRedirect(returnUrl));
            }

            if (linkingAccount)
            {
                ModelState.Remove("Register.Password");
            }

            if (!ModelState.IsValid)
            {
                return(LogOnView(model));
            }

            AuthenticatedUser user;

            try
            {
                if (linkingAccount)
                {
                    var result = await AuthService.ReadExternalLoginCredential(OwinContext);

                    if (result.ExternalIdentity == null)
                    {
                        return(ExternalLinkExpired());
                    }

                    user = await AuthService.Register(
                        model.Register.Username,
                        model.Register.EmailAddress,
                        result.Credential);
                }
                else
                {
                    user = await AuthService.Register(
                        model.Register.Username,
                        model.Register.EmailAddress,
                        CredentialBuilder.CreatePbkdf2Password(model.Register.Password));
                }
            }
            catch (EntityException ex)
            {
                ModelState.AddModelError("Register", ex.Message);
                return(LogOnView(model));
            }

            // Send a new account email
            if (NuGetContext.Config.Current.ConfirmEmailAddresses && !String.IsNullOrEmpty(user.User.UnconfirmedEmailAddress))
            {
                MessageService.SendNewAccountEmail(
                    new MailAddress(user.User.UnconfirmedEmailAddress, user.User.Username),
                    Url.ConfirmationUrl(
                        "Confirm",
                        "Users",
                        user.User.Username,
                        user.User.EmailConfirmationToken));
            }

            // If we are an administrator and Gallery.EnforcedAuthProviderForAdmin is set
            // to require a specific authentication provider, challenge that provider if needed.
            ActionResult challenge;

            if (ShouldChallengeEnforcedProvider(
                    NuGetContext.Config.Current.EnforcedAuthProviderForAdmin, user, returnUrl, out challenge))
            {
                return(challenge);
            }

            // Create session
            await AuthService.CreateSessionAsync(OwinContext, user);

            return(RedirectFromRegister(returnUrl));
        }
Ejemplo n.º 14
0
        public virtual async Task<ActionResult> Register(LogOnViewModel model, string returnUrl, bool linkingAccount)
        {
            // I think it should be obvious why we don't want the current URL to be the return URL here ;)
            ViewData[Constants.ReturnUrlViewDataKey] = returnUrl;

            if (Request.IsAuthenticated)
            {
                TempData["Message"] = Strings.AlreadyLoggedIn;
                return SafeRedirect(returnUrl);
            }

            if (linkingAccount)
            {
                ModelState.Remove("Register.Password");
            }

            if (!ModelState.IsValid)
            {
                return LogOnView(model);
            }

            AuthenticatedUser user;
            try
            {
                if (linkingAccount)
                {
                    var result = await _authService.ReadExternalLoginCredential(OwinContext);
                    if (result.ExternalIdentity == null)
                    {
                        return ExternalLinkExpired();
                    }

                    user = await _authService.Register(
                        model.Register.Username,
                        model.Register.EmailAddress,
                        result.Credential);
                }
                else
                {
                    user = await _authService.Register(
                        model.Register.Username,
                        model.Register.EmailAddress,
                        _credentialBuilder.CreatePasswordCredential(model.Register.Password));
                }
            }
            catch (EntityException ex)
            {
                ModelState.AddModelError("Register", ex.Message);
                return LogOnView(model);
            }

            // Send a new account email
            if (NuGetContext.Config.Current.ConfirmEmailAddresses && !string.IsNullOrEmpty(user.User.UnconfirmedEmailAddress))
            {
                _messageService.SendNewAccountEmail(
                    new MailAddress(user.User.UnconfirmedEmailAddress, user.User.Username),
                    Url.ConfirmationUrl(
                        "Confirm",
                        "Users",
                        user.User.Username,
                        user.User.EmailConfirmationToken));
            }

            // If we are an administrator and Gallery.EnforcedAuthProviderForAdmin is set
            // to require a specific authentication provider, challenge that provider if needed.
            ActionResult challenge;
            if (ShouldChallengeEnforcedProvider(
                NuGetContext.Config.Current.EnforcedAuthProviderForAdmin, user, returnUrl, out challenge))
            {
                return challenge;
            }

            // Create session
            await _authService.CreateSessionAsync(OwinContext, user);
            return RedirectFromRegister(returnUrl);
        }
Ejemplo n.º 15
0
 private ActionResult RegisterView(LogOnViewModel existingModel)
 {
     return(AuthenticationView("Register", existingModel));
 }
Ejemplo n.º 16
0
        public virtual async Task<ActionResult> LinkExternalAccount(string returnUrl)
        {
            // Extract the external login info
            var result = await _authService.AuthenticateExternalLogin(OwinContext);
            if (result.ExternalIdentity == null)
            {
                // User got here without an external login cookie (or an expired one)
                // Send them to the logon action
                return ExternalLinkExpired();
            }

            if (result.Authentication != null)
            {
                // If we are an administrator and Gallery.EnforcedAuthProviderForAdmin is set
                // to require a specific authentication provider, challenge that provider if needed.
                ActionResult challenge;
                if (ShouldChallengeEnforcedProvider(
                    NuGetContext.Config.Current.EnforcedAuthProviderForAdmin, result.Authentication, returnUrl, out challenge))
                {
                    return challenge;
                }

                // Create session
                await _authService.CreateSessionAsync(OwinContext, result.Authentication);
                return SafeRedirect(returnUrl);
            }
            else
            {
                // Gather data for view model
                var authUI = result.Authenticator.GetUI();
                var email = result.ExternalIdentity.GetClaimOrDefault(ClaimTypes.Email);
                var name = result
                    .ExternalIdentity
                    .GetClaimOrDefault(ClaimTypes.Name);

                // Check for a user with this email address
                User existingUser = null;
                if (!string.IsNullOrEmpty(email))
                {
                    existingUser = _userService.FindByEmailAddress(email);
                }

                var external = new AssociateExternalAccountViewModel()
                {
                    ProviderAccountNoun = authUI.AccountNoun,
                    AccountName = name,
                    FoundExistingUser = existingUser != null
                };

                var model = new LogOnViewModel
                {
                    External = external,
                    SignIn = new SignInViewModel
                    {
                        UserNameOrEmail = email
                    },
                    Register = new RegisterViewModel
                    {
                        EmailAddress = email
                    }
                };

                return LogOnView(model);
            }
        }
Ejemplo n.º 17
0
 private ActionResult SignInNuGetAccountView(LogOnViewModel existingModel)
 {
     return(AuthenticationView("SignInNuGetAccount", existingModel));
 }
Ejemplo n.º 18
0
        public virtual async Task<ActionResult> SignIn(LogOnViewModel model, string returnUrl, bool linkingAccount)
        {
            // I think it should be obvious why we don't want the current URL to be the return URL here ;)
            ViewData[Constants.ReturnUrlViewDataKey] = returnUrl;

            if (Request.IsAuthenticated)
            {
                TempData["Message"] = Strings.AlreadyLoggedIn;
                return SafeRedirect(returnUrl);
            }

            if (!ModelState.IsValid)
            {
                return LogOnView(model);
            }

            var authenticationResult = await _authService.Authenticate(model.SignIn.UserNameOrEmail, model.SignIn.Password);


            if (authenticationResult.Result != PasswordAuthenticationResult.AuthenticationResult.Success)
            {
                string modelErrorMessage = string.Empty;

                if (authenticationResult.Result == PasswordAuthenticationResult.AuthenticationResult.BadCredentials)
                {
                    modelErrorMessage = Strings.UsernameAndPasswordNotFound;
                }
                else if (authenticationResult.Result == PasswordAuthenticationResult.AuthenticationResult.AccountLocked)
                {
                    string timeRemaining =
                        authenticationResult.LockTimeRemainingMinutes == 1
                            ? Strings.AMinute
                            : string.Format(CultureInfo.CurrentCulture, Strings.Minutes,
                                authenticationResult.LockTimeRemainingMinutes);

                    modelErrorMessage = string.Format(CultureInfo.CurrentCulture, Strings.UserAccountLocked, timeRemaining);
                }

                ModelState.AddModelError("SignIn", modelErrorMessage);
                return LogOnView(model);
            }

            var user = authenticationResult.AuthenticatedUser;
            
            if (linkingAccount)
            {
                // Link with an external account
                user = await AssociateCredential(user);
                if (user == null)
                {
                    return ExternalLinkExpired();
                }
            }

            // If we are an administrator and Gallery.EnforcedAuthProviderForAdmin is set
            // to require a specific authentication provider, challenge that provider if needed.
            ActionResult challenge;
            if (ShouldChallengeEnforcedProvider(
                NuGetContext.Config.Current.EnforcedAuthProviderForAdmin, user, returnUrl, out challenge))
            {
                return challenge;
            }

            // Create session
            await _authService.CreateSessionAsync(OwinContext, user);
            return SafeRedirect(returnUrl);
        }
        public virtual async Task <ActionResult> LinkExternalAccount(string returnUrl)
        {
            // Extract the external login info
            var result = await _authService.AuthenticateExternalLogin(OwinContext);

            if (result.ExternalIdentity == null)
            {
                // User got here without an external login cookie (or an expired one)
                // Send them to the logon action
                return(ExternalLinkExpired());
            }

            if (result.Authentication != null)
            {
                // If we are an administrator and Gallery.EnforcedAuthProviderForAdmin is set
                // to require a specific authentication provider, challenge that provider if needed.
                ActionResult challenge;
                if (ShouldChallengeEnforcedProvider(
                        NuGetContext.Config.Current.EnforcedAuthProviderForAdmin, result.Authentication, returnUrl, out challenge))
                {
                    return(challenge);
                }

                if (ShouldEnforceMultiFactorAuthentication(result))
                {
                    // Invoke the authentication again enforcing multi-factor authentication for the same provider.
                    return(ChallengeAuthentication(
                               Url.LinkExternalAccount(returnUrl),
                               result.Authenticator.Name,
                               new AuthenticationPolicy()
                    {
                        Email = result.LoginDetails.EmailUsed, EnforceMultiFactorAuthentication = true
                    }));
                }

                // Create session
                await _authService.CreateSessionAsync(OwinContext, result.Authentication);

                return(SafeRedirect(returnUrl));
            }
            else
            {
                // Gather data for view model
                string name   = null;
                string email  = null;
                var    authUI = result.Authenticator.GetUI();
                try
                {
                    var userInfo = result.Authenticator.GetIdentityInformation(result.ExternalIdentity);
                    name  = userInfo.Name;
                    email = userInfo.Email;
                }
                catch (Exception)
                {
                    // Consume the exception for now, for backwards compatibility to previous MSA provider.
                    email = result.ExternalIdentity.GetClaimOrDefault(ClaimTypes.Email);
                    name  = result.ExternalIdentity.GetClaimOrDefault(ClaimTypes.Name);
                }

                // Check for a user with this email address
                User existingUser = null;
                if (!string.IsNullOrEmpty(email))
                {
                    existingUser = _userService.FindByEmailAddress(email);
                }

                var foundExistingUser        = existingUser != null;
                var existingUserLinkingError = AssociateExternalAccountViewModel.ExistingUserLinkingErrorType.None;

                if (foundExistingUser)
                {
                    if (existingUser is Organization)
                    {
                        existingUserLinkingError = AssociateExternalAccountViewModel.ExistingUserLinkingErrorType.AccountIsOrganization;
                    }
                    else if (existingUser.Credentials.Any(c => c.IsExternal()) && !existingUser.IsAdministrator)
                    {
                        existingUserLinkingError = AssociateExternalAccountViewModel.ExistingUserLinkingErrorType.AccountIsAlreadyLinked;
                    }
                }

                var external = new AssociateExternalAccountViewModel()
                {
                    ProviderAccountNoun      = authUI.AccountNoun,
                    AccountName              = name,
                    FoundExistingUser        = foundExistingUser,
                    ExistingUserLinkingError = existingUserLinkingError
                };

                var model = new LogOnViewModel
                {
                    External = external,
                    SignIn   = new SignInViewModel
                    {
                        UserNameOrEmail = email
                    },
                    Register = new RegisterViewModel
                    {
                        EmailAddress = email
                    }
                };

                return(LinkExternalView(model));
            }
        }