73 lines
1.8 KiB
C#
73 lines
1.8 KiB
C#
|
namespace Parking_space_WebAPI.Services;
|
||
|
using Microsoft.EntityFrameworkCore;
|
||
|
using Parking_space_WebAPI.Authorization;
|
||
|
using Parking_space_WebAPI.Entities;
|
||
|
using Parking_space_WebAPI.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.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);
|
||
|
}
|
||
|
|
||
|
|
||
|
|
||
|
|
||
|
|
||
|
}
|