Skip to content
Snippets Groups Projects
Commit 1483b4c4 authored by Abdelsamad, Mouaz R (UG - SISC)'s avatar Abdelsamad, Mouaz R (UG - SISC)
Browse files

Merge branch 'MA/BookingServiceV2' into 'main'

Booking Service v2

See merge request ma03081/COM3014!26
parents bfe67a8b e6fa7b5e
No related branches found
No related tags found
No related merge requests found
Showing
with 607 additions and 17 deletions
......@@ -10,8 +10,16 @@ DB_USER=user
DB_PASSWORD=user
DB_CHARSET=utf8mb4
# Keeping these for dev purposes, will remove at the end
#DB_PORT=3308
#DB_NAME=AspNetCoreDb
#DB_USER=root
#DB_PASSWORD=
#DB_CHARSET=utf8mb4
# Service ports
USER_MICROSERVICE_PORT=5089
FLIGHT_MICROSERVICE_PORT=5175
GATEWAY_API_PORT=5267
CLIENT_PORT=4200
\ No newline at end of file
BOOKING_MICROSERVICE_PORT=5207
CLIENT_PORT=4200
**/.classpath
**/.dockerignore
**/.env
**/.git
**/.gitignore
**/.project
**/.settings
**/.toolstarget
**/.vs
**/.vscode
**/*.*proj.user
**/*.dbmdl
**/*.jfm
**/azds.yaml
**/bin
**/charts
**/docker-compose*
**/Dockerfile*
**/node_modules
**/npm-debug.log
**/obj
**/secrets.dev.yaml
**/values.dev.yaml
LICENSE
README.md
!**/.gitignore
!.git/HEAD
!.git/config
!.git/packed-refs
!.git/refs/heads/**
\ No newline at end of file
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<UserSecretsId>1b0c76fc-55fe-4ae7-9921-1d071955c125</UserSecretsId>
<DockerDefaultTargetOS>Linux</DockerDefaultTargetOS>
<DockerfileContext>.</DockerfileContext>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="8.0.3" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="8.0.3" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="8.0.3">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.19.6" />
<PackageReference Include="Pomelo.EntityFrameworkCore.MySql" Version="8.0.2" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.4.0" />
</ItemGroup>
</Project>
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="Current" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<ActiveDebugProfile>http</ActiveDebugProfile>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
<DebuggerFlavor>ProjectDebugger</DebuggerFlavor>
</PropertyGroup>
</Project>
\ No newline at end of file
@BookingMicroservice_HostAddress = http://localhost:5207
GET {{BookingMicroservice_HostAddress}}/weatherforecast/
Accept: application/json
###
......@@ -3,9 +3,7 @@ Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.9.34622.214
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FlightBooking.Service", "FlightBooking.Service\FlightBooking.Service.csproj", "{0043031F-8453-4554-90A8-DA1921F95235}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FlightBooking.Service.Tests", "FlightBooking.Service.Tests\FlightBooking.Service.Tests.csproj", "{C7FCD62C-5D7D-44BB-8A38-821BEBE2BBC9}"
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BookingMicroservice", "BookingMicroservice.csproj", "{FF90ADFD-EC0A-4189-B734-59CD531D1FD6}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
......@@ -13,19 +11,15 @@ Global
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{0043031F-8453-4554-90A8-DA1921F95235}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{0043031F-8453-4554-90A8-DA1921F95235}.Debug|Any CPU.Build.0 = Debug|Any CPU
{0043031F-8453-4554-90A8-DA1921F95235}.Release|Any CPU.ActiveCfg = Release|Any CPU
{0043031F-8453-4554-90A8-DA1921F95235}.Release|Any CPU.Build.0 = Release|Any CPU
{C7FCD62C-5D7D-44BB-8A38-821BEBE2BBC9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{C7FCD62C-5D7D-44BB-8A38-821BEBE2BBC9}.Debug|Any CPU.Build.0 = Debug|Any CPU
{C7FCD62C-5D7D-44BB-8A38-821BEBE2BBC9}.Release|Any CPU.ActiveCfg = Release|Any CPU
{C7FCD62C-5D7D-44BB-8A38-821BEBE2BBC9}.Release|Any CPU.Build.0 = Release|Any CPU
{FF90ADFD-EC0A-4189-B734-59CD531D1FD6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{FF90ADFD-EC0A-4189-B734-59CD531D1FD6}.Debug|Any CPU.Build.0 = Debug|Any CPU
{FF90ADFD-EC0A-4189-B734-59CD531D1FD6}.Release|Any CPU.ActiveCfg = Release|Any CPU
{FF90ADFD-EC0A-4189-B734-59CD531D1FD6}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {1CCB1631-8F04-4C14-AC4D-9CFC54B609B7}
SolutionGuid = {1F564B53-A9C7-46CC-8ADD-A2CB5381ADB7}
EndGlobalSection
EndGlobal
namespace BookingMicroservice.Clients
{
public class FlightServiceClient : IFlightServiceClient
{
private readonly HttpClient httpClient;
private const string FLIGHT_API_PATH = "api/Flight";
private const string SEAT_API_PATH = "api/Seat";
public FlightServiceClient(HttpClient httpClient)
{
this.httpClient = httpClient;
}
public async Task<HttpResponseMessage> GetFlightCapacityAsync(int flightId, int classType)
{
return await httpClient.GetAsync($"{FLIGHT_API_PATH}/{flightId}/capacity?classType={classType}");
}
public async Task<HttpResponseMessage> IsSeatAvailableAsync(int seatId)
{
return await httpClient.GetAsync($"{SEAT_API_PATH}/{seatId}/isAvailable");
}
public async Task<HttpResponseMessage> BookSeatAsync(int seatId)
{
return await httpClient.PutAsync($"{SEAT_API_PATH}/{seatId}", null);
}
}
}
namespace BookingMicroservice.Clients
{
public interface IFlightServiceClient
{
Task<HttpResponseMessage> GetFlightCapacityAsync(int flightId, int classType);
Task<HttpResponseMessage> IsSeatAvailableAsync(int seatId);
Task<HttpResponseMessage> BookSeatAsync(int seatId);
}
}
using BookingMicroservice.Exceptions;
using BookingMicroservice.Models;
using BookingMicroservice.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Security.Claims;
namespace BookingMicroservice.Controllers
{
[ApiController]
[Route("api/[Controller]")]
public class BookingController : ControllerBase
{
private readonly IReservationComplianceService reservationComplianceService;
private readonly IBookingService bookingService;
public BookingController(IReservationComplianceService reservationComplianceService, IBookingService bookingService)
{
this.reservationComplianceService = reservationComplianceService;
this.bookingService = bookingService;
}
[Authorize]
[HttpGet()]
public IActionResult GetBookings(int? flightId = null, int? userId = null, BookingClass? bookingClass = null)
{
List<Booking> bookings = bookingService.GetBookings(flightId, userId, bookingClass);
if (bookings == null)
return BadRequest("Unable to get bookings");
return Ok(bookings);
}
[Authorize]
[HttpGet("{id}")]
public IActionResult GetBooking([FromRoute] int id)
{
Booking? booking = bookingService.GetBooking(id);
if(booking == null)
return NotFound($"Could not find booking with id: {id}");
return Ok(booking);
}
[Authorize]
[HttpPost()]
public async Task<IActionResult> MakeBooking([FromBody] BookingCreation bookingCreationModel)
{
// TODO: add stripe handling
string? userIdValue = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
if (!int.TryParse(userIdValue, out int userId))
return BadRequest("Unable to get User Id from Token");
try
{
Booking? booking = await reservationComplianceService.TryCreateBookingAsync(bookingCreationModel.FlightId, userId, bookingCreationModel.BookingClass, bookingCreationModel.SeatId);
if (booking == null)
return BadRequest("Error in creating booking");
return Ok(booking);
}
catch (InvalidOperationException exception)
{
return BadRequest(exception.Message);
}
catch (BookingException exception)
{
return BadRequest(exception.Message);
}
}
[Authorize]
[HttpPut("{bookingId}")]
public async Task<IActionResult> UpdatedBookingSeat([FromRoute] int bookingId, [FromBody] BookingUpdate bookingUpdateModel)
{
try
{
await reservationComplianceService.TryBookSeatAsync(bookingId, bookingUpdateModel.SeatId);
return Ok(new { BookedSeat = true, Message = "Seat booked successfully." });
}
catch (InvalidOperationException exception)
{
return BadRequest(exception.Message);
}
catch (BookingException exception)
{
return Ok(new { BookedSeat = false, Message = exception.Message });
}
}
}
}
FROM mcr.microsoft.com/dotnet/aspnet:8.0 AS base
USER app
WORKDIR /app
EXPOSE 8080
EXPOSE 8081
FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build
ARG BUILD_CONFIGURATION=Release
WORKDIR /src
COPY ["BookingMicroservice.csproj", "."]
RUN dotnet restore "./BookingMicroservice.csproj"
COPY . .
WORKDIR "/src/."
RUN dotnet build "./BookingMicroservice.csproj" -c $BUILD_CONFIGURATION -o /app/build
FROM build AS publish
ARG BUILD_CONFIGURATION=Release
RUN dotnet publish "./BookingMicroservice.csproj" -c $BUILD_CONFIGURATION -o /app/publish /p:UseAppHost=false
FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "BookingMicroservice.dll"]
\ No newline at end of file
namespace BookingMicroservice.Exceptions
{
public class BookingException : Exception
{
public BookingException(string message) : base(message) { }
}
}
using System.Net;
using System.Text.Json;
namespace BookingMicroservice.Handlers
{
public class ExceptionHandler
{
private readonly RequestDelegate next;
public ExceptionHandler(RequestDelegate next)
{
this.next = next;
}
public async Task Invoke(HttpContext context)
{
try
{
await next(context);
}
catch (Exception ex)
{
if (!context.Response.HasStarted)
{
var response = context.Response;
response.ContentType = "application/json";
response.StatusCode = (int)HttpStatusCode.InternalServerError;
var result = JsonSerializer.Serialize(new
{
response.StatusCode,
ex.Message
});
await response.WriteAsync(result);
}
}
}
}
}
using System.Net;
namespace BookingMicroservice.Handlers
{
public class RequestCookieHandler : DelegatingHandler
{
private readonly IHttpContextAccessor httpContextAccessor;
public RequestCookieHandler(IHttpContextAccessor httpContextAccessor)
{
this.httpContextAccessor = httpContextAccessor;
}
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
HttpContext? context = httpContextAccessor.HttpContext;
if (context?.Request.Cookies != null && request.RequestUri != null)
{
CookieContainer cookieContainer = new CookieContainer();
foreach (KeyValuePair<string, string> cookie in context.Request.Cookies)
{
if (!string.IsNullOrEmpty(cookie.Value) && (cookie.Key == "AccessToken" || cookie.Key == "RefreshToken"))
cookieContainer.Add(request.RequestUri, new Cookie(cookie.Key, cookie.Value));
}
var cookieHeader = cookieContainer.GetCookieHeader(request.RequestUri);
if (!string.IsNullOrEmpty(cookieHeader))
request.Headers.Add("Cookie", cookieHeader);
}
return await base.SendAsync(request, cancellationToken);
}
}
}
using Microsoft.EntityFrameworkCore;
namespace BookingMicroservice.Models
{
public class ApplicationDbContext : DbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
public DbSet<Booking> Bookings { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
}
}
}
namespace BookingMicroservice.Models
{
public class Booking
{
public int Id { get; private set; }
public int FlightId { get; private set; }
public int UserId { get; private set; }
public BookingClass BookingClass { get; private set; }
public int? SeatId { get; private set; }
public Booking(int flightId, int userId, BookingClass bookingClass, int? seatId)
{
FlightId = flightId;
UserId = userId;
BookingClass = bookingClass;
SeatId = seatId;
}
public Booking() { }
public void SetSeatNumber(int seatId)
{
SeatId = seatId;
}
}
public enum BookingClass
{
BUSINESS = 0,
ECONOMY = 1
}
}
namespace BookingMicroservice.Models
{
public class BookingCreation
{
public required int FlightId { get; set; }
public required BookingClass BookingClass { get; set; }
public int? SeatId { get; set; }
}
}
namespace BookingMicroservice.Models
{
public class BookingUpdate
{
public required int SeatId { get; set; }
}
}
using BookingMicroservice.Clients;
using BookingMicroservice.Handlers;
using BookingMicroservice.Models;
using BookingMicroservice.Services;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using System.Text;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddHttpContextAccessor();
builder.Services.AddTransient<RequestCookieHandler>();
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddDbContext<ApplicationDbContext>(options =>
options.UseMySql(builder.Configuration.GetConnectionString("DefaultConnection"),
new MariaDbServerVersion(new Version(10, 4, 20))));
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"] ?? throw new InvalidOperationException("JWT Key is not configured."))),
ValidateIssuer = true,
ValidateAudience = true,
ValidIssuer = builder.Configuration["Jwt:Issuer"] ?? throw new InvalidOperationException("JWT Issuer is not configured."),
ValidAudience = builder.Configuration["Jwt:Audience"] ?? throw new InvalidOperationException("JWT Audience is not configured.")
};
options.Events = new JwtBearerEvents
{
OnAuthenticationFailed = context =>
{
Console.WriteLine("Authentication failed: " + context.Exception.Message);
return Task.CompletedTask;
},
OnTokenValidated = context =>
{
Console.WriteLine("Token validated");
return Task.CompletedTask;
}
};
});
builder.Services.AddHttpClient<IFlightServiceClient, FlightServiceClient>(client =>
{
string? baseURL = builder.Configuration["FlightMicroservice:BaseUrl"];
if (string.IsNullOrEmpty(baseURL))
throw new InvalidOperationException("FlightMicroservice BaseUrl is not configured.");
baseURL = baseURL.EndsWith("/") ? baseURL : baseURL + "/";
client.BaseAddress = new Uri(baseURL);
}).AddHttpMessageHandler<RequestCookieHandler>(); ;
builder.Services.AddScoped<IBookingService, BookingService>();
builder.Services.AddScoped<IReservationComplianceService, ReservationComplianceService>();
var app = builder.Build();
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseMiddleware<ExceptionHandler>();
app.UseHttpsRedirection();
// Middleware to check for the access token in cookies
app.Use(async (context, next) =>
{
var accessToken = context.Request.Cookies["AccessToken"];
if (!string.IsNullOrEmpty(accessToken))
{
context.Request.Headers.Append("Authorization", "Bearer " + accessToken);
}
await next();
});
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();
{
"$schema": "http://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:37680",
"sslPort": 44321
}
},
{
"profiles": {
"http": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"launchUrl": "swagger",
"applicationUrl": "http://localhost:5000",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"dotnetRunMessages": true,
"applicationUrl": "http://localhost:5207"
},
"https": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"launchUrl": "swagger",
"applicationUrl": "https://localhost:7287;http://localhost:5000",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"dotnetRunMessages": true,
"applicationUrl": "https://localhost:7116;http://localhost:5207"
},
"IIS Express": {
"commandName": "IISExpress",
......@@ -36,6 +27,26 @@
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"Container (Dockerfile)": {
"commandName": "Docker",
"launchBrowser": true,
"launchUrl": "{Scheme}://{ServiceHost}:{ServicePort}/swagger",
"environmentVariables": {
"ASPNETCORE_HTTPS_PORTS": "8081",
"ASPNETCORE_HTTP_PORTS": "8080"
},
"publishAllPorts": true,
"useSSL": true
}
},
"$schema": "http://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:4639",
"sslPort": 44398
}
}
}
\ No newline at end of file
using BookingMicroservice.Models;
using Microsoft.EntityFrameworkCore;
using System.Diagnostics.CodeAnalysis;
namespace BookingMicroservice.Services
{
public class BookingService : IBookingService
{
private readonly ApplicationDbContext dbContext;
public BookingService(ApplicationDbContext dbContext)
{
this.dbContext = dbContext;
}
public List<Booking> GetBookings(int? flightId = null, int? userId = null, BookingClass? bookingClass = null)
{
IQueryable<Booking> query = dbContext.Bookings.AsQueryable();
if (flightId.HasValue)
query = query.Where(booking => booking.FlightId == flightId.Value);
if (userId.HasValue)
query = query.Where(booking => booking.UserId == userId.Value);
if (bookingClass.HasValue)
query = query.Where(booking => booking.BookingClass == bookingClass.Value);
List<Booking> bookings = query.ToList();
return bookings;
}
public Booking CreateBooking(int flightId, int userId, BookingClass bookingClass)
{
Booking booking = new Booking(flightId, userId, bookingClass, null);
dbContext.Bookings.Add(booking);
dbContext.SaveChanges();
return booking;
}
public Booking? GetBooking(int bookingId)
{
Booking? booking = dbContext.Bookings.SingleOrDefault(booking => booking.Id == bookingId);
return booking;
}
public void DeleteBooking(int bookingId)
{
Booking? booking = GetBooking(bookingId);
if (booking == null)
throw new KeyNotFoundException($"A Booking with the provided Id: {bookingId} doesnt exist");
dbContext.Bookings.Remove(booking);
dbContext.SaveChanges();
}
public Booking UpdateBooking(int bookingId, int seatId)
{
Booking? booking = GetBooking(bookingId);
if (booking == null)
throw new KeyNotFoundException($"A Booking with the provided Id: {bookingId} doesnt exist");
booking.SetSeatNumber(seatId);
int affectedRows = dbContext.Bookings
.Where(booking => booking.Id == bookingId)
.ExecuteUpdate(setters => setters
.SetProperty(booking => booking.SeatId, seatId));
dbContext.SaveChanges();
if (affectedRows == 0)
throw new DbUpdateException("Operation was not able to update the Database");
return booking;
}
}
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment