diff --git a/auth/auth.go b/auth/auth.go index eb067f9..5b69a06 100644 --- a/auth/auth.go +++ b/auth/auth.go @@ -59,6 +59,7 @@ const ( redirectURLKind = "RedirectURL" superusersKind = "Superusers" discordBotCredentialsKind = "DiscordBotCredentials" + discordBotTokenKind = "DiscordBotTokenKind" prodKey = "prod" ) @@ -75,6 +76,8 @@ var ( prodSuperusersLock = sync.RWMutex{} prodDiscordBotCredentials *DiscordBotCredentials prodDiscordBotCredentialsLock = sync.RWMutex{} + prodDiscordBotToken *DiscordBotToken + prodDiscordBotTokenLock = sync.RWMutex{} router *mux.Router RedirectURLResource *Resource @@ -85,6 +88,10 @@ type DiscordBotCredentials struct { Password string } +type DiscordBotToken struct { + Token string +} + func getDiscordBotCredentialsKey(ctx context.Context) *datastore.Key { return datastore.NewKey(ctx, discordBotCredentialsKind, prodKey, 0, nil) } @@ -119,6 +126,40 @@ func getDiscordBotCredentials(ctx context.Context) (*DiscordBotCredentials, erro return prodDiscordBotCredentials, nil } +func getDiscordBotTokenKey(ctx context.Context) *datastore.Key { + return datastore.NewKey(ctx, discordBotTokenKind, prodKey, 0, nil) +} + +func SetDiscordBotToken(ctx context.Context, discordBotToken *DiscordBotToken) error { + return datastore.RunInTransaction(ctx, func(ctx context.Context) error { + currentDiscordBotToken := &DiscordBotToken{} + if err := datastore.Get(ctx, getDiscordBotTokenKey(ctx), currentDiscordBotToken); err == nil { + return HTTPErr{"DiscordBotToken already configured", http.StatusBadRequest} + } + if _, err := datastore.Put(ctx, getDiscordBotTokenKey(ctx), discordBotToken); err != nil { + return err + } + return nil + }, &datastore.TransactionOptions{XG: false}) +} + +func GetDiscordBotToken(ctx context.Context) (*DiscordBotToken, error) { + prodDiscordBotTokenLock.RLock() + if prodDiscordBotToken != nil { + defer prodDiscordBotTokenLock.RUnlock() + return prodDiscordBotToken, nil + } + prodDiscordBotTokenLock.RUnlock() + prodDiscordBotTokenLock.Lock() + defer prodDiscordBotTokenLock.Unlock() + foundDiscordBotToken := &DiscordBotToken{} + if err := datastore.Get(ctx, getDiscordBotTokenKey(ctx), foundDiscordBotToken); err != nil { + return nil, err + } + prodDiscordBotToken = foundDiscordBotToken + return prodDiscordBotToken, nil +} + func init() { RedirectURLResource = &Resource{ Delete: deleteRedirectURL, diff --git a/game/handler.go b/game/handler.go index 6e60618..329e9a6 100644 --- a/game/handler.go +++ b/game/handler.go @@ -660,6 +660,7 @@ type configuration struct { SendGrid *auth.SendGrid Superusers *auth.Superusers DiscordBotCredentials *auth.DiscordBotCredentials + DiscordBotToken *auth.DiscordBotToken } func handleConfigure(w ResponseWriter, r Request) error { @@ -694,6 +695,11 @@ func handleConfigure(w ResponseWriter, r Request) error { return err } } + if conf.DiscordBotToken != nil { + if err := auth.SetDiscordBotToken(ctx, conf.DiscordBotToken); err != nil { + return err + } + } return nil }