Initial commit
This commit is contained in:
commit
b6014c6ffc
47 files changed
+4329
No files matched your search
@@ -0,0 +1,74 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"vlog/internal/auth"
|
||||
)
|
||||
|
||||
// Login kicks off the OIDC authorization-code flow.
|
||||
func (h *Handlers) Login(w http.ResponseWriter, r *http.Request) {
|
||||
h.Authenticator.BeginLogin(w, r)
|
||||
}
|
||||
|
||||
// Callback completes the OIDC flow: verifies the ID token, JIT-provisions
|
||||
// the user row, mints our own session JWT, and redirects into the app.
|
||||
func (h *Handlers) Callback(w http.ResponseWriter, r *http.Request) {
|
||||
claims, err := h.Authenticator.HandleCallback(r.Context(), w, r)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusUnauthorized, "login failed: "+err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
var name *string
|
||||
if claims.Name != "" {
|
||||
name = &claims.Name
|
||||
}
|
||||
|
||||
var userID string
|
||||
err = h.dbGet(r.Context(), &userID, `
|
||||
INSERT INTO users (id, oidc_sub, email, name)
|
||||
VALUES (?, ?, ?, ?)
|
||||
ON CONFLICT (oidc_sub) DO UPDATE SET email = excluded.email, name = excluded.name
|
||||
RETURNING id
|
||||
`, uuid.New().String(), claims.Sub, claims.Email, name)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "failed to provision user")
|
||||
return
|
||||
}
|
||||
|
||||
token, err := auth.MintSessionJWT(h.JWTSecret, userID, claims.Email)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "failed to mint session")
|
||||
return
|
||||
}
|
||||
|
||||
auth.SetSessionCookie(w, token, h.SecureCookies)
|
||||
http.Redirect(w, r, "/", http.StatusFound)
|
||||
}
|
||||
|
||||
// Logout clears the session cookie.
|
||||
func (h *Handlers) Logout(w http.ResponseWriter, r *http.Request) {
|
||||
auth.ClearSessionCookie(w, h.SecureCookies)
|
||||
writeJSON(w, http.StatusOK, map[string]bool{"ok": true})
|
||||
}
|
||||
|
||||
// Me returns the current authenticated user.
|
||||
func (h *Handlers) Me(w http.ResponseWriter, r *http.Request) {
|
||||
userID, _ := auth.UserIDFromContext(r.Context())
|
||||
|
||||
var user struct {
|
||||
ID string `db:"id" json:"id"`
|
||||
Email string `db:"email" json:"email"`
|
||||
Name *string `db:"name" json:"name"`
|
||||
}
|
||||
err := h.dbGet(r.Context(), &user, `SELECT id, email, name FROM users WHERE id = ?`, userID)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusUnauthorized, "user not found")
|
||||
return
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusOK, user)
|
||||
}
|
||||
Reference in new issue
Block a user