IMPLEMETS
public class AuthService : IAuthService
{
readonly UserManager _userManager;
readonly SignInManager _signInManager;
public AuthService(UserManager<IdentityUser> userManager, SignInManager<IdentityUser> signInManager)
{
_signInManager = signInManager;
_userManager = userManager;
}
public async Task Login(LoginDTO loginDTO)
{
IdentityUser? userDB = await _userManager.FindByEmailAsync(loginDTO.Email);
if (userDB is null)
{
throw new Exception("Credentials are not correct.");
}
bool isAllowed = await _userManager.CheckPasswordAsync(userDB, loginDTO.Password);
if (!isAllowed)
{
throw new Exception("Credentials are not correct.");
}
await _signInManager.SignInAsync(userDB,true);
}
public async Task Register(RegisterDTO registerDTO)
{
IdentityUser user = new IdentityUser()
{
Email = registerDTO.Email,
UserName = registerDTO.UserName,
};
IdentityResult result = await _userManager.CreateAsync(user, registerDTO.Password);
if (result.Succeeded)
{
await _userManager.AddToRoleAsync(user,"User");
}
}
public async Task Logout()
{
await _signInManager.SignOutAsync();
}
}
}
INTERFACE
public interface IAuthService
{
public Task Login(LoginDTO loginDTO);
public Task Register(RegisterDTO registerDTO);
public Task Logout();
}
AuthDTO
public class LoginDTO
{
[Required]
public string UserName { get; set; }
[Required]
public string Email { get; set; }
[Required]
public string Password { get; set; }
}
public class RegisterDTO
{
[Required(ErrorMessage = "Username is required")]
[StringLength(16, ErrorMessage = "Must be between 3 and 16 characters", MinimumLength = 3)]
public string UserName { get; set; }
[Required(ErrorMessage = "Email is required")]
[StringLength(16, ErrorMessage = "Must be between 5 and 50 characters", MinimumLength = 5)]
[RegularExpression("^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+$", ErrorMessage = "Must be a valid email")]
public string Email { get; set; }
[Required(ErrorMessage = "Password is required")]
[StringLength(255, ErrorMessage = "Must be between 5 and 255 characters", MinimumLength = 5)]
[DataType(DataType.Password)]
public string Password { get; set; }
[Required(ErrorMessage = "Confirm Password is required")]
[StringLength(255, ErrorMessage = "Must be between 5 and 255 characters", MinimumLength = 5)]
[DataType(DataType.Password)]
[Compare("Password")]
public string RepeatPassword { get; set; }
}
Top comments (0)