Exemple #1
0
        public async Task <ActionResult> ForgotPassword(ForgotPasswordViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = await UserManager.FindByEmailAsync(model.Email);

                if (user == null || !(await UserManager.IsEmailConfirmedAsync(user.Id)))
                {
                    // Don't reveal that the user does not exist or is not confirmed
                    return(View("ForgotPasswordConfirmation"));
                }

                // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
                // Send an email with this link
                string code = await UserManager.GeneratePasswordResetTokenAsync(user.Id);

                var callbackUrl = Url.Action("ResetPassword", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                await UserManager.SendEmailAsync(user.Id, "Alteração de Senha", "Altere a sua senha clicando <a href=\"" + callbackUrl + "\">aqui</a>");

                return(View("ForgotPasswordConfirmation"));
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
        public async Task <ActionResult> LogIn(AccountLogInViewModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                AppUserEntity user = null;

                //
                if (_RegularExpressions.SimpleEmail.IsMatch(model.EmailOrUsername))
                {
                    user = await _appUserManager.FindByEmailAsync(model.EmailOrUsername);
                }
                else
                {
                    user = await _appUserManager.FindByNameAsync(model.EmailOrUsername);
                }

                //
                if (user != null && user.Realms.Contains(Realm.AdminWebsite))
                {
                    _signInManager.InitialPersistenceState = model.RememberMe;

                    var result = await _signInManager.PasswordSignInAsync(
                        user.UserName,
                        model.Password,
                        model.RememberMe,
                        shouldLockout : true
                        );

                    switch (result)
                    {
                    case SignInStatus.LockedOut:
                    {
                        return(RedirectToAction("Locked", "Account"));
                    }

                    case SignInStatus.Success:
                    {
                        return(RedirectToLocal(returnUrl));
                    }
                    }
                }

                ModelState.AddModelError("credentials", GetLocalizedString <AreaResources>("InvalidCredentialsMessage"));
            }

            ViewBag.ReturnUrl = returnUrl;

            return(View(model));
        }
        public async Task <IHttpActionResult> ForgotPassword(string email)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            var user = await AppUserManager.FindByEmailAsync(email);

            if (user == null)
            {
                return(BadRequest("El email es incorrecto."));
            }

            var code = await AppUserManager.GeneratePasswordResetTokenAsync(user.Id);

            code = HttpUtility.UrlEncode(code);

            var callbackUrl = string.Concat(
                Request.RequestUri.Scheme,
                "://",
                Request.RequestUri.Authority,
                "/#!/resetPassword?key=",
                user.Id,
                "&code=",
                code
                );
            await AppUserManager.SendEmailAsync(user.Id, "Recuperar Contraseña", "Por favor, recupere su contraseña siguiendo <a href=\"" + callbackUrl + "\">este enlace.</a>");

            return(Ok());
        }
Exemple #4
0
        public async Task <IActionResult> OnPostSendVerificationEmailAsync()
        {
            if (!ModelState.IsValid)
            {
                return(Page());
            }

            var user = await _userManager.FindByEmailAsync(Input.Email);

            if (user == null)
            {
                ModelState.AddModelError(string.Empty, "Verification email sent. Please check your email.");
            }

            var userId = await _userManager.GetUserIdAsync(user);

            var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

            var callbackUrl = Url.Page(
                "/Account/ConfirmEmail",
                pageHandler: null,
                values: new { userId = userId, code = code },
                protocol: Request.Scheme);
            await _emailSender.SendEmailAsync(
                Input.Email,
                "Confirm your email",
                $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");

            ModelState.AddModelError(string.Empty, "Verification email sent. Please check your email.");
            return(Page());
        }
        public async Task <IActionResult> ForgetPassword(ForgetPassword model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            var user = await _userManager.FindByEmailAsync(model.Email);

            if (user == null || !(await _userManager.IsEmailConfirmedAsync(user)))
            {
                return(View("ForgetPasswordConfirm"));
            }

            var code = await _userManager.GeneratePasswordResetTokenAsync(user);

            var callBackUrl = Url.RouteUrl(
                "GetResetPassword",
                new
            {
                key = user.GeneratedKey, code
            }, Request.Scheme);

            var message = $"<a href=\"{callBackUrl}\"> Rest Password </a>";

            await _emailSender.SendEmailAsync(user.Email, "Rest Password", message);

            return(View("ForgetPasswordConfirm"));
        }
        public async Task <IActionResult> OnPostAsync()
        {
            if (!ModelState.IsValid)
            {
                return(Page());
            }

            var user = await _userManager.FindByEmailAsync(Input.Email);

            if (user == null)
            {
                // Don't reveal that the user does not exist
                return(RedirectToPage("./ResetPasswordConfirmation"));
            }

            var result = await _userManager.ResetPasswordAsync(user, Input.Code, Input.Password);

            if (result.Succeeded)
            {
                return(RedirectToPage("./ResetPasswordConfirmation"));
            }

            foreach (var error in result.Errors)
            {
                ModelState.AddModelError(string.Empty, error.Description);
            }
            return(Page());
        }
        public async Task <IHttpActionResult> Register(RegisterClientModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var client = new Client
            {
                UserName = model.Email,
                Email    = model.Email,
                Name     = model.Name,
                Address  = model.Address,
                Location = model.Location
            };

            IdentityResult result;
            var            existingUser = await _userManager.FindByEmailAsync(client.Email);

            if (existingUser != null)
            {
                result = IdentityResult.Failed(new[] { "User with this email already exists" });
            }
            else
            {
                result = await _clientManager.CreateAsync(client, model.Password);
            }

            if (!result.Succeeded)
            {
                return(GetErrorResult(result));
            }

            return(Ok());
        }
Exemple #8
0
        public async Task <IActionResult> LoginViaEmailCode(LoginViaCodeInputModel parameters)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState.Values.SelectMany(state => state.Errors)
                                  .Select(error => error.ErrorMessage)
                                  .FirstOrDefault()));
            }

            var user = await _userManager.FindByEmailAsync(parameters.Key);

            if (user == null)
            {
                return(BadRequest("User does not exist"));
            }
            var singInResult = await _signInManager.CheckPasswordSignInAsync(user, parameters.Code, false);

            if (!singInResult.Succeeded)
            {
                return(BadRequest("Invalid password"));
            }

            await _signInManager.SignInAsync(user, parameters.RememberMe);

            return(Ok());
        }
        public async Task <IHttpActionResult> Login(LoginModel model)
        {
            if (ModelState.IsValid)
            {
                var user = await AppUserManager.FindByEmailAsync(model.Email);

                //We don't want a deleted user to be able to log in.
                if (user != null && !user.IsDeleted)
                {
                    var valid = await AppUserManager.CheckPasswordAsync(user, model.Password);

                    if (valid)
                    {
                        await SignInAsync(user, model.RememberMe);

                        return(Ok());
                    }
                }

                ModelState.AddModelError("", "Invalid username or password.");
            }

            // If we got this far, something failed, redisplay form
            return(BadRequest(ModelState));
        }
        public async Task <IActionResult> OnPostAsync()
        {
            if (ModelState.IsValid)
            {
                var user = await _userManager.FindByEmailAsync(Input.Email);

                if (user == null || !(await _userManager.IsEmailConfirmedAsync(user)))
                {
                    // Don't reveal that the user does not exist or is not confirmed
                    return(RedirectToPage("./ForgotPasswordConfirmation"));
                }

                // For more information on how to enable account confirmation and password reset please
                // visit https://go.microsoft.com/fwlink/?LinkID=532713
                var code = await _userManager.GeneratePasswordResetTokenAsync(user);

                var callbackUrl = Url.Page(
                    "/Account/ResetPassword",
                    pageHandler: null,
                    values: new { code },
                    protocol: Request.Scheme);

                await _emailSender.SendEmailAsync(
                    Input.Email,
                    "Reset Password",
                    $"Please reset your password by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");

                return(RedirectToPage("./ForgotPasswordConfirmation"));
            }

            return(Page());
        }
Exemple #11
0
        public static async Task <int> GetCurrentUserIdAsync(this AppUserManager appUserManager, string userEmail)
        {
            AppUser currentUser = await appUserManager.FindByEmailAsync(userEmail);

            int currentUserId = int.Parse(await appUserManager.GetUserIdAsync(currentUser));

            return(currentUserId);
        }
Exemple #12
0
        public async Task <JsonResult> EmailExists(string email)
        {
            AppUser user = await UserManager.FindByEmailAsync(email);

            return(user == null?Json(true) : Json($"Email {email} is already in use."));

            //return repository.EmailExists(email) ? Json(true): Json($"Email {email} is already in use.");
        }
        public async Task <IHttpActionResult> Register(RegisterSantaModel model)
        {
            //var model = new RegisterSantaModel();

            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            IdentityResult result;
            var            existingUser = await _userManager.FindByEmailAsync(model.Email);

            if (existingUser != null)
            {
                result = IdentityResult.Failed(new[] { "User with this email already exists" });
            }
            else
            {
                var santa = new Santa
                {
                    UserName  = model.Email,
                    Email     = model.Email,
                    Name      = model.Name,
                    PhotoPath = ""
                };

                result = await _santaManager.CreateAsync(santa, model.Password);

                if (result.Succeeded)
                {
                    var photoPath = HttpContext.Current.Server.MapPath("~/App_Data/Photos");
                    if (!Directory.Exists(photoPath))
                    {
                        Directory.CreateDirectory(photoPath);
                    }

                    var fileExtension = Path.GetExtension(model.Photo.Filename);
                    var filename      = $"{santa.Id}{fileExtension}";

                    photoPath = Path.Combine(photoPath, filename);
                    File.WriteAllBytes(photoPath, model.Photo.Content);
                    santa.PhotoPath = photoPath;
                    await _santaManager.UpdateAsync(santa);
                }
            }

            if (!result.Succeeded)
            {
                return(GetErrorResult(result));
            }

            return(Ok());
        }
        protected async Task <AppUser> GetCurrentUser()
        {
            if (_currentUser == null)
            {
                var email = _userEmail;
                if (string.IsNullOrWhiteSpace(email))
                {
                    return(null);
                }

                _currentUser = await _appUserManager.FindByEmailAsync(email);
            }

            return(_currentUser);
        }
Exemple #15
0
        public async Task <ActionResult> ForgotPassword(string email)
        {
            AppUser user = await _userManager.FindByEmailAsync(email);

            if (!string.IsNullOrEmpty(email) && user != null)
            {
                string code = await _userManager.GeneratePasswordResetTokenAsync(user.Id);

                string callbackUrl = Url.Action("ResetPassword", "Account", new { code = code }, protocol: Request.Url.Scheme);
                _mailingRepository.ResetPasswordMail(user.Email, callbackUrl);
                return(PartialView("ForgotPasswordConfirmation"));
            }
            ModelState.AddModelError("", "User Not Found");
            Response.StatusCode = (int)HttpStatusCode.BadRequest;
            return(PartialView());
        }
Exemple #16
0
        public async Task <IHttpActionResult> ForgotPassword(ForgotPasswordModel username)
        {
            var user = await AppUserManager.FindByEmailAsync(username.UserName);

            if (user == null)
            {
                return(BadRequest("Invalid email address"));
            }
            var token = await AppUserManager.GeneratePasswordResetTokenAsync(user.Id);

            var callbackUrl = Request.RequestUri.Scheme + "://" + Request.RequestUri.Authority +
                              "/ResetPassword?userId=" + user.Id + "&code=" + HttpUtility.UrlEncode(token);
            await
            AppUserManager.SendEmailAsync(user.Id, "Password Reset",
                                          "Please reset your password by clicking " + callbackUrl);

            return(Ok());
        }
        public async Task <IHttpActionResult> RecoverPassword(string email)
        {
            var user = await AppUserManager.FindByEmailAsync(email);

            if (user == null)
            {
                return(BadRequest("E-mail is not registered"));
            }

            string code = await AppUserManager.GeneratePasswordResetTokenAsync(user.Id);

            string password = GetAutoGenPwd();

            var callbackUrl = new Uri(Url.Link("ResetPasswordRoute", new { userId = user.Id, code, password }));

            await AppUserManager.SendEmailAsync(user.Id, "KeetFit Password Recovery", "Please follow <a href=\"" + callbackUrl + "\">this</a> link to reset your password. Then you'll be able to use new generated password: '******' for login.");

            return(Ok());
        }
Exemple #18
0
        public async Task SignIn(UserLoginModel model)
        {
            if (model == null)
            {
                return;
            }

            var user = await _appUserManager.FindByEmailAsync(model.Email);

            if (user == null)
            {
                return;
            }

            var isPassword = await _appUserManager.CheckPasswordAsync(user, model.Password);


            var s = isPassword;
        }
        public async Task <IHttpActionResult> RecoveryPassword(string email)
        {
            var user = await AppUserManager.FindByEmailAsync(email);

            if (user == null)
            {
                Logger.ServiceLog.Warn($"Пользователь с email {email} не зарегистрирован.");
                return(GetErrorFromModel("email", $"Пользователь с email {email} не зарегистрирован."));
            }
            var recoveryToken = AppUserManager.GeneratePasswordResetTokenAsync(user.Id);
            var code          = HttpUtility.UrlEncode(recoveryToken.Result);
            var password      = RandomPasswordService.Generate(6);
            var callBackUri   = new Uri(Url.Link("RecoveryPasswordRoute", new { userId = user.Id, code, newPassword = password }));

            await AppUserManager.SendEmailAsync(user.Id, "Восстановление пароля",
                                                "Ваш новый пароль: <strong>" + password + "</strong> <br> Для его подтверждения перейдите по ссылке <a href=\"" + callBackUri + "\">ССылка</a>");

            Logger.ServiceLog.Info($"Пользователю на email {email} успешно выслана инструкция по восстановдению пароля.");
            return(Ok("Инструкция по смене пароля выслана на почту"));
        }
Exemple #20
0
        public async Task <IHttpActionResult> ForgotPassword(ForgotPasswordBindingModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            //Use later when isEmailConfirmed implemented
            //if (user == null || !(await AppUserManager.IsEmailConfirmedAsync(user.Id)))
            var user = await AppUserManager.FindByEmailAsync(model.Email);

            //var role = await this.AppRoleManager.FindByIdAsync(Id);
            if (user == null)
            {
                // Don't reveal that the user does not exist or is not confirmed
                return(Ok());
            }


            string pcode = await AppUserManager.GeneratePasswordResetTokenAsync(user.Id);

            System.Web.HttpUtility.UrlEncode(pcode);

            var callbackUrl = "http://rip-offnigeria.com/index.html#/resetpwd/" + user.Id + "/" + pcode;

            string response = "<h4>Reset password</h4>" +
                              "<p>" +
                              "<p>Dear " + user.Name + "," +
                              "<p>" +
                              "<p class=\"lead\">To get back into your rip-off Nigeria account,you'll need to create a new password.</p>" +
                              "<p class=\"lead\">Click the link below to open a secure browser window.</p>";


            await this.AppUserManager.SendEmailAsync(user.Id,
                                                     "Reset your password",
                                                     response + "<a href=\"" + callbackUrl + "\">Reset your password now</a>");

            // If we got this far, something failed, redisplay form
            return(Ok());
        }
Exemple #21
0
        public async Task <ActionResult> New(CreateUserModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            var identiyUser = await _userManager.FindByEmailAsync(model.Email);

            if (identiyUser != null)
            {
                return(RedirectToAction("Index", "User"));
            }

            var user = new ExtendedUser
            {
                Email    = model.Email,
                FullName = model.FullName,
                UserName = model.Email,
                Id       = Guid.NewGuid().ToString()
            };

            var result = await _userManager.CreateAsync(user, model.Password);

            //Genrate Token
            var token      = _userManager.GenerateEmailConfirmationTokenAsync(user.Id);
            var confirmUrl = Url.Action("ConfirmEmail", "Account", new { userid = user.Id, token = token }, Request.Url.Scheme);

            await _userManager.SendEmailAsync(user.Id, "Email Confirmation", $"Use link to confirm email:{confirmUrl}");

            if (result.Succeeded)
            {
                return(RedirectToAction("Index", "User"));
            }

            ModelState.AddModelError("", result.Errors.FirstOrDefault());

            return(View(model));
        }
Exemple #22
0
        public async Task <HttpResponseMessage> ResetPassword(HttpRequestMessage request, AppUserViewModel model)
        {
            if (ModelState.IsValid)
            {
                var userEmail = await AppUserManager.FindByEmailAsync(model.Email);

                if (userEmail == null)
                {
                    return(request.CreateErrorResponse(HttpStatusCode.NoContent, "Email không tồn tại"));
                }
                //Send an email with link
                string sendLink = await AppUserManager.GeneratePasswordResetTokenAsync(userEmail.Id);

                await AppUserManager.SendEmailAsync(userEmail.Id, "Reset password", "Click here ");

                return(request.CreateResponse(HttpStatusCode.OK, sendLink));
            }
            else
            {
                return(request.CreateErrorResponse(HttpStatusCode.NoContent, "Models không thỏa mãn yêu cầu"));
            }
        }
Exemple #23
0
        // TODO: Apply capcha
        public async Task <IHttpActionResult> RegisterUser(RegisterUserReq registerUserDto)
        {
            // Create user
            IdentityResult identityResult = AppUserManager.RegisterUser(registerUserDto);

            if (!identityResult.Succeeded)
            {
                return(BadRequestWithIdentityErrors(identityResult));
            }

            // Send confirmation email
            AppUser appUser = await AppUserManager.FindByEmailAsync(registerUserDto.Email);

            var resultMessage = await SendEmailConfirmationAsync(appUser);

            // Configure reponse
            var response = new BaseResponseDto();

            response.Message = Responses.UserRegisteredMessage + " " + resultMessage;

            return(Ok(response));
        }
    public async Task <IHttpActionResult> GetPasscode(string email)
    {
        ApplicationUser user = await AppUserManager.FindByEmailAsync(email);

        if (user == null)
        {
            return(BadRequest());
        }
        string code = PassCode.GeneratePresharedKey();

        user.PasscodeHash      = code;
        user.LockoutEndDateUtc = DateTime.UtcNow.AddMinutes(30);
        IdentityResult userResult = await this.AppUserManager.UpdateAsync(user);

        if (!userResult.Succeeded)
        {
            return(GetErrorResult(userResult));
        }
        await this.AppUserManager.SendEmailAsync(user.Id, "Login Passcode", code);

        return(Ok());
    }
        public async Task <IActionResult> LoginPostAsync(string returnUrl = null)
        {
            returnUrl = returnUrl ?? Url.Content("~/");
            if (ModelState.IsValid)
            {
                AppUser user = await userManager.FindByEmailAsync(UserSignInModel.Email);

                if (user != null)
                {
                    await signInManager.SignOutAsync();

                    var result = await signInManager.PasswordSignInAsync(
                        UserSignInModel.UserName, UserSignInModel.Password, UserSignInModel.RememberMe, lockoutOnFailure : true);

                    if (result.Succeeded)
                    {
                        bool asd = User.Identity.IsAuthenticated;
                        return(Redirect(returnUrl));
                    }

                    if (result.IsLockedOut)
                    {
                        return(RedirectToPage("./Lockout"));
                    }
                    else
                    {
                        ModelState.AddModelError(string.Empty, "Invalid login attempt.");
                        return(View(UserSignInModel));
                    }
                }
                else
                {
                    ModelState.AddModelError(nameof(UserSignInModel.Email), "Invalid user or password");
                }
            }

            return(View());
        }
Exemple #26
0
        public async Task <HttpResponseMessage> CheckUser(HttpRequestMessage request, string id)
        {
            //var username = AppUserManager.FindByNameAsync(id).Result;
            var username = AppUserManager.FindByEmailAsync(id).Result;

            if (username != null)
            {
                var rolesForUser = await AppUserManager.GetRolesAsync(username.Id);

                if (rolesForUser.Count() > 0)
                {
                    foreach (var item in rolesForUser.ToList())
                    {
                        // item should be the name of the role
                        var result = await AppUserManager.RemoveFromRoleAsync(username.Id, item);
                    }
                }
                _userService.DeleteTableUser(username.Id);
                _unitOfWork.Commit();
                return(request.CreateResponse(HttpStatusCode.OK, Common.Constants.MessageSystem.ChangePasswordSuccess));
            }
            return(request.CreateResponse(HttpStatusCode.OK));
        }
Exemple #27
0
        public async Task <OperationDetails> Register(RegisDTO userDto)
        {
            try
            {
                AppUser user = await _userMng.FindByEmailAsync(userDto.Email);

                if (user == null)
                {
                    var entityId = await CreateClient(userDto);

                    user = new AppUser {
                        UserName = userDto.Email, Email = userDto.Email, BusinessEntityID = entityId
                    };
                    var result = await _userMng.CreateAsync(user, userDto.Password);

                    if (result.Errors.Count() > 0)
                    {
                        return(new OperationDetails(OperationDetails.Statuses.Error, result.Errors.FirstOrDefault(), ""));
                    }

                    await _userMng.AddToRoleAsync(user.Id, userDto.Role);

                    _userMng.Dispose();

                    return(new OperationDetails(OperationDetails.Statuses.Success, "Registration was successful!", ""));
                }
                else
                {
                    return(new OperationDetails(OperationDetails.Statuses.Error, "User with this login exists", "Email"));
                }
            }
            catch (Exception e)
            {
                return(new OperationDetails(OperationDetails.Statuses.Error, $"{e.Message}", "Exception"));
            }
        }
Exemple #28
0
        protected async Task <IHttpActionResult> ChangeProfileInternal <T>(UserManager <T> userManager, IProfileChangeModel model, Action <User> updateModel)
            where T : User
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            using (var scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                IdentityResult result;
                try
                {
                    var id   = User.Identity.GetUserId();
                    var user = await userManager.FindByIdAsync(id);

                    if (user != null)
                    {
                        if (await userManager.CheckPasswordAsync(user, model.Password))
                        {
                            updateModel(user);

                            if (!string.IsNullOrEmpty(model.NewPassword.Password) && !string.IsNullOrEmpty(model.NewPassword.PasswordConfirmation))
                            {
                                if (model.NewPassword.Password == model.NewPassword.PasswordConfirmation)
                                {
                                    result = await userManager.ChangePasswordAsync(user.Id, model.Password, model.NewPassword.Password);

                                    if (!result.Succeeded)
                                    {
                                        throw new ChangeProfileException(result);
                                    }
                                }
                                else
                                {
                                    throw new ChangeProfileException(IdentityResult.Failed(new[] { "Passwords don't match" }));
                                }
                            }
                        }
                        else
                        {
                            throw new ChangeProfileException(IdentityResult.Failed(new[] { "Incorrect password" }));
                        }

                        var existingUserWithThisEmail = await _commonUserManager.FindByEmailAsync(user.Email);

                        if (existingUserWithThisEmail != null && existingUserWithThisEmail.Id != user.Id)
                        {
                            throw new ChangeProfileException(IdentityResult.Failed(new[] { "User with this email already exists" }));
                        }

                        result = await userManager.UpdateAsync(user);

                        if (!result.Succeeded)
                        {
                            throw new ChangeProfileException(result);
                        }
                    }
                    else
                    {
                        throw new ChangeProfileException(IdentityResult.Failed(new[] { "User does not exists" }));
                    }

                    scope.Complete();
                    return(Ok());
                }
                catch (ChangeProfileException ex)
                {
                    scope.Dispose();
                    return(GetErrorResult(ex.Result));
                }
                catch (Exception ex)
                {
                    scope.Dispose();
                    return(GetErrorResult(IdentityResult.Failed(ex.Message)));
                }
            }
        }
Exemple #29
0
        public async Task <ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var lastMonth    = DateTime.Now.AddMonths(-1);
                var existingUser = await UserManager.FindByEmailAsync(model.Email);

                CompanyTeamMemberInvite invite = null;
                bool hasInvite = false;

                if (existingUser != null)
                {
                    this.SetNotificationMessage(NotificationType.Error, string.Format("Email {0} is already taken.", model.Email));
                    return(View(model));
                }

                if (!model.TermsAndConditions)
                {
                    this.SetNotificationMessage(NotificationType.Error, "You must accept the Terms and Conditions and Privacy Policy.");
                    return(View(model));
                }

                // Check for invite
                if (model.Invite != null)
                {
                    invite = _companyManager.GetTeamMemberInvite(model.Invite.UniqueId);

                    if (invite == null)
                    {
                        return(View("InviteUnavailable"));
                    }

                    if (invite.ResultantUserId.HasValue)
                    {
                        this.SetNotificationMessage(NotificationType.Error, "There is already an account creating using this invitation. Please login to start using the application.");
                        return(View(model));
                    }

                    hasInvite = true;
                }

                IdentityResult result;
                AppUser        registeredUser;

                using (var scope = new TransactionScope())
                {
                    // Create new user.
                    registeredUser = new AppUser
                    {
                        UserName  = model.Email,
                        Email     = model.Email,
                        FirstName = model.FirstName,
                        LastName  = model.LastName
                    };
                    result = await UserManager.CreateAsync(registeredUser, model.Password);

                    if (result.Succeeded)
                    {
                        // Mark the latest terms and conditions as accepted
                        _termsAndConditionsManager.AcceptTermsAndConditions(registeredUser.Id);

                        // Check if the user has been invited.
                        if (hasInvite)
                        {
                            invite.ResultantUserId = registeredUser.Id;
                            _companyManager.AcceptTeamMemberInvite(invite);
                        }
                        else
                        {
                            // Create a new company.
                            var newCompany = _companyManager.Create(new Company
                            {
                                Name          = model.CompanyName,
                                StartMonth    = lastMonth,
                                ReportTitle   = DefaultReportTitle,
                                TwitterHandle = model.TwitterHandle
                            });

                            // Associate the user to the company.
                            _companyManager.AddUser(newCompany.Id, registeredUser.Id, true);

                            // Create a trial subscription
                            _subscriptionManager.CreateTrialSubscription(newCompany.Id);
                        }
                    }

                    // Complete the scope.
                    scope.Complete();
                }

                // Send the email confirmation email.
                if (result.Succeeded)
                {
                    // store UTM info
                    var utmInfo = GetUtmInfo();
                    if (utmInfo != null)
                    {
                        utmInfo.UserId = registeredUser.Id;
                        _adminManager.StoreUtmInfo(utmInfo);
                    }

                    var callbackUrl = await SendEmailConfirmationTokenAsync(registeredUser.Id, registeredUser.UniqueId, "Confirm your account");

                    ViewBag.Link = callbackUrl;

                    return(Redirect("http://supdate.com/confirm-email"));
                }

                AddErrors(result);
            }

            // If we got this far, something failed, redisplay form

            return(View(model));
        }
Exemple #30
0
        //[HttpPost("sign-in", Name = "PostLogin")]
        public async Task <IActionResult> Login(LoginAccount account, string returnTo)
        {
            if (account.Email.IndexOf('@') > -1)
            {
                //Validate email format
                string emailRegex = @"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}" +
                                    @"\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" +
                                    @".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$";
                Regex re = new Regex(emailRegex);
                if (!re.IsMatch(account.Email))
                {
                    ModelState.AddModelError("Email", "ایمیل معتبر نمیباشد");
                }
                if (ModelState.IsValid)
                {
                    var user = await _userManager.FindByEmailAsync(account.Email);

                    if (user != null)
                    {
                        var result = await _signInManager.PasswordSignInAsync(

                            userName : user.UserName,
                            password : account.Password,
                            isPersistent : account.RememberMe,
                            lockoutOnFailure : true);


                        if (result.Succeeded)
                        {
                            return(RedirectToLocal(returnTo));
                        }

                        if (result.RequiresTwoFactor)
                        {
                            return(RedirectToRoute("GetSendCode", new { returnTo, rememberMe = account.RememberMe }));
                        }

                        if (result.IsLockedOut)
                        {
                            // todo create lockout view
                            return(View("LockOut"));
                        }

                        if (result.IsNotAllowed)
                        {
                            if (_userManager.Options.SignIn.RequireConfirmedPhoneNumber)
                            {
                                if (!await _userManager.IsPhoneNumberConfirmedAsync(new User {
                                    UserName = account.Email
                                }))
                                {
                                    ModelState.AddModelError(string.Empty, "شماره تلفن شما تایید نشده است.");

                                    return(View(account));
                                }
                            }


                            if (_userManager.Options.SignIn.RequireConfirmedEmail)
                            {
                                if (!await _userManager.IsEmailConfirmedAsync(new User {
                                    UserName = account.Email
                                }))
                                {
                                    ModelState.AddModelError(string.Empty, "آدرس ایمیل شما تایید نشده است.");

                                    return(View(account));
                                }
                            }
                        }
                    }
                }
            }
            else
            {
                //validate Username format
                string emailRegex = @"^[a-zA-Z0-9]*$";
                Regex  re         = new Regex(emailRegex);
                if (!re.IsMatch(account.Email))
                {
                    ModelState.AddModelError("Email", "نام کاربری معتبر نمیباشد");
                }
                else
                {
                    if (ModelState.IsValid)
                    {
                        var user = await _userManager.FindByNameAsync(account.Email);

                        if (user != null)
                        {
                            var result = await _signInManager.PasswordSignInAsync(

                                userName : account.Email,
                                password : account.Password,
                                isPersistent : account.RememberMe,
                                lockoutOnFailure : false);


                            if (result.Succeeded)
                            {
                                return(RedirectToLocal(returnTo));
                            }

                            if (result.RequiresTwoFactor)
                            {
                                return(RedirectToRoute("GetSendCode", new { returnTo, rememberMe = account.RememberMe }));
                            }

                            if (result.IsLockedOut)
                            {
                                // todo create lockout view
                                return(View("LockOut"));
                            }

                            if (result.IsNotAllowed)
                            {
                                if (_userManager.Options.SignIn.RequireConfirmedPhoneNumber)
                                {
                                    if (!await _userManager.IsPhoneNumberConfirmedAsync(new User {
                                        UserName = account.Email
                                    }))
                                    {
                                        ModelState.AddModelError(string.Empty, "شماره تلفن شما تایید نشده است.");

                                        return(View(account));
                                    }
                                }


                                if (_userManager.Options.SignIn.RequireConfirmedEmail)
                                {
                                    if (!await _userManager.IsEmailConfirmedAsync(new User {
                                        UserName = account.Email
                                    }))
                                    {
                                        ModelState.AddModelError(string.Empty, "آدرس ایمیل شما تایید نشده است.");

                                        return(View(account));
                                    }
                                }
                            }
                        }
                    }
                }
            }

            ModelState.AddModelError(string.Empty, "نام کاربری و یا کلمه‌ی عبور وارد شده معتبر نیستند.");

            return(View(account));
        }