70 lines
1.7 KiB
C#
70 lines
1.7 KiB
C#
using JWTdemo.Authorization;
|
|
using JWTdemo.Services;
|
|
using JWTdemo.Entities;
|
|
using JWTdemo.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.chatuser.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.chatuser;
|
|
}
|
|
|
|
public User? GetById(int id)
|
|
{
|
|
return _dbContext.chatuser.FirstOrDefault(x => x.Id == id);
|
|
}
|
|
|
|
|
|
|
|
} |