simplify WebApplication builder

This commit is contained in:
ig 2023-03-20 10:20:56 +01:00
parent e025b8cd11
commit 5ef49de742
4 changed files with 82 additions and 119 deletions

View File

@ -7,25 +7,32 @@ using Microsoft.AspNetCore.Mvc;
namespace InnovEnergy.App.Backend.Controllers; namespace InnovEnergy.App.Backend.Controllers;
using Token = String;
[ApiController] [ApiController]
[Route("api/")] [Route("api/")]
public class Controller : ControllerBase public class Controller : ControllerBase
{ {
[HttpPost(nameof(Login))] [HttpPost(nameof(Login))]
public ActionResult<Session> Login(Credentials credentials) public ActionResult<Session> Login(String username, String password)
{ {
var session = credentials.Login(); var user = Db.GetUserByEmail(username);
return session is null if (user is null || !user.VerifyPassword(password))
? Unauthorized() return Unauthorized();
: session;
var session = new Session(user);
return Db.Create(session)
? session
: Unauthorized();
} }
[HttpPost(nameof(Logout))] [HttpPost(nameof(Logout))]
public ActionResult Logout() public ActionResult Logout(Token authToken)
{ {
var session = GetSession(); var session = Db.GetSession(authToken);
return session.Logout() return session.Logout()
? Ok() ? Ok()
@ -34,15 +41,15 @@ public class Controller : ControllerBase
[HttpGet(nameof(GetUserById))] [HttpGet(nameof(GetUserById))]
public ActionResult<User> GetUserById(Int64 id) public ActionResult<User> GetUserById(Int64 id, Token authToken)
{ {
var caller = GetSession()?.User; var session = Db.GetSession(authToken)?.User;
if (caller == null) if (session == null)
return Unauthorized(); return Unauthorized();
var user = Db.GetUserById(id); var user = Db.GetUserById(id);
if (user is null || !caller.HasAccessTo(user)) if (user is null || !session.HasAccessTo(user))
return Unauthorized(); return Unauthorized();
user.Password = ""; user.Password = "";
@ -51,9 +58,9 @@ public class Controller : ControllerBase
[HttpGet(nameof(GetInstallationById))] [HttpGet(nameof(GetInstallationById))]
public ActionResult<Installation> GetInstallationById(Int64 id) public ActionResult<Installation> GetInstallationById(Int64 id, Token authToken)
{ {
var user = GetSession()?.User; var user = Db.GetSession(authToken)?.User;
if (user == null) if (user == null)
return Unauthorized(); return Unauthorized();
@ -66,9 +73,9 @@ public class Controller : ControllerBase
} }
[HttpGet(nameof(GetUsersWithAccessToInstallation))] [HttpGet(nameof(GetUsersWithAccessToInstallation))]
public ActionResult<IEnumerable<Object>> GetUsersWithAccessToInstallation(Int64 id) public ActionResult<IEnumerable<Object>> GetUsersWithAccessToInstallation(Int64 id, Token authToken)
{ {
var user = GetSession()?.User; var user = Db.GetSession(authToken)?.User;
if (user == null) if (user == null)
return Unauthorized(); return Unauthorized();
@ -93,9 +100,9 @@ public class Controller : ControllerBase
} }
[HttpGet(nameof(GetUsersWithAccessToFolder))] [HttpGet(nameof(GetUsersWithAccessToFolder))]
public ActionResult<IEnumerable<Object>> GetUsersWithAccessToFolder(Int64 id) public ActionResult<IEnumerable<Object>> GetUsersWithAccessToFolder(Int64 id, Token authToken)
{ {
var user = GetSession()?.User; var user = Db.GetSession(authToken)?.User;
if (user == null) if (user == null)
return Unauthorized(); return Unauthorized();
@ -114,9 +121,9 @@ public class Controller : ControllerBase
} }
[HttpGet(nameof(GetFolderById))] [HttpGet(nameof(GetFolderById))]
public ActionResult<Folder> GetFolderById(Int64 id) public ActionResult<Folder> GetFolderById(Int64 id, Token authToken)
{ {
var user = GetSession()?.User; var user = Db.GetSession(authToken)?.User;
if (user == null) if (user == null)
return Unauthorized(); return Unauthorized();
@ -130,9 +137,9 @@ public class Controller : ControllerBase
[HttpGet(nameof(GetAllInstallations))] [HttpGet(nameof(GetAllInstallations))]
public ActionResult<IEnumerable<Installation>> GetAllInstallations() public ActionResult<IEnumerable<Installation>> GetAllInstallations(Token authToken)
{ {
var user = GetSession()?.User; var user = Db.GetSession(authToken)?.User;
if (user is null) if (user is null)
return Unauthorized(); return Unauthorized();
@ -143,9 +150,9 @@ public class Controller : ControllerBase
[HttpGet(nameof(GetAllFolders))] [HttpGet(nameof(GetAllFolders))]
public ActionResult<IEnumerable<Folder>> GetAllFolders() public ActionResult<IEnumerable<Folder>> GetAllFolders(Token authToken)
{ {
var user = GetSession()?.User; var user = Db.GetSession(authToken)?.User;
if (user is null) if (user is null)
return Unauthorized(); return Unauthorized();
@ -155,9 +162,9 @@ public class Controller : ControllerBase
[HttpGet(nameof(GetAllFoldersAndInstallations))] [HttpGet(nameof(GetAllFoldersAndInstallations))]
public ActionResult<IEnumerable<TreeNode>> GetAllFoldersAndInstallations() public ActionResult<IEnumerable<TreeNode>> GetAllFoldersAndInstallations(Token authToken)
{ {
var user = GetSession()?.User; var user = Db.GetSession(authToken)?.User;
if (user is null) if (user is null)
return Unauthorized(); return Unauthorized();
@ -167,26 +174,26 @@ public class Controller : ControllerBase
[HttpPost(nameof(CreateUser))] [HttpPost(nameof(CreateUser))]
public ActionResult<User> CreateUser(User newUser) public ActionResult<User> CreateUser(User newUser, Token authToken)
{ {
return GetSession().Create(newUser) return Db.GetSession(authToken).Create(newUser)
? newUser ? newUser
: Unauthorized() ; : Unauthorized() ;
} }
[HttpPost(nameof(CreateInstallation))] [HttpPost(nameof(CreateInstallation))]
public async Task<ActionResult<Installation>> CreateInstallation(Installation installation) public async Task<ActionResult<Installation>> CreateInstallation(Installation installation, Token authToken)
{ {
if (!await GetSession().Create(installation)) if (!await Db.GetSession(authToken).Create(installation))
return Unauthorized(); return Unauthorized();
return installation; return installation;
} }
[HttpPost(nameof(CreateFolder))] [HttpPost(nameof(CreateFolder))]
public ActionResult<Folder> CreateFolder(Folder folder) public ActionResult<Folder> CreateFolder(Folder folder, Token authToken)
{ {
var session = GetSession(); var session = Db.GetSession(authToken);
if (!session.Create(folder)) if (!session.Create(folder))
return Unauthorized(); return Unauthorized();
@ -195,9 +202,9 @@ public class Controller : ControllerBase
} }
[HttpPost(nameof(GrantUserAccessToFolder))] [HttpPost(nameof(GrantUserAccessToFolder))]
public ActionResult GrantUserAccessToFolder(FolderAccess folderAccess) public ActionResult GrantUserAccessToFolder(FolderAccess folderAccess, Token authToken)
{ {
var session = GetSession(); var session = Db.GetSession(authToken);
// TODO: automatic BadRequest when properties are null during deserialization // TODO: automatic BadRequest when properties are null during deserialization
var folder = Db.GetFolderById(folderAccess.FolderId); var folder = Db.GetFolderById(folderAccess.FolderId);
@ -210,9 +217,9 @@ public class Controller : ControllerBase
[HttpPost(nameof(RevokeUserAccessToFolder))] [HttpPost(nameof(RevokeUserAccessToFolder))]
public ActionResult RevokeUserAccessToFolder(FolderAccess folderAccess) public ActionResult RevokeUserAccessToFolder(FolderAccess folderAccess, Token authToken)
{ {
var session = GetSession(); var session = Db.GetSession(authToken);
// TODO: automatic BadRequest when properties are null during deserialization // TODO: automatic BadRequest when properties are null during deserialization
var folder = Db.GetFolderById(folderAccess.FolderId); var folder = Db.GetFolderById(folderAccess.FolderId);
@ -225,9 +232,9 @@ public class Controller : ControllerBase
[HttpPost(nameof(GrantUserAccessToInstallation))] [HttpPost(nameof(GrantUserAccessToInstallation))]
public ActionResult GrantUserAccessToInstallation(InstallationAccess installationAccess) public ActionResult GrantUserAccessToInstallation(InstallationAccess installationAccess, Token authToken)
{ {
var session = GetSession(); var session = Db.GetSession(authToken);
// TODO: automatic BadRequest when properties are null during deserialization // TODO: automatic BadRequest when properties are null during deserialization
var installation = Db.GetFolderById(installationAccess.InstallationId); var installation = Db.GetFolderById(installationAccess.InstallationId);
@ -239,9 +246,9 @@ public class Controller : ControllerBase
} }
[HttpPost(nameof(RevokeUserAccessToInstallation))] [HttpPost(nameof(RevokeUserAccessToInstallation))]
public ActionResult RevokeUserAccessToInstallation(InstallationAccess installationAccess) public ActionResult RevokeUserAccessToInstallation(InstallationAccess installationAccess, Token authToken)
{ {
var session = GetSession(); var session = Db.GetSession(authToken);
// TODO: automatic BadRequest when properties are null during deserialization // TODO: automatic BadRequest when properties are null during deserialization
var installation = Db.GetFolderById(installationAccess.InstallationId); var installation = Db.GetFolderById(installationAccess.InstallationId);
@ -255,9 +262,9 @@ public class Controller : ControllerBase
[HttpPut(nameof(UpdateUser))] [HttpPut(nameof(UpdateUser))]
public ActionResult<User> UpdateUser(User updatedUser) public ActionResult<User> UpdateUser(User updatedUser, Token authToken)
{ {
var session = GetSession(); var session = Db.GetSession(authToken);
if (!session.Update(updatedUser)) if (!session.Update(updatedUser))
return Unauthorized(); return Unauthorized();
@ -269,9 +276,9 @@ public class Controller : ControllerBase
[HttpPut(nameof(UpdateInstallation))] [HttpPut(nameof(UpdateInstallation))]
public ActionResult<Installation> UpdateInstallation(Installation installation) public ActionResult<Installation> UpdateInstallation(Installation installation, Token authToken)
{ {
var session = GetSession(); var session = Db.GetSession(authToken);
if (!session.Update(installation)) if (!session.Update(installation))
return Unauthorized(); return Unauthorized();
@ -281,9 +288,9 @@ public class Controller : ControllerBase
[HttpPut(nameof(UpdateFolder))] [HttpPut(nameof(UpdateFolder))]
public ActionResult<Folder> UpdateFolder(Folder folder) public ActionResult<Folder> UpdateFolder(Folder folder, Token authToken)
{ {
var session = GetSession(); var session = Db.GetSession(authToken);
if (!session.Update(folder)) if (!session.Update(folder))
return Unauthorized(); return Unauthorized();
@ -292,9 +299,9 @@ public class Controller : ControllerBase
} }
[HttpDelete(nameof(DeleteUser))] [HttpDelete(nameof(DeleteUser))]
public ActionResult DeleteUser(Int64 userId) public ActionResult DeleteUser(Int64 userId, Token authToken)
{ {
var session = GetSession(); var session = Db.GetSession(authToken);
var user = Db.GetUserById(userId); var user = Db.GetUserById(userId);
return session.Delete(user) return session.Delete(user)
@ -303,9 +310,9 @@ public class Controller : ControllerBase
} }
[HttpDelete(nameof(DeleteInstallation))] [HttpDelete(nameof(DeleteInstallation))]
public ActionResult DeleteInstallation(Int64 installationId) public ActionResult DeleteInstallation(Int64 installationId, Token authToken)
{ {
var session = GetSession(); var session = Db.GetSession(authToken);
var installation = Db.GetInstallationById(installationId); var installation = Db.GetInstallationById(installationId);
return session.Delete(installation) return session.Delete(installation)
@ -314,11 +321,10 @@ public class Controller : ControllerBase
} }
[HttpDelete(nameof(DeleteFolder))] [HttpDelete(nameof(DeleteFolder))]
public ActionResult DeleteFolder(Int64 folderId) public ActionResult DeleteFolder(Int64 folderId, Token authToken)
{ {
var session = GetSession(); var session = Db.GetSession(authToken);
var folder = Db.GetFolderById(folderId);
var folder = Db.GetFolderById(folderId);
return session.Delete(folder) return session.Delete(folder)
? Ok() ? Ok()
@ -326,11 +332,7 @@ public class Controller : ControllerBase
} }
private static Session? GetSession()
{
var ctxAccessor = new HttpContextAccessor();
return ctxAccessor.HttpContext?.Items["Session"] as Session;
}
} }

View File

@ -1,6 +0,0 @@
using System.Diagnostics.CodeAnalysis;
namespace InnovEnergy.App.Backend.DataTypes;
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)]
public record Credentials(String Username, String Password);

View File

@ -1,27 +0,0 @@
using InnovEnergy.App.Backend.Database;
using InnovEnergy.App.Backend.Relations;
using InnovEnergy.Lib.Utils;
namespace InnovEnergy.App.Backend.DataTypes.Methods;
public static class CredentialsMethods
{
public static Session? Login(this Credentials credentials)
{
var (username, password) = credentials;
if (username.IsNullOrEmpty() || password.IsNullOrEmpty())
return null;
var user = Db.GetUserByEmail(username);
if (user is null || !user.VerifyPassword(password))
return null;
var session = new Session(user);
return Db.Create(session)
? session
: null;
}
}

View File

@ -1,4 +1,3 @@
using InnovEnergy.App.Backend.Database;
using Microsoft.OpenApi.Models; using Microsoft.OpenApi.Models;
namespace InnovEnergy.App.Backend; namespace InnovEnergy.App.Backend;
@ -10,53 +9,48 @@ public static class Program
//Db.CreateFakeRelations(); //Db.CreateFakeRelations();
var builder = WebApplication.CreateBuilder(args); var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers(); //builder.Services.AddHttpContextAccessor();
builder.Services.AddHttpContextAccessor(); //builder.Services.AddEndpointsApiExplorer();
builder.Services.AddEndpointsApiExplorer(); //builder.Services.AddCors(o => o.AddDefaultPolicy(p => p.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod()));
builder.Services.AddCors(o => o.AddDefaultPolicy(p => p.WithOrigins("*").AllowAnyHeader().AllowAnyMethod()));
builder.Services.AddControllers();
builder.Services.AddSwaggerGen(c => builder.Services.AddSwaggerGen(c =>
{ {
c.SwaggerDoc("v1", new OpenApiInfo { Title = "InnovEnergy Backend API", Version = "v1" }); c.SwaggerDoc("v1", OpenApiInfo);
c.UseAllOfToExtendReferenceSchemas(); c.UseAllOfToExtendReferenceSchemas();
c.OperationFilter<HeaderFilter>(); //Todo testing throw me out
c.SupportNonNullableReferenceTypes(); c.SupportNonNullableReferenceTypes();
}); });
var app = builder.Build(); var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment()) if (app.Environment.IsDevelopment())
{ {
app.UseSwagger(); app.UseSwagger();
app.UseSwaggerUI(cfg => cfg.EnableFilter()); app.UseSwaggerUI();
} }
app.UseCors(); app.UseCors(p => p.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod()) ;
app.UseHttpsRedirection(); app.UseHttpsRedirection();
app.UseAuthorization(); //app.UseAuthorization();
app.Use(SetSessionUser);
app.MapControllers(); app.MapControllers();
app.Run(); app.Run();
} }
private static OpenApiInfo OpenApiInfo { get; } = new OpenApiInfo
private static async Task SetSessionUser(HttpContext ctx, RequestDelegate next)
{ {
var headers = ctx.Request.Headers; Title = "InnovEnergy Backend API",
var hasToken = headers.TryGetValue("auth", out var token) ; Version = "v1"
};
if (hasToken) }
{
var session = Db.GetSession(token);
if (session is not null)
ctx.Items["Session"] = session;
}
await next(ctx); // var x = new CorsPolicy
} // {
} // Headers = { "*" },
// Origins = { "*" },
// Methods = { "*" }
// };