This repository has been archived on 2024-03-28. You can view files and clone it, but cannot push or open issues or pull requests.
atsebay.t/auth_oidc.go

140 lines
3.9 KiB
Go
Raw Normal View History

2020-03-04 11:07:12 +00:00
package main
import (
"context"
"encoding/hex"
"flag"
"fmt"
"log"
"net/http"
"golang.org/x/oauth2"
"github.com/coreos/go-oidc/v3/oidc"
2020-03-04 11:07:12 +00:00
"github.com/julienschmidt/httprouter"
)
var (
2020-09-14 08:23:44 +00:00
oidcClientID = ""
oidcSecret = ""
2020-03-08 00:06:44 +00:00
oidcRedirectURL = "https://srs.nemunai.re"
2020-09-14 08:23:44 +00:00
oauth2Config oauth2.Config
oidcVerifier *oidc.IDTokenVerifier
nextSessionMap = map[string]string{}
2020-03-04 11:07:12 +00:00
)
func init() {
flag.StringVar(&oidcClientID, "oidc-clientid", oidcClientID, "ClientID for OIDC")
flag.StringVar(&oidcSecret, "oidc-secret", oidcSecret, "Secret for OIDC")
2020-03-08 00:06:44 +00:00
flag.StringVar(&oidcRedirectURL, "oidc-redirect", oidcRedirectURL, "Base URL for the redirect after connection")
2020-03-04 11:07:12 +00:00
router.GET("/auth/CRI", redirectOIDC_CRI)
router.GET("/auth/complete", OIDC_CRI_complete)
}
func initializeOIDC() {
if oidcClientID != "" && oidcSecret != "" {
2020-09-14 08:23:44 +00:00
provider, err := oidc.NewProvider(context.Background(), "https://cri.epita.fr")
2020-03-04 11:07:12 +00:00
if err != nil {
log.Fatal("Unable to setup oidc:", err)
}
oauth2Config = oauth2.Config{
ClientID: oidcClientID,
ClientSecret: oidcSecret,
2020-03-08 00:06:44 +00:00
RedirectURL: oidcRedirectURL + baseURL + "/auth/complete",
2020-03-04 11:07:12 +00:00
// Discovery returns the OAuth2 endpoints.
Endpoint: provider.Endpoint(),
// "openid" is a required scope for OpenID Connect flows.
2020-11-24 13:06:29 +00:00
Scopes: []string{oidc.ScopeOpenID, "profile", "email", "epita"},
2020-03-04 11:07:12 +00:00
}
oidcConfig := oidc.Config{
2020-09-14 08:23:44 +00:00
ClientID: oidcClientID,
2020-03-04 11:07:12 +00:00
}
oidcVerifier = provider.Verifier(&oidcConfig)
}
}
func redirectOIDC_CRI(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
session, err := NewSession()
// Save next parameter
if len(r.URL.Query().Get("next")) > 0 {
nextSessionMap[fmt.Sprintf("%x", session.Id)] = r.URL.Query().Get("next")
}
2020-03-04 11:07:12 +00:00
if err != nil {
http.Error(w, fmt.Sprintf("{'errmsg':%q}", err.Error()), http.StatusInternalServerError)
} else {
http.Redirect(w, r, oauth2Config.AuthCodeURL(hex.EncodeToString(session.Id)), http.StatusFound)
}
}
func OIDC_CRI_complete(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
idsession, err := hex.DecodeString(r.URL.Query().Get("state"))
if err != nil {
http.Error(w, fmt.Sprintf("{'errmsg':%q}", err.Error()), http.StatusBadRequest)
return
}
session, err := getSession(idsession)
if err != nil {
http.Error(w, fmt.Sprintf("{'errmsg':%q}", err.Error()), http.StatusBadRequest)
return
}
oauth2Token, err := oauth2Config.Exchange(context.Background(), r.URL.Query().Get("code"))
if err != nil {
http.Error(w, "Failed to exchange token: "+err.Error(), http.StatusInternalServerError)
return
}
rawIDToken, ok := oauth2Token.Extra("id_token").(string)
if !ok {
http.Error(w, "No id_token field in oauth2 token.", http.StatusInternalServerError)
return
}
idToken, err := oidcVerifier.Verify(context.Background(), rawIDToken)
if err != nil {
http.Error(w, "Failed to verify ID Token: "+err.Error(), http.StatusInternalServerError)
return
}
var claims struct {
2021-09-15 22:26:09 +00:00
Firstname string `json:"given_name"`
Lastname string `json:"family_name"`
Nickname string `json:"nickname"`
Username string `json:"preferred_username"`
Email string `json:"email"`
Groups []map[string]interface{} `json:"groups"`
2020-03-04 11:07:12 +00:00
}
if err := idToken.Claims(&claims); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
2021-09-15 22:26:09 +00:00
groups := ","
for _, g := range claims.Groups {
if slug, ok := g["slug"]; ok {
groups += slug.(string) + ","
}
}
2021-01-09 14:06:26 +00:00
2021-11-18 11:12:28 +00:00
if _, err := completeAuth(w, claims.Username, claims.Email, claims.Firstname, claims.Lastname, groups, &session); err != nil {
2020-03-04 11:07:12 +00:00
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Retrieve next URL associated with session
if next, ok := nextSessionMap[fmt.Sprintf("%x", session.Id)]; ok {
http.Redirect(w, r, next, http.StatusFound)
delete(nextSessionMap, fmt.Sprintf("%x", session.Id))
} else {
http.Redirect(w, r, "/", http.StatusFound)
}
2020-03-04 11:07:12 +00:00
}