Skip to content

Commit

Permalink
add auth
Browse files Browse the repository at this point in the history
  • Loading branch information
cyrogabrielcc committed Apr 5, 2021
1 parent f73c332 commit c83d2ec
Show file tree
Hide file tree
Showing 2 changed files with 121 additions and 0 deletions.
84 changes: 84 additions & 0 deletions Controllers/UserController.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using DataDriven.Data;
using DataDriven.Models;
using System;
using Microsoft.AspNetCore.Authorization;
using System.Linq;
using DataDriven.Services;

namespace DataDriven.Controllers
{
[Route("v1/users")]
public class UserController : Controller
{
//===============================POST - Criando user============================================
[HttpPost]
[Route("")]
[AllowAnonymous]

public async Task<ActionResult<User>> Post([FromServices] DataContext context, [FromBody] User model)
{
if(!ModelState.IsValid) return BadRequest(ModelState);

try
{
context.Users.Add(model);
await context.SaveChangesAsync();
return model;
}

catch (Exception)
{
return BadRequest(new { message = "Não foi possível criar usuário" });
}
}

//===============================POST - Login============================================

[HttpPost]
[Route("login")]
[AllowAnonymous]

public async Task<ActionResult<dynamic>> Authenticate([FromServices] DataContext context, [FromBody] User model)
{
var user = await context.Users
.AsNoTracking()
.Where(x => x.Username == model.Username && x.Password == model.Password)
.FirstOrDefaultAsync();

//se os usuários foram encontrados no banco
if(user == null) return NotFound(new { message = "Usuário ou senha inválidos"});

var token = TokenService.GenerateToken(user);

return new{
user = user,
token = token
};
}

//===============================GET-Anonimo============================================
[HttpGet]
[Route("anonimo")]
[AllowAnonymous]
public string Anonimo() => "Anonimo";

[HttpGet]
[Route("autenticado")]
[AllowAnonymous]
public string Autenticado() => "Autenticado";

[HttpGet]
[Route("funcionario")]
[Authorize(Roles="employee")]
public string Funcionario() => "funcionario";

[HttpGet]
[Route("gerente")]
[Authorize(Roles="manager")]
public string Gerente() => "Gerente";
}
}
37 changes: 37 additions & 0 deletions Services/TokenService.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
using System;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using DataDriven.Models;
using Microsoft.IdentityModel.Tokens;






namespace DataDriven.Services
{
public static class TokenService
{
public static string GenerateToken(User user)
{

var tokenHandler = new JwtSecurityTokenHandler();
var key = Encoding.ASCII.GetBytes(Settings.Secret);
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(new Claim[]
{
new Claim(ClaimTypes.Name, user.Id.ToString()),
new Claim(ClaimTypes.Role, user.Role.ToString()),
}),
Expires =DateTime.UtcNow.AddHours(2),
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature),
};
var token = tokenHandler.CreateToken(tokenDescriptor);

return tokenHandler.WriteToken(token);
}
}
}

0 comments on commit c83d2ec

Please sign in to comment.