-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
140 lines (116 loc) · 4.69 KB
/
Program.cs
File metadata and controls
140 lines (116 loc) · 4.69 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
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.IdentityModel.Tokens;
using PlatinumDev.HotelsWebAPI.Auth;
using PlatinumDev.HotelsWebAPI.DAL.Repository;
using PlatinumDev.HotelsWebAPI.DAL.Service;
using PlatinumDev.HotelsWebAPI.Infrastruct;
using System.Text;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddDbContext<HotelDbContext>(options =>
{
options.UseSqlite(builder.Configuration.GetConnectionString("Sqlite"));
});
builder.Services.AddScoped<IHotelRepository, HotelRepository>();
builder.Services.AddSingleton<ITokenService>(new TokenService());
builder.Services.AddSingleton<IUserRepository>(new UserRepository());
builder.Services.AddAuthorization();
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(opt =>
{
opt.TokenValidationParameters = new()
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = builder.Configuration["Jwt:Issuer"],
ValidAudience = builder.Configuration["Jwt:Audience"],
IssuerSigningKey = new SymmetricSecurityKey(
Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"]))
};
});
var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
using var scope = app.Services.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<HotelDbContext>();
db.Database.EnsureCreated();
}
app.MapGet("/login", [AllowAnonymous] async (HttpContext context,
ITokenService tokenService, IUserRepository userRepository) =>
{
UserModel userModel = new()
{
UserName = context.Request.Query["username"],
Password = context.Request.Query["password"]
};
var userDto = userRepository.GetUser(userModel);
if (userDto == null) return Results.Unauthorized();
var token = tokenService.BuildToken(builder.Configuration["Jwt:Key"],
builder.Configuration["Jwt:Issuer"], userDto);
return Results.Ok(token);
});
app.MapGet("/hotels", [Authorize] async (IHotelRepository repository) =>
Results.Extensions.Xml(await repository.GetHotelsAsync()))
.Produces<List<Hotel>>(StatusCodes.Status200OK)
.WithName("GetAllHotels")
.WithTags("Getters");
app.MapGet("/hotels/{id}", [Authorize] async (int id, IHotelRepository repository) =>
await repository.GetHotelAsync(id) is Hotel hotel
? Results.Ok(hotel)
: Results.NotFound())
.Produces<Hotel>(StatusCodes.Status200OK)
.WithName("GetHotel")
.WithTags("Getters");
app.MapPost("/hotels", [Authorize] async ([FromBody] Hotel hotel, IHotelRepository repository) =>
{
await repository.InsertHotelAsync(hotel);
await repository.SaveAsync();
return Results.Created($"/hotels/{hotel.Id}", hotel);
})
.Accepts<Hotel>("application/json")
.Produces<Hotel>(StatusCodes.Status201Created)
.WithName("CreateHotel")
.WithTags("Creators");
app.MapPut("/hotels", [Authorize] async ([FromBody] Hotel hotel, IHotelRepository repository) =>
{
await repository.UpdateHotelAsync(hotel);
await repository.SaveAsync();
return Results.NoContent();
})
.Accepts<Hotel>("application/json")
.Produces<Hotel>(StatusCodes.Status201Created)
.WithName("UpdateHotel")
.WithTags("Updaters"); ;
app.MapDelete("hotels/{id}", [Authorize] async (int id, IHotelRepository repository) =>
{
await repository.DeleteHotelAsync(id);
await repository.SaveAsync();
return Results.NoContent();
})
.WithName("DeleteHotel")
.WithTags("Deleters");
app.MapGet("/hotels/search/name/{query}", [Authorize] async (string query, IHotelRepository repository) =>
await repository.GetHotelsAsync(query) is IEnumerable<Hotel> hotels
? Results.Ok(hotels)
: Results.NotFound(Array.Empty<Hotel>()))
.Produces<List<Hotel>>(StatusCodes.Status200OK)
.Produces(StatusCodes.Status404NotFound)
.WithName("SearchHotel")
.WithTags("Getters")
.ExcludeFromDescription();
app.MapGet("hotels/search/location/{coordinate}", [Authorize]
async (Coordinate coordinate, IHotelRepository repository) =>
await repository.GetHotelsAsync(coordinate) is IEnumerable<Hotel> hotels
? Results.Ok(hotels)
: Results.NotFound(Array.Empty<Hotel>()))
.ExcludeFromDescription();
app.UseHttpsRedirection();
app.Run();