study-lib-backend/API/Controllers/UsersController.cs
2020-12-20 18:53:24 +01:00

89 lines
2.9 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(UserViewModel 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)
}),
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);
var userViewModel = new
{
ID = user.Id,
UserName = user.UserName,
FullName = user.FullName
};
return Ok(new { token, user = userViewModel });
}
else
{
return BadRequest("Username or password is incorrect");
}
}
}
}