From 58edbb6661c8f7d147f438716b286aa84c6bcb14 Mon Sep 17 00:00:00 2001 From: crupest Date: Mon, 22 Apr 2019 15:47:52 +0800 Subject: Add change password api. --- Timeline/Services/UserService.cs | 42 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) (limited to 'Timeline/Services/UserService.cs') diff --git a/Timeline/Services/UserService.cs b/Timeline/Services/UserService.cs index 8615d0c5..75ad3331 100644 --- a/Timeline/Services/UserService.cs +++ b/Timeline/Services/UserService.cs @@ -49,6 +49,22 @@ namespace Timeline.Services NotExists } + public enum ChangePasswordResult + { + /// + /// Success to change password. + /// + Success, + /// + /// The user does not exists. + /// + NotExists, + /// + /// Old password is wrong. + /// + BadOldPassword + } + public interface IUserService { /// @@ -113,6 +129,17 @@ namespace Timeline.Services /// if the user is deleted. /// if the user doesn't exist. Task DeleteUser(string username); + + /// + /// Try to change a user's password with old password. + /// + /// The name of user to change password of. + /// The user's old password. + /// The user's new password. + /// if success. + /// if user does not exist. + /// if old password is wrong. + Task ChangePassword(string username, string oldPassword, string newPassword); } public class UserService : IUserService @@ -252,5 +279,20 @@ namespace Timeline.Services await _databaseContext.SaveChangesAsync(); return DeleteUserResult.Deleted; } + + public async Task ChangePassword(string username, string oldPassword, string newPassword) + { + var user = await _databaseContext.Users.Where(u => u.Name == username).SingleOrDefaultAsync(); + if (user == null) + return ChangePasswordResult.NotExists; + + var verifyResult = _passwordService.VerifyPassword(user.EncryptedPassword, oldPassword); + if (!verifyResult) + return ChangePasswordResult.BadOldPassword; + + user.EncryptedPassword = _passwordService.HashPassword(newPassword); + await _databaseContext.SaveChangesAsync(); + return ChangePasswordResult.Success; + } } } -- cgit v1.2.3