Mandanten, OAuth, Cleanup von der Main Methode.
This commit is contained in:
108
utils/authentication.go
Normal file
108
utils/authentication.go
Normal file
@ -0,0 +1,108 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"github.com/coreos/go-oidc/v3/oidc"
|
||||
"github.com/gofiber/fiber/v2"
|
||||
"github.com/gofiber/fiber/v2/middleware/adaptor"
|
||||
"golang.org/x/oauth2"
|
||||
)
|
||||
|
||||
func setCallbackCookie(w http.ResponseWriter, r *http.Request, name, value string) {
|
||||
setCallbackCookieExp(w, r, name, value, int(time.Hour.Seconds()))
|
||||
}
|
||||
|
||||
func setCallbackCookieExp(w http.ResponseWriter, r *http.Request, name, value string, maxAge int) {
|
||||
c := &http.Cookie{
|
||||
Name: name,
|
||||
Value: value,
|
||||
Path: "/",
|
||||
MaxAge: maxAge,
|
||||
Secure: r.TLS != nil,
|
||||
HttpOnly: true,
|
||||
}
|
||||
http.SetCookie(w, c)
|
||||
}
|
||||
|
||||
func CreateOIDCClient(ctx context.Context, app *fiber.App, logger *slog.Logger) {
|
||||
provider, err := oidc.NewProvider(ctx, "https://keycloak.kocoder.xyz/realms/che")
|
||||
if err != nil {
|
||||
logger.Error("Error generating OIDC Provider. ", "error", err)
|
||||
}
|
||||
|
||||
oauthConfig := oauth2.Config{
|
||||
ClientID: os.Getenv("CLIENT_ID"),
|
||||
ClientSecret: os.Getenv("CLIENT_SECRET"),
|
||||
RedirectURL: "http://localhost:3000/api/auth/callback",
|
||||
|
||||
Endpoint: provider.Endpoint(),
|
||||
|
||||
Scopes: []string{oidc.ScopeOpenID, oidc.ScopeOfflineAccess, "profile", "email"},
|
||||
}
|
||||
|
||||
app.Get("/api/auth", adaptor.HTTPHandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
state, err := RandString(16)
|
||||
if err != nil {
|
||||
logger.Warn("Unable to create a state", "error", err)
|
||||
http.Error(w, "Unable to create a state", http.StatusInternalServerError)
|
||||
}
|
||||
|
||||
setCallbackCookie(w, r, "state", state)
|
||||
|
||||
http.Redirect(w, r, oauthConfig.AuthCodeURL(state), http.StatusFound)
|
||||
}))
|
||||
|
||||
app.Get("/api/auth/callback", adaptor.HTTPHandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
state, err := r.Cookie("state")
|
||||
if err != nil {
|
||||
logger.Warn("State cookie not found", "error", err)
|
||||
http.Error(w, "state not found", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
if r.URL.Query().Get("state") != state.Value {
|
||||
logger.Warn("State cookie and header not matching", "error", err)
|
||||
http.Error(w, "states not matching", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
oauth2Token, err := oauthConfig.Exchange(ctx, r.URL.Query().Get("code"))
|
||||
if err != nil {
|
||||
logger.Warn("Failed to exchange token", "error", err)
|
||||
http.Error(w, "Failed to exchange token: "+err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
userInfo, err := provider.UserInfo(ctx, oauth2.StaticTokenSource(oauth2Token))
|
||||
if err != nil {
|
||||
logger.Warn("failed to get userinfo", "error", err)
|
||||
http.Error(w, "Failed to get userinfo: "+err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
resp := struct {
|
||||
Token *oauth2.Token
|
||||
UserInfo *oidc.UserInfo
|
||||
}{oauth2Token, userInfo}
|
||||
|
||||
data, err := json.MarshalIndent(resp, "", " ")
|
||||
if err != nil {
|
||||
logger.Warn("Failed to parse JSON", "error", err)
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
setCallbackCookieExp(w, r, "state", "", -1)
|
||||
|
||||
_, err = w.Write(data)
|
||||
if err != nil {
|
||||
logger.Error("Unable to send response", "error", err)
|
||||
}
|
||||
}))
|
||||
}
|
||||
Reference in New Issue
Block a user