using System.Security.Claims; using CodeLiturgy.Data.Application.Users; using CodeLiturgy.Data.Auth; using CodeLiturgy.Data.Auth.Context.Users; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using Controller = Microsoft.AspNetCore.Mvc.Controller; namespace CodeLiturgy.Views.Controllers { public class AuthController : LoggedInUserController { private readonly IAuthManager _authManager; public AuthController( ApplicationUserManager userManager, ILogger logger, IAuthManager authManager) : base(userManager, logger) { _userManager = userManager; _logger = logger; _authManager = authManager; } public async Task Index() { await OnEveryAction(); return View(); } [AllowAnonymous] [ActionName("LoginAction")] public async Task LoginAction(LoginRequest loginRequest) { var (identity,success) = await _authManager.DoLogin(loginRequest); if (!success) return Redirect(AuthLoginRoute); if (success) { await HttpContext.SignInAsync( CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(identity), new AuthenticationProperties { IsPersistent = true, ExpiresUtc = DateTime.UtcNow.Add(SessionConstants.DefaultSessionMaxAge) }); HttpContext.Session.SetString("hello", "world"); return Redirect(RootLocation); } return Redirect(RootLocation); } public async Task Login() { #if DEBUG // Check if the debug user exists, if not create it if (!await _userManager.Users.AnyAsync(x => x.Email == "debuguser@admin.com")) { var registerRequest = new RegisterRequest(); registerRequest.Email = "debuguser@admin.com"; registerRequest.Username = "debuguser"; registerRequest.Password = "debuguser"; await _authManager.CreateUserAsync(registerRequest); } var (identity,success) = await _authManager.DoLogin(new LoginRequest{Email = "debuguser@admin.com", Password = "debuguser"}); await HttpContext.SignInAsync( CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(identity), new AuthenticationProperties { IsPersistent = true, ExpiresUtc = DateTime.UtcNow.Add(SessionConstants.DefaultSessionMaxAge) }); HttpContext.Session.SetString("hello", "world"); return Redirect(RootLocation); #else this.HandleGlobalization(); return View(); #endif } public async Task Account() { await OnEveryAction(); this.HandleGlobalization(); return View(); } public async Task Logout() { await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme); return Redirect("/"); } public async Task Signup() { await OnEveryAction(); return View(); } [Microsoft.AspNetCore.Mvc.ActionName("SignupAction")] public async Task SignupAction(RegisterRequest registerRequest) { var result = await _authManager.CreateUserAsync(registerRequest); if (result.Succeeded) { return RedirectToAction("Login"); } return RedirectToAction("Signup"); } } }