about summary refs log tree commit diff
path: root/nix/templates/goapp/frontend/src
diff options
context:
space:
mode:
Diffstat (limited to 'nix/templates/goapp/frontend/src')
-rw-r--r--nix/templates/goapp/frontend/src/handlers.go66
-rw-r--r--nix/templates/goapp/frontend/src/init.go25
-rw-r--r--nix/templates/goapp/frontend/src/main.go9
-rw-r--r--nix/templates/goapp/frontend/src/types.go27
4 files changed, 84 insertions, 43 deletions
diff --git a/nix/templates/goapp/frontend/src/handlers.go b/nix/templates/goapp/frontend/src/handlers.go
index 8fdd325..2cbacde 100644
--- a/nix/templates/goapp/frontend/src/handlers.go
+++ b/nix/templates/goapp/frontend/src/handlers.go
@@ -12,7 +12,7 @@ import (
 )
 
 func indexHandler(w http.ResponseWriter, r *http.Request) {
-	session, err := globalState.sessions.Get(r, "session")
+	session, err := globalState.sessions.Get(r, options.CookieName)
 	if err != nil {
 		log.Println("error getting the session")
 	}
@@ -37,9 +37,14 @@ func indexHandler(w http.ResponseWriter, r *http.Request) {
 			},
 		},
 	}
-	tpl.NextLinks = []Link{
-		{"Login", "/login"},
-	}
+
+	//  session.Values["id_token"] = claimsIDToken
+	//  session.Values["userinfo"] = claimsUserInfo
+	//  session.Values["logged"] = true
+	//
+	log.Println("logged", session.Values["logged"])
+	log.Println("id-token", session.Values["id_token"])
+	log.Println("userinfo", session.Values["userinfo"])
 
 	if logged, ok := session.Values["logged"].(bool); ok && logged {
 		tpl.LoggedIn = true
@@ -68,6 +73,10 @@ func indexHandler(w http.ResponseWriter, r *http.Request) {
 		tpl.Claims.UserInfo.Name = filterText(tpl.Claims.UserInfo.Name, options.Filters)
 		tpl.RawToken = rawTokens[tpl.Claims.IDToken.JWTIdentifier]
 		tpl.AuthorizeCodeURL = acURLs[tpl.Claims.IDToken.JWTIdentifier].String()
+
+		tpl.NextLinks = []Link{{"Logout", "/logout"}}
+	} else {
+		tpl.NextLinks = []Link{{"Login", "/login"}}
 	}
 
 	w.Header().Add("Content-Type", "text/html")
@@ -129,12 +138,11 @@ func logoutHandler(w http.ResponseWriter, r *http.Request) {
 	http.Redirect(w, r, "/", http.StatusFound)
 }
 
-func oauthCallbackHandler(res http.ResponseWriter, req *http.Request) {
+func oauthCallbackHandler(w http.ResponseWriter, r *http.Request) {
 	log.Println("hit the oauth callback handler")
-	if req.FormValue("error") != "" {
-		log.Printf("got an error from the idp: %s", req.FormValue("error"))
-		http.Redirect(res, req, fmt.Sprintf("/error?%s", req.Form.Encode()), http.StatusFound)
-
+	if r.FormValue("error") != "" {
+		log.Printf("got an error from the idp: %s", r.FormValue("error"))
+		http.Redirect(w, r, fmt.Sprintf("/error?%s", r.Form.Encode()), http.StatusFound)
 		return
 	}
 
@@ -146,24 +154,32 @@ func oauthCallbackHandler(res http.ResponseWriter, req *http.Request) {
 		ok         bool
 	)
 
+	log.Println(r.URL)
+
 	// The state should be checked here in production
-	if token, err = oauth2Config.Exchange(req.Context(), req.URL.Query().Get("code")); err != nil {
+	if token, err = oauth2Config.Exchange(
+		r.Context(),
+		r.URL.Query().Get("code"),
+		//  oauth2.SetAuthURLParam("client_id", oauth2Config.ClientID),
+		//  oauth2.SetAuthURLParam("client_secret", oauth2Config.ClientSecret),
+	); err != nil {
 		log.Println("Unable to exchange authorization code for tokens")
-		writeErr(res, err, "unable to exchange authorization code for tokens", http.StatusInternalServerError)
+		log.Println(err)
+		writeErr(w, err, "unable to exchange authorization code for tokens", http.StatusInternalServerError)
 		return
 	}
 
 	// Extract the ID Token from OAuth2 token.
 	if idTokenRaw, ok = token.Extra("id_token").(string); !ok {
 		log.Println("missing id token")
-		writeErr(res, nil, "missing id token", http.StatusInternalServerError)
+		writeErr(w, nil, "missing id token", http.StatusInternalServerError)
 		return
 	}
 
 	// Parse and verify ID Token payload.
-	if idToken, err = verifier.Verify(req.Context(), idTokenRaw); err != nil {
+	if idToken, err = verifier.Verify(r.Context(), idTokenRaw); err != nil {
 		log.Printf("unable to verify id token or token is invalid: %+v", idTokenRaw)
-		writeErr(res, err, "unable to verify id token or token is invalid", http.StatusInternalServerError)
+		writeErr(w, err, "unable to verify id token or token is invalid", http.StatusInternalServerError)
 		return
 	}
 
@@ -172,15 +188,15 @@ func oauthCallbackHandler(res http.ResponseWriter, req *http.Request) {
 
 	if err = idToken.Claims(&claimsIDToken); err != nil {
 		log.Printf("unable to decode id token claims: %+v", &claimsIDToken)
-		writeErr(res, err, "unable to decode id token claims", http.StatusInternalServerError)
+		writeErr(w, err, "unable to decode id token claims", http.StatusInternalServerError)
 		return
 	}
 
 	var userinfo *oidc.UserInfo
 
-	if userinfo, err = provider.UserInfo(req.Context(), oauth2.StaticTokenSource(token)); err != nil {
+	if userinfo, err = provider.UserInfo(r.Context(), oauth2.StaticTokenSource(token)); err != nil {
 		log.Printf("unable to retreive userinfo claims")
-		writeErr(res, err, "unable to retrieve userinfo claims", http.StatusInternalServerError)
+		writeErr(w, err, "unable to retrieve userinfo claims", http.StatusInternalServerError)
 		return
 	}
 
@@ -188,15 +204,15 @@ func oauthCallbackHandler(res http.ResponseWriter, req *http.Request) {
 
 	if err = userinfo.Claims(&claimsUserInfo); err != nil {
 		log.Printf("unable to decode userinfo claims")
-		writeErr(res, err, "unable to decode userinfo claims", http.StatusInternalServerError)
+		writeErr(w, err, "unable to decode userinfo claims", http.StatusInternalServerError)
 		return
 	}
 
 	var session *sessions.Session
 
-	if session, err = globalState.sessions.Get(req, options.CookieName); err != nil {
+	if session, err = globalState.sessions.Get(r, options.CookieName); err != nil {
 		log.Printf("unable to get session from cookie")
-		writeErr(res, err, "unable to get session from cookie", http.StatusInternalServerError)
+		writeErr(w, err, "unable to get session from cookie", http.StatusInternalServerError)
 		return
 	}
 
@@ -204,11 +220,11 @@ func oauthCallbackHandler(res http.ResponseWriter, req *http.Request) {
 	session.Values["userinfo"] = claimsUserInfo
 	session.Values["logged"] = true
 	rawTokens[claimsIDToken.JWTIdentifier] = idTokenRaw
-	acURLs[claimsIDToken.JWTIdentifier] = req.URL
+	acURLs[claimsIDToken.JWTIdentifier] = r.URL
 
-	if err = session.Save(req, res); err != nil {
+	if err = session.Save(r, w); err != nil {
 		log.Printf("unable to save session")
-		writeErr(res, err, "unable to save session", http.StatusInternalServerError)
+		writeErr(w, err, "unable to save session", http.StatusInternalServerError)
 		return
 	}
 
@@ -216,11 +232,11 @@ func oauthCallbackHandler(res http.ResponseWriter, req *http.Request) {
 
 	if redirectUrl, ok = session.Values["redirect-url"].(string); ok {
 		log.Printf("all fine!")
-		http.Redirect(res, req, redirectUrl, http.StatusFound)
+		http.Redirect(w, r, redirectUrl, http.StatusFound)
 		return
 	}
 
-	http.Redirect(res, req, "/", http.StatusFound)
+	http.Redirect(w, r, "/", http.StatusFound)
 }
 
 func writeErr(w http.ResponseWriter, err error, msg string, statusCode int) {
diff --git a/nix/templates/goapp/frontend/src/init.go b/nix/templates/goapp/frontend/src/init.go
index 97e58f0..75fd87d 100644
--- a/nix/templates/goapp/frontend/src/init.go
+++ b/nix/templates/goapp/frontend/src/init.go
@@ -2,8 +2,10 @@ package main
 
 import (
 	"context"
+	//  "crypto/tls"
 	"fmt"
 	"log"
+	//  "net/http"
 	"net/url"
 	"os"
 	"strings"
@@ -32,12 +34,17 @@ func dbInit() {
 
 func sessionInit() {
 	log.Println("[i] Setting up Session Storage...")
+	session_key, err := os.ReadFile(options.SessionKeyPath)
+	if err != nil {
+		log.Println("Could not read Session key")
+		panic(err)
+	}
 	store, err := NewSqliteStore(
 		sessiondbPath,
 		"sessions",
 		"/",
 		3600,
-		[]byte(os.Getenv("SESSION_KEY")))
+		session_key)
 	if err != nil {
 		panic(err)
 	}
@@ -60,17 +67,29 @@ func oauth2Init() (err error) {
 	}
 
 	verifier = provider.Verifier(&oidc.Config{ClientID: options.ClientID})
+
+	clientSecretBytes, err := os.ReadFile(options.ClientSecretPath)
+	if err != nil {
+		panic(err)
+	}
+	clientSecret := strings.TrimSpace(string(clientSecretBytes))
+
 	log.Printf("[ ] ClientID: %s", options.ClientID)
-	log.Printf("[ ] ClientSecret: %s", options.ClientSecret)
+	log.Printf("[ ] ClientSecret: %s", clientSecret)
 	log.Printf("[ ] redirectURL: %s", redirectURL.String())
 	log.Printf("[ ] providerEndpoint: %+v", provider.Endpoint())
 	log.Printf("[ ] Scopes: %s", options.Scopes)
+	log.Printf("[ ] Endpoint: %+v", provider.Endpoint())
+
 	oauth2Config = oauth2.Config{
 		ClientID:     options.ClientID,
-		ClientSecret: options.ClientSecret,
+		ClientSecret: clientSecret,
 		RedirectURL:  redirectURL.String(),
 		Endpoint:     provider.Endpoint(),
 		Scopes:       strings.Split(options.Scopes, ","),
 	}
+
+	oauth2Config.Endpoint.AuthStyle = oauth2.AuthStyleInParams
+
 	return nil
 }
diff --git a/nix/templates/goapp/frontend/src/main.go b/nix/templates/goapp/frontend/src/main.go
index fcf4224..72ec7ee 100644
--- a/nix/templates/goapp/frontend/src/main.go
+++ b/nix/templates/goapp/frontend/src/main.go
@@ -38,18 +38,21 @@ func main() {
 
 	rootCmd := &cobra.Command{Use: "goapp", RunE: root}
 
-	rootCmd.Flags().StringVar(&options.Host, "host", "0.0.0.0", "Specifies the tcp host to listen on")
+	rootCmd.Flags().StringVar(&options.Host, "host", "127.0.0.1", "Specifies the tcp host to listen on")
 	rootCmd.Flags().IntVar(&options.Port, "port", 8080, "Specifies the port to listen on")
 	rootCmd.Flags().StringVar(&options.PublicURL, "public-url", "http://localhost:8080/", "Specifies the root URL to generate the redirect URI")
 	rootCmd.Flags().StringVar(&options.ClientID, "id", "", "Specifies the OpenID Connect Client ID")
-	rootCmd.Flags().StringVarP(&options.ClientSecret, "secret", "s", "", "Specifies the OpenID Connect Client Secret")
+	rootCmd.Flags().StringVarP(&options.ClientSecretPath, "oidc-secret-path", "s", "", "Specifies the OpenID Connect Client Secret path")
 	rootCmd.Flags().StringVarP(&options.Issuer, "issuer", "i", "", "Specifies the URL for the OpenID Connect OP")
 	rootCmd.Flags().StringVar(&options.Scopes, "scopes", "openid,profile,email,groups", "Specifies the OpenID Connect scopes to request")
 	rootCmd.Flags().StringVar(&options.CookieName, "cookie-name", "oidc-client", "Specifies the storage cookie name to use")
 	rootCmd.Flags().StringSliceVar(&options.Filters, "filters", []string{}, "If specified filters the specified text from html output (not json) out of the email addresses, display names, audience, etc")
 	rootCmd.Flags().StringSliceVar(&options.GroupsFilter, "groups-filter", []string{}, "If specified only shows the groups in this list")
-	rootCmd.Flags().StringVar(&options.LogFilePath, "logpath", "./server.log", "Specifies the path to store the server logs at")
+	rootCmd.Flags().StringVar(&options.LogFilePath, "logfilepath", "./server.log", "Specifies the path to store the server logs at")
 	rootCmd.Flags().StringVar(&options.TemplatesPath, "templatespath", "./templates", "Specifies the path to where the templates are stored")
+	rootCmd.Flags().StringVar(&options.DatabasePath, "databasepath", "./main.db", "Specifies the path to where the database is stored")
+	rootCmd.Flags().StringVar(&options.SessionDBPath, "sessiondbpath", "./sessions.db", "Specifies the path to where the session database is stored")
+	rootCmd.Flags().StringVar(&options.SessionKeyPath, "sessionkeypath", "", "Specifies the path to where the session key is stored")
 
 	_ = rootCmd.MarkFlagRequired("id")
 	_ = rootCmd.MarkFlagRequired("secret")
diff --git a/nix/templates/goapp/frontend/src/types.go b/nix/templates/goapp/frontend/src/types.go
index 7efcc70..97e0db5 100644
--- a/nix/templates/goapp/frontend/src/types.go
+++ b/nix/templates/goapp/frontend/src/types.go
@@ -50,16 +50,19 @@ type ClamsAddress struct {
 }
 
 type Options struct {
-	Host          string
-	Port          int
-	LogFilePath   string
-	TemplatesPath string
-	ClientID      string
-	ClientSecret  string
-	Issuer        string
-	PublicURL     string
-	Scopes        string
-	CookieName    string
-	Filters       []string
-	GroupsFilter  []string
+	ClientID         string
+	ClientSecretPath string
+	CookieName       string
+	DatabasePath     string
+	Filters          []string
+	GroupsFilter     []string
+	Host             string
+	Issuer           string
+	LogFilePath      string
+	Port             int
+	PublicURL        string
+	Scopes           string
+	SessionDBPath    string
+	SessionKeyPath   string
+	TemplatesPath    string
 }