Backend/TCM_API/Services/UserService.cs

77 lines
1.9 KiB
C#
Raw Normal View History

2025-02-19 20:10:10 +08:00
namespace TCM_API.Services;
using Microsoft.EntityFrameworkCore;
using TCM_API.Authorization;
using TCM_API.Entities;
using TCM_API.Models;
public interface IUserService
{
AuthenticateResponse? Authenticate(AuthenticateRequest model);
IEnumerable<User> GetAll();
User? GetById(int id);
}
public class UserService : IUserService
{
/*
// users hardcoded for simplicity, store in a db with hashed passwords in production applications
private List<User> user_test = new List<User>
{
new User { Id = 1, FirstName = "Test", LastName = "User", Username = "test", Password = "test" },
new User { Id = 2, FirstName = "Test", LastName = "User", Username = "admin", Password = "admin" }
};
public DbSet<User> user_test { get; set; } = null!;
public List<User> GetUsers ()
{
return _dbContext.user_test.ToList();
}
*/
private readonly IJwtUtils _jwtUtils;
public UserService(IJwtUtils jwtUtils, SqlContext dbContext)
{
_jwtUtils = jwtUtils;
_dbContext = dbContext;
}
private readonly SqlContext _dbContext;
public AuthenticateResponse? Authenticate(AuthenticateRequest model)
{
var user = _dbContext.user_table.SingleOrDefault(
x => (x.username == model.Username || x.email == model.Username)
&& x.password == model.Password);
// return null if user not found
2025-02-22 17:03:21 +08:00
if (user == null ) return null;
if (!int.TryParse(user.level, out int level) || level % 2 != 0)
{
return null;
}
2025-02-19 20:10:10 +08:00
// authentication successful so generate jwt token
var token = _jwtUtils.GenerateJwtToken(user);
return new AuthenticateResponse(user, token);
}
public IEnumerable<User> GetAll()
{
return _dbContext.user_table;
}
public User? GetById(int id)
{
return _dbContext.user_table.FirstOrDefault(x => x.id == id);
}
}