implement auth using Auth0

This commit is contained in:
2025-12-29 23:49:23 -07:00
parent c9100383e4
commit cc74842e63
18 changed files with 797 additions and 212 deletions
+86
View File
@@ -0,0 +1,86 @@
package site
import (
"fmt"
"net/http"
)
// GET /login
func (s *Server) loginPage(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
state, err := s.auth.NewState(ctx)
if err != nil {
http.Error(w, fmt.Sprintf("failed to generate random state: %v", err), http.StatusInternalServerError)
return
}
base64EncodedState := fmt.Sprintf("%x", state[:])
http.Redirect(w, r, s.auth.AuthCodeURL(base64EncodedState), http.StatusTemporaryRedirect)
}
// POST /login
func (s *Server) login(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
email := r.FormValue("email")
if email == "" {
http.Error(w, "no email provided", http.StatusBadRequest)
return
}
acct, err := s.accts.GetAccountByEmail(ctx, email)
if err != nil {
http.Error(w, fmt.Sprintf("failed to create account: %v", err), http.StatusInternalServerError)
return
}
//http.Redirect(w, r, fmt.Sprintf("/site/accounts/%d", acct.ID), http.StatusSeeOther)
http.Redirect(w, r, fmt.Sprintf("/accounts/%d", acct.ID), http.StatusSeeOther)
}
// GET /login/callback
func (s *Server) loginCallback(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
q := r.URL.Query()
// obtain token and profile
accessToken, expiration, err := s.auth.Exchange(ctx, q.Get("state"), q.Get("code"))
if err != nil {
http.Error(w, "Failed to exchange an authorization code for a token", http.StatusUnauthorized)
return
}
// set access_token cookie and redirect to a reasonable place
w.Header().Set("Set-Cookie", (&http.Cookie{
Name: "access_token",
Value: accessToken,
Path: "/",
Expires: expiration,
MaxAge: 0, // using Expiration instead
Secure: true,
SameSite: http.SameSiteStrictMode,
}).String())
http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
}
// GET /logout
func (s *Server) logoutPage(w http.ResponseWriter, r *http.Request) {
host := r.Header.Get("X-Forwarded-Host")
if host == "" {
host = r.Host
}
deleteCookieInResponse(w, "access_token")
if ck, err := r.Cookie("access_token"); err == nil && ck != nil {
if err := s.auth.DeleteOAuthTokens(r.Context(), ck.Value); err != nil {
fmt.Println("[ERROR] failed to delete auth token:", err)
}
}
http.Redirect(w, r, s.auth.GetLogoutURL(host).String(), http.StatusTemporaryRedirect)
}