Skip to content

Commit

Permalink
update all controllers, add transfer stuff
Browse files Browse the repository at this point in the history
  • Loading branch information
fixterjake committed May 7, 2024
1 parent 191f898 commit 6ac90b4
Show file tree
Hide file tree
Showing 45 changed files with 5,699 additions and 709 deletions.
86 changes: 54 additions & 32 deletions Memphis.API/Controllers/AirportsController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,18 +10,34 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json;
using Sentry;
using Constants = Memphis.Shared.Utils.Constants;

namespace Memphis.API.Controllers;

[ApiController]
[Route("[controller]")]
[Produces("application/json")]
public class AirportsController(DatabaseContext context, RedisService redisService, LoggingService loggingService,
IValidator<AirportDto> validator, ISentryClient sentryHub, ILogger<AirportsController> logger)
: ControllerBase
public class AirportsController : ControllerBase
{
private readonly DatabaseContext _context;
private readonly RedisService _redisService;
private readonly LoggingService _loggingService;
private readonly IValidator<AirportDto> _validator;
private readonly ISentryClient _sentryHub;
private readonly ILogger<AirportsController> _logger;

public AirportsController(DatabaseContext context, RedisService redisService, LoggingService loggingService,
IValidator<AirportDto> validator, ISentryClient sentryHub, ILogger<AirportsController> logger)
{
_context = context;
_redisService = redisService;
_loggingService = loggingService;
_validator = validator;
_sentryHub = sentryHub;
_logger = logger;
}


[HttpPost]
[Authorize(Roles = Constants.CanAirports)]
[ProducesResponseType(typeof(Response<Airport>), 201)]
Expand All @@ -33,10 +49,12 @@ public async Task<ActionResult<Response<Airport>>> CreateAirport(AirportDto payl
{
try
{
if (!await redisService.ValidateRoles(Request.HttpContext.User, Constants.CanAirportsList))
if (!await _redisService.ValidateRoles(Request.HttpContext.User, Constants.CanAirportsList))
{
return StatusCode(401);
}

ValidationResult validation = await validator.ValidateAsync(payload);
ValidationResult validation = await _validator.ValidateAsync(payload);
if (!validation.IsValid)
{
return BadRequest(new Response<IList<ValidationFailure>>
Expand All @@ -47,14 +65,14 @@ public async Task<ActionResult<Response<Airport>>> CreateAirport(AirportDto payl
});
}

Microsoft.EntityFrameworkCore.ChangeTracking.EntityEntry<Airport> result = await context.Airports.AddAsync(new Airport
Microsoft.EntityFrameworkCore.ChangeTracking.EntityEntry<Airport> result = await _context.Airports.AddAsync(new Airport
{
Name = payload.Name,
Icao = payload.Icao,
});
await context.SaveChangesAsync();
await _context.SaveChangesAsync();
string newData = JsonConvert.SerializeObject(result.Entity);
await loggingService.AddWebsiteLog(Request, $"Created airport {result.Entity.Id}", string.Empty, newData);
await _loggingService.AddWebsiteLog(Request, $"Created airport {result.Entity.Id}", string.Empty, newData);

return StatusCode(201, new Response<Airport>
{
Expand All @@ -65,8 +83,8 @@ public async Task<ActionResult<Response<Airport>>> CreateAirport(AirportDto payl
}
catch (Exception ex)
{
logger.LogError("CreateAirport error '{Message}'\n{StackTrace}", ex.Message, ex.StackTrace);
return sentryHub.CaptureException(ex).ReturnActionResult();
_logger.LogError("CreateAirport error '{Message}'\n{StackTrace}", ex.Message, ex.StackTrace);
return _sentryHub.CaptureException(ex).ReturnActionResult();
}
}

Expand All @@ -77,7 +95,7 @@ public async Task<ActionResult<Response<IList<Airport>>>> GetAirports()
{
try
{
List<Airport> result = await context.Airports.ToListAsync();
List<Airport> result = await _context.Airports.ToListAsync();
return Ok(new Response<IList<Airport>>
{
StatusCode = 200,
Expand All @@ -87,8 +105,8 @@ public async Task<ActionResult<Response<IList<Airport>>>> GetAirports()
}
catch (Exception ex)
{
logger.LogError("GetAirports error '{Message}'\n{StackTrace}", ex.Message, ex.StackTrace);
return sentryHub.CaptureException(ex).ReturnActionResult();
_logger.LogError("GetAirports error '{Message}'\n{StackTrace}", ex.Message, ex.StackTrace);
return _sentryHub.CaptureException(ex).ReturnActionResult();
}
}

Expand All @@ -100,7 +118,7 @@ public async Task<ActionResult<Response<IList<Airport>>>> GetAirport(int airport
{
try
{
Airport? result = await context.Airports.FindAsync(airportId);
Airport? result = await _context.Airports.FindAsync(airportId);
if (result == null)
{
return NotFound(new Response<int>
Expand All @@ -120,8 +138,8 @@ public async Task<ActionResult<Response<IList<Airport>>>> GetAirport(int airport
}
catch (Exception ex)
{
logger.LogError("GetAirport error '{Message}'\n{StackTrace}", ex.Message, ex.StackTrace);
return sentryHub.CaptureException(ex).ReturnActionResult();
_logger.LogError("GetAirport error '{Message}'\n{StackTrace}", ex.Message, ex.StackTrace);
return _sentryHub.CaptureException(ex).ReturnActionResult();
}
}

Expand All @@ -137,10 +155,12 @@ public async Task<ActionResult<Response<Airport>>> UpdateAirport(AirportDto payl
{
try
{
if (!await redisService.ValidateRoles(Request.HttpContext.User, Constants.CanAirportsList))
if (!await _redisService.ValidateRoles(Request.HttpContext.User, Constants.CanAirportsList))
{
return StatusCode(401);
}

ValidationResult validation = await validator.ValidateAsync(payload);
ValidationResult validation = await _validator.ValidateAsync(payload);
if (!validation.IsValid)
{
return BadRequest(new Response<IList<ValidationFailure>>
Expand All @@ -151,7 +171,7 @@ public async Task<ActionResult<Response<Airport>>> UpdateAirport(AirportDto payl
});
}

Airport? airport = await context.Airports.FindAsync();
Airport? airport = await _context.Airports.FindAsync();
if (airport == null)
{
return NotFound(new Response<string?>
Expand All @@ -165,10 +185,10 @@ public async Task<ActionResult<Response<Airport>>> UpdateAirport(AirportDto payl
airport.Name = payload.Name;
airport.Icao = payload.Icao;
airport.Updated = DateTimeOffset.UtcNow;
await context.SaveChangesAsync();
await _context.SaveChangesAsync();
string newData = JsonConvert.SerializeObject(airport);

await loggingService.AddWebsiteLog(Request, $"Updated airport '{airport.Id}'", oldData, newData);
await _loggingService.AddWebsiteLog(Request, $"Updated airport '{airport.Id}'", oldData, newData);

return Ok(new Response<Airport>
{
Expand All @@ -179,8 +199,8 @@ public async Task<ActionResult<Response<Airport>>> UpdateAirport(AirportDto payl
}
catch (Exception ex)
{
logger.LogError("UpdateAirport error '{Message}'\n{StackTrace}", ex.Message, ex.StackTrace);
return sentryHub.CaptureException(ex).ReturnActionResult();
_logger.LogError("UpdateAirport error '{Message}'\n{StackTrace}", ex.Message, ex.StackTrace);
return _sentryHub.CaptureException(ex).ReturnActionResult();
}
}

Expand All @@ -195,10 +215,12 @@ public async Task<ActionResult<Response<string>>> DeleteAirport(int airportId)
{
try
{
if (!await redisService.ValidateRoles(Request.HttpContext.User, Constants.CanAirportsList))
if (!await _redisService.ValidateRoles(Request.HttpContext.User, Constants.CanAirportsList))
{
return StatusCode(401);
}

Airport? airport = await context.Airports.FindAsync(airportId);
Airport? airport = await _context.Airports.FindAsync(airportId);
if (airport == null)
{
return NotFound(new Response<int>
Expand All @@ -210,12 +232,12 @@ public async Task<ActionResult<Response<string>>> DeleteAirport(int airportId)
}

string oldData = JsonConvert.SerializeObject(airport);
context.Airports.Remove(airport);
await context.SaveChangesAsync();
_context.Airports.Remove(airport);
await _context.SaveChangesAsync();

await loggingService.AddWebsiteLog(Request, $"Deleted airport '{airportId}'", oldData, string.Empty);
await _loggingService.AddWebsiteLog(Request, $"Deleted airport '{airportId}'", oldData, string.Empty);

await redisService.RemoveCached("airports");
await _redisService.RemoveCached("airports");
return Ok(new Response<string?>
{
StatusCode = 200,
Expand All @@ -224,8 +246,8 @@ public async Task<ActionResult<Response<string>>> DeleteAirport(int airportId)
}
catch (Exception ex)
{
logger.LogError("DeleteAirport error '{Message}'\n{StackTrace}", ex.Message, ex.StackTrace);
return sentryHub.CaptureException(ex).ReturnActionResult();
_logger.LogError("DeleteAirport error '{Message}'\n{StackTrace}", ex.Message, ex.StackTrace);
return _sentryHub.CaptureException(ex).ReturnActionResult();
}
}
}
56 changes: 38 additions & 18 deletions Memphis.API/Controllers/AuthController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,13 @@
using Memphis.API.Extensions;
using Memphis.API.Services;
using Memphis.Shared.Dtos.auth;
using Memphis.Shared.Dtos.Auth;
using Memphis.Shared.Enums;
using Memphis.Shared.Utils;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using Newtonsoft.Json;
using Sentry;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
Expand All @@ -18,10 +18,22 @@ namespace Memphis.API.Controllers;
[ApiController]
[Route("[controller]")]
[Produces("application/json")]
public class AuthController(DatabaseContext context, RedisService redisService, ISentryClient sentryHub,
ILogger<AuthController> logger)
: ControllerBase
public class AuthController : ControllerBase
{
private readonly DatabaseContext _context;
private readonly RedisService _redisService;
private readonly ISentryClient _sentryHub;
private readonly ILogger<AuthController> _logger;

public AuthController(DatabaseContext context, RedisService redisService, ISentryClient sentryHub, ILogger<AuthController> logger)
{
_context = context;
_redisService = redisService;
_sentryHub = sentryHub;
_logger = logger;
}


[HttpGet("redirect")]
[ProducesResponseType(301)]
[ProducesResponseType(typeof(Response<Guid>), 500)]
Expand All @@ -42,14 +54,14 @@ public async Task<IActionResult> RedirectToVatsim()
}
catch (Exception ex)
{
return sentryHub.CaptureException(ex).ReturnActionResult();
return _sentryHub.CaptureException(ex).ReturnActionResult();
}
}

[HttpGet("callback")]
[ProducesResponseType(301)]
[HttpPost("callback")]
[ProducesResponseType(typeof(Response<string>), 200)]
[ProducesResponseType(typeof(Response<Guid>), 500)]
public async Task<IActionResult> ProcessCallback(string code)
public async Task<ActionResult<Response<string>>> ProcessCallback(CodeDto payload)
{
try
{
Expand All @@ -61,8 +73,6 @@ public async Task<IActionResult> ProcessCallback(string code)
throw new ArgumentNullException("CONNECT_CLIENT_SECRET env variable not found");
var redirectUrl = Environment.GetEnvironmentVariable("CONNECT_REDIRECT_URL") ??
throw new ArgumentNullException("CONNECT_REDIRECT_URL env variable not found");
var uiRedirect = Environment.GetEnvironmentVariable("CONNEXT_REDIRECT_URL_UI") ??
throw new ArgumentNullException("CONNEXT_REDIRECT_URL_UI env variable not found");
var issuer = Environment.GetEnvironmentVariable("JWT_ISSUER") ??
throw new ArgumentNullException("JWT_ISSUER env variable not found");
var audience = Environment.GetEnvironmentVariable("JWT_AUDIENCE") ??
Expand All @@ -77,7 +87,7 @@ public async Task<IActionResult> ProcessCallback(string code)
{
["client_id"] = clientId,
["client_secret"] = clientSecret,
["code"] = code,
["code"] = payload.Code,
["grant_type"] = "authorization_code",
["redirect_uri"] = redirectUrl
});
Expand All @@ -92,7 +102,7 @@ public async Task<IActionResult> ProcessCallback(string code)
var token = JsonConvert.DeserializeObject<VatsimTokenDto>(content);
if (token == null)
{
logger.LogError("Invalid VATSIM token response:\nconnect response code: {Code}\ncontent: {Content}",
_logger.LogError("Invalid VATSIM token response:\nconnect response code: {Code}\ncontent: {Content}",
response.StatusCode, content);
throw new InvalidDataException("Invalid VATSIM token response");
}
Expand All @@ -102,7 +112,7 @@ public async Task<IActionResult> ProcessCallback(string code)

if (data == null)
{
logger.LogError("Invalid VATSIM data response:\nconnect response code: {Code}\ndata: {Data}",
_logger.LogError("Invalid VATSIM data response:\nconnect response code: {Code}\ndata: {Data}",
response.StatusCode, data);
throw new InvalidDataException("Invalid VATSIM data response");
}
Expand All @@ -119,7 +129,7 @@ public async Task<IActionResult> ProcessCallback(string code)
new("region", data.Data.VatsimDetails.Region.Id),
new("division", data.Data.VatsimDetails.Division.Id),
};
var user = await context.Users.Include(x => x.Roles).FirstOrDefaultAsync(x => x.Id == data.Data.Cid);
var user = await _context.Users.Include(x => x.Roles).FirstOrDefaultAsync(x => x.Id == data.Data.Cid);

if (user == null || user.Status == UserStatus.REMOVED)
{
Expand All @@ -136,7 +146,12 @@ public async Task<IActionResult> ProcessCallback(string code)
)
);
var accessTokenNone = new JwtSecurityTokenHandler().WriteToken(jwtNone);
return RedirectPreserveMethod($"{uiRedirect}?accessToken={accessTokenNone}");
return Ok(new Response<string>
{
StatusCode = 200,
Message = "Logged in",
Data = accessTokenNone
});
}

claims.Add(new Claim("isMember", $"{true}"));
Expand All @@ -151,7 +166,7 @@ public async Task<IActionResult> ProcessCallback(string code)
roles.AddRange(user.Roles.Select(x => x.NameShort).ToList());
claims.AddRange(roles.Select(x => new Claim("roles", x)));

await redisService.SetRoles(roles, user.Id);
await _redisService.SetRoles(roles, user.Id);

var jwt = new JwtSecurityToken(
issuer,
Expand All @@ -163,11 +178,16 @@ public async Task<IActionResult> ProcessCallback(string code)
)
);
var accessToken = new JwtSecurityTokenHandler().WriteToken(jwt);
return RedirectPreserveMethod($"{uiRedirect}?accessToken={accessToken}");
return Ok(new Response<string>
{
StatusCode = 200,
Message = "Logged in",
Data = accessToken
});
}
catch (Exception ex)
{
return sentryHub.CaptureException(ex).ReturnActionResult();
return _sentryHub.CaptureException(ex).ReturnActionResult();
}
}
}
Loading

0 comments on commit 6ac90b4

Please sign in to comment.