This repository has been archived on 2025-08-09. You can view files and clone it. You cannot open issues or pull requests or push a commit.
Files
web-app-template/utils/auth.go
Tim f826718c03
All checks were successful
Build Docker Image / Explore-Gitea-Actions (push) Successful in 47s
#73 begin implement keycloak
2024-08-25 21:52:35 +02:00

87 lines
1.8 KiB
Go

package utils
import (
"encoding/json"
"errors"
"io"
"log"
"net/http"
"strings"
"github.com/golang-jwt/jwt/v5"
)
func InitializeAuth() {
resp, err := http.Get("https://auth.me-fit.eu/realms/me-fit/protocol/openid-connect/certs")
if err != nil {
log.Fatalf("error getting certs: %v\n", err)
}
body, err := io.ReadAll(resp.Body)
if err != nil {
log.Fatalf("error reading body: %v\n", err)
}
var certs map[string]interface{}
err = json.Unmarshal(body, &certs)
if err != nil {
log.Fatalf("error unmarshalling certs: %v\n", err)
}
log.Println("initialized auth", certs["keys"].([]interface{})[0].(map[string]interface{})["kid"])
}
func keyFunc() jwt.Keyfunc {
return func(token *jwt.Token) (interface{}, error) {
return []byte("secret"), nil
}
}
func isAuthorized(r *http.Request) (*jwt.Token, error) {
auth := r.Header.Get("Authorization")
if auth == "" {
return nil, errors.New("no authorization header")
}
tokenStr := strings.Split(auth, " ")[1]
if tokenStr == "" {
return nil, errors.New("no authorization header")
}
token, err := jwt.Parse(tokenStr, keyFunc(), nil)
if err != nil {
return nil, errors.New("no authorization header")
}
if !token.Valid {
return nil, errors.New("no authorization header")
}
return token, nil
}
// func VerifyToken(token string) (*auth.Token, error) {
// if app == nil {
// setup()
// }
//
// client, err := app.Auth(context.Background())
// if err != nil {
// log.Fatalf("error getting Auth client: %v\n", err)
// }
// return client.VerifyIDToken(context.Background(), token)
// }
//
// func setup() {
// opt := option.WithCredentialsFile("./secrets/firebase.json")
//
// firebaseApp, err := firebase.NewApp(context.Background(), nil, opt)
//
// if err != nil {
// log.Fatalf("error initializing app: %v", err)
// }
//
// app = firebaseApp
// }