50 lines
1.2 KiB
Go
50 lines
1.2 KiB
Go
package db
|
|
|
|
import (
|
|
"context"
|
|
"time"
|
|
|
|
"git.haelnorr.com/h/oslstats/internal/discord"
|
|
"github.com/pkg/errors"
|
|
"github.com/uptrace/bun"
|
|
)
|
|
|
|
type DiscordToken struct {
|
|
bun.BaseModel `bun:"table:discord_tokens,alias:dt"`
|
|
|
|
DiscordID string `bun:"discord_id,pk,notnull"`
|
|
AccessToken string `bun:"access_token,notnull"`
|
|
RefreshToken string `bun:"refresh_token,notnull"`
|
|
ExpiresAt int64 `bun:"expires_at,notnull"`
|
|
}
|
|
|
|
func UpdateDiscordToken(ctx context.Context, tx bun.Tx, user *User, token *discord.Token) error {
|
|
if user == nil {
|
|
return errors.New("user cannot be nil")
|
|
}
|
|
if token == nil {
|
|
return errors.New("token cannot be nil")
|
|
}
|
|
expiresAt := time.Now().Add(time.Duration(token.ExpiresIn) * time.Second).Unix()
|
|
|
|
discordToken := &DiscordToken{
|
|
DiscordID: user.DiscordID,
|
|
AccessToken: token.AccessToken,
|
|
RefreshToken: token.RefreshToken,
|
|
ExpiresAt: expiresAt,
|
|
}
|
|
|
|
_, err := tx.NewInsert().
|
|
Model(discordToken).
|
|
On("CONFLICT (discord_id) DO UPDATE").
|
|
Set("access_token = EXCLUDED.access_token").
|
|
Set("refresh_token = EXCLUDED.refresh_token").
|
|
Set("expires_at = EXCLUDED.expires_at").
|
|
Exec(ctx)
|
|
|
|
if err != nil {
|
|
return errors.Wrap(err, "tx.NewInsert")
|
|
}
|
|
return nil
|
|
}
|