Example #1
0
    public override IEnumerable <Expression <Func <User, bool> > > GetPredicates()
    {
        if (Email.HasValue())
        {
            yield return(entity => entity.Email == Email);
        }

        if (SignupToken.HasValue())
        {
            yield return(entity => entity.SignupToken == SignupToken);
        }

        if (ResetPasswordToken.HasValue())
        {
            yield return(entity => entity.ResetPasswordToken == ResetPasswordToken);
        }

        if (IdToExclude.HasValue)
        {
            yield return(entity => entity.Id != IdToExclude);
        }

        if (SearchValue.HasValue())
        {
            yield return(entity => entity.FirstName.Contains(SearchValue) ||
                         entity.LastName.Contains(SearchValue) ||
                         entity.Email.Contains(SearchValue));
        }
    }
Example #2
0
        public async Task <OmbiIdentityResult> ResetPassword([FromBody] ResetPasswordToken token)
        {
            var user = await UserManager.FindByEmailAsync(token.Email);

            if (user == null)
            {
                return(new OmbiIdentityResult
                {
                    Successful = false,
                    Errors = new List <string> {
                        "Please check you email."
                    }
                });
            }
            var validToken = WebUtility.UrlDecode(token.Token);

            validToken = validToken.Replace(" ", "+");
            var tokenValid = await UserManager.ResetPasswordAsync(user, validToken, token.Password);

            if (tokenValid.Succeeded)
            {
                return(new OmbiIdentityResult
                {
                    Successful = true,
                });
            }
            return(new OmbiIdentityResult
            {
                Errors = tokenValid.Errors.Select(x => x.Description).ToList()
            });
        }
Example #3
0
        public override ResetPasswordToken GenerateResetPasswordToken(IResetPasswordTokenOwner owner, ApplicationStore applicationStore, string urlBack = "")
        {
            var account = owner as Account;

            ResetPasswordToken token = null;
            var tokens = resetPasswordTokenRepository.ListByOwnerCode(account.Code);

            if (!tokens.IsNull())
            {
                token = tokens.Where(t => t.ExpiresUtc > DateTime.UtcNow.AddMinutes(60) && t.ApplicationStoreCode == applicationStore.Code).FirstOrDefault();

                if (!token.IsNull())
                {
                    return(token);
                }
            }

            if (token.IsNull())
            {
                base.DeleteAllResetPasswordTokens(account.Code);

                token = new ResetPasswordToken(account.Code, applicationStore.Code, urlBack);
                resetPasswordTokenRepository.Add(token);
            }

            return(token);
        }
        public async Task <IActionResult> ResetPassword(ResetPasswordRequestModel model)
        {
            await _loggingService.SaveAuditLog($"Retrieving user with email {model.Email}", AuditActionEnum.Read);

            var user = await _userRepository.GetUserByEmail(model.Email);

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

            var token = TokenHelper.GenerateResetPasswordToken();

            var resetPasswordToken = new ResetPasswordToken
            {
                Token          = token,
                ExpirationDate = DateTime.Now.AddMinutes(30),
                UserId         = user.UserId
            };

            await _loggingService.SaveAuditLog($"Creating reset-password token for user with user id {user.UserId}",
                                               AuditActionEnum.Create);

            await _authenticationRepository.CreateToken(resetPasswordToken);

            await _emailService.SendEmail(new EmailData(token, model.Email, EmailTypeEnum.PasswordRecovery));

            return(Ok());
        }
Example #5
0
        public override ResetPasswordToken GenerateResetPasswordToken(IResetPasswordTokenOwner owner, ApplicationStore applicationStore, string urlBack = "")
        {
            var customer = owner as CustomerImport;

            ResetPasswordToken token = null;
            var tokens = resetPasswordTokenRepository.ListByOwnerCode(customer.AccountCode);

            if (!tokens.IsNull())
            {
                token = tokens.Where(t => t.ExpiresUtc > DateTime.UtcNow.AddMinutes(15) && t.ApplicationStoreCode == applicationStore.Code).FirstOrDefault();

                if (!token.IsNull() && (DateTime.UtcNow - token.GeneratedUtc).TotalSeconds > Config.SecondsToRegeneratePasswordRecovery)
                {
                    token = null;
                }
            }

            if (token.IsNull())
            {
                base.DeleteAllResetPasswordTokens(customer.AccountCode);

                token = new ResetPasswordToken(customer.AccountCode, applicationStore.Code, urlBack);
                resetPasswordTokenRepository.Add(token);
            }

            return(token);
        }
        public async Task <object> ForgotPassword(string Email)
        {
            try
            {
                if (Email == null)
                {
                    return(new Response <bool>(Constants.NOT_FOUND_CODE, false, Constants.NOT_FOUND));
                }

                var user = await UserManager.FindByEmailAsync(Email);

                if (user == null || !(await UserManager.IsEmailConfirmedAsync(user)))
                {
                    // Don't reveal that the user does not exist or is not confirmed
                    return(new Response <bool>(Constants.NOT_FOUND_CODE, false, Constants.NOT_FOUND));
                }
                var rand = new RandomGenerator();
                var code = rand.RandomToken();

                EmailBodyDefaultParams emailBodyDefaultParams = db.EmailBodyDefaultParams
                                                                .Where(e => e.EmailTypeName == "reset_password_api").FirstOrDefault();
                string body = EmailSender.CreateEmailBody(emailBodyDefaultParams);
                body = body.Replace("{callbackurl}", "#");
                body = body.Replace("{callbackdisplaytext}", code);

                var contentAppName = db.ContentManagement.Where(cm => cm.Name == "app_name")
                                     .FirstOrDefault();
                string AppName = contentAppName == null ? "Fuel Services" : contentAppName.DisplayName;

                var simpleResponse = EmailSender.SendEmail(Email, AppName, body);

                ResetPasswordToken resetPasswordToken = new ResetPasswordToken()
                {
                    ResetPasswordCode = code,
                    UserId            = user.Id,
                    ResetPasswordCodeValidityEndDate = DateTime.Now.AddMinutes(ResetPasswordConstants.Validity),
                };
                var prevAttempts = db.ResetPasswordTokens.Where(x => x.UserId == user.Id && x.Status == ResetPasswordTokenStatus.PendingValidation)
                                   .ToList();
                prevAttempts.ForEach((x) => {
                    x.Status = ResetPasswordTokenStatus.Expired;
                });
                db.ResetPasswordTokens.UpdateRange(prevAttempts);
                db.ResetPasswordTokens.Add(resetPasswordToken);
                await db.SaveChangesAsync();

                return(new Response <bool>(Constants.SUCCESS_CODE, true, Constants.SUCCESS));
            }
            catch (Exception e)
            {
                Serilog.Log.Error(e, Constants.LogTemplates.RESET_PASSWORD_EX, Email);
                return(new Response <bool>(Constants.SOMETHING_WRONG_CODE, false, GetExceptionMessage(e)));
            }
        }
        public async Task ResetPassword_WhenCalled_AttemptToSaveUserWithTheNewPasswordExpected()
        {
            // ARRANGE
            var newPassword = "******";
            var token       = new ResetPasswordToken
            {
                Token = "the token"
            };

            _tokenProvider.IsTokenExpired(Arg.Any <string>(), Arg.Any <int>()).Returns(false);
            _resetPasswordTokenRepository.SingleOrDefaultAsync(Arg.Any <Expression <Func <ResetPasswordToken, bool> > >())
            .Returns(x =>
            {
                var store = new List <ResetPasswordToken> {
                    token
                };
                return(store.Single(x.ArgAt <Expression <Func <ResetPasswordToken, bool> > >(0).Compile()));
            });
            var user = new User
            {
                PasswordHash       = Encoding.ASCII.GetBytes("the old password hash"),
                PasswordSalt       = Encoding.ASCII.GetBytes("the old password salt"),
                ResetPasswordToken = new ResetPasswordToken()
            };

            _userRepository.SingleOrDefaultAsync(Arg.Any <Expression <Func <User, bool> > >())
            .Returns(x =>
            {
                var store = new List <User> {
                    user
                };
                return(store.Single(x.ArgAt <Expression <Func <User, bool> > >(0).Compile()));
            });
            User actualUserEntityToSave = null;

            _userRepository.When(x => x.Update(Arg.Any <User>())).Do(x => actualUserEntityToSave = x.ArgAt <User>(0));
            var computedNewPassword = ComputedPassword.Create(
                Encoding.ASCII.GetBytes("the new password hash"), Encoding.ASCII.GetBytes("the new password salt"));

            SetPasswordProvider((newPassword, computedNewPassword));
            var expectedUserEntityToSave = new User
            {
                PasswordHash = computedNewPassword.Hash,
                PasswordSalt = computedNewPassword.Salt
            };

            // ACT
            await _sut.ResetPassword(token.Token, newPassword);

            // ASSERT
            actualUserEntityToSave.Should().BeEquivalentTo(expectedUserEntityToSave);
            await _unitOfWork.Received().CompleteAsync();
        }
Example #8
0
        public async Task <ResetPasswordToken> ResetPasswordAsync(Utilizer utilizer, string membershipId, string usernameOrEmailAddress)
        {
            if (string.IsNullOrEmpty(usernameOrEmailAddress))
            {
                throw ErtisAuthException.ValidationError(new []
                {
                    "Username or email required!"
                });
            }

            var membership = await this.membershipService.GetAsync(membershipId);

            if (membership == null)
            {
                throw ErtisAuthException.MembershipNotFound(membershipId);
            }

            var user = await this.GetUserWithPasswordAsync(usernameOrEmailAddress, usernameOrEmailAddress, membershipId);

            if (user == null)
            {
                throw ErtisAuthException.UserNotFound(usernameOrEmailAddress, "username or email_address");
            }

            if (utilizer.Role == Rbac.ReservedRoles.Administrator || utilizer.Id == user.Id)
            {
                var tokenClaims = new TokenClaims(Guid.NewGuid().ToString(), user, membership);
                tokenClaims.AddClaim("token_type", "reset_token");
                var resetToken         = this.jwtService.GenerateToken(tokenClaims, HashAlgorithms.SHA2_256, Encoding.UTF8);
                var resetPasswordToken = new ResetPasswordToken(resetToken, TimeSpan.FromHours(1));

                await this.eventService.FireEventAsync(this, new ErtisAuthEvent
                {
                    EventType    = ErtisAuthEventType.UserPasswordReset,
                    UtilizerId   = user.Id,
                    Document     = resetPasswordToken,
                    MembershipId = membershipId
                });

                return(resetPasswordToken);
            }
            else
            {
                throw ErtisAuthException.AccessDenied("Unauthorized access");
            }
        }
Example #9
0
        public void DeleteResetPasswordToken(ResetPasswordToken token)
        {
            using (var transaction = Connection.BeginTransaction())
            {
                try
                {
                    resetPasswordTokenRepository.Delete(token);

                    transaction.Commit();
                }
                catch
                {
                    transaction.Rollback();
                    throw;
                }
            }
        }
        public CompletePasswordResetResponse CompletePasswordReset(CompletePasswordResetRequest request)
        {
            CompletePasswordResetResponse response = new CompletePasswordResetResponse();

            try
            {
                Common.Helpers.ValidationHelper.ValidateRequiredField(request.Username, "User name");
                Common.Helpers.ValidationHelper.ValidateRequiredField(request.Token, "Token");
                Common.Helpers.ValidationHelper.ValidateRequiredField(request.NewPassword, "New Password");

                Common.Helpers.ValidationHelper.ValidateStringLength(request.NewPassword, "New Password", Constants.MaxPasswordLength);

                Common.Helpers.ValidationHelper.ValidateUsername(request.Username);
                ValidationHelper.ValidatePassword(request.NewPassword);

                ResetPasswordToken token = ResetPasswordToken.FromBytes(EncryptionHelper.DecryptURL(Convert.FromBase64String(request.Token)));

                Common.Helpers.ValidationHelper.Assert(token.Username.Equals(request.Username), "Invalid input.");
                Common.Helpers.ValidationHelper.Assert(DateTime.Now < token.ExpiresOn, "Password reset request has expired.");

                DbContext context = DataController.CreateDbContext();

                UserController.ChangePassword(token.Username, request.NewPassword);
            }
            catch (AuthenticationException ex)
            {
                throw new WebFaultException <string>(ex.Message, System.Net.HttpStatusCode.BadRequest);
            }
            catch (Common.Exceptions.ValidationException ex)
            {
                throw new WebFaultException <string>(ex.Message, System.Net.HttpStatusCode.BadRequest);
            }
            catch (Exception ex)
            {
                ExceptionHelper.Log(ex, string.Empty);
                throw new WebFaultException <string>("An unknown error has occurred.", System.Net.HttpStatusCode.InternalServerError);
            }

            return(response);
        }
Example #11
0
        public static void SendPasswordResetEmail(string firstName, string lastName, string emailAddress, string username)
        {
            DateTime expiresOn = DateTime.UtcNow + Settings.Default.ResetPasswordTokenExpiryInterval;

            long random = Common.Helpers.RandomHelper.RandomLong();

            ResetPasswordToken token = new ResetPasswordToken(username, expiresOn, random);

            string encryptedToken = Convert.ToBase64String(EncryptionHelper.EncryptURL(token.AsBytes()));

            string subject = "Initial Round Password Reset";

            string recipientName = string.Format("{0} {1}", firstName, lastName);

            if (string.IsNullOrWhiteSpace(recipientName))
            {
                recipientName = username;
            }

            string resetUri = string.Format("{0}Account/CompletePasswordReset?Token={1}",
                                            CloudConfigurationManager.GetSetting("RootURI"),
                                            HttpUtility.UrlEncode(encryptedToken));

            string body = Interpolate(ResetPasswordTemplate,
                                      KeyValue.Of("FullName", recipientName),
                                      KeyValue.Of("ResetURI", resetUri));

            Enqueue(new EmailMessage
            {
                Subject   = subject,
                Body      = body,
                Recipient = new EmailRecipient
                {
                    EmailAddress = emailAddress,
                    FullName     = recipientName
                },
                SendDate = DateTime.UtcNow,
                UseHtml  = true
            });
        }