Added password reset form (#336)

* Added password reset form

* added using to commentsPartial

without this i was experiencing an error when browsing to my profile page

* (Hopefully) final password reset form

* Update ProjectLighthouse.Servers.Website/Pages/PasswordResetPage.cshtml.cs

Co-authored-by: Jayden <jvyden@jvyden.xyz>

* Update ProjectLighthouse.Servers.Website/Pages/PasswordResetRequestForm.cshtml

Co-authored-by: Jayden <jvyden@jvyden.xyz>

* Update ProjectLighthouse.Servers.Website/Pages/PasswordResetRequestForm.cshtml

Co-authored-by: Jayden <jvyden@jvyden.xyz>

* Update ProjectLighthouse.Servers.Website/Pages/PasswordResetRequestForm.cshtml.cs

Co-authored-by: Jayden <jvyden@jvyden.xyz>

* Update ProjectLighthouse.Servers.Website/Pages/PasswordResetRequestForm.cshtml.cs

Co-authored-by: Jayden <jvyden@jvyden.xyz>

* Update ProjectLighthouse.Servers.Website/Pages/PasswordResetRequestForm.cshtml.cs

Co-authored-by: Jayden <jvyden@jvyden.xyz>

* Update ProjectLighthouse/Database.cs

Co-authored-by: Jayden <jvyden@jvyden.xyz>

* Update ProjectLighthouse.Servers.Website/Pages/LoginForm.cshtml

Co-authored-by: Jayden <jvyden@jvyden.xyz>

* Stopped leaking user email addresses

* Made UserFromPasswordResetToken async

* Made UserFromPasswordResetToken async

* Indented login form row div

* Fix AddedPasswordResetTokens migration not having proper attributes

* Adjust password reset email text

* Clean up password reset request form

Co-authored-by: Jayden <jvyden@jvyden.xyz>
This commit is contained in:
Zaprit 2022-06-25 21:30:10 +01:00 committed by GitHub
commit 0b27969a22
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
10 changed files with 256 additions and 12 deletions

View file

@ -54,15 +54,23 @@
{ {
@await Html.PartialAsync("Partials/CaptchaPartial") @await Html.PartialAsync("Partials/CaptchaPartial")
} }
<input type="submit" value="Log in" id="submit" class="ui blue button"> <div class="row">
@if (ServerConfiguration.Instance.Authentication.RegistrationEnabled) <input type="submit" value="Log in" id="submit" class="ui blue button">
{ @if (ServerConfiguration.Instance.Authentication.RegistrationEnabled)
<a href="/register"> {
<a href="/register">
<div class="ui button">
<i class="user alternate add icon"></i>
Register
</div>
</a>
}
</div>
<br/>
<a href="/passwordResetRequest">
<div class="ui button"> <div class="ui button">
<i class="user alternate add icon"></i> Forgot Password?
Register
</div> </div>
</a> </a>
}
</form> </form>

View file

@ -1,4 +1,5 @@
@using System.Web @using System.Web
@using System.IO
@using LBPUnion.ProjectLighthouse.PlayerData.Profiles @using LBPUnion.ProjectLighthouse.PlayerData.Profiles
<div class="ui yellow segment" id="comments"> <div class="ui yellow segment" id="comments">
<h2>Comments</h2> <h2>Comments</h2>

View file

@ -4,7 +4,6 @@ using LBPUnion.ProjectLighthouse.Configuration;
using LBPUnion.ProjectLighthouse.Helpers; using LBPUnion.ProjectLighthouse.Helpers;
using LBPUnion.ProjectLighthouse.PlayerData.Profiles; using LBPUnion.ProjectLighthouse.PlayerData.Profiles;
using LBPUnion.ProjectLighthouse.Servers.Website.Pages.Layouts; using LBPUnion.ProjectLighthouse.Servers.Website.Pages.Layouts;
using LBPUnion.ProjectLighthouse.Types;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
namespace LBPUnion.ProjectLighthouse.Servers.Website.Pages; namespace LBPUnion.ProjectLighthouse.Servers.Website.Pages;
@ -19,8 +18,21 @@ public class PasswordResetPage : BaseLayout
[UsedImplicitly] [UsedImplicitly]
public async Task<IActionResult> OnPost(string password, string confirmPassword) public async Task<IActionResult> OnPost(string password, string confirmPassword)
{ {
User? user = this.Database.UserFromWebRequest(this.Request); User? user;
if (user == null) return this.Redirect("~/login"); if (Request.Query.ContainsKey("token"))
{
user = await this.Database.UserFromPasswordResetToken(Request.Query["token"][0]);
if (user == null)
{
this.Error = "This password reset link either is invalid or has expired. Please try again.";
return this.Page();
}
}
else
{
user = this.Database.UserFromWebRequest(this.Request);
if (user == null) return this.Redirect("~/login");
}
if (string.IsNullOrWhiteSpace(password)) if (string.IsNullOrWhiteSpace(password))
{ {
@ -48,6 +60,8 @@ public class PasswordResetPage : BaseLayout
[UsedImplicitly] [UsedImplicitly]
public IActionResult OnGet() public IActionResult OnGet()
{ {
if (this.Request.Query.ContainsKey("token")) return this.Page();
User? user = this.Database.UserFromWebRequest(this.Request); User? user = this.Database.UserFromWebRequest(this.Request);
if (user == null) return this.Redirect("~/login"); if (user == null) return this.Redirect("~/login");

View file

@ -0,0 +1,34 @@
@page "/passwordResetRequest"
@model LBPUnion.ProjectLighthouse.Servers.Website.Pages.PasswordResetRequestForm
@{
Layout = "Layouts/BaseLayout";
Model.Title = "Password Reset";
}
@if (!string.IsNullOrWhiteSpace(Model.Error))
{
<div class="ui negative message">
<div class="header">
Uh oh!
</div>
<p style="white-space: pre-line">@Model.Error</p>
</div>
}
@if (!string.IsNullOrWhiteSpace(Model.Status))
{
<div class="ui positive message">
<div class="header">
Success!
</div>
<p style="white-space: pre-line">@Model.Status</p>
</div>
}
<form class="ui form" method="post">
@Html.AntiForgeryToken()
<input type="text" autocomplete="no" id="username" placeholder="Username" name="username"/><br/><br/>
<input type="submit" value="Request Password Reset" class="ui blue button"/>
</form>

View file

@ -0,0 +1,67 @@
using JetBrains.Annotations;
using LBPUnion.ProjectLighthouse.Configuration;
using LBPUnion.ProjectLighthouse.Helpers;
using LBPUnion.ProjectLighthouse.PlayerData;
using LBPUnion.ProjectLighthouse.PlayerData.Profiles;
using LBPUnion.ProjectLighthouse.Servers.Website.Pages.Layouts;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
namespace LBPUnion.ProjectLighthouse.Servers.Website.Pages;
public class PasswordResetRequestForm : BaseLayout
{
public string? Error { get; private set; }
public string? Status { get; private set; }
public PasswordResetRequestForm(Database database) : base(database)
{ }
[UsedImplicitly]
public async Task<IActionResult> OnPost(string username)
{
if (!ServerConfiguration.Instance.Mail.MailEnabled)
{
this.Error = "Email is not configured on this server, so password resets cannot be issued. Please contact your instance administrator for more details.";
return this.Page();
}
if (string.IsNullOrWhiteSpace(username))
{
this.Error = "The username field is required.";
return this.Page();
}
User? user = await this.Database.Users.FirstOrDefaultAsync(u => u.Username == username);
if (user == null)
{
this.Error = "User does not exist.";
return this.Page();
}
PasswordResetToken token = new()
{
Created = DateTime.Now,
UserId = user.UserId,
ResetToken = CryptoHelper.GenerateAuthToken(),
};
string messageBody = $"Hello, {user.Username}.\n\n" +
"A request to reset your account's password was issued. If this wasn't you, this can probably be ignored.\n\n" +
$"If this was you, your {ServerConfiguration.Instance.Customization.ServerName} password can be reset at the following link:\n" +
$"{ServerConfiguration.Instance.ExternalUrl}/passwordReset?token={token.ResetToken}";
SMTPHelper.SendEmail(user.EmailAddress, $"Project Lighthouse Password Reset Request for {user.Username}", messageBody);
this.Database.PasswordResetTokens.Add(token);
await this.Database.SaveChangesAsync();
this.Status = $"Password reset email sent to {CensorHelper.MaskEmail(user.EmailAddress)}.";
return this.Page();
}
public void OnGet() => this.Page();
}

View file

@ -46,6 +46,7 @@ public class Database : DbContext
public DbSet<GriefReport> Reports { get; set; } public DbSet<GriefReport> Reports { get; set; }
public DbSet<EmailVerificationToken> EmailVerificationTokens { get; set; } public DbSet<EmailVerificationToken> EmailVerificationTokens { get; set; }
public DbSet<EmailSetToken> EmailSetTokens { get; set; } public DbSet<EmailSetToken> EmailSetTokens { get; set; }
public DbSet<PasswordResetToken> PasswordResetTokens { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder options) protected override void OnConfiguring(DbContextOptionsBuilder options)
=> options.UseMySql(ServerConfiguration.Instance.DbConnectionString, MySqlServerVersion.LatestSupportedServerVersion); => options.UseMySql(ServerConfiguration.Instance.DbConnectionString, MySqlServerVersion.LatestSupportedServerVersion);
@ -358,6 +359,27 @@ public class Database : DbContext
#endregion #endregion
#region Password Reset Token
public async Task<User?> UserFromPasswordResetToken(string resetToken)
{
PasswordResetToken? token = await this.PasswordResetTokens.FirstOrDefaultAsync(token => token.ResetToken == resetToken);
if (token == null)
{
return null;
}
if (token.Created < DateTime.Now.AddHours(-1)) // if token is expired
{
this.PasswordResetTokens.Remove(token);
return null;
}
return await this.Users.FirstOrDefaultAsync(user => user.UserId == token.UserId);
}
#endregion
public async Task<Photo?> PhotoFromSubject(PhotoSubject subject) public async Task<Photo?> PhotoFromSubject(PhotoSubject subject)
=> await this.Photos.FirstOrDefaultAsync(p => p.PhotoSubjectIds.Contains(subject.PhotoSubjectId.ToString())); => await this.Photos.FirstOrDefaultAsync(p => p.PhotoSubjectIds.Contains(subject.PhotoSubjectId.ToString()));
public async Task RemoveUser(User? user) public async Task RemoveUser(User? user)

View file

@ -1,4 +1,5 @@
using System; using System;
using System.IO;
using System.Text; using System.Text;
using LBPUnion.ProjectLighthouse.Configuration; using LBPUnion.ProjectLighthouse.Configuration;
using LBPUnion.ProjectLighthouse.Types; using LBPUnion.ProjectLighthouse.Types;
@ -94,4 +95,23 @@ public static class CensorHelper
return sb.ToString(); return sb.ToString();
} }
public static string MaskEmail(string email)
{
if (string.IsNullOrEmpty(email) || !email.Contains('@')) return email;
string[] emailArr = email.Split('@');
string domainExt = Path.GetExtension(email);
string maskedEmail = string.Format("{0}****{1}@{2}****{3}{4}",
emailArr[0][0],
emailArr[0].Substring(emailArr[0].Length - 1),
emailArr[1][0],
emailArr[1]
.Substring(emailArr[1].Length - domainExt.Length - 1,
1),
domainExt);
return maskedEmail;
}
} }

View file

@ -0,0 +1,41 @@
using System;
using LBPUnion.ProjectLighthouse;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace ProjectLighthouse.Migrations
{
[DbContext(typeof(Database))]
[Migration("20220624210701_AddedPasswordResetTokens")]
public partial class AddedPasswordResetTokens : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "PasswordResetTokens",
columns: table => new
{
TokenId = table.Column<int>(type: "int", nullable: false)
.Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn),
UserId = table.Column<int>(type: "int", nullable: false),
ResetToken = table.Column<string>(type: "longtext", nullable: true)
.Annotation("MySql:CharSet", "utf8mb4"),
Created = table.Column<DateTime>(type: "datetime(6)", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_PasswordResetTokens", x => x.TokenId);
})
.Annotation("MySql:CharSet", "utf8mb4");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "PasswordResetTokens");
}
}
}

View file

@ -16,7 +16,7 @@ namespace ProjectLighthouse.Migrations
{ {
#pragma warning disable 612, 618 #pragma warning disable 612, 618
modelBuilder modelBuilder
.HasAnnotation("ProductVersion", "6.0.5") .HasAnnotation("ProductVersion", "6.0.6")
.HasAnnotation("Relational:MaxIdentifierLength", 64); .HasAnnotation("Relational:MaxIdentifierLength", 64);
modelBuilder.Entity("LBPUnion.ProjectLighthouse.Administration.CompletedMigration", b => modelBuilder.Entity("LBPUnion.ProjectLighthouse.Administration.CompletedMigration", b =>
@ -390,6 +390,26 @@ namespace ProjectLighthouse.Migrations
b.ToTable("GameTokens"); b.ToTable("GameTokens");
}); });
modelBuilder.Entity("LBPUnion.ProjectLighthouse.PlayerData.PasswordResetToken", b =>
{
b.Property<int>("TokenId")
.ValueGeneratedOnAdd()
.HasColumnType("int");
b.Property<DateTime>("Created")
.HasColumnType("datetime(6)");
b.Property<string>("ResetToken")
.HasColumnType("longtext");
b.Property<int>("UserId")
.HasColumnType("int");
b.HasKey("TokenId");
b.ToTable("PasswordResetTokens");
});
modelBuilder.Entity("LBPUnion.ProjectLighthouse.PlayerData.Photo", b => modelBuilder.Entity("LBPUnion.ProjectLighthouse.PlayerData.Photo", b =>
{ {
b.Property<int>("PhotoId") b.Property<int>("PhotoId")

View file

@ -0,0 +1,17 @@
using System;
using System.ComponentModel.DataAnnotations;
namespace LBPUnion.ProjectLighthouse.PlayerData;
public class PasswordResetToken
{
// ReSharper disable once UnusedMember.Global
[Key]
public int TokenId { get; set; }
public int UserId { get; set; }
public string ResetToken { get; set; }
public DateTime Created { get; set; }
}