Esempio n. 1
0
        public async Task <IActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationModel model, string returnUrl = null)
        {
            if (ModelState.IsValid)
            {
                // Get the information about the user from the external login provider
                var info = await _signInManager.GetExternalLoginInfoAsync();

                if (info == null)
                {
                    return(View("ExternalLoginFailure"));
                }
                var user = new ApplicationUser {
                    UserName = model.Email, Email = model.Email
                };
                var result = await _userManager.CreateAsync(user);

                if (result.Succeeded)
                {
                    result = await _userManager.AddLoginAsync(user, info);

                    if (result.Succeeded)
                    {
                        await _signInManager.SignInAsync(user, isPersistent : false);

                        _logger.LogInformation(6, "User created an account using {Name} provider.", info.LoginProvider);
                        return(RedirectToLocal(returnUrl));
                    }
                }
                AddErrors(result);
            }

            ViewData["ReturnUrl"] = returnUrl;
            return(View(model));
        }
        public async Task <IActionResult> ExternalLoginCallback(string remoteError = null)
        {
            if (!string.IsNullOrEmpty(remoteError))
            {
                return(RedirectToDefault.WithError(remoteError));
            }

            var result = await _authService.ExternalSignInAsync();

            if (result.Succeeded)
            {
                return(RedirectToDefault);
            }

            if (result.IsLockedOut)
            {
                return(View("Lockout"));
            }

            var externalInfo = await _authService.GetExternalLoginInfoAsync();

            var provider          = externalInfo.LoginProvider;
            var email             = externalInfo.Principal.FindFirstValue(ClaimTypes.Email);
            var userName          = email.Split('@')[0];
            var confirmationModel = new ExternalLoginConfirmationModel
            {
                Provider = provider,
                Email    = email,
                UserName = userName
            };

            return(View("ExternalLoginConfirmation", confirmationModel));
        }
Esempio n. 3
0
        public async Task <ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationModel model, string returnUrl = null)
        {
            try
            {
                if (_accountService.IsSignedIn(User))
                {
                    return(RedirectToAction(ConstantMessages.AccountConstant.AccountControllerConstant.Lockout,
                                            ConstantMessages.AccountConstant.AccountControllerConstant.ManageController));
                }

                if (ModelState.IsValid)
                {
                    // Get the information about the user from the external login provider
                    var info = await _accountService.GetExternalLoginInfoAsync();

                    if (info == null)
                    {
                        return(View(ConstantMessages.AccountConstant.AccountControllerConstant.ExternalLoginFailureView));
                    }
                    var user = new ApplicationUser {
                        UserName = model.Email, Email = model.Email
                    };
                    var result = await _accountService.CreateAsync(user);

                    // NOTE: Used for end to end testing only
                    //Just for automated testing adding a claim named 'ManageStore' - Not required for production
                    var manageClaim = info.Principal.Claims.Where(c => c.Type ==
                                                                  ConstantMessages.AccountConstant.AccountControllerConstant.ManageStore).FirstOrDefault();
                    if (manageClaim != null)
                    {
                        await _accountService.AddClaimAsync(user, manageClaim);
                    }

                    if (result.Succeeded)
                    {
                        result = await _accountService.AddLoginAsync(user, info);

                        if (result.Succeeded)
                        {
                            await _accountService.SignInAsync(user, isPersistent : false);

                            return(RedirectToLocal(returnUrl));
                        }
                    }
                    AddErrors(result);
                }

                ViewBag.ReturnUrl = returnUrl;
                return(View(model));
            }
            catch (Exception ex)
            {
                ErrorViewModel errorModel = GlobalExceptionHandler.GetErrorPage(ex.ToString());
                return(View(ConstantMessages.AccountConstant.AccountControllerConstant.ErrorView, errorModel));
            }
        }
        public async Task <IActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model).WithError(JoinWithHtmlLineBreak(ModelState.GetErrorMessages())));
            }

            var result = await _authService.ExternalLoginConfirmation(model.Email, model.UserName);

            return(result.Succeeded
                ? RedirectToDefault
                : View(model).WithError(JoinWithHtmlLineBreak(result.GetAllErrors())));
        }
Esempio n. 5
0
        //[AllowAnonymous]
        public async Task <IActionResult> ExternalLoginConfirmation([FromBody] ExternalLoginConfirmationModel model, string returnUrl = null)
        {
            if (ModelState.IsValid)
            {
                // Get the information about the user from the external login provider
                var info = await _signInManager.GetExternalLoginInfoAsync();

                if (info == null)
                {
                    ModelState.AddModelError("", "ExternalLoginFailure");
                    return(BadRequest(this.ModelState));
                    //return View("ExternalLoginFailure");
                }
                var user = new ApplicationUser {
                    UserName = model.Email, Email = model.Email
                };
                var result = await _userManager.CreateAsync(user);

                if (result.Succeeded)
                {
                    result = await _userManager.AddLoginAsync(user, info);

                    if (result.Succeeded)
                    {
                        var profile = new Profile
                        {
                            UserId      = user.Id,
                            UserName    = user.UserName,
                            DisplayName = "",
                            AboutMe     = "Add your info here!",
                            Image       = "images/User.jpg"
                        };
                        _context.Profiles.Add(profile);
                        await _context.SaveChangesAsync();

                        await _userManager.AddClaimAsync(user, new Claim("profileId", profile.ProfileId.ToString()));

                        await _signInManager.SignInAsync(user, isPersistent : false);

                        _logger.LogInformation(6, "User created an account using {Name} provider.", info.LoginProvider);
                        var userViewModel = await GetUser(user.UserName);

                        return(Ok(userViewModel));
                    }
                }
                AddErrors(result);
            }

            // ViewData["ReturnUrl"] = returnUrl;
            return(BadRequest(this.ModelState));
        }
Esempio n. 6
0
        //[AllowAnonymous]
        public async Task <IActionResult> ExternalLoginConfirmation([FromBody] ExternalLoginConfirmationModel model, string returnUrl = null)
        {
            if (ModelState.IsValid)
            {
                // Get the information about the user from the external login provider
                var info = await _signInManager.GetExternalLoginInfoAsync();

                if (info == null)
                {
                    ModelState.AddModelError("", "ExternalLoginFailure");
                    return(BadRequest(this.ModelState));
                    //return View("ExternalLoginFailure");
                }
                var user = new ApplicationUser {
                    UserName = model.Email, Email = model.Email
                };
                var result = await _userManager.CreateAsync(user);

                if (result.Succeeded)
                {
                    result = await _userManager.AddLoginAsync(user, info);

                    if (result.Succeeded)
                    {
                        await _signInManager.SignInAsync(user, isPersistent : false);

                        _logger.LogInformation(6, "User created an account using {Name} provider.", info.LoginProvider);
                        var userViewModel = await GetUser(user.UserName);

                        return(Ok(userViewModel));
                    }
                }
                AddErrors(result);
            }

            // ViewData["ReturnUrl"] = returnUrl;
            return(BadRequest(this.ModelState));
        }
Esempio n. 7
0
        public async Task <ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationModel model, string returnUrl)
        {
            if (User.Identity.IsAuthenticated)
            {
                return(RedirectToAction("Index", "Manage"));
            }

            if (ModelState.IsValid)
            {
                // Get the information about the user from the external login provider
                var info = await AuthenticationManager.GetExternalLoginInfoAsync();

                if (info == null)
                {
                    return(View("ExternalLoginFailure"));
                }
                var user = new ApplicationUser {
                    UserName = model.Email, Email = model.Email
                };
                var result = await this.userService.CreateAsync(user);

                if (result.Succeeded)
                {
                    result = await this.userService.AddLoginAsync(user.Id, info.Login);

                    if (result.Succeeded)
                    {
                        await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false);

                        return(RedirectToLocal(returnUrl));
                    }
                }
                AddErrors(result);
            }

            ViewBag.ReturnUrl = returnUrl;
            return(View(model));
        }
        public async Task<ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationModel model, string returnUrl)
        {
            if (User.Identity.IsAuthenticated)
            {
                return RedirectToAction("Index", "Manage");
            }

            if (ModelState.IsValid)
            {
                // Get the information about the user from the external login provider
                var info = await AuthenticationManager.GetExternalLoginInfoAsync();
                if (info == null)
                {
                    return View("ExternalLoginFailure");
                }
                var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
                var result = await this.userService.CreateAsync(user);
                if (result.Succeeded)
                {
                    result = await this.userService.AddLoginAsync(user.Id, info.Login);
                    if (result.Succeeded)
                    {
                        await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
                        return RedirectToLocal(returnUrl);
                    }
                }
                AddErrors(result);
            }

            ViewBag.ReturnUrl = returnUrl;
            return View(model);
        }
Esempio n. 9
0
        public virtual async Task <ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationModel model)
        {
            if (User.Identity.IsAuthenticated)
            {
                return(RedirectToLocal(model.ReturnUrl));
            }

            var currentLanguage = WorkContext.CurrentLanguage;
            var countries       = await _countriesService.GetAsSelectListAsync();

            model.UserMustAcceptTerms = CurrentSettings.ShowAcceptTermsSignUp;
            model.CurrentLanguage     = currentLanguage;
            model.CountriesList       = countries;

            if (CurrentSettings.UseGoogleRecaptchaForSignup && CurrentSettings.ShowRecaptchaAfterNFailedAttempt - 1 <= FailedAttempts)
            {
                ViewBag.publicKey = CurrentSettings.GoogleRecaptchaSiteKey;

                if (CurrentSettings.ShowRecaptchaAfterNFailedAttempt <= FailedAttempts)
                {
                    if (!ReCaptcha.Validate(CurrentSettings.GoogleRecaptchaSecretKey))
                    {
                        IncreaseFailedAttempts();
                        ViewBag.RecaptchaLastErrors = ReCaptcha.GetLastErrors(HttpContext);
                        return(View(model));
                    }
                }
            }

            if (!CurrentSettings.ShowAcceptTermsSignUp)
            {
                ModelState.Remove("AcceptTerms");
            }

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

            var duplicatedEmail = await UserManager.FindByEmailAsync(model.Email);

            if (duplicatedEmail != null)
            {
                ModelState.AddModelError("Email", string.Format(_localizationService.GetResource("DuplicateEmail"), model.Email));
                IncreaseFailedAttempts();
                return(View(model));
            }


            // Get the information about the user from the external login provider
            var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();

            if (loginInfo == null)
            {
                return(View("Error"));
            }

            var user = new TblUsers()
            {
                UserName       = loginInfo.Email,
                Email          = loginInfo.Email,
                RegisterDate   = DateTime.Now,
                FirstName      = model.FName,
                LastName       = model.LName,
                UserCountryId  = model.Country,
                EmailConfirmed = true,
                Avatar         = (await DownloadUserAvatar(model.Avatar)).SaveToAppData("socialAvatar.png")
            };
            var result = await UserManager.CreateAsync(user, model.Password);

            if (result.Succeeded)
            {
                EventPublisher.Publish(new UserSignupEvent(user));

                result = await UserManager.AddLoginAsync(user.Id, loginInfo.Login);

                if (result.Succeeded)
                {
                    await SignInManager.SignInAsync(user, isPersistent : true, rememberBrowser : false);

                    EventPublisher.Publish(new UserLoggedinEvent(user));
                    return(RedirectToLocal(model.ReturnUrl));
                }
            }

            foreach (var error in result.Errors)
            {
                ModelState.AddModelError("", error);
            }
            IncreaseFailedAttempts();
            return(View(model));
        }
Esempio n. 10
0
        public ActionResult ExternalLoginConfirmation(ExternalLoginConfirmationModel model, string returnUrl, string token)
        {
            string accountData;

            // TODO: @eric, The local account might never be created??
            if ((User != null && User.Identity.IsAuthenticated) || !_encoder.TryUnprotect(model.ExternalLoginData, out accountData))
            {
                return(RedirectToAction("Manage"));
            }

            var account = JsonConvert.DeserializeObject <OAuthAccount>(accountData);

            if (ModelState.IsValid)
            {
                if (!_membershipProvider.HasLocalAccount(model.EmailAddress))
                {
                    var roles = new Collection <string> {
                        AuthorizationRoles.User
                    };

                    // Add the GlobalAdmin role to the first user of the system.
                    if (!_isFirstUserChecked)
                    {
                        _isFirstUserChecked = true;
                        if (_userRepository.Count() == 0)
                        {
                            roles.Add(AuthorizationRoles.GlobalAdmin);
                        }
                    }

                    // TODO: Should we be using and merging User.UserEntity if authenticated?
                    User user = _membershipProvider.CreateOAuthAccount(account, new User {
                        EmailAddress = model.EmailAddress,
                        FullName     = model.FullName,
                        Roles        = roles
                    });

                    if (!String.IsNullOrEmpty(token))
                    {
                        AddInvitedUserToOrganization(token, user);
                    }

                    _membershipProvider.OAuthLogin(account, remember: true);

                    if (!user.IsEmailAddressVerified)
                    {
                        user.VerifyEmailAddressToken = _membershipProvider.GenerateVerifyEmailToken(user.EmailAddress);
                        _mailer.SendVerifyEmailAsync(user);
                    }

                    if (Settings.Current.WebsiteMode == WebsiteMode.Dev && user.Roles.Contains(AuthorizationRoles.GlobalAdmin))
                    {
                        _dataHelper.CreateSampleOrganizationAndProject(user.Id);
                    }

                    return(RedirectToLocal(returnUrl));
                }

                ModelState.AddModelError("EmailAddress", "Email Address already exists. Please enter a different Email Address.");
            }

            _isFirstUserChecked         = false;
            ViewBag.ProviderDisplayName = _membershipProvider.GetOAuthClientData(account.Provider).DisplayName;
            ViewBag.ReturnUrl           = returnUrl;
            ViewBag.Token = token;

            return(View(model));
        }