83 lines
2.7 KiB
C#
83 lines
2.7 KiB
C#
![]() |
using Microsoft.AspNetCore.Http;
|
|||
|
using Microsoft.AspNetCore.Identity;
|
|||
|
using Microsoft.AspNetCore.Mvc;
|
|||
|
using Microsoft.Extensions.Options;
|
|||
|
using Microsoft.IdentityModel.Tokens;
|
|||
|
using StudyLib.API.Models;
|
|||
|
using System;
|
|||
|
using System.Collections.Generic;
|
|||
|
using System.IdentityModel.Tokens.Jwt;
|
|||
|
using System.Linq;
|
|||
|
using System.Security.Claims;
|
|||
|
using System.Text;
|
|||
|
using System.Threading.Tasks;
|
|||
|
|
|||
|
namespace StudyLib.API.Controllers
|
|||
|
{
|
|||
|
[Route("api/[controller]")]
|
|||
|
[ApiController]
|
|||
|
public class UsersController : ControllerBase
|
|||
|
{
|
|||
|
private UserManager<User> _userManager;
|
|||
|
private SignInManager<User> _signInManager;
|
|||
|
private readonly ApplicationSettings _appSettings;
|
|||
|
|
|||
|
public UsersController(UserManager<User> userManager, SignInManager<User> signInManager, IOptions<ApplicationSettings> appSettings )
|
|||
|
{
|
|||
|
_userManager = userManager;
|
|||
|
_signInManager = signInManager;
|
|||
|
_appSettings = appSettings.Value;
|
|||
|
}
|
|||
|
|
|||
|
[HttpPost("register")]
|
|||
|
public async Task<ActionResult<User>> UserRegister(User user)
|
|||
|
{
|
|||
|
var userModel = new User
|
|||
|
{
|
|||
|
UserName = user.UserName,
|
|||
|
FullName = user.FullName
|
|||
|
};
|
|||
|
|
|||
|
try
|
|||
|
{
|
|||
|
var result = await _userManager.CreateAsync(userModel, user.Password);
|
|||
|
return Ok(result);
|
|||
|
}
|
|||
|
catch (Exception ex)
|
|||
|
{
|
|||
|
throw ex;
|
|||
|
}
|
|||
|
|
|||
|
}
|
|||
|
|
|||
|
[HttpPost("login")]
|
|||
|
public async Task<ActionResult<User>> UserLogin(Login loginObject)
|
|||
|
{
|
|||
|
var user = await _userManager.FindByNameAsync(loginObject.UserName);
|
|||
|
if (user != null && await _userManager.CheckPasswordAsync(user, loginObject.Password))
|
|||
|
{
|
|||
|
var tokenDescriptor = new SecurityTokenDescriptor
|
|||
|
{
|
|||
|
Subject = new ClaimsIdentity(new Claim[]
|
|||
|
{
|
|||
|
new Claim("UserID", user.ID.ToString())
|
|||
|
}),
|
|||
|
Expires = DateTime.UtcNow.AddDays(1),
|
|||
|
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_appSettings.JWTSecret)), SecurityAlgorithms.HmacSha256Signature)
|
|||
|
};
|
|||
|
var tokenHandler = new JwtSecurityTokenHandler();
|
|||
|
var securityToken = tokenHandler.CreateToken(tokenDescriptor);
|
|||
|
var token = tokenHandler.WriteToken(securityToken);
|
|||
|
return Ok(new { token });
|
|||
|
}
|
|||
|
else
|
|||
|
{
|
|||
|
return BadRequest("Username or password is incorrect");
|
|||
|
}
|
|||
|
|
|||
|
}
|
|||
|
|
|||
|
|
|||
|
}
|
|||
|
}
|