tgstation-server
The /tg/station 13 server suite
DatabaseSeeder.cs
Go to the documentation of this file.
1 using Microsoft.EntityFrameworkCore;
2 using System;
3 using System.Linq;
4 using System.Threading;
5 using System.Threading.Tasks;
9 
11 {
14  {
19 
25  {
26  this.cryptographySuite = cryptographySuite ?? throw new ArgumentNullException(nameof(cryptographySuite));
27  }
28 
33  void SeedAdminUser(IDatabaseContext databaseContext)
34  {
35  var admin = new User
36  {
38  CreatedAt = DateTimeOffset.Now,
40  Name = Api.Models.User.AdminName,
41  CanonicalName = Api.Models.User.AdminName.ToUpperInvariant(),
42  Enabled = true,
43  };
44  cryptographySuite.SetUserPassword(admin, Api.Models.User.DefaultAdminPassword, true);
45  databaseContext.Users.Add(admin);
46  }
47 
49  public async Task SeedDatabase(IDatabaseContext databaseContext, CancellationToken cancellationToken)
50  {
51  SeedAdminUser(databaseContext);
52  await databaseContext.Save(cancellationToken).ConfigureAwait(false);
53  }
54 
56  public async Task ResetAdminPassword(IDatabaseContext databaseContext, CancellationToken cancellationToken)
57  {
58  var admin = await databaseContext.Users.Where(x => x.CanonicalName == Api.Models.User.AdminName.ToUpperInvariant()).FirstOrDefaultAsync(cancellationToken).ConfigureAwait(false);
59  if (admin == default)
60  SeedAdminUser(databaseContext);
61  else
62  {
63  admin.Enabled = true;
64  cryptographySuite.SetUserPassword(admin, Api.Models.User.DefaultAdminPassword, false);
65  }
66 
67  await databaseContext.Save(cancellationToken).ConfigureAwait(false);
68  }
69  }
70 }
readonly ICryptographySuite cryptographySuite
The ICryptographySuite for the DatabaseContext<TParentContext>
For initially seeding a database
async Task SeedDatabase(IDatabaseContext databaseContext, CancellationToken cancellationToken)
Initially seed a given databaseContext
AdministrationRights
Rights for Models.Administration
Contains various cryptographic functions
async Task ResetAdminPassword(IDatabaseContext databaseContext, CancellationToken cancellationToken)
Changes the admin password in IDatabaseContext back to it's default and enables the account
InstanceManagerRights
Rights for managing Models.Instances
DatabaseSeeder(ICryptographySuite cryptographySuite)
Construct a DatabaseSeeder
void SetUserPassword(User user, string newPassword, bool newUser)
Sets a User.PasswordHash for a given user
DbSet< User > Users
The Users in the IDatabaseContext
Task Save(CancellationToken cancellationToken)
Saves changes made to the IDatabaseContext
void SeedAdminUser(IDatabaseContext databaseContext)
Add a default admin User to a given databaseContext