61 lines
1.5 KiB
C#
61 lines
1.5 KiB
C#
using System.Text.RegularExpressions;
|
|
using SpacetimeDB;
|
|
|
|
public static partial class Module
|
|
{
|
|
[Table(Name = "User", Public = true)]
|
|
public partial class User
|
|
{
|
|
[PrimaryKey]
|
|
public Identity Identity;
|
|
public string? Name;
|
|
public string? Color;
|
|
public bool Online;
|
|
}
|
|
|
|
/// Takes a name and checks if it's acceptable as a user's name.
|
|
private static string ValidateName(string name)
|
|
{
|
|
if (string.IsNullOrEmpty(name))
|
|
{
|
|
throw new Exception("Names must not be empty");
|
|
}
|
|
return name;
|
|
}
|
|
|
|
[Reducer]
|
|
public static void SetName(ReducerContext ctx, string name)
|
|
{
|
|
name = ValidateName(name);
|
|
|
|
var user = ctx.Db.User.Identity.Find(ctx.Sender);
|
|
if (user is not null)
|
|
{
|
|
user.Name = name;
|
|
ctx.Db.User.Identity.Update(user);
|
|
}
|
|
}
|
|
|
|
private static string ValidateColor(string color)
|
|
{
|
|
var regex = new Regex("^([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$");
|
|
if (!regex.IsMatch(color))
|
|
{
|
|
throw new Exception("Invalid color code");
|
|
}
|
|
return color;
|
|
}
|
|
|
|
[Reducer]
|
|
public static void SetColor(ReducerContext ctx, string color)
|
|
{
|
|
color = ValidateColor(color);
|
|
|
|
var user = ctx.Db.User.Identity.Find(ctx.Sender);
|
|
if (user is not null)
|
|
{
|
|
user.Color = color;
|
|
ctx.Db.User.Identity.Update(user);
|
|
}
|
|
}
|
|
}
|