From 88110f536f9c3843ecf5016122e101f8a424af77 Mon Sep 17 00:00:00 2001 From: ivarlovlie Date: Sat, 22 Jan 2022 22:43:38 +0100 Subject: Initial commit --- .../Api/Internal/Account/CreateSessionRoute.cs | 41 ++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 src/server/Api/Internal/Account/CreateSessionRoute.cs (limited to 'src/server/Api/Internal/Account/CreateSessionRoute.cs') diff --git a/src/server/Api/Internal/Account/CreateSessionRoute.cs b/src/server/Api/Internal/Account/CreateSessionRoute.cs new file mode 100644 index 0000000..09e05b6 --- /dev/null +++ b/src/server/Api/Internal/Account/CreateSessionRoute.cs @@ -0,0 +1,41 @@ +namespace IOL.BookmarkThing.Server.Api.Internal.Account; + +public class CreateSessionRoute : RouteBaseInternalAsync.WithRequest.WithActionResult +{ + private readonly AppDbContext _context; + + public CreateSessionRoute(AppDbContext context) { + _context = context; + } + + [AllowAnonymous] + [ApiVersionNeutral] + [ApiExplorerSettings(IgnoreApi = true)] + [HttpPost("~/v{version:apiVersion}/account/create-session")] + public override async Task HandleAsync(CreateSessionRequest payload, CancellationToken cancellationToken = default) { + var user = _context.Users.SingleOrDefault(u => u.Username == payload.Username); + if (user == default || !user.VerifyPassword(payload.Password)) { + return BadRequest(new ErrorResult("Invalid username or password")); + } + + var claims = user.DefaultClaims(); + var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme); + var principal = new ClaimsPrincipal(identity); + var authenticationProperties = new AuthenticationProperties { + AllowRefresh = true, + IssuedUtc = DateTimeOffset.UtcNow, + }; + + if (payload.Persist) { + authenticationProperties.ExpiresUtc = DateTimeOffset.UtcNow.AddYears(100); + authenticationProperties.IsPersistent = true; + } + + await HttpContext.SignInAsync(principal, authenticationProperties); + // Return new LoggedInInternalUser here, because it is not materialised in AppControllerBase yet. + return Ok(new LoggedInInternalUser { + Id = user.Id, + Username = user.Username + }); + } +} -- cgit v1.3