You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
77 lines
2.2 KiB
77 lines
2.2 KiB
using System.ComponentModel.DataAnnotations;
|
|
using Microsoft.AspNetCore.Identity;
|
|
using Microsoft.AspNetCore.Mvc;
|
|
using SignInResult = Microsoft.AspNetCore.Identity.SignInResult;
|
|
|
|
namespace OAuthServer.Controllers;
|
|
|
|
[ApiController]
|
|
[Route("")]
|
|
public class LoginController : ControllerBase
|
|
{
|
|
private readonly SignInManager<IdentityUser> _signInManager;
|
|
private readonly UserManager<IdentityUser> _userManager;
|
|
|
|
public LoginController(SignInManager<IdentityUser> signInManager, UserManager<IdentityUser> userManager)
|
|
{
|
|
_signInManager = signInManager;
|
|
_userManager = userManager;
|
|
}
|
|
|
|
public record RegisterRequest(string Username, [StringLength(1024)] string Password);
|
|
|
|
[HttpPost]
|
|
[Route("register")]
|
|
public async Task<ActionResult<string>> Register([FromBody] RegisterRequest registerRequest)
|
|
{
|
|
IdentityUser user = new IdentityUser
|
|
{
|
|
UserName = registerRequest.Username,
|
|
};
|
|
|
|
IdentityResult registerResult = await _userManager.CreateAsync(user, registerRequest.Password);
|
|
if (!registerResult.Succeeded)
|
|
{
|
|
return BadRequest(registerResult);
|
|
}
|
|
|
|
IdentityResult roleResult = await _userManager.AddToRoleAsync(user, "User");
|
|
if (!roleResult.Succeeded)
|
|
{
|
|
throw new Exception($"Adding role User for {registerRequest.Username} not successful: {roleResult}");
|
|
}
|
|
|
|
return Ok("Registered");
|
|
}
|
|
|
|
|
|
public record LoginRequest(string Username, [StringLength(1024)] string Password);
|
|
|
|
[HttpPost]
|
|
[Route("login")]
|
|
public async Task<ActionResult> Login([FromBody] LoginRequest loginRequest)
|
|
{
|
|
SignInResult result = await _signInManager.PasswordSignInAsync(loginRequest.Username, loginRequest.Password,
|
|
isPersistent: true, lockoutOnFailure: false);
|
|
|
|
if (result.Succeeded)
|
|
{
|
|
return Ok();
|
|
}
|
|
|
|
if (result.IsLockedOut)
|
|
{
|
|
return Unauthorized("Account disabled");
|
|
}
|
|
|
|
return Unauthorized("Username or password invalid");
|
|
}
|
|
|
|
[HttpPost]
|
|
[Route("logout")]
|
|
public async Task<ActionResult> Logout()
|
|
{
|
|
await _signInManager.SignOutAsync();
|
|
return Ok("Successfully logged out");
|
|
}
|
|
} |