Compare commits

...

1 Commits

5 changed files with 156 additions and 4 deletions

View File

@ -5,6 +5,7 @@ using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using FirmTracker_Server.Entities; using FirmTracker_Server.Entities;
using System.Security.Claims; using System.Security.Claims;
using FirmTracker_Server.Exceptions;
namespace FirmTracker_Server.Controllers namespace FirmTracker_Server.Controllers
{ {
@ -50,6 +51,69 @@ namespace FirmTracker_Server.Controllers
} }
return Ok(roleClaim); 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 // New method to get all users
/* [HttpGet("all")] /* [HttpGet("all")]
[AllowAnonymous] [AllowAnonymous]

View File

@ -0,0 +1,8 @@
namespace FirmTracker_Server.Models
{
public class ChangePasswordDto
{
public string OldPassword { get; set; }
public string NewPassword { get; set; }
}
}

View File

@ -0,0 +1,8 @@
namespace FirmTracker_Server.Models
{
public class ResetPasswordDto
{
public string UserMail { get; set; }
public string NewPassword { get; set; }
}
}

View File

@ -73,9 +73,10 @@ namespace FirmTracker_Server
builder.Services.AddCors(options => builder.Services.AddCors(options =>
{ {
options.AddPolicy("AllowSpecificOrigin", 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() .AllowAnyHeader()
.AllowAnyMethod()); .AllowAnyMethod()
.AllowCredentials());
}); });
builder.Services.ConfigureAutoMapper(); builder.Services.ConfigureAutoMapper();
builder.Services.ConfigureServiceInjection(); builder.Services.ConfigureServiceInjection();
@ -122,8 +123,8 @@ namespace FirmTracker_Server
{ {
Console.WriteLine("Nie uda³o siê uruchomiæ swaggera"); Console.WriteLine("Nie uda³o siê uruchomiæ swaggera");
} }
app.UseHttpsRedirection();
app.UseRouting();
app.UseCors("AllowSpecificOrigin"); app.UseCors("AllowSpecificOrigin");

View File

@ -23,6 +23,8 @@ namespace FirmTracker_Server.Services
UserDto GetById(int id); UserDto GetById(int id);
int AddUser(CreateUserDto dto); int AddUser(CreateUserDto dto);
string CreateTokenJwt(LoginDto 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) public int AddUser(CreateUserDto dto)
{ {
var user = Mapper.Map<User>(dto); var user = Mapper.Map<User>(dto);
// Encrypt or hash the password based on NewEncryption flag // 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()); user.Role = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(dto.Role.ToLower());
using (var session = SessionFactory.OpenSession()) 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<User>(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<User>(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) public string CreateTokenJwt(LoginDto dto)
{ {
User user = null; User user = null;