Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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;
- using Microsoft.AspNetCore.Http;
- using Microsoft.AspNetCore.Identity;
- using Microsoft.AspNetCore.Mvc;
- using Microsoft.Extensions.Configuration;
- using Microsoft.Extensions.Logging;
- using Microsoft.IdentityModel.Tokens;
- using NameThatTitle.Domain.Interfaces.Repositories;
- using NameThatTitle.Domain.Models.Users;
- using NameThatTitle.WebApp.ViewModels;
- namespace NameThatTitle.WebApp.Controllers
- {
- [Route("api/[controller]")]
- [ApiController]
- public class AccountController : ControllerBase
- {
- //private readonly ILogger logger; - NLog not support 2.1 yet
- private readonly UserManager<UserAccount> userManager;
- private readonly SignInManager<UserAccount> signInManager;
- private readonly IConfiguration configuration;
- private readonly IAsyncRepository<UserProfile> profileRep;
- public AccountController(
- UserManager<UserAccount> userManager,
- SignInManager<UserAccount> signInManager,
- IConfiguration configuration,
- IAsyncRepository<UserProfile> profileRep/*,
- ILogger logger*/)
- {
- this.userManager = userManager;
- this.signInManager = signInManager;
- this.configuration = configuration;
- this.profileRep = profileRep;
- //this.logger = logger;
- }
- [HttpGet("test")]
- public IActionResult Test()
- {
- return Ok(new {
- message = "It's work!"
- });
- }
- [HttpPost("[action]")]
- public async Task<IActionResult> Register([FromBody] RegisterModel model)
- {
- if (!ModelState.IsValid)
- {
- var errors = ModelState.Values.SelectMany(v => v.Errors.Select(e => e.ErrorMessage));
- return BadRequest(errors);
- }
- var userAccount = new UserAccount { Email = model.Email, UserName = model.UserName };
- var result = await userManager.CreateAsync(userAccount, model.Password);
- if (result.Succeeded)
- {
- var userProfile = await profileRep.AddAsync(new UserProfile
- {
- Id = userAccount.Id,
- UserName = userAccount.UserName
- });
- var token = GetToken(model.UserName, model.Password);
- return Ok(token);
- }
- return BadRequest(result.Errors);
- }
- [HttpPost("[action]")]
- public async Task<IActionResult> Auth([FromBody] TokenRequest tokenRequest)
- {
- var token = await GetToken(tokenRequest.Login, tokenRequest.Password);
- if (token == null)
- {
- return UnprocessableEntity(new { message = "Invalid username or password." });
- }
- return Ok(token);
- }
- private async Task<string> GetToken(string login, string password)
- {
- var identity = await GetIdentity(login, password);
- if (identity == null)
- {
- return null;
- }
- var now = DateTime.UtcNow;
- // created JWT-token
- var jwt = new JwtSecurityToken(
- notBefore: now,
- claims: identity.Claims,
- expires: now.Add(TimeSpan.FromMinutes(int.Parse(configuration["Jwt:LifeTime"]))),
- signingCredentials: new SigningCredentials(
- new SymmetricSecurityKey(
- Encoding.ASCII.GetBytes(configuration["Jwt:Key"])),
- SecurityAlgorithms.HmacSha256));
- string token = new JwtSecurityTokenHandler().WriteToken(jwt);
- return token;
- }
- private async Task<ClaimsIdentity> GetIdentity(string login, string password)
- {
- var user = login.Contains('@') ?
- await userManager.FindByEmailAsync(login) :
- await userManager.FindByNameAsync(login);
- if (user != null)
- {
- var check = await userManager.CheckPasswordAsync(user, password);
- if (check)
- {
- ClaimsPrincipal principal = null;
- try
- {
- principal = await signInManager.CreateUserPrincipalAsync(user);
- }
- catch (Exception ex)
- {
- throw;
- }
- var result = (ClaimsIdentity)principal.Identity;
- return result;
- //var roles = await userManager.GetRolesAsync(user);
- //var claims = new List<Claim>
- //{
- // new Claim(ClaimsIdentity.DefaultNameClaimType, user.UserName)
- //};
- //foreach (var role in roles)
- //{
- // claims.Add(new Claim(ClaimsIdentity.DefaultRoleClaimType, role));
- //}
- //var claimsIdentity =
- // new ClaimsIdentity(claims, "Token", ClaimsIdentity.DefaultNameClaimType,
- // ClaimsIdentity.DefaultRoleClaimType);
- //return claimsIdentity;
- }
- }
- return null;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement