-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
f73c332
commit c83d2ec
Showing
2 changed files
with
121 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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"; | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | ||
} | ||
} | ||
} |