2023-12-31 13:12:20 -08:00
|
|
|
package api
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/base64"
|
|
|
|
"fmt"
|
|
|
|
"net/http"
|
|
|
|
|
2024-04-15 00:24:45 -07:00
|
|
|
"github.com/pagefaultgames/pokerogue-server/api/account"
|
2024-04-14 17:03:53 -07:00
|
|
|
"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 09:41:05 -07:00
|
|
|
func Init() {
|
2024-04-14 17:03:53 -07:00
|
|
|
scheduleStatRefresh()
|
|
|
|
daily.Init()
|
|
|
|
}
|
|
|
|
|
2024-04-21 13:52:26 -07:00
|
|
|
func getTokenFromRequest(r *http.Request) ([]byte, error) {
|
2024-04-01 19:54:55 -07:00
|
|
|
if r.Header.Get("Authorization") == "" {
|
2024-04-21 13:52:26 -07:00
|
|
|
return nil, fmt.Errorf("missing token")
|
2023-12-31 13:12:20 -08:00
|
|
|
}
|
|
|
|
|
2024-04-01 19:54:55 -07:00
|
|
|
token, err := base64.StdEncoding.DecodeString(r.Header.Get("Authorization"))
|
2023-12-31 13:12:20 -08:00
|
|
|
if err != nil {
|
2024-04-21 13:52:26 -07:00
|
|
|
return nil, fmt.Errorf("failed to decode token: %s", err)
|
2023-12-31 13:12:20 -08:00
|
|
|
}
|
2024-04-21 15:57:27 -07:00
|
|
|
|
2024-04-15 00:24:45 -07:00
|
|
|
if len(token) != account.TokenSize {
|
2024-04-21 13:52:26 -07:00
|
|
|
return nil, fmt.Errorf("invalid token length: got %d, expected %d", len(token), account.TokenSize)
|
|
|
|
}
|
|
|
|
|
|
|
|
return token, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func getUsernameFromRequest(r *http.Request) (string, error) {
|
|
|
|
token, err := getTokenFromRequest(r)
|
|
|
|
if err != nil {
|
|
|
|
return "", err
|
2023-12-31 13:12:20 -08:00
|
|
|
}
|
|
|
|
|
2024-03-18 16:55:02 -07:00
|
|
|
username, err := db.FetchUsernameFromToken(token)
|
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-08 15:15:09 -07:00
|
|
|
func getUUIDFromRequest(r *http.Request) ([]byte, error) {
|
2024-04-21 13:52:26 -07:00
|
|
|
token, err := getTokenFromRequest(r)
|
2023-12-31 13:12:20 -08:00
|
|
|
if err != nil {
|
2024-04-21 13:52:26 -07:00
|
|
|
return nil, err
|
2023-12-31 13:12:20 -08:00
|
|
|
}
|
|
|
|
|
2024-04-08 15:15:09 -07:00
|
|
|
uuid, err := db.FetchUUIDFromToken(token)
|
2023-12-31 13:12:20 -08:00
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("failed to validate token: %s", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
return uuid, nil
|
|
|
|
}
|