-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
267 lines (208 loc) · 6.91 KB
/
Copy pathProgram.cs
File metadata and controls
267 lines (208 loc) · 6.91 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
using DemoMinimalAPI.Data;
using DemoMinimalAPI.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
using Microsoft.OpenApi.Models;
using MiniValidation;
using NetDevPack.Identity.Jwt;
using NetDevPack.Identity.Model;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddAuthorization();
builder.Services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo
{
Title = "Minimal API Sample",
Description = "Develop by Victor",
Contact = new OpenApiContact { Name = "Victor", Email = "teste@teste.com" },
License = new OpenApiLicense { Name = "MIT" }
});
c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
{
Description = "Insira o token JWT desta maneira: Bearer {seu token}",
Name = "Authorization",
Scheme = "Bearer",
BearerFormat = "JWT",
In = ParameterLocation.Header,
Type = SecuritySchemeType.ApiKey
});
c.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "Bearer"
}
},
new string[] {}
}
});
});
builder.Services.AddDbContext<MinimalContextDb>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
builder.Services.AddIdentityEntityFrameworkContextConfiguration(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection"),
b => b.MigrationsAssembly("DemoMinimalAPI")));
builder.Services.AddIdentityConfiguration();
builder.Services.AddJwtConfiguration(builder.Configuration, "AppSettings");
builder.Services.AddAuthorizationBuilder()
.AddPolicy("ExcluirFornecedor", policy => policy.RequireClaim("ExcluirFornecedor"));
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseAuthConfiguration();
app.UseHttpsRedirection();
#region Autenticação
app.MapPost("/registro", [AllowAnonymous] async (
SignInManager<IdentityUser> signInManager,
UserManager<IdentityUser> userManager,
IOptions<AppJwtSettings> appJwtSettings,
RegisterUser registerUser) =>
{
if (registerUser == null)
return Results.BadRequest("Usuário não informado");
if (!MiniValidator.TryValidate(registerUser, out var errors))
return Results.ValidationProblem(errors);
var user = new IdentityUser
{
UserName = registerUser.Email,
Email = registerUser.Email,
EmailConfirmed = true
};
var result = await userManager.CreateAsync(user, registerUser.Password);
if (!result.Succeeded)
return Results.BadRequest(result.Errors);
var jwt = new JwtBuilder()
.WithUserManager(userManager)
.WithJwtSettings(appJwtSettings.Value)
.WithEmail(user.Email)
.WithJwtClaims()
.WithUserClaims()
.WithUserRoles()
.BuildUserResponse();
return Results.Ok(jwt);
}).ProducesValidationProblem()
.Produces(StatusCodes.Status200OK)
.Produces(StatusCodes.Status400BadRequest)
.WithName("RegistroUsuario")
.WithTags("Usuario");
app.MapPost("/login", [AllowAnonymous] async (
SignInManager<IdentityUser> signInManager,
UserManager<IdentityUser> userManager,
IOptions<AppJwtSettings> appJwtSettings,
LoginUser loginUser) =>
{
if (loginUser == null)
return Results.BadRequest("Usuário não informado");
if (!MiniValidator.TryValidate(loginUser, out var errors))
return Results.ValidationProblem(errors);
var result = await signInManager.PasswordSignInAsync(loginUser.Email, loginUser.Password, true, true);
if (result.IsLockedOut)
return Results.BadRequest("Usuário Bloqueado");
if (!result.Succeeded)
return Results.BadRequest("Usuário ou senha inválidos");
var jwt = new JwtBuilder()
.WithUserManager(userManager)
.WithJwtSettings(appJwtSettings.Value)
.WithEmail(loginUser.Email)
.WithJwtClaims()
.WithUserClaims()
.WithUserRoles()
.BuildUserResponse();
return Results.Ok(jwt);
}).ProducesValidationProblem()
.Produces(StatusCodes.Status200OK)
.Produces(StatusCodes.Status400BadRequest)
.WithName("LoginUsuario")
.WithTags("Usuario"); ;
#endregion
#region Fornecedor
//GET: /fornecedor
app.MapGet("/fornecedor", [AllowAnonymous] async (
MinimalContextDb context) =>
await context.Fornecedores.ToListAsync())
.WithName("GetFornecedor")
.WithTags("Fornecedor");
//GET: /fornecedor/id
app.MapGet("/fornecedor/{id}", [Authorize] async (
Guid id,
MinimalContextDb context) =>
await context.Fornecedores.FindAsync(id)
is Fornecedor fornecedor
? Results.Ok(fornecedor)
: Results.NotFound()
).Produces<Fornecedor>(StatusCodes.Status200OK)
.Produces(StatusCodes.Status404NotFound)
.WithName("GetFornecedorById")
.WithTags("Fornecedor");
//POST: /fornecedor
app.MapPost("/fornecedor", [AllowAnonymous] async (
MinimalContextDb context,
Fornecedor fornecedor) =>
{
if (!MiniValidator.TryValidate(fornecedor, out var errors))
return Results.ValidationProblem(errors);
context.Fornecedores.Add(fornecedor);
var result = await context.SaveChangesAsync();
return result > 0
? Results.Created($"/fornecedor/{fornecedor.Id}", fornecedor)
: Results.BadRequest("Houve um problema ao salvar o registro ");
}).ProducesValidationProblem()
.Produces<Fornecedor>(StatusCodes.Status201Created)
.Produces(StatusCodes.Status400BadRequest)
.WithName("PostFornecedor")
.WithTags("Fornecedor");
//PUT: /fornecedor/id
app.MapPut("/fornecedor/{id}", [Authorize] async (
Guid id,
MinimalContextDb context,
Fornecedor fornecedor) =>
{
var fornecedorBanco = await context.Fornecedores
.AsNoTracking<Fornecedor>()
.FirstOrDefaultAsync(f => f.Id == id);
if (fornecedor == null)
return Results.NotFound();
if (!MiniValidator.TryValidate(fornecedor, out var errors))
return Results.ValidationProblem(errors);
context.Fornecedores.Update(fornecedor);
var result = await context.SaveChangesAsync();
return result > 0
? Results.NoContent()
: Results.BadRequest("Houve um problema ao salvar o registro ");
}).ProducesValidationProblem()
.Produces(StatusCodes.Status204NoContent)
.Produces(StatusCodes.Status400BadRequest)
.WithName("PutFornecedor")
.WithTags("Fornecedor");
//DELETE: /fornecedor/id
app.MapDelete("/fornecedor/{id}", [Authorize] async (
Guid id,
MinimalContextDb context) =>
{
var fornecedor = await context.Fornecedores.FindAsync(id);
if (fornecedor == null) return Results.NotFound();
context.Fornecedores.Remove(fornecedor);
var result = await context.SaveChangesAsync();
return result > 0
? Results.NoContent()
: Results.BadRequest("Houve um problema ao salvar o registro");
}).Produces(StatusCodes.Status400BadRequest)
.Produces(StatusCodes.Status204NoContent)
.Produces(StatusCodes.Status404NotFound)
.RequireAuthorization("ExcluirFornecedor")
.WithName("DeleteFornecedor")
.WithTags("Fornecedor");
#endregion
app.Run();