using System; using System.Collections.Generic; using System.IdentityModel.Tokens.Jwt; using System.Linq; using System.Security.Claims; using System.Security.Cryptography; using System.Text; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.IdentityModel.Tokens; using MyCore.Interfaces.DTO; using MyCore.Interfaces.Models; using MyCore.Service.Services; using MyCore.Services; namespace MyCore.Controllers { [Authorize] [Route("api/token")] [ApiController] public class TokenController : ControllerBase { private TokensService _tokenService; private UserDatabaseService _userService; public TokenController(TokensService tokenService, UserDatabaseService userService) { _tokenService = tokenService; _userService = userService; } /// /// Connect user /// /// login info [ProducesResponseType(typeof(UserInfo), 200)] [ProducesResponseType(typeof(string), 401)] [ProducesResponseType(typeof(string), 500)] [AllowAnonymous] [HttpPost] public ActionResult ConnectUser([FromBody] LoginDTO loginDTO) { try { UserInfo user = null; if (IsValidUserAndPasswordCombination(loginDTO.Email, loginDTO.Password)) { user = _userService.GetByEmail(loginDTO.Email); user.Token = _tokenService.GenerateToken(loginDTO.Email).ToString(); } if (user != null) { return new OkObjectResult(user); } else { throw new UnauthorizedAccessException("Bad credential"); } } catch (UnauthorizedAccessException ex) { return new UnauthorizedObjectResult(ex.Message) {}; } catch (Exception ex) { return new ObjectResult(ex.Message) { StatusCode = 500 }; } } private bool IsValidUserAndPasswordCombination(string email, string password) { // Test if is database and is correct List users = _userService.GetAll(); UserInfo user = users.Where(u => u.Email == email).FirstOrDefault(); if (user != null && user.Password == password) { return true; } return false; /*if (email == "thomas.fransolet@hotmail.be" && password == "MonsieurMagic") { return true; } else return false;*/ } } }