Last active
June 7, 2024 04:56
-
-
Save gistlyn/8864f788fb863a3293ba334753868310 to your computer and use it in GitHub Desktop.
apikeys
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using MyApp.Data; | |
using ServiceStack; | |
using ServiceStack.Data; | |
using ServiceStack.OrmLite; | |
using ServiceStack.Configuration; | |
[assembly: HostingStartup(typeof(MyApp.ConfigureApiKeys))] | |
namespace MyApp; | |
public class ConfigureApiKeys : IHostingStartup | |
{ | |
public void Configure(IWebHostBuilder builder) => builder | |
.ConfigureServices(services => | |
{ | |
services.AddPlugin(new ApiKeysFeature | |
{ | |
// Optional: Available Scopes Admin Users can assign to any API Key | |
// Features = [ | |
// "Paid", | |
// "Tracking", | |
// ], | |
// Optional: Available Features Admin Users can assign to any API Key | |
// Scopes = [ | |
// "todo:read", | |
// "todo:write", | |
// ], | |
// Optional: Limit available Scopes Users can assign to their own API Keys | |
// UserScopes = [ | |
// "todo:read", | |
// ], | |
// Optional: Limit available Features Users can assign to their own API Keys | |
// UserFeatures = [ | |
// "Tracking", | |
// ], | |
}); | |
}) | |
.ConfigureAppHost(appHost => | |
{ | |
using var db = appHost.Resolve<IDbConnectionFactory>().Open(); | |
var feature = appHost.GetPlugin<ApiKeysFeature>(); | |
feature.InitSchema(db); | |
// Optional: Create API Key for specified Users on Startup | |
if (feature.ApiKeyCount(db) == 0 && db.TableExists(IdentityUsers.TableName)) | |
{ | |
var createApiKeysFor = new [] { "admin@email.com", "manager@email.com" }; | |
var users = IdentityUsers.GetByUserNames(db, createApiKeysFor); | |
foreach (var user in users) | |
{ | |
List<string> scopes = user.UserName == "admin@email.com" | |
? [RoleNames.Admin] | |
: []; | |
feature.Insert(db, | |
new() { Name = "Seed API Key", UserId = user.Id, UserName = user.UserName, Scopes = scopes }); | |
} | |
} | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment