diff options
| author | ivarlovlie <git@ivarlovlie.no> | 2023-02-25 13:15:44 +0100 |
|---|---|---|
| committer | ivarlovlie <git@ivarlovlie.no> | 2023-02-25 13:15:44 +0100 |
| commit | 900bb5e845c3ad44defbd427cae3d44a4a43321f (patch) | |
| tree | df3d96a93771884add571e82336c29fc3d9c7a1c /code/api/src/Endpoints/Internal/Account/UpdateAccountRoute.cs | |
| download | greatoffice-900bb5e845c3ad44defbd427cae3d44a4a43321f.tar.xz greatoffice-900bb5e845c3ad44defbd427cae3d44a4a43321f.zip | |
feat: Initial commit
Diffstat (limited to 'code/api/src/Endpoints/Internal/Account/UpdateAccountRoute.cs')
| -rw-r--r-- | code/api/src/Endpoints/Internal/Account/UpdateAccountRoute.cs | 59 |
1 files changed, 59 insertions, 0 deletions
diff --git a/code/api/src/Endpoints/Internal/Account/UpdateAccountRoute.cs b/code/api/src/Endpoints/Internal/Account/UpdateAccountRoute.cs new file mode 100644 index 0000000..1081240 --- /dev/null +++ b/code/api/src/Endpoints/Internal/Account/UpdateAccountRoute.cs @@ -0,0 +1,59 @@ +namespace IOL.GreatOffice.Api.Endpoints.Internal.Account; + +public class UpdateAccountRoute : RouteBaseAsync.WithRequest<UpdateAccountRoute.Payload>.WithActionResult +{ + private readonly MainAppDatabase _database; + private readonly IStringLocalizer<SharedResources> _localizer; + + public UpdateAccountRoute(MainAppDatabase database, IStringLocalizer<SharedResources> localizer) { + _database = database; + _localizer = localizer; + } + + public class Payload + { + public string Username { get; set; } + + public string Password { get; set; } + } + + [HttpPost("~/_/account/update")] + public override async Task<ActionResult> HandleAsync(Payload request, CancellationToken cancellationToken = default) { + var user = _database.Users.SingleOrDefault(c => c.Id == LoggedInUser.Id); + if (user == default) { + await HttpContext.SignOutAsync(); + return Unauthorized(); + } + + if (request.Password.IsNullOrWhiteSpace() && request.Username.IsNullOrWhiteSpace()) { + return KnownProblem(_localizer["Invalid request"], _localizer["No data was submitted"]); + } + + var problem = new KnownProblemModel(); + + if (request.Password.HasValue() && request.Password.Length < 6) { + problem.AddError("password", _localizer["The new password must contain at least 6 characters"]); + } + + if (request.Password.HasValue()) { + user.HashAndSetPassword(request.Password); + } + + if (request.Username.HasValue() && !request.Username.IsValidEmailAddress()) { + problem.AddError("username", _localizer["The new username does not look like a valid email address"]); + } + + if (problem.Errors.Any()) { + problem.Title = _localizer["Invalid form"]; + problem.Subtitle = _localizer["One or more validation errors occured"]; + return KnownProblem(problem); + } + + if (request.Username.HasValue()) { + user.Username = request.Username.Trim(); + } + + await _database.SaveChangesAsync(cancellationToken); + return Ok(); + } +}
\ No newline at end of file |
