auth-api/src/db/renewalTokens.go

62 lines
1.6 KiB
Go
Raw Normal View History

2021-01-05 16:49:50 +01:00
package db
import (
"context"
2022-01-22 15:43:33 +01:00
"gitea.larvit.se/pwrpln/auth-api/src/utils"
2021-01-05 16:49:50 +01:00
)
// RenewalTokenCreate obtain a new renewal token
func (d Db) RenewalTokenCreate(accountID string) (string, error) {
d.Log.Context = []interface{}{
"accountID", accountID,
}
d.Log.Debug("Creating new renewal token")
2021-01-05 16:49:50 +01:00
newToken := utils.RandString(60)
insertSQL := "INSERT INTO \"renewalTokens\" (\"accountId\",token) VALUES($1,$2);"
_, insertErr := d.DbPool.Exec(context.Background(), insertSQL, accountID, newToken)
if insertErr != nil {
d.Log.Error("Could not insert into database table \"renewalTokens\"", "err", insertErr.Error())
2021-01-05 16:49:50 +01:00
return "", insertErr
}
return newToken, nil
}
// RenewalTokenGet checks if a valid renewal token exists in database
func (d Db) RenewalTokenGet(token string) (string, error) {
2021-06-22 22:52:48 +02:00
d.Log.Debug("Trying to get a renewal token")
2021-01-05 16:49:50 +01:00
sql := "SELECT \"accountId\" FROM \"renewalTokens\" WHERE exp >= now() AND token = $1"
var foundAccountID string
err := d.DbPool.QueryRow(context.Background(), sql, token).Scan(&foundAccountID)
if err != nil {
if err.Error() == "no rows in result set" {
return "", nil
}
2021-06-22 22:52:48 +02:00
d.Log.Error("Database error when fetching renewal token", "err", err.Error())
2021-01-05 16:49:50 +01:00
return "", err
}
return foundAccountID, nil
}
// RenewalTokenRm removes a renewal token from the database
func (d Db) RenewalTokenRm(token string) error {
2021-06-22 22:52:48 +02:00
d.Log.Debug("Trying to remove a renewal token")
2021-01-05 16:49:50 +01:00
sql := "DELETE FROM \"renewalTokens\" WHERE token = $1"
_, err := d.DbPool.Exec(context.Background(), sql, token)
if err != nil {
2021-06-22 22:52:48 +02:00
d.Log.Error("Database error when trying to remove token", "err", err.Error())
2021-01-05 16:49:50 +01:00
return err
}
return nil
}