rogueserver/api/common.go

60 lines
1.4 KiB
Go
Raw Normal View History

2023-12-31 13:12:20 -08:00
package api
import (
"encoding/base64"
"fmt"
2024-04-15 00:24:45 -07:00
"github.com/pagefaultgames/pokerogue-server/api/account"
"github.com/pagefaultgames/pokerogue-server/api/daily"
2024-04-14 16:25:36 -07:00
"github.com/pagefaultgames/pokerogue-server/db"
2023-12-31 13:12:20 -08:00
)
2024-04-19 03:05:52 -07:00
func Init() {
scheduleStatRefresh()
daily.Init()
}
2024-04-19 03:05:52 -07:00
func usernameFromTokenHeader(token string) (string, error) {
if token == "" {
2023-12-31 13:12:20 -08:00
return "", fmt.Errorf("missing token")
}
2024-04-19 03:05:52 -07:00
decoded, err := base64.StdEncoding.DecodeString(token)
2023-12-31 13:12:20 -08:00
if err != nil {
return "", fmt.Errorf("failed to decode token: %s", err)
}
2024-04-19 03:05:52 -07:00
if len(decoded) != account.TokenSize {
2024-04-15 00:24:45 -07:00
return "", fmt.Errorf("invalid token length: got %d, expected %d", len(token), account.TokenSize)
2023-12-31 13:12:20 -08:00
}
2024-04-19 03:05:52 -07:00
username, err := db.FetchUsernameFromToken(decoded)
2023-12-31 13:12:20 -08:00
if err != nil {
return "", fmt.Errorf("failed to validate token: %s", err)
}
return username, nil
}
2024-04-19 03:05:52 -07:00
func uuidFromTokenHeader(token string) ([]byte, error) {
if token == "" {
2023-12-31 13:12:20 -08:00
return nil, fmt.Errorf("missing token")
}
2024-04-19 03:05:52 -07:00
decoded, err := base64.StdEncoding.DecodeString(token)
2023-12-31 13:12:20 -08:00
if err != nil {
return nil, fmt.Errorf("failed to decode token: %s", err)
}
2024-04-19 03:05:52 -07:00
if len(decoded) != account.TokenSize {
2024-04-15 00:24:45 -07:00
return nil, fmt.Errorf("invalid token length: got %d, expected %d", len(token), account.TokenSize)
2023-12-31 13:12:20 -08:00
}
2024-04-19 03:05:52 -07:00
uuid, err := db.FetchUUIDFromToken(decoded)
2023-12-31 13:12:20 -08:00
if err != nil {
return nil, fmt.Errorf("failed to validate token: %s", err)
}
return uuid, nil
}