using System; using System.Collections.Generic; using System.IO; using System.Security.Claims; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Dough.Models; using Dough.Models.Database; using Dough.Models.Payloads; using Dough.Models.Results; using Dough.Services; using Dough.Utilities; using IdentityServer4; using IdentityServer4.Services; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Http; namespace Dough.Controllers { [AllowAnonymous] public class AccountController : BaseController { private readonly MainDbContext _context; private readonly IIdentityServerInteractionService _interaction; private readonly EmailService _emailService; public AccountController(MainDbContext context, IIdentityServerInteractionService interaction, EmailService emailService) { _context = context; _interaction = interaction; _emailService = emailService; } [HttpGet("login")] public ActionResult GetLogin() { var pathToLoginFile = Path.Combine(Directory.GetCurrentDirectory(), "AppData", "login.html"); var fileContent = System.IO.File.ReadAllText(pathToLoginFile); return Content(fileContent, "text/html"); } [HttpPost("login")] [ValidateAntiForgeryToken] public async Task PostLogin(LoginPayload payload) { if (!_interaction.IsValidReturnUrl(payload.ReturnUrl)) return BadRequest(new ErrorResult()); var user = _context.Users.SingleByNameOrDefault(payload.Username); if (user == default) { await Task.Delay(1500); return BadRequest(new ErrorResult("Username or password is incorrect","Please try again with a different username and/or password")); } if (!user.VerifyPassword(payload.Password)) { await Task.Delay(1000); return BadRequest(new ErrorResult("Username or password is incorrect","Please try again with a different username and/or password")); } var props = new AuthenticationProperties { AllowRefresh = true, IssuedUtc = DateTime.UtcNow, }; if (payload.Persist) { props.IsPersistent = true; props.ExpiresUtc = DateTime.UtcNow.AddDays(15); } var identityServerUser = new IdentityServerUser(user.Id.ToString()) { DisplayName = user.Username, AuthenticationTime = DateTime.UtcNow, }; await HttpContext.SignInAsync(identityServerUser, props); return Ok(payload.ReturnUrl); } [HttpGet("forgot")] public async Task ForgotPassword(string username) { var user = _context.Users.SingleByNameOrDefault(username); if (user == default) return Ok(); return Ok(); } [Authorize] [HttpGet("me")] public ActionResult GetClaimsForUser() { return Ok(LoggedInUser); } } }