Parking_space_WEBAPI/WebApi_data_value/Services/UserService.cs

73 lines
1.8 KiB
C#
Raw Normal View History

2024-03-05 19:49:58 +08:00
namespace Parking_space_WebAPI.Services;
2024-02-01 13:48:38 +08:00
using Microsoft.EntityFrameworkCore;
2024-03-05 19:49:58 +08:00
using Parking_space_WebAPI.Authorization;
using Parking_space_WebAPI.Entities;
using Parking_space_WebAPI.Models;
2024-02-01 13:48:38 +08:00
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.parking_spaces_user.SingleOrDefault(x => x.username == model.username && x.password == model.password);
// return null if user not found
if (user == null) return null;
// authentication successful so generate jwt token
var token = _jwtUtils.GenerateJwtToken(user);
return new AuthenticateResponse(user, token);
}
public IEnumerable<User> GetAll()
{
return _dbContext.parking_spaces_user;
}
public User? GetById(int id)
{
return _dbContext.parking_spaces_user.FirstOrDefault(x => x.id == id);
}
}