Skip to content

Commit f5bb417

Browse files
authored
Add a NewUser role with separate perms, minor restricted role handling improvements (#1106)
This adds a `NewUser` role to `GameUserRole` which is inbetween `User` and `Restricted`. Newly created accounts will have their role set to`NewUser` instead of `User`. New users have their own, separate role-perms in `refreshGameServer.json`, and said config now also has an `HoursUntilNewAccountNoLongerNew` option, which defines how old an account must be in order to be automatically promoted from new user to normal user. This automatic promotion is done by `NewUserJob`. This closes #1098. Additionally, this PR also does the following: - Adds separate, hard-coded role-perms and write-block status for the `Restricted` and `Banned` roles if requested (normally `RoleService` already takes care of blocking upload requests by such users, but this is just a fallback incase the service fails, also useful incase we add other things which need role-perms, and this generally makes the methods simpler). I've added this in this PR because I already had to edit the methods to handle new user perms. - Adds `TimeProvider` to `WorkContext` so we could easily modify the current time there to test the `NewUserJob`. This doesn't make other jobs, which also use current time (like `CoolLevelsJob` and `DiscordIntegrationJob`), use the time provider yet though. That should be done and tested in another PR. Also, this PR still needs unit tests for the new config migrations, and manual testing on a real Refresh instance.
2 parents 6c68d94 + dcd3c66 commit f5bb417

19 files changed

Lines changed: 364 additions & 28 deletions

File tree

‎Refresh.Core/Configuration/GameServerConfig.cs‎

Lines changed: 46 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ namespace Refresh.Core.Configuration;
88
[SuppressMessage("ReSharper", "RedundantDefaultMemberInitializer")]
99
public class GameServerConfig : Config
1010
{
11-
public override int CurrentConfigVersion => 28;
11+
public override int CurrentConfigVersion => 29;
1212
public override int Version { get; set; } = 0;
1313

1414
protected override void Migrate(int oldVer, dynamic oldConfig)
@@ -17,14 +17,17 @@ protected override void Migrate(int oldVer, dynamic oldConfig)
1717
// to more cleanly split the perms between certain roles, and to make their enforcement easier.
1818
if (oldVer < 27)
1919
{
20+
this.NewUserPermissions = new();
2021
this.NormalUserPermissions = new();
2122
this.TrustedUserPermissions = new();
2223

2324
// filesize quota limit was added during version 11, but the version wasn't bumped, so catch error to be safe
25+
// Migrate filesize quota
2426
if (oldVer >= 11)
2527
{
2628
try
2729
{
30+
this.NewUserPermissions.UserFilesizeQuota = (int)oldConfig.UserFilesizeQuota;
2831
this.NormalUserPermissions.UserFilesizeQuota = (int)oldConfig.UserFilesizeQuota;
2932
this.TrustedUserPermissions.UserFilesizeQuota = (int)oldConfig.UserFilesizeQuota;
3033
}
@@ -34,8 +37,13 @@ protected override void Migrate(int oldVer, dynamic oldConfig)
3437
}
3538
}
3639

40+
// Migrate asset flags/safety level
3741
if (oldVer >= 18)
3842
{
43+
this.NewUserPermissions.BlockedAssetFlags.Dangerous = (bool)oldConfig.BlockedAssetFlags.Dangerous;
44+
this.NewUserPermissions.BlockedAssetFlags.Media = (bool)oldConfig.BlockedAssetFlags.Media;
45+
this.NewUserPermissions.BlockedAssetFlags.Modded = (bool)oldConfig.BlockedAssetFlags.Modded;
46+
3947
this.NormalUserPermissions.BlockedAssetFlags.Dangerous = (bool)oldConfig.BlockedAssetFlags.Dangerous;
4048
this.NormalUserPermissions.BlockedAssetFlags.Media = (bool)oldConfig.BlockedAssetFlags.Media;
4149
this.NormalUserPermissions.BlockedAssetFlags.Modded = (bool)oldConfig.BlockedAssetFlags.Modded;
@@ -50,12 +58,14 @@ protected override void Migrate(int oldVer, dynamic oldConfig)
5058
if (oldVer >= 2)
5159
{
5260
int oldSafetyLevel = (int)oldConfig.MaximumAssetSafetyLevel;
53-
this.NormalUserPermissions.BlockedAssetFlags = new ConfigAssetFlags
61+
ConfigAssetFlags fromSafetyLevel = new ConfigAssetFlags
5462
{
5563
Dangerous = oldSafetyLevel < 3,
5664
Modded = oldSafetyLevel < 2,
5765
Media = oldSafetyLevel < 1,
5866
};
67+
this.NormalUserPermissions.BlockedAssetFlags = fromSafetyLevel;
68+
this.NewUserPermissions.BlockedAssetFlags = fromSafetyLevel;
5969
}
6070

6171
// Asset safety level for trusted users was added in config version 12, so dont try to migrate if we are coming from a version older than that
@@ -80,8 +90,13 @@ protected override void Migrate(int oldVer, dynamic oldConfig)
8090
}
8191

8292
// Timed level upload limits were added in version 19.
93+
// Migrate level limits
8394
if (oldVer >= 19)
8495
{
96+
this.NewUserPermissions.LevelUploadRateLimit.Enabled = (bool)oldConfig.TimedLevelUploadLimits.Enabled;
97+
this.NewUserPermissions.LevelUploadRateLimit.TimeSpanHours = (int)oldConfig.TimedLevelUploadLimits.TimeSpanHours;
98+
this.NewUserPermissions.LevelUploadRateLimit.UploadQuota = (int)oldConfig.TimedLevelUploadLimits.LevelQuota;
99+
85100
this.NormalUserPermissions.LevelUploadRateLimit.Enabled = (bool)oldConfig.TimedLevelUploadLimits.Enabled;
86101
this.NormalUserPermissions.LevelUploadRateLimit.TimeSpanHours = (int)oldConfig.TimedLevelUploadLimits.TimeSpanHours;
87102
this.NormalUserPermissions.LevelUploadRateLimit.UploadQuota = (int)oldConfig.TimedLevelUploadLimits.LevelQuota;
@@ -94,37 +109,61 @@ protected override void Migrate(int oldVer, dynamic oldConfig)
94109
// Read-only mode was added for both normal and trusted users in version 20.
95110
if (oldVer >= 20)
96111
{
112+
this.NewUserPermissions.ReadOnlyMode = (bool)oldConfig.ReadOnlyMode;
97113
this.NormalUserPermissions.ReadOnlyMode = (bool)oldConfig.ReadOnlyMode;
98114
this.TrustedUserPermissions.ReadOnlyMode = (bool)oldConfig.ReadonlyModeForTrustedUsers;
99115
}
100116
}
101117

102-
// In version 28, PhotoUploadRateLimit and PlaylistUploadRateLimit were added to RolePermissions, and various renamings related to level upload rate-limiting
103-
// were done to prepare for this: the class TimedLevelUploadLimitProperties was renamed to EntityUploadRateLimitProperties, its attribute LevelQuota was renamed to UploadQuota,
104-
// and RolePermissions' attribute TimedLevelUploadLimits was renamed to LevelUploadRateLimit
118+
// In version 28, PhotoUploadRateLimit and PlaylistUploadRateLimit were added to RolePermissions
119+
// and various attributes related to level rate-limiting were renamed
105120
else if (oldVer == 27)
106121
{
107122
this.NormalUserPermissions.LevelUploadRateLimit.Enabled = (bool)oldConfig.NormalUserPermissions.TimedLevelUploadLimits.Enabled;
108123
this.NormalUserPermissions.LevelUploadRateLimit.TimeSpanHours = (int)oldConfig.NormalUserPermissions.TimedLevelUploadLimits.TimeSpanHours;
109124
this.NormalUserPermissions.LevelUploadRateLimit.UploadQuota = (int)oldConfig.NormalUserPermissions.TimedLevelUploadLimits.LevelQuota;
125+
126+
this.NormalUserPermissions.LevelUploadRateLimit.Enabled = (bool)oldConfig.NormalUserPermissions.TimedLevelUploadLimits.Enabled;
127+
this.NormalUserPermissions.LevelUploadRateLimit.TimeSpanHours = (int)oldConfig.NormalUserPermissions.TimedLevelUploadLimits.TimeSpanHours;
128+
this.NormalUserPermissions.LevelUploadRateLimit.UploadQuota = (int)oldConfig.NormalUserPermissions.TimedLevelUploadLimits.LevelQuota;
110129

111130
this.TrustedUserPermissions.LevelUploadRateLimit.Enabled = (bool)oldConfig.TrustedUserPermissions.TimedLevelUploadLimits.Enabled;
112131
this.TrustedUserPermissions.LevelUploadRateLimit.TimeSpanHours = (int)oldConfig.TrustedUserPermissions.TimedLevelUploadLimits.TimeSpanHours;
113132
this.TrustedUserPermissions.LevelUploadRateLimit.UploadQuota = (int)oldConfig.TrustedUserPermissions.TimedLevelUploadLimits.LevelQuota;
114133
}
134+
135+
// In version 29, the NewUser role and its related config options
136+
// (NewUserPermissions and HoursUntilNewAccountNoLongerNew) were added
137+
else if (oldVer < 29)
138+
{
139+
this.NewUserPermissions = oldConfig.NormalUserPermissions;
140+
}
115141
}
116142

117143
public string LicenseText { get; set; } = "Welcome to Refresh!";
118144

119145
/// <summary>
120-
/// Role-specific permissions for normal users and below
146+
/// Role-specific permissions for new users.
147+
/// </summary>
148+
public RolePermissions NewUserPermissions = new();
149+
/// <summary>
150+
/// Role-specific permissions for normal, not-new users.
121151
/// </summary>
122152
public RolePermissions NormalUserPermissions = new();
123153
/// <summary>
124-
/// Role-specific permissions for trusted users and above
154+
/// Role-specific permissions for trusted users and above.
125155
/// </summary>
126156
public RolePermissions TrustedUserPermissions = new();
127157

158+
/// <summary>
159+
/// The minimum age (time after registration) an account must have before it automatically gets promoted from
160+
/// NewUser to User.
161+
/// We do this by using NewUserJob to compare the account's age, and if it is old enough, we update their role.
162+
/// Currently, the only difference between new users and regular users is that we apply NewUserPermissions
163+
/// instead of NormalUserPermissions, which you can freely configure in this config.
164+
/// </summary>
165+
public int HoursUntilNewAccountNoLongerNew { get; set; } = 24 * 7; // TODO should we think of a better name?
166+
128167
public bool AllowUsersToUseIpAuthentication { get; set; } = false;
129168
public bool PermitPsnLogin { get; set; } = true;
130169
public bool PermitRpcnLogin { get; set; } = true;

‎Refresh.Core/Configuration/RolePermissions.cs‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,4 +33,25 @@ public RolePermissions() {}
3333
/// The amount of data the user is allowed to upload before all resource uploads get blocked, defaults to 100mb.
3434
/// </summary>
3535
public int UserFilesizeQuota { get; set; } = 100 * 1_048_576;
36+
37+
// Not configurable because "Restricted" and "Banned" already imply a user has no uploading perms.
38+
public static RolePermissions FromRestrictedUser => new()
39+
{
40+
ReadOnlyMode = true,
41+
BlockedAssetFlags = new(AssetFlags.Dangerous | AssetFlags.Modded | AssetFlags.Media),
42+
// Not enabled because restricted may not upload UGC anyway, also we already enable read-only mode for them
43+
LevelUploadRateLimit = new()
44+
{
45+
Enabled = false,
46+
},
47+
PhotoUploadRateLimit = new()
48+
{
49+
Enabled = false,
50+
},
51+
PlaylistUploadRateLimit = new()
52+
{
53+
Enabled = false,
54+
},
55+
UserFilesizeQuota = 0,
56+
};
3657
}

‎Refresh.Core/Extensions/GameUserExtensions.cs‎

Lines changed: 14 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,14 @@ public static class GameUserExtensions
77
{
88
public static bool IsWriteBlocked(this GameUser user, GameServerConfig config)
99
{
10+
// Admins may always bypass this
1011
if (user.Role == GameUserRole.Admin) return false;
11-
return GetRolePermissionsForUser(user, config).ReadOnlyMode;
12+
13+
// Restricted and Banned may not upload/edit any UGC, they also have no role perms because unnecessary
14+
else if (user.Role <= GameUserRole.Restricted) return true;
15+
16+
// Determine based on role perms
17+
else return GetRolePermissionsForUser(user, config).ReadOnlyMode;
1218
}
1319

1420
public static bool MayModifyUser(this GameUser user, GameUser targetUser)
@@ -26,9 +32,12 @@ public static bool MayModifyUser(this GameUser user, GameUser targetUser)
2632

2733
public static RolePermissions GetRolePermissionsForUser(this GameUser user, GameServerConfig config)
2834
{
29-
if (user.Role >= GameUserRole.Trusted)
30-
return config.TrustedUserPermissions;
31-
32-
return config.NormalUserPermissions;
35+
return user.Role switch
36+
{
37+
>= GameUserRole.Trusted => config.TrustedUserPermissions,
38+
GameUserRole.User => config.NormalUserPermissions,
39+
GameUserRole.NewUser => config.NewUserPermissions,
40+
_ => RolePermissions.FromRestrictedUser,
41+
};
3342
}
3443
}

‎Refresh.Core/Services/RoleService.cs‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,12 +31,13 @@ internal RoleService(GameAuthenticationService authService, GameServerConfig con
3131
if (!(authAttrib?.Required ?? true)) return null;
3232

3333
MinimumRoleAttribute? roleAttrib = method.GetCustomAttribute<MinimumRoleAttribute>();
34-
GameUserRole minimumRole = roleAttrib?.MinimumRole ?? GameUserRole.User;
34+
GameUserRole minimumRole = roleAttrib?.MinimumRole ?? GameUserRole.NewUser;
3535

3636
GameUser? user = (GameUser?)this._authService.AuthenticateToken(context, database)?.User;
3737
if (user == null) return null; // Let AuthenticationProvider handle 401
3838

3939
// if the user's role is lower than the minimum role for this endpoint, then return unauthorized
40+
// by default, Restricted and Banned will be rejected by this since the default role is NewUser
4041
if (user.Role < minimumRole)
4142
{
4243
return Unauthorized;

‎Refresh.Database/Models/Users/GameUser.cs‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -105,8 +105,8 @@ public partial class GameUser : IRateLimitUser
105105
/// If `true`, unescape XML tags sent to /filter
106106
/// </summary>
107107
public bool UnescapeXmlSequences { get; set; }
108-
109-
public GameUserRole Role { get; set; }
108+
109+
public GameUserRole Role { get; set; } = GameUserRole.NewUser;
110110

111111
/// <summary>
112112
/// Whether planets containing mods or VoiceRecordings should be shown in-game

‎Refresh.Database/Models/Users/GameUserRole.cs‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,12 @@ public enum GameUserRole : sbyte
3030
/// </summary>
3131
User = 0,
3232
/// <summary>
33+
/// A newly registered user. Can have different, usually more restrictive configurable perms than regular users.
34+
/// Useful to make spam more difficult, for example. The duration in which an account's age makes it "new" is defined by config.
35+
/// Automatically promoted to User by NewUserJob.
36+
/// </summary>
37+
NewUser = -32,
38+
/// <summary>
3339
/// A user with read-only permissions. May log in and play, but cannot do things such as publish levels or post comments.
3440
/// </summary>
3541
Restricted = -126,

‎Refresh.GameServer/RefreshGameServer.cs‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -185,12 +185,14 @@ protected override void SetupServices()
185185

186186
protected virtual void SetupWorkers()
187187
{
188-
this.WorkerManager = RefreshWorkerManager.Create(this.Logger, this._dataStore, this._databaseProvider);
188+
this.WorkerManager = RefreshWorkerManager.Create(this.Logger, this._dataStore, this._databaseProvider, this.GetTimeProvider());
189189

190190
if (this._configStore.Integration.DiscordWebhookEnabled && this._configStore.GameServer.PermitShowingOnlineUsers)
191191
{
192192
this.WorkerManager.AddJob(new DiscordIntegrationJob(this._configStore.Integration, this._configStore.GameServer));
193193
}
194+
195+
this.WorkerManager.AddJob(new NewUserJob(this._configStore.GameServer.HoursUntilNewAccountNoLongerNew));
194196
}
195197

196198
/// <inheritdoc/>

‎Refresh.Interfaces.Game/Endpoints/Levels/PublishEndpoints.cs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -192,7 +192,7 @@ public Response StartPublish(RequestContext context,
192192
{
193193
if (dataContext.User!.IsWriteBlocked(config))
194194
{
195-
dataContext.Database.AddPublishFailNotification("The server is in read-only mode.", body.Title, dataContext.User!);
195+
dataContext.Database.AddPublishFailNotification($"The server is in read-only mode.", body.Title, dataContext.User!);
196196
return Unauthorized;
197197
}
198198

‎Refresh.Interfaces.Workers/RefreshWorkerManager.cs‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
using Bunkum.Core.Storage;
22
using NotEnoughLogs;
3+
using Refresh.Common.Time;
34
using Refresh.Database;
45
using Refresh.Interfaces.Workers.Migrations;
56
using Refresh.Interfaces.Workers.Repeating;
@@ -9,9 +10,9 @@ namespace Refresh.Interfaces.Workers;
910

1011
public static class RefreshWorkerManager
1112
{
12-
public static WorkerManager Create(Logger logger, IDataStore dataStore, GameDatabaseProvider databaseProvider)
13+
public static WorkerManager Create(Logger logger, IDataStore dataStore, GameDatabaseProvider databaseProvider, IDateTimeProvider timeProvider)
1314
{
14-
WorkerManager manager = new(logger, dataStore, databaseProvider);
15+
WorkerManager manager = new(logger, dataStore, databaseProvider, timeProvider);
1516

1617
manager.AddJob<PunishmentExpiryJob>();
1718
manager.AddJob<CleanupExpiredObjectsJob>();
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
using Refresh.Common;
2+
using Refresh.Database;
3+
using Refresh.Database.Models.Users;
4+
using Refresh.Workers;
5+
6+
namespace Refresh.Interfaces.Workers.Repeating;
7+
8+
/// <summary>
9+
/// A job that handles promoting new users to regular users, depending on their account age and the server config.
10+
/// </summary>
11+
// TODO also set users back as "new" if duration in config is updated to result in user being "new" again
12+
public class NewUserJob : RepeatingJob
13+
{
14+
private readonly int _requiredAccountAge;
15+
protected override int Interval => 60_000 * 5; // 5 minutes, no need to execute too often
16+
17+
public NewUserJob(int requiredAccountAge)
18+
{
19+
this._requiredAccountAge = requiredAccountAge;
20+
}
21+
22+
public override void ExecuteJob(WorkContext context)
23+
{
24+
DateTimeOffset now = context.TimeProvider.Now;
25+
DatabaseList<GameUser> newUsers = context.Database.GetAllUsersWithRole(GameUserRole.NewUser);
26+
27+
foreach (GameUser user in newUsers.Items.ToList())
28+
{
29+
// If an account is, e.g., 2 hours and 40 minutes old, and max age for new users is 3 hours, we wouldn't
30+
// consider max to be reached yet, so floor the difference.
31+
long accountAge = (long)Math.Floor(now.Subtract(user.JoinDate).TotalHours);
32+
33+
context.Logger.LogDebug(RefreshContext.Worker, $"{nameof(NewUserJob)} - new user: {user}, join date: {user.JoinDate}, current time: {now}, account age: {accountAge}h, configured required age: {this._requiredAccountAge}h.");
34+
if (accountAge < this._requiredAccountAge) continue; // Don't promote user if they haven't reached max age yet
35+
36+
context.Logger.LogInfo(RefreshContext.Worker, $"Promoting {user} to regular user since their account is {accountAge} hours old now (configured required age: {this._requiredAccountAge}h).");
37+
context.Database.SetUserRole(user, GameUserRole.User);
38+
}
39+
}
40+
}

0 commit comments

Comments
 (0)