Skip to content

Commit 86f37f6

Browse files
author
Vadim Belov
committed
Enhance password handling in BaseAuthController
Added logic to handle users who have never set a password by introducing the `CanSetPasswordIfNeverHadAsync` method. Updated the `ChangePassword` method to check this condition and provide more specific error messages. Improved password verification logic to return an "Unauthorized" error for incorrect current passwords. Added XML documentation for the new method while retaining existing documentation for `GetUserRolesAsync`.
1 parent c84b9cb commit 86f37f6

1 file changed

Lines changed: 18 additions & 5 deletions

File tree

Sources/EasyExtensions.AspNetCore.Authorization/Controllers/BaseAuthController.cs

Lines changed: 18 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -44,14 +44,18 @@ public async Task<IActionResult> ChangePassword([FromBody] ChangePasswordRequest
4444
{
4545
Guid userId = User.GetUserId();
4646
string? phc = await FindUserPhcAsync(userId);
47-
if (string.IsNullOrWhiteSpace(phc))
47+
bool canSetIfNeverHad = await CanSetPasswordIfNeverHadAsync(userId);
48+
if (string.IsNullOrWhiteSpace(phc) && !canSetIfNeverHad)
4849
{
49-
return this.ApiNotFound("User not found");
50+
return this.ApiNotFound("User or password does not exist");
5051
}
51-
bool isValidPassword = _passwordHasher.Verify(request.CurrentPassword, phc);
52-
if (!isValidPassword)
52+
if (!string.IsNullOrWhiteSpace(phc))
5353
{
54-
return this.ApiBadRequest("Invalid current password");
54+
bool isValidPassword = _passwordHasher.Verify(request.CurrentPassword, phc);
55+
if (!isValidPassword)
56+
{
57+
return this.ApiUnauthorized("Current password is incorrect");
58+
}
5559
}
5660
string newPhc = _passwordHasher.Hash(request.NewPassword);
5761
await SetUserPasswordPhcAsync(userId, newPhc);
@@ -224,6 +228,15 @@ public async Task<IActionResult> LoginWithGoogle([FromQuery] string token)
224228
/// roles.</returns>
225229
public abstract Task<IEnumerable<string>> GetUserRolesAsync(Guid userId);
226230

231+
/// <summary>
232+
/// Determines whether a password can be set for the specified user if the user has never previously set a
233+
/// password.
234+
/// </summary>
235+
/// <param name="userId">The unique identifier of the user to evaluate. This value must correspond to an existing user.</param>
236+
/// <returns>A task that represents the asynchronous operation. The task result is <see langword="true"/> if the user is
237+
/// eligible to set a password for the first time; otherwise, <see langword="false"/>.</returns>
238+
public abstract Task<bool> CanSetPasswordIfNeverHadAsync(Guid userId);
239+
227240
/// <summary>
228241
/// Handles logic to be executed after a user has changed their password.
229242
/// </summary>

0 commit comments

Comments
 (0)