rogueserver/api/common.go

60 lines
1.3 KiB
Go
Raw Normal View History

2023-12-31 13:12:20 -08:00
package api
import (
"encoding/base64"
"fmt"
"net/http"
"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
)
func Init() {
scheduleStatRefresh()
daily.Init()
}
2024-04-01 19:54:55 -07:00
func getUsernameFromRequest(r *http.Request) (string, error) {
if r.Header.Get("Authorization") == "" {
2023-12-31 13:12:20 -08:00
return "", fmt.Errorf("missing token")
}
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 {
return "", fmt.Errorf("failed to decode token: %s", err)
}
if len(token) != 32 {
return "", fmt.Errorf("invalid token length: got %d, expected 32", len(token))
}
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-01 19:54:55 -07:00
if r.Header.Get("Authorization") == "" {
2023-12-31 13:12:20 -08:00
return nil, fmt.Errorf("missing token")
}
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 {
return nil, fmt.Errorf("failed to decode token: %s", err)
}
if len(token) != 32 {
return nil, fmt.Errorf("invalid token length: got %d, expected 32", len(token))
}
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
}