This commit is contained in:
Elijah R 2024-04-04 00:57:59 -04:00
commit b626220fd3
17 changed files with 35217 additions and 0 deletions

400
.gitignore vendored Normal file
View file

@ -0,0 +1,400 @@
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
##
## Get latest from https://github.com/github/gitignore/blob/main/VisualStudio.gitignore
# User-specific files
*.rsuser
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Mono auto generated files
mono_crash.*
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
[Ww][Ii][Nn]32/
[Aa][Rr][Mm]/
[Aa][Rr][Mm]64/
bld/
[Bb]in/
[Oo]bj/
[Ll]og/
[Ll]ogs/
# Visual Studio 2015/2017 cache/options directory
.vs/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/
# Visual Studio 2017 auto generated files
Generated\ Files/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUnit
*.VisualState.xml
TestResult.xml
nunit-*.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
# Benchmark Results
BenchmarkDotNet.Artifacts/
# .NET Core
project.lock.json
project.fragment.lock.json
artifacts/
# ASP.NET Scaffolding
ScaffoldingReadMe.txt
# StyleCop
StyleCopReport.xml
# Files built by Visual Studio
*_i.c
*_p.c
*_h.h
*.ilk
*.meta
*.obj
*.iobj
*.pch
*.pdb
*.ipdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*_wpftmp.csproj
*.log
*.tlog
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc
# Chutzpah Test files
_Chutzpah*
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opendb
*.opensdf
*.sdf
*.cachefile
*.VC.db
*.VC.VC.opendb
# Visual Studio profiler
*.psess
*.vsp
*.vspx
*.sap
# Visual Studio Trace Files
*.e2e
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# AxoCover is a Code Coverage Tool
.axoCover/*
!.axoCover/settings.json
# Coverlet is a free, cross platform Code Coverage Tool
coverage*.json
coverage*.xml
coverage*.info
# Visual Studio code coverage results
*.coverage
*.coveragexml
# NCrunch
_NCrunch_*
.*crunch*.local.xml
nCrunchTemp_*
# MightyMoose
*.mm.*
AutoTest.Net/
# Web workbench (sass)
.sass-cache/
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# Note: Comment the next line if you want to checkin your web deploy settings,
# but database connection strings (with potential passwords) will be unencrypted
*.pubxml
*.publishproj
# Microsoft Azure Web App publish settings. Comment the next line if you want to
# checkin your Azure Web App publish settings, but sensitive information contained
# in these scripts will be unencrypted
PublishScripts/
# NuGet Packages
*.nupkg
# NuGet Symbol Packages
*.snupkg
# The packages folder can be ignored because of Package Restore
**/[Pp]ackages/*
# except build/, which is used as an MSBuild target.
!**/[Pp]ackages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/[Pp]ackages/repositories.config
# NuGet v3's project.json files produces more ignorable files
*.nuget.props
*.nuget.targets
# Microsoft Azure Build Output
csx/
*.build.csdef
# Microsoft Azure Emulator
ecf/
rcf/
# Windows Store app package directories and files
AppPackages/
BundleArtifacts/
Package.StoreAssociation.xml
_pkginfo.txt
*.appx
*.appxbundle
*.appxupload
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!?*.[Cc]ache/
# Others
ClientBin/
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.jfm
*.pfx
*.publishsettings
orleans.codegen.cs
# Including strong name files can present a security risk
# (https://github.com/github/gitignore/pull/2483#issue-259490424)
#*.snk
# Since there are multiple workflows, uncomment next line to ignore bower_components
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
#bower_components/
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
ServiceFabricBackup/
*.rptproj.bak
# SQL Server files
*.mdf
*.ldf
*.ndf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
*.rptproj.rsuser
*- [Bb]ackup.rdl
*- [Bb]ackup ([0-9]).rdl
*- [Bb]ackup ([0-9][0-9]).rdl
# Microsoft Fakes
FakesAssemblies/
# GhostDoc plugin setting file
*.GhostDoc.xml
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
node_modules/
# Visual Studio 6 build log
*.plg
# Visual Studio 6 workspace options file
*.opt
# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
*.vbw
# Visual Studio 6 auto-generated project file (contains which files were open etc.)
*.vbp
# Visual Studio 6 workspace and project file (working project files containing files to include in project)
*.dsw
*.dsp
# Visual Studio 6 technical files
*.ncb
*.aps
# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
**/*.DesktopClient/ModelManifest.xml
**/*.Server/GeneratedArtifacts
**/*.Server/ModelManifest.xml
_Pvt_Extensions
# Paket dependency manager
.paket/paket.exe
paket-files/
# FAKE - F# Make
.fake/
# CodeRush personal settings
.cr/personal
# Python Tools for Visual Studio (PTVS)
__pycache__/
*.pyc
# Cake - Uncomment if you are using it
# tools/**
# !tools/packages.config
# Tabs Studio
*.tss
# Telerik's JustMock configuration file
*.jmconfig
# BizTalk build output
*.btp.cs
*.btm.cs
*.odx.cs
*.xsd.cs
# OpenCover UI analysis results
OpenCover/
# Azure Stream Analytics local run output
ASALocalRun/
# MSBuild Binary and Structured Log
*.binlog
# NVidia Nsight GPU debugger configuration file
*.nvuser
# MFractors (Xamarin productivity tool) working folder
.mfractor/
# Local History for Visual Studio
.localhistory/
# Visual Studio History (VSHistory) files
.vshistory/
# BeatPulse healthcheck temp database
healthchecksdb
# Backup folder for Package Reference Convert tool in Visual Studio 2017
MigrationBackup/
# Ionide (cross platform F# VS Code tools) working folder
.ionide/
# Fody - auto-generated XML schema
FodyWeavers.xsd
# VS Code files for those working on multiple tools
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
*.code-workspace
# Local History for Visual Studio Code
.history/
# Windows Installer files from build outputs
*.cab
*.msi
*.msix
*.msm
*.msp
# JetBrains Rider
*.sln.iml
.idea/
config.toml

16
CollabVMAuthServer.sln Normal file
View file

@ -0,0 +1,16 @@

Microsoft Visual Studio Solution File, Format Version 12.00
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CollabVMAuthServer", "CollabVMAuthServer\CollabVMAuthServer.csproj", "{1DB49726-1720-435F-A912-82349A761813}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{1DB49726-1720-435F-A912-82349A761813}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{1DB49726-1720-435F-A912-82349A761813}.Debug|Any CPU.Build.0 = Debug|Any CPU
{1DB49726-1720-435F-A912-82349A761813}.Release|Any CPU.ActiveCfg = Release|Any CPU
{1DB49726-1720-435F-A912-82349A761813}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
EndGlobal

View file

@ -0,0 +1,13 @@
namespace Computernewb.CollabVMAuthServer;
public class AuthServerInformation
{
public bool registrationOpen { get; set; }
public AuthServerInformationCaptcha hcaptcha { get; set; }
}
public class AuthServerInformationCaptcha
{
public bool required { get; set; }
public string? siteKey { get; set; }
}

View file

@ -0,0 +1,20 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<InvariantGlobalization>true</InvariantGlobalization>
<PublishAot>false</PublishAot>
<RootNamespace>Computernewb.CollabVMAuthServer</RootNamespace>
<Company>Computernewb Development Team</Company>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Isopoh.Cryptography.Argon2" Version="2.0.0" />
<PackageReference Include="MailKit" Version="4.4.0" />
<PackageReference Include="MySqlConnector" Version="2.3.6" />
<PackageReference Include="Samboy063.Tomlet" Version="5.3.1" />
</ItemGroup>
</Project>

View file

@ -0,0 +1,103 @@
using Isopoh.Cryptography.Argon2;
using MySqlConnector;
namespace Computernewb.CollabVMAuthServer;
public class Database
{
private readonly string connectionString;
public Database(MySQLConfig config)
{
connectionString = new MySqlConnectionStringBuilder
{
Server = config.Host,
UserID = config.Username,
Password = config.Password,
Database = config.Database
}.ToString();
}
public async Task Init()
{
await using var conn = new MySqlConnection(connectionString);
await conn.OpenAsync();
await using var cmd = conn.CreateCommand();
cmd.CommandText = """
CREATE TABLE IF NOT EXISTS users (
id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(20) NOT NULL UNIQUE KEY,
password TEXT NOT NULL,
email TEXT NOT NULL UNIQUE KEY,
email_verified BOOLEAN NOT NULL DEFAULT 0,
email_verification_code CHAR(8) DEFAULT NULL,
cvm_rank INT UNSIGNED NOT NULL DEFAULT 0,
banned BOOLEAN NOT NULL DEFAULT 0
);
""";
await cmd.ExecuteNonQueryAsync();
cmd.CommandText = """
CREATE TABLE IF NOT EXISTS sessions (
token CHAR(32) NOT NULL PRIMARY KEY,
username VARCHAR(20) NOT NULL,
created TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
last_used TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (username) REFERENCES users(username) ON UPDATE CASCADE ON DELETE CASCADE
)
""";
await cmd.ExecuteNonQueryAsync();
}
public async Task<User?> GetUser(string? username = null, string? email = null)
{
if (username == null && email == null)
throw new ArgumentException("username or email must be provided");
await using var conn = new MySqlConnection(connectionString);
await conn.OpenAsync();
await using var cmd = conn.CreateCommand();
if (username != null)
{
cmd.CommandText = "SELECT * FROM users WHERE username = @username";
cmd.Parameters.AddWithValue("@username", username);
}
else if (email != null)
{
cmd.CommandText = "SELECT * FROM users WHERE email = @email";
cmd.Parameters.AddWithValue("@email", email);
}
await using var reader = await cmd.ExecuteReaderAsync();
if (!await reader.ReadAsync())
return null;
return new User
{
Id = reader.GetUInt32("id"),
Username = reader.GetString("username"),
Password = reader.GetString("password"),
Email = reader.GetString("email"),
EmailVerified = reader.GetBoolean("email_verified"),
EmailVerificationCode = reader.GetString("email_verification_code"),
Rank = (Rank)reader.GetUInt32("cvm_rank"),
Banned = reader.GetBoolean("banned")
};
}
public async Task RegisterAccount(string username, string email, string password, bool verified,
string? verificationcode = null)
{
await using var db = new MySqlConnection(connectionString);
await db.OpenAsync();
await using var cmd = db.CreateCommand();
cmd.CommandText = """
INSERT INTO users
(username, password, email, email_verified, email_verification_code)
VALUES
(@username, @password, @email, @email_verified, @email_verification_code)
""";
cmd.Parameters.AddWithValue("@username", username);
cmd.Parameters.AddWithValue("@password", Argon2.Hash(password));
cmd.Parameters.AddWithValue("@email", email);
cmd.Parameters.AddWithValue("@email_verified", verified);
cmd.Parameters.AddWithValue("@email_verification_code", verificationcode);
await cmd.ExecuteNonQueryAsync();
}
}

View file

@ -0,0 +1,48 @@
namespace Computernewb.CollabVMAuthServer;
public class IConfig
{
public RegistrationConfig Registration { get; set; }
public HTTPConfig HTTP { get; set; }
public MySQLConfig MySQL { get; set; }
public SMTPConfig SMTP { get; set; }
public hCaptchaConfig hCaptcha { get; set; }
}
public class RegistrationConfig
{
public bool EmailVerificationRequired { get; set; }
public bool EmailDomainWhitelist { get; set; }
public string[] AllowedEmailDomains { get; set; }
}
public class HTTPConfig
{
public string Host { get; set; }
public int Port { get; set; }
}
public class MySQLConfig
{
public string Host { get; set; }
public string Username { get; set; }
public string Password { get; set; }
public string Database { get; set; }
}
public class SMTPConfig
{
public string Host { get; set; }
public int Port { get; set; }
public string Username { get; set; }
public string Password { get; set; }
public string FromName { get; set; }
public string FromEmail { get; set; }
public string VerificationCodeSubject { get; set; }
public string VerificationCodeBody { get; set; }
}
public class hCaptchaConfig
{
public bool Enabled { get; set; }
public string? Secret { get; set; }
public string? SiteKey { get; set; }
}

View file

@ -0,0 +1,38 @@
using MailKit.Net.Smtp;
using MailKit.Security;
using MimeKit;
namespace Computernewb.CollabVMAuthServer;
public class Mailer
{
private SMTPConfig Config;
public Mailer(SMTPConfig config)
{
Config = config;
}
public async Task SendVerificationCode(string username, string email, string code)
{
var message = new MimeMessage();
message.From.Add(new MailboxAddress(Config.FromName, Config.FromEmail));
message.To.Add(new MailboxAddress(username, email));
message.Subject = Config.VerificationCodeSubject
.Replace("$USERNAME", username)
.Replace("$EMAIL", email)
.Replace("$CODE", code);
message.Body = new TextPart("plain")
{
Text = Config.VerificationCodeBody
.Replace("$USERNAME", username)
.Replace("$EMAIL", email)
.Replace("$CODE", code)
};
using var client = new SmtpClient();
await client.ConnectAsync(Config.Host, Config.Port, SecureSocketOptions.StartTlsWhenAvailable);
await client.AuthenticateAsync(Config.Username, Config.Password);
await client.SendAsync(message);
await client.DisconnectAsync(true);
Utilities.Log(LogLevel.INFO, $"Sent verification code to {username} <{email}>");
}
}

View file

@ -0,0 +1,72 @@
using System.Net;
using Tomlet;
namespace Computernewb.CollabVMAuthServer;
public class Program
{
public static IConfig Config { get; private set; }
public static Database Database { get; private set; }
public static hCaptchaClient? hCaptcha { get; private set; }
public static Mailer Mailer { get; private set; }
public static string[] BannedPasswords { get; set; }
public static readonly Random Random = new Random();
public static async Task Main(string[] args)
{
Utilities.Log(LogLevel.INFO, "CollabVM Authentication Server starting up");
// Read config.toml
string configraw;
try
{
configraw = File.ReadAllText("config.toml");
}
catch (Exception ex)
{
Utilities.Log(LogLevel.FATAL, "Failed to read config.toml: " + ex.Message);
Environment.Exit(1);
return;
}
// Parse config.toml to IConfig
try
{
Config = TomletMain.To<IConfig>(configraw);
} catch (Exception ex)
{
Utilities.Log(LogLevel.FATAL, "Failed to parse config.toml: " + ex.Message);
Environment.Exit(1);
return;
}
// Initialize database
Database = new Database(Config.MySQL);
await Database.Init();
Utilities.Log(LogLevel.INFO, "Connected to database");
// Create mailer
Mailer = new Mailer(Config.SMTP);
// Create hCaptcha client
if (Config.hCaptcha.Enabled)
{
hCaptcha = new hCaptchaClient(Config.hCaptcha.Secret!, Config.hCaptcha.SiteKey!);
Utilities.Log(LogLevel.INFO, "hCaptcha enabled");
}
else
{
Utilities.Log(LogLevel.INFO, "hCaptcha disabled");
}
// load password list
BannedPasswords = await File.ReadAllLinesAsync("rockyou.txt");
// Configure web server
var builder = WebApplication.CreateBuilder(args);
#if !DEBUG
builder.Logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Warning);
#endif
builder.WebHost.UseKestrel(k =>
{
k.Listen(IPAddress.Parse(Config.HTTP.Host), Config.HTTP.Port);
});
var app = builder.Build();
app.Lifetime.ApplicationStarted.Register(() => Utilities.Log(LogLevel.INFO, $"Webserver listening on {Config.HTTP.Host}:{Config.HTTP.Port}"));
// Register routes
Routes.RegisterRoutes(app);
app.Run();
}
}

View file

@ -0,0 +1,9 @@
namespace Computernewb.CollabVMAuthServer;
public class RegisterPayload
{
public string username { get; set; }
public string password { get; set; }
public string email { get; set; }
public string? captchaToken { get; set; }
}

View file

@ -0,0 +1,10 @@
namespace Computernewb.CollabVMAuthServer;
public class RegisterResponse
{
public bool success { get; set; }
public string? error { get; set; }
public bool? verificationRequired { get; set; } = null;
public string? username { get; set; }
public string? email { get; set; }
}

View file

@ -0,0 +1,232 @@
using System.ComponentModel.DataAnnotations;
using System.Text.Json;
using System.Text.Json.Serialization;
using Isopoh.Cryptography.Argon2;
namespace Computernewb.CollabVMAuthServer;
public static class Routes
{
public static void RegisterRoutes(WebApplication app)
{
app.MapGet("/api/v1/info", HandleInfo);
app.MapPost("/api/v1/register", (Delegate) HandleRegister);
app.MapPost("/api/v1/verify", (Delegate) HandleVerify);
}
private static async Task<IResult> HandleVerify(HttpContext context)
{
// Check payload
if (context.Request.ContentType != "application/json")
{
context.Response.StatusCode = 400;
return Results.Json(new RegisterResponse
{
success = false,
error = "Invalid request body"
}, Utilities.JsonSerializerOptions);
}
var payload = await context.Request.ReadFromJsonAsync<VerifyPayload>();
if (payload == null || string.IsNullOrWhiteSpace(payload.username) ||
string.IsNullOrWhiteSpace(payload.password) || string.IsNullOrWhiteSpace(payload.password))
{
context.Response.StatusCode = 400;
return Results.Json(new RegisterResponse
{
success = false,
error = "Invalid request body"
}, Utilities.JsonSerializerOptions);
}
// Validate username and password
var user = await Program.Database.GetUser(payload.username);
if (user == null || !Argon2.Verify(user.Password, payload.password))
{
context.Response.StatusCode = 403;
return Results.Json(new RegisterResponse
{
success = false,
error = "Invalid username or password"
}, Utilities.JsonSerializerOptions);
}
// Check if account is verified
if (user.EmailVerified)
{
context.Response.StatusCode = 400;
return Results.Json(new RegisterResponse
{
success = false,
error = "Account is already verified"
}, Utilities.JsonSerializerOptions);
}
// Check if code is correct
if (user.EmailVerificationCode != payload.code)
{
context.Response.StatusCode = 400;
return Results.Json(new RegisterResponse
{
success = false,
error = "Invalid verification code"
}, Utilities.JsonSerializerOptions);
}
// Verify the account
}
private static async Task<IResult> HandleRegister(HttpContext context)
{
// Check payload
if (context.Request.ContentType != "application/json")
{
context.Response.StatusCode = 400;
return Results.Json(new RegisterResponse
{
success = false,
error = "Invalid request body"
}, Utilities.JsonSerializerOptions);
}
var payload = await context.Request.ReadFromJsonAsync<RegisterPayload>();
if (payload == null || string.IsNullOrWhiteSpace(payload.username) || string.IsNullOrWhiteSpace(payload.password) || string.IsNullOrWhiteSpace(payload.email))
{
context.Response.StatusCode = 400;
return Results.Json(new RegisterResponse
{
success = false,
error = "Invalid request body"
}, Utilities.JsonSerializerOptions);
}
// Check captcha response
if (Program.Config.hCaptcha.Enabled)
{
if (string.IsNullOrWhiteSpace(payload.captchaToken))
{
context.Response.StatusCode = 400;
return Results.Json(new RegisterResponse
{
success = false,
error = "Missing hCaptcha token"
}, Utilities.JsonSerializerOptions);
}
var result =
await Program.hCaptcha!.Verify(payload.captchaToken, context.Connection.RemoteIpAddress!.ToString());
if (!result.success)
{
context.Response.StatusCode = 400;
return Results.Json(new RegisterResponse
{
success = false,
error = "Invalid captcha response"
}, Utilities.JsonSerializerOptions);
}
}
// Make sure username isn't taken
var user = await Program.Database.GetUser(payload.username);
if (user != null)
{
context.Response.StatusCode = 400;
return Results.Json(new RegisterResponse
{
success = false,
error = "That username is taken."
}, Utilities.JsonSerializerOptions);
}
// Check if E-Mail is in use
user = await Program.Database.GetUser(email: payload.email);
if (user != null)
{
context.Response.StatusCode = 400;
return Results.Json(new RegisterResponse
{
success = false,
error = "That E-Mail is already in use."
}, Utilities.JsonSerializerOptions);
}
// Validate username
if (!Utilities.ValidateUsername(payload.username))
{
context.Response.StatusCode = 400;
return Results.Json(new RegisterResponse
{
success = false,
error = "Usernames can contain only numbers, letters, spaces, dashes, underscores, and dots, and must be between 3 and 20 characters."
}, Utilities.JsonSerializerOptions);
}
// Validate E-Mail
if (!new EmailAddressAttribute().IsValid(payload.email))
{
context.Response.StatusCode = 400;
return Results.Json(new RegisterResponse
{
success = false,
error = "Malformed E-Mail address."
}, Utilities.JsonSerializerOptions);
}
if (Program.Config.Registration.EmailDomainWhitelist &&
!Program.Config.Registration.AllowedEmailDomains.Contains(payload.email.Split("@")[1]))
{
context.Response.StatusCode = 400;
return Results.Json(new RegisterResponse
{
success = false,
error = "That E-Mail domain is not allowed."
}, Utilities.JsonSerializerOptions);
}
// Validate password
if (!Utilities.ValidatePassword(payload.password))
{
context.Response.StatusCode = 400;
return Results.Json(new RegisterResponse
{
success = false,
error = "Passwords must be at least 8 characters and must contain an uppercase and lowercase letter, a number, and a symbol."
}, Utilities.JsonSerializerOptions);
}
if (Program.BannedPasswords.Contains(payload.password))
{
context.Response.StatusCode = 400;
return Results.Json(new RegisterResponse
{
success = false,
error = "That password is commonly used and is not allowed."
}, Utilities.JsonSerializerOptions);
}
// Create the account
if (Program.Config.Registration.EmailVerificationRequired)
{
var code = Program.Random.Next(10000000, 99999999).ToString();
await Program.Database.RegisterAccount(payload.username, payload.email, payload.password, false, code);
await Program.Mailer.SendVerificationCode(payload.username, payload.email, code);
return Results.Json(new RegisterResponse
{
success = true,
verificationRequired = true,
email = payload.email,
username = payload.username
}, Utilities.JsonSerializerOptions);
}
else
{
await Program.Database.RegisterAccount(payload.username, payload.email, payload.password, true, null);
return Results.Json(new RegisterResponse
{
success = true,
verificationRequired = false,
email = payload.email,
username = payload.username
}, Utilities.JsonSerializerOptions);
}
}
private static IResult HandleInfo(HttpContext context)
{
return Results.Json(new AuthServerInformation
{
// TODO: Implement registration closure
registrationOpen = true,
hcaptcha =
new() {
required = Program.Config.hCaptcha.Enabled,
siteKey = Program.Config.hCaptcha.Enabled ? Program.Config.hCaptcha.SiteKey : null
}
});
}
}

View file

@ -0,0 +1,9 @@
namespace Computernewb.CollabVMAuthServer;
public class Session
{
public string Token { get; set; }
public uint UserId { get; set; }
public DateTime Created { get; set; }
public DateTime LastUsed { get; set; }
}

View file

@ -0,0 +1,20 @@
namespace Computernewb.CollabVMAuthServer;
public class User
{
public uint Id { get; set; }
public string Username { get; set; }
public string Password { get; set; }
public string Email { get; set; }
public bool EmailVerified { get; set; }
public string EmailVerificationCode { get; set; }
public Rank Rank { get; set; }
public bool Banned { get; set; }
}
public enum Rank : uint
{
Registered = 1,
Admin = 2,
Moderator = 3,
}

View file

@ -0,0 +1,87 @@
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Text.RegularExpressions;
namespace Computernewb.CollabVMAuthServer;
public enum LogLevel
{
DEBUG,
INFO,
WARN,
ERROR,
FATAL
}
public static class Utilities
{
public static JsonSerializerOptions JsonSerializerOptions => new JsonSerializerOptions
{
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull
};
public static void Log(LogLevel level, string msg)
{
#if !DEBUG
if (level == LogLevel.DEBUG)
return;
#endif
StringBuilder logstr = new StringBuilder();
logstr.Append("[");
logstr.Append(DateTime.Now.ToString("G"));
logstr.Append("] [");
switch (level)
{
case LogLevel.DEBUG:
logstr.Append("DEBUG");
break;
case LogLevel.INFO:
logstr.Append("INFO");
break;
case LogLevel.WARN:
logstr.Append("WARN");
break;
case LogLevel.ERROR:
logstr.Append("ERROR");
break;
case LogLevel.FATAL:
logstr.Append("FATAL");
break;
default:
throw new ArgumentException("Invalid log level");
}
logstr.Append("] ");
logstr.Append(msg);
switch (level)
{
case LogLevel.DEBUG:
case LogLevel.INFO:
Console.WriteLine(logstr.ToString());
break;
case LogLevel.WARN:
case LogLevel.ERROR:
case LogLevel.FATAL:
Console.Error.Write(logstr.ToString());
break;
}
}
public static bool ValidateUsername(string username)
{
return username.Length >= 3 &&
username.Length <= 20 &&
username[0] != ' ' &&
username[^1] != ' ' &&
new Regex("^[a-zA-Z0-9 \\-_\\.]+$").IsMatch(username);
}
public static bool ValidatePassword(string password)
{
return password.Length > 8 &&
new Regex("[a-z]").IsMatch(password) &&
new Regex("[A-Z]").IsMatch(password) &&
new Regex("[!@#$%^&*()\\-_=+\\\\|\\[\\];:'\\\",<.>/?`~]").IsMatch(password) &&
new Regex("[0-9]").IsMatch(password);
}
}

View file

@ -0,0 +1,8 @@
namespace Computernewb.CollabVMAuthServer;
public class VerifyPayload
{
public string username { get; set; }
public string password { get; set; }
public string code { get; set; }
}

View file

@ -0,0 +1,41 @@
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Text.Json.Serialization.Metadata;
namespace Computernewb.CollabVMAuthServer;
public class hCaptchaClient
{
private string secret;
private string sitekey;
private HttpClient http;
public hCaptchaClient(string secret, string sitekey)
{
this.secret = secret;
this.sitekey = sitekey;
this.http = new HttpClient();
}
public async Task<hCaptchaResponse> Verify(string token, string ip)
{
var response = await http.PostAsync("https://api.hcaptcha.com/siteverify", new FormUrlEncodedContent(new []
{
new KeyValuePair<string, string>("secret", secret),
new KeyValuePair<string, string>("response", token),
new KeyValuePair<string, string>("remoteip", ip),
new KeyValuePair<string, string>("sitekey", sitekey)
}));
response.EnsureSuccessStatusCode();
return await response.Content.ReadFromJsonAsync<hCaptchaResponse>() ?? throw new Exception("Failed to parse hCaptcha response");
}
}
public class hCaptchaResponse
{
public bool success { get; set; }
public string challenge_ts { get; set; }
public string hostname { get; set; }
public bool? credit { get; set; }
[JsonPropertyName("error-codes")]
public string[]? error_codes { get; set; }
}

34091
rockyou.txt Normal file

File diff suppressed because it is too large Load diff