From 941743af458b9aa70b395decb24f40641f1e5cbb Mon Sep 17 00:00:00 2001 From: Maciej Maciejewski Date: Wed, 6 Nov 2024 22:01:08 +0100 Subject: [PATCH] =?UTF-8?q?dodanie=20zmian=20z=20resetem=20has=C5=82a=20or?= =?UTF-8?q?az=20zmian=C4=85=20has=C5=82a=20przez=20usera,=20zmiana=20podej?= =?UTF-8?q?=C5=9Bcia=20do=20szyfrowania=20hase=C5=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Controllers/UserController.cs | 64 ++++++++++++++++++++++++++++++ Models/ChangePasswordDto.cs | 8 ++++ Models/ResetPasswordDto.cs | 8 ++++ Program.cs | 7 ++-- Services/UserService.cs | 73 ++++++++++++++++++++++++++++++++++- 5 files changed, 156 insertions(+), 4 deletions(-) create mode 100644 Models/ChangePasswordDto.cs create mode 100644 Models/ResetPasswordDto.cs diff --git a/Controllers/UserController.cs b/Controllers/UserController.cs index 77e437a..0e6f797 100644 --- a/Controllers/UserController.cs +++ b/Controllers/UserController.cs @@ -5,6 +5,7 @@ using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using FirmTracker_Server.Entities; using System.Security.Claims; +using FirmTracker_Server.Exceptions; namespace FirmTracker_Server.Controllers { @@ -50,6 +51,69 @@ namespace FirmTracker_Server.Controllers } return Ok(roleClaim); } + + [HttpPost("change-password")] + [Authorize(Roles = Roles.User + "," + Roles.Admin)] + public ActionResult ChangePassword([FromBody] ChangePasswordDto dto) + { + if (!ModelState.IsValid) + { + return BadRequest("Invalid data."); + } + + // Get the user ID from the claims of the authenticated user + var userIdClaim = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier)?.Value; + + if (userIdClaim == null || !int.TryParse(userIdClaim, out var userId)) + { + return Unauthorized("User ID not found."); + } + + try + { + // Pass the userId to the service to find the user + var success = UserService.ChangePassword(userId, dto); + if (!success) + { + return BadRequest("Password change failed."); + } + + return Ok("Password changed successfully."); + } + catch (WrongUserOrPasswordException ex) + { + return BadRequest(ex.Message); + } + catch (Exception ex) + { + return StatusCode(500, "An error occurred: " + ex.Message); + } + } + [HttpPost("reset-password")] + [Authorize(Roles = Roles.Admin)] + public ActionResult ResetPassword([FromBody] ResetPasswordDto dto) + { + if (!ModelState.IsValid) + { + return BadRequest("Invalid data."); + } + + try + { + // Reset password for the user + var success = UserService.ResetPassword(dto.UserMail, dto.NewPassword); + if (!success) + { + return BadRequest("Password reset failed."); + } + + return Ok("Password has been successfully reset."); + } + catch (Exception ex) + { + return StatusCode(500, "An error occurred: " + ex.Message); + } + } // New method to get all users /* [HttpGet("all")] [AllowAnonymous] diff --git a/Models/ChangePasswordDto.cs b/Models/ChangePasswordDto.cs new file mode 100644 index 0000000..f7752c5 --- /dev/null +++ b/Models/ChangePasswordDto.cs @@ -0,0 +1,8 @@ +namespace FirmTracker_Server.Models +{ + public class ChangePasswordDto + { + public string OldPassword { get; set; } + public string NewPassword { get; set; } + } +} \ No newline at end of file diff --git a/Models/ResetPasswordDto.cs b/Models/ResetPasswordDto.cs new file mode 100644 index 0000000..448a0c7 --- /dev/null +++ b/Models/ResetPasswordDto.cs @@ -0,0 +1,8 @@ +namespace FirmTracker_Server.Models +{ + public class ResetPasswordDto + { + public string UserMail { get; set; } + public string NewPassword { get; set; } + } +} diff --git a/Program.cs b/Program.cs index 2c10c9c..a8d86cf 100644 --- a/Program.cs +++ b/Program.cs @@ -73,9 +73,10 @@ namespace FirmTracker_Server builder.Services.AddCors(options => { options.AddPolicy("AllowSpecificOrigin", - policy => policy.WithOrigins("http://localhost:3000") + policy => policy.WithOrigins("http://localhost:3000", "https://localhost:7039", "https://localhost:5075", "https://localhost:3000") .AllowAnyHeader() - .AllowAnyMethod()); + .AllowAnyMethod() + .AllowCredentials()); }); builder.Services.ConfigureAutoMapper(); builder.Services.ConfigureServiceInjection(); @@ -122,8 +123,8 @@ namespace FirmTracker_Server { Console.WriteLine("Nie uda³o siê uruchomiæ swaggera"); } - app.UseHttpsRedirection(); + app.UseRouting(); app.UseCors("AllowSpecificOrigin"); diff --git a/Services/UserService.cs b/Services/UserService.cs index 4b5cc53..58c39c0 100644 --- a/Services/UserService.cs +++ b/Services/UserService.cs @@ -23,6 +23,8 @@ namespace FirmTracker_Server.Services UserDto GetById(int id); int AddUser(CreateUserDto dto); string CreateTokenJwt(LoginDto dto); + bool ChangePassword(int userMail, ChangePasswordDto dto); + bool ResetPassword(string userId, string newPassword); } @@ -54,12 +56,13 @@ namespace FirmTracker_Server.Services } } + public int AddUser(CreateUserDto dto) { var user = Mapper.Map(dto); // Encrypt or hash the password based on NewEncryption flag - user.PassHash = dto.NewEncryption ? SimplerAES.Encrypt(dto.Password) : PasswordHasher.HashPassword(user, dto.Password); + user.PassHash = SimplerAES.Encrypt(dto.Password); //: PasswordHasher.HashPassword(user, dto.Password); user.Role = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(dto.Role.ToLower()); using (var session = SessionFactory.OpenSession()) @@ -78,7 +81,75 @@ namespace FirmTracker_Server.Services } } } + public bool ChangePassword(int userId, ChangePasswordDto dto) + { + using (var session = SessionFactory.OpenSession()) + using (var transaction = session.BeginTransaction()) + { + // Find user by ID + var user = session.Get(userId); + if (user == null) + { + throw new WrongUserOrPasswordException("User not found."); + } + // Verify old password + var oldPasswordCorrect = false; + if (user.NewEncryption) + { + oldPasswordCorrect = SimplerAES.Decrypt(user.PassHash) == SimplerAES.Decrypt(dto.OldPassword); + } + else + { + oldPasswordCorrect = SimplerAES.Decrypt(user.PassHash) == SimplerAES.Decrypt(dto.OldPassword); + } + + if (!oldPasswordCorrect) + { + throw new WrongUserOrPasswordException("The old password is incorrect."); + } + + + if (user.NewEncryption) + { + user.PassHash = SimplerAES.Encrypt(dto.NewPassword); + } + else + { + user.PassHash = SimplerAES.Encrypt(dto.NewPassword); + } + + session.Update(user); + transaction.Commit(); + return true; + } + } + public bool ResetPassword(string userMail, string newPassword) + { + using (var session = SessionFactory.OpenSession()) + using (var transaction = session.BeginTransaction()) + { + var user = session.Get(userMail); + if (user == null) + { + throw new Exception("User not found"); + } + + // Encrypt or hash the new password + if (user.NewEncryption) + { + user.PassHash = SimplerAES.Encrypt(newPassword); // Or apply hashing if needed + } + else + { + user.PassHash = SimplerAES.Encrypt(newPassword); + } + + session.Update(user); + transaction.Commit(); + return true; + } + } public string CreateTokenJwt(LoginDto dto) { User user = null;