Parking_space_ASPNET/Parking_spaces/Services/UserService.cs

53 lines
1.4 KiB
C#
Raw Normal View History

2024-02-01 11:37:15 +08:00
namespace Parking_spaces.Services;
using Parking_spaces.Authorization;
using Parking_spaces.Entities;
using Parking_spaces.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> _users = new List<User>
{
new User { Id = 1, FirstName = "Developer", LastName = "Manager", Username = "test", Password = "test" },
new User { Id = 2, FirstName = "Developer", LastName = "Engineer", Username = "admin", Password = "admin" }
};
private readonly IJwtUtils _jwtUtils;
public UserService(IJwtUtils jwtUtils)
{
_jwtUtils = jwtUtils;
}
public AuthenticateResponse? Authenticate(AuthenticateRequest model)
{
var user = _users.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 _users;
}
public User? GetById(int id)
{
return _users.FirstOrDefault(x => x.Id == id);
}
}