Advertisement
MrModest

AccountController.cs

Jul 16th, 2018
233
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 5.63 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IdentityModel.Tokens.Jwt;
  4. using System.Linq;
  5. using System.Security.Claims;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8. using Microsoft.AspNetCore.Http;
  9. using Microsoft.AspNetCore.Identity;
  10. using Microsoft.AspNetCore.Mvc;
  11. using Microsoft.Extensions.Configuration;
  12. using Microsoft.Extensions.Logging;
  13. using Microsoft.IdentityModel.Tokens;
  14. using NameThatTitle.Domain.Interfaces.Repositories;
  15. using NameThatTitle.Domain.Models.Users;
  16. using NameThatTitle.WebApp.ViewModels;
  17.  
  18. namespace NameThatTitle.WebApp.Controllers
  19. {
  20.     [Route("api/[controller]")]
  21.     [ApiController]
  22.     public class AccountController : ControllerBase
  23.     {
  24.         //private readonly ILogger logger; - NLog not support 2.1 yet
  25.  
  26.         private readonly UserManager<UserAccount> userManager;
  27.         private readonly SignInManager<UserAccount> signInManager;
  28.         private readonly IConfiguration configuration;
  29.         private readonly IAsyncRepository<UserProfile> profileRep;
  30.  
  31.         public AccountController(
  32.             UserManager<UserAccount> userManager,
  33.             SignInManager<UserAccount> signInManager,
  34.             IConfiguration configuration,
  35.             IAsyncRepository<UserProfile> profileRep/*,
  36.             ILogger logger*/)
  37.         {
  38.             this.userManager = userManager;
  39.             this.signInManager = signInManager;
  40.             this.configuration = configuration;
  41.             this.profileRep = profileRep;
  42.  
  43.             //this.logger = logger;
  44.         }
  45.  
  46.         [HttpGet("test")]
  47.         public IActionResult Test()
  48.         {
  49.             return Ok(new {
  50.                 message = "It's work!"
  51.             });
  52.         }
  53.  
  54.         [HttpPost("[action]")]
  55.         public async Task<IActionResult> Register([FromBody] RegisterModel model)
  56.         {
  57.             if (!ModelState.IsValid)
  58.             {
  59.                 var errors = ModelState.Values.SelectMany(v => v.Errors.Select(e => e.ErrorMessage));
  60.                 return BadRequest(errors);
  61.             }
  62.  
  63.             var userAccount = new UserAccount { Email = model.Email, UserName = model.UserName };
  64.             var result = await userManager.CreateAsync(userAccount, model.Password);
  65.             if (result.Succeeded)
  66.             {
  67.                 var userProfile = await profileRep.AddAsync(new UserProfile
  68.                 {
  69.                     Id = userAccount.Id,
  70.                     UserName = userAccount.UserName
  71.                 });
  72.  
  73.                 var token = GetToken(model.UserName, model.Password);
  74.  
  75.                 return Ok(token);
  76.             }
  77.  
  78.             return BadRequest(result.Errors);
  79.         }
  80.  
  81.         [HttpPost("[action]")]
  82.         public async Task<IActionResult> Auth([FromBody] TokenRequest tokenRequest)
  83.         {
  84.             var token = await GetToken(tokenRequest.Login, tokenRequest.Password);
  85.  
  86.             if (token == null)
  87.             {
  88.                 return UnprocessableEntity(new { message = "Invalid username or password." });
  89.             }
  90.  
  91.             return Ok(token);
  92.         }
  93.  
  94.         private async Task<string> GetToken(string login, string password)
  95.         {
  96.             var identity = await GetIdentity(login, password);
  97.             if (identity == null)
  98.             {
  99.                 return null;
  100.             }
  101.  
  102.             var now = DateTime.UtcNow;
  103.             // created JWT-token
  104.             var jwt = new JwtSecurityToken(
  105.                     notBefore: now,
  106.                     claims: identity.Claims,
  107.                     expires: now.Add(TimeSpan.FromMinutes(int.Parse(configuration["Jwt:LifeTime"]))),
  108.                     signingCredentials: new SigningCredentials(
  109.                         new SymmetricSecurityKey(
  110.                             Encoding.ASCII.GetBytes(configuration["Jwt:Key"])),
  111.                         SecurityAlgorithms.HmacSha256));
  112.  
  113.             string token = new JwtSecurityTokenHandler().WriteToken(jwt);
  114.  
  115.             return token;
  116.         }
  117.  
  118.         private async Task<ClaimsIdentity> GetIdentity(string login, string password)
  119.         {
  120.             var user = login.Contains('@') ?
  121.                 await userManager.FindByEmailAsync(login) :
  122.                 await userManager.FindByNameAsync(login);
  123.  
  124.             if (user != null)
  125.             {
  126.                 var check = await userManager.CheckPasswordAsync(user, password);
  127.  
  128.                 if (check)
  129.                 {
  130.                     ClaimsPrincipal principal = null;
  131.  
  132.                     try
  133.                     {
  134.                         principal = await signInManager.CreateUserPrincipalAsync(user);
  135.                     }
  136.                     catch (Exception ex)
  137.                     {
  138.  
  139.                         throw;
  140.                     }
  141.  
  142.                     var result = (ClaimsIdentity)principal.Identity;
  143.  
  144.                     return result;
  145.                     //var roles = await userManager.GetRolesAsync(user);
  146.  
  147.                     //var claims = new List<Claim>
  148.                     //{
  149.                     //    new Claim(ClaimsIdentity.DefaultNameClaimType, user.UserName)
  150.                     //};
  151.  
  152.                     //foreach (var role in roles)
  153.                     //{
  154.                     //    claims.Add(new Claim(ClaimsIdentity.DefaultRoleClaimType, role));
  155.                     //}
  156.  
  157.                     //var claimsIdentity =
  158.                     //    new ClaimsIdentity(claims, "Token", ClaimsIdentity.DefaultNameClaimType,
  159.                     //        ClaimsIdentity.DefaultRoleClaimType);
  160.  
  161.                     //return claimsIdentity;
  162.                 }
  163.             }
  164.  
  165.             return null;
  166.         }
  167.     }
  168. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement