96 lines
3.2 KiB
C#
96 lines
3.2 KiB
C#
using Microsoft.AspNetCore.Mvc;
|
|
using Microsoft.AspNetCore.Cors;
|
|
using Microsoft.AspNetCore.Authorization;
|
|
using Microsoft.IdentityModel.Tokens;
|
|
using System.IdentityModel.Tokens.Jwt;
|
|
|
|
using AutoMapper;
|
|
|
|
using skydiveLogs_api.Business.Interface;
|
|
using skydiveLogs_api.DataContract;
|
|
using skydiveLogs_api.Model;
|
|
|
|
using System;
|
|
using System.Text;
|
|
using System.Security.Claims;
|
|
|
|
|
|
namespace skydiveLogs_api.Controllers
|
|
{
|
|
[Route("api/[controller]")]
|
|
[ApiController]
|
|
public class UserController : ControllerBase
|
|
{
|
|
public UserController(IUserService userService,
|
|
IMapper mapper)
|
|
{
|
|
_userService = userService;
|
|
_mapper = mapper;
|
|
}
|
|
|
|
// POST: api/User
|
|
[AllowAnonymous]
|
|
[HttpPost("Authenticate")]
|
|
[EnableCors]
|
|
public IActionResult Authenticate([FromBody] UserReq value)
|
|
{
|
|
IActionResult result;
|
|
var foundUser = _userService.GetByLogin(value.Login, value.Password);
|
|
|
|
if (foundUser == null)
|
|
{
|
|
result = BadRequest(new { message = "Username or password is incorrect" });
|
|
}
|
|
else
|
|
{
|
|
foundUser.Password = null;
|
|
var resp = _mapper.Map<UserResp>(foundUser);
|
|
resp.Token = CreateToken(value);
|
|
|
|
result = Ok(resp);
|
|
}
|
|
|
|
return result;
|
|
}
|
|
|
|
// POST: api/User
|
|
[AllowAnonymous]
|
|
[HttpPost]
|
|
[EnableCors]
|
|
public void Post([FromBody] UserReq value)
|
|
{
|
|
_userService.AddNewUser(_mapper.Map<User>(value));
|
|
}
|
|
|
|
private string CreateToken(UserReq model)
|
|
{
|
|
//var tokenHandler = new JwtSecurityTokenHandler();
|
|
//var key = Encoding.ASCII.GetBytes("azertyuiopqsdfghjklmwxcvbn");
|
|
//var tokenDescriptor = new SecurityTokenDescriptor
|
|
//{
|
|
// Subject = new ClaimsIdentity(new Claim[]
|
|
// {
|
|
// new Claim(ClaimTypes.Name, model.Login)
|
|
// }),
|
|
// Expires = DateTime.UtcNow.AddMinutes(30),
|
|
// SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
|
|
//};
|
|
//var token = tokenHandler.CreateToken(tokenDescriptor);
|
|
//return tokenHandler.WriteToken(token);
|
|
|
|
var key = new SymmetricSecurityKey(System.Text.Encoding.UTF8.GetBytes("azertyuiopqsdfghjklmwxcvbn" /* this._configuration["jwt:key"] */));
|
|
var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
|
|
|
|
var token = new JwtSecurityToken("toto" /* this._configuration["jwt:issuer"] */,
|
|
"toto" /* this._configuration["jwt:issuer"] */,
|
|
expires: System.DateTime.Now.AddMinutes(30),
|
|
signingCredentials: credentials);
|
|
|
|
return new JwtSecurityTokenHandler().WriteToken(token);
|
|
}
|
|
|
|
private readonly IUserService _userService;
|
|
private readonly IMapper _mapper;
|
|
}
|
|
}
|