study-lib-backend/API/Controllers/UsersController.cs

89 lines
2.9 KiB
C#
Raw Normal View History

2020-12-16 21:41:14 +01:00
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")]
2020-12-20 18:53:24 +01:00
public async Task<ActionResult<User>> UserRegister(UserViewModel user)
2020-12-16 21:41:14 +01:00
{
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[]
{
2020-12-20 18:53:24 +01:00
new Claim("UserID", user.Id)
2020-12-16 21:41:14 +01:00
}),
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);
2020-12-20 18:53:24 +01:00
var userViewModel = new
{
ID = user.Id,
UserName = user.UserName,
FullName = user.FullName
};
return Ok(new { token, user = userViewModel });
2020-12-16 21:41:14 +01:00
}
else
{
return BadRequest("Username or password is incorrect");
}
}
}
}