Skip to content

High performance, self-hosted, newsletter and mailing list manager with a modern dashboard. Single binary app.

Add OIDC auth hooks (init, callback, session) and finish OIDC support.

Kailash Nadh1e875afa67de
diff --git a/cmd/auth.go b/cmd/auth.go
index 3ca81568..d8144c56 100644
--- a/cmd/auth.go
+++ b/cmd/auth.go
@@ -33,6 +33,84 @@ var oidcProviders = map[string]bool{
// handleLoginPage renders the login page and handles the login form.
func handleLoginPage(c echo.Context) error {
+ // Process POST login request.
+ var loginErr error
+ if c.Request().Method == http.MethodPost {
+ loginErr = doLogin(c)
+ if loginErr == nil {
+ return c.Redirect(http.StatusFound, utils.SanitizeURI(c.FormValue("next")))
+ }
+ }
+
+ return renderLoginPage(c, loginErr)
+}
+
+// handleLogout logs a user out.
+func handleLogout(c echo.Context) error {
+ var (
+ sess = c.Get(auth.SessionKey).(*simplesessions.Session)
+ )
+
+ // Clear the session.
+ _ = sess.Destroy()
+
+ return c.JSON(http.StatusOK, okResp{true})
+}
+
+// handleOIDCLogin initializes an OIDC request and redirects to the OIDC provider for login.
+func handleOIDCLogin(c echo.Context) error {
+ app := c.Get("app").(*App)
+
+ // Verify that the request came from the login page (CSRF).
+ nonce, err := c.Cookie("nonce")
+ if err != nil || nonce.Value == "" || nonce.Value != c.FormValue("nonce") {
+ return echo.NewHTTPError(http.StatusUnauthorized, app.i18n.T("users.invalidRequest"))
+ }
+
+ next := utils.SanitizeURI(c.FormValue("next"))
+ if next == "/" {
+ next = uriAdmin
+ }
+
+ return c.Redirect(http.StatusFound, app.auth.GetOIDCAuthURL(next, nonce.Value))
+}
+
+// handleOIDCFinish receives the redirect callback from the OIDC provider and completes the handshake.
+func handleOIDCFinish(c echo.Context) error {
+ app := c.Get("app").(*App)
+
+ nonce, err := c.Cookie("nonce")
+ if err != nil || nonce.Value == "" {
+ return renderLoginPage(c, echo.NewHTTPError(http.StatusUnauthorized, app.i18n.T("users.invalidRequest")))
+ }
+
+ // Validate the OIDC token.
+ oidcToken, claims, err := app.auth.ExchangeOIDCToken(c.Request().URL.Query().Get("code"), nonce.Value)
+ if err != nil {
+ return renderLoginPage(c, err)
+ }
+
+ // Get the user by e-mail received from OIDC.
+ user, err := app.core.GetUser(0, "", claims.Email)
+ if err != nil {
+ return renderLoginPage(c, err)
+ }
+
+ // Update user login.
+ if err := app.core.UpdateUserLogin(user.ID, claims.Picture); err != nil {
+ return renderLoginPage(c, err)
+ }
+
+ // Set the session.
+ if err := app.auth.SetSession(user, oidcToken, c); err != nil {
+ return renderLoginPage(c, err)
+ }
+
+ return c.Redirect(http.StatusFound, utils.SanitizeURI(c.QueryParam("state")))
+}
+
+// renderLoginPage renders the login page and handles the login form.
+func renderLoginPage(c echo.Context, loginErr error) error {
var (
app = c.Get("app").(*App)
next = utils.SanitizeURI(c.FormValue("next"))
@@ -71,17 +149,11 @@ func handleLoginPage(c echo.Context) error {
NextURI: next,
}
- // Login request.
- if c.Request().Method == http.MethodPost {
- err := doLogin(c)
- if err == nil {
- return c.Redirect(http.StatusFound, utils.SanitizeURI(c.FormValue("next")))
- }
-
- if e, ok := err.(*echo.HTTPError); ok {
+ if loginErr != nil {
+ if e, ok := loginErr.(*echo.HTTPError); ok {
out.Error = e.Message.(string)
} else {
- out.Error = err.Error()
+ out.Error = loginErr.Error()
}
}
@@ -94,27 +166,15 @@ func handleLoginPage(c echo.Context) error {
c.SetCookie(&http.Cookie{
Name: "nonce",
Value: nonce,
- Secure: true,
HttpOnly: true,
- SameSite: http.SameSiteStrictMode,
+ Path: "/",
+ SameSite: http.SameSiteLaxMode,
})
out.Nonce = nonce
return c.Render(http.StatusOK, "admin-login", out)
}
-// handleLogout logs a user out.
-func handleLogout(c echo.Context) error {
- var (
- sess = c.Get(auth.SessionKey).(*simplesessions.Session)
- )
-
- // Clear the session.
- _ = sess.Destroy()
-
- return c.JSON(http.StatusOK, okResp{true})
-}
-
// doLogin logs a user in with a username and password.
func doLogin(c echo.Context) error {
var (
@@ -159,49 +219,3 @@ func doLogin(c echo.Context) error {
return nil
}
-
-// handleOIDCLogin initializes an OIDC request and redirects to the OIDC provider for login.
-func handleOIDCLogin(c echo.Context) error {
- app := c.Get("app").(*App)
-
- // Verify that the request came from the login page (CSRF).
- nonce, err := c.Cookie("nonce")
- if err != nil || nonce.Value == "" || nonce.Value != c.FormValue("nonce") {
- return echo.NewHTTPError(http.StatusUnauthorized, app.i18n.T("users.invalidRequest"))
- }
-
- return c.Redirect(http.StatusFound, app.auth.GetOIDCAuthURL(c.Request().URL.RequestURI(), nonce.Value))
-}
-
-// handleOIDCFinish receives the redirect callback from the OIDC provider and completes the handshake.
-func handleOIDCFinish(c echo.Context) error {
- app := c.Get("app").(*App)
-
- nonce, err := c.Cookie("nonce")
- if err != nil || nonce.Value == "" {
- return echo.NewHTTPError(http.StatusUnauthorized, app.i18n.T("users.invalidRequest"))
- }
-
- code := c.Request().URL.Query().Get("code")
- if err != nil {
- return echo.NewHTTPError(http.StatusUnauthorized, app.i18n.T("users.invalidRequest"))
- }
-
- oidcToken, u, err := app.auth.ExchangeOIDCToken(code, nonce.Value)
- if err != nil {
- return err
- }
-
- // Get the user by e-mail received from OIDC.
- user, err := app.core.GetUser(0, "", u.Email.String)
- if err != nil {
- return err
- }
-
- // Set the session.
- if err := app.auth.SetSession(user, oidcToken, c); err != nil {
- return err
- }
-
- return c.Redirect(http.StatusFound, utils.SanitizeURI(c.QueryParam("state")))
-}
diff --git a/cmd/init.go b/cmd/init.go
index a67295ac..17500287 100644
--- a/cmd/init.go
+++ b/cmd/init.go
@@ -942,15 +942,11 @@ func initAuth(db *sql.DB, ko *koanf.Koanf, co *core.Core) *auth.Auth {
if ko.Bool("security.oidc.enabled") {
oidcCfg = auth.OIDCConfig{
+ Enabled: true,
ProviderURL: ko.String("security.oidc.provider_url"),
ClientID: ko.String("security.oidc.client_id"),
ClientSecret: ko.String("security.oidc.client_secret"),
- RedirectURL: ko.String("security.oidc.redirect_url"),
- Skipper: func(c echo.Context) bool {
- // Skip OIDC check if the request is already BasicAuth'd.
- // This context flag is set in basicAuth().
- return c.Get(basicAuthd) != nil
- },
+ RedirectURL: fmt.Sprintf("%s/auth/oidc", strings.TrimRight(ko.String("app.root_url"), "/")),
}
}
diff --git a/cmd/users.go b/cmd/users.go
index dea4c7d2..830ec78b 100644
--- a/cmd/users.go
+++ b/cmd/users.go
@@ -229,10 +229,12 @@ func handleUpdateUserProfile(c echo.Context) error {
email := strings.TrimSpace(u.Email.String)
// Validate fields.
- if !utils.ValidateEmail(email) {
- return echo.NewHTTPError(http.StatusBadRequest, app.i18n.Ts("globals.messages.invalidFields", "name", "email"))
+ if user.PasswordLogin {
+ if !utils.ValidateEmail(email) {
+ return echo.NewHTTPError(http.StatusBadRequest, app.i18n.Ts("globals.messages.invalidFields", "name", "email"))
+ }
+ u.Email = null.String{String: email, Valid: true}
}
- u.Email = null.String{String: email, Valid: true}
if u.PasswordLogin && u.Password.String != "" {
if !strHasLen(u.Password.String, 8, stdInputMaxLen) {
diff --git a/i18n/en.json b/i18n/en.json
index 946d617e..8399ffd6 100644
--- a/i18n/en.json
+++ b/i18n/en.json
@@ -366,6 +366,7 @@
"settings.security.OIDCURL": "Provider URL",
"settings.security.OIDCClientID": "Client ID",
"settings.security.OIDCClientSecret": "Client secret",
+ "settings.security.OIDCRedirectURL": "Redirect URL for oAuth provider",
"settings.appearance.adminHelp": "Custom CSS to apply to the admin UI.",
"settings.appearance.adminName": "Admin",
"settings.appearance.customCSS": "Custom CSS",
diff --git a/internal/auth/auth.go b/internal/auth/auth.go
index 8939b5f6..3a9bbc97 100644
--- a/internal/auth/auth.go
+++ b/internal/auth/auth.go
@@ -16,7 +16,6 @@ import (
"github.com/coreos/go-oidc/v3/oidc"
"github.com/knadh/listmonk/models"
"github.com/labstack/echo/v4"
- "github.com/labstack/echo/v4/middleware"
"github.com/zerodha/simplesessions/stores/postgres/v3"
"github.com/zerodha/simplesessions/v3"
"golang.org/x/oauth2"
@@ -35,15 +34,19 @@ const (
sessTypeOIDC = "oidc"
)
+type OIDCclaim struct {
+ Email string `json:"email"`
+ EmailVerified bool `json:"email_verified"`
+ Sub string `json:"sub"`
+ Picture string `json:"picture"`
+}
+
type OIDCConfig struct {
Enabled bool `json:"enabled"`
ProviderURL string `json:"provider_url"`
RedirectURL string `json:"redirect_url"`
ClientID string `json:"client_id"`
ClientSecret string `json:"client_secret"`
-
- // Skipper defines a function to skip middleware.
- Skipper middleware.Skipper
}
type BasicAuthConfig struct {
@@ -71,7 +74,6 @@ type Auth struct {
cfg Config
oauthCfg oauth2.Config
verifier *oidc.IDTokenVerifier
- skipper middleware.Skipper
sess *simplesessions.Manager
sessStore *postgres.Store
cb *Callbacks
@@ -89,22 +91,21 @@ func New(cfg Config, db *sql.DB, cb *Callbacks, lo *log.Logger) (*Auth, error) {
if cfg.OIDC.Enabled {
provider, err := oidc.NewProvider(context.Background(), cfg.OIDC.ProviderURL)
if err != nil {
- panic(err)
- }
-
- a.verifier = provider.Verifier(&oidc.Config{
- ClientID: cfg.OIDC.ClientID,
- })
-
- a.oauthCfg = oauth2.Config{
- ClientID: cfg.OIDC.ClientID,
- ClientSecret: cfg.OIDC.ClientSecret,
- Endpoint: provider.Endpoint(),
- RedirectURL: cfg.OIDC.RedirectURL,
- Scopes: []string{oidc.ScopeOpenID, "profile", "email"},
+ lo.Printf("error initializing OIDC OAuth provider: %v", err)
+ } else {
+
+ a.verifier = provider.Verifier(&oidc.Config{
+ ClientID: cfg.OIDC.ClientID,
+ })
+
+ a.oauthCfg = oauth2.Config{
+ ClientID: cfg.OIDC.ClientID,
+ ClientSecret: cfg.OIDC.ClientSecret,
+ Endpoint: provider.Endpoint(),
+ RedirectURL: cfg.OIDC.RedirectURL,
+ Scopes: []string{oidc.ScopeOpenID, "profile", "email"},
+ }
}
-
- a.skipper = cfg.OIDC.Skipper
}
// Initialize session manager.
@@ -166,33 +167,32 @@ func (o *Auth) GetOIDCAuthURL(state, nonce string) string {
// ExchangeOIDCToken takes an OIDC authorization code (recieved via redirect from the OIDC provider),
// validates it, and returns an OIDC token for subsequent auth.
-func (o *Auth) ExchangeOIDCToken(code, nonce string) (string, models.User, error) {
- var user models.User
-
+func (o *Auth) ExchangeOIDCToken(code, nonce string) (string, OIDCclaim, error) {
tk, err := o.oauthCfg.Exchange(context.TODO(), code)
if err != nil {
- return "", user, echo.NewHTTPError(http.StatusUnauthorized, fmt.Sprintf("error exchanging token: %v", err))
+ return "", OIDCclaim{}, echo.NewHTTPError(http.StatusUnauthorized, fmt.Sprintf("error exchanging token: %v", err))
}
rawIDTk, ok := tk.Extra("id_token").(string)
if !ok {
- return "", user, echo.NewHTTPError(http.StatusUnauthorized, "`id_token` missing.")
+ return "", OIDCclaim{}, echo.NewHTTPError(http.StatusUnauthorized, "`id_token` missing.")
}
idTk, err := o.verifier.Verify(context.TODO(), rawIDTk)
if err != nil {
- return "", user, echo.NewHTTPError(http.StatusUnauthorized, fmt.Sprintf("error verifying ID token: %v", err))
+ return "", OIDCclaim{}, echo.NewHTTPError(http.StatusUnauthorized, fmt.Sprintf("error verifying ID token: %v", err))
}
if idTk.Nonce != nonce {
- return "", user, echo.NewHTTPError(http.StatusUnauthorized, "nonce did not match")
+ return "", OIDCclaim{}, echo.NewHTTPError(http.StatusUnauthorized, "nonce did not match")
}
- if err := idTk.Claims(&user); err != nil {
- return "", user, errors.New("error getting user from OIDC")
+ var claims OIDCclaim
+ if err := idTk.Claims(&claims); err != nil {
+ return "", OIDCclaim{}, errors.New("error getting user from OIDC")
}
- return rawIDTk, user, nil
+ return rawIDTk, claims, nil
}
// Middleware is the HTTP middleware used for wrapping HTTP handlers registered on the echo router.
@@ -272,11 +272,6 @@ func (o *Auth) Perm(next echo.HandlerFunc, perm string) echo.HandlerFunc {
// SetSession creates and sets a session (post successful login/auth).
func (o *Auth) SetSession(u models.User, oidcToken string, c echo.Context) error {
- // sess, err := o.sess.Acquire(nil, c, c)
- // if err != nil {
- // return echo.NewHTTPError(http.StatusInternalServerError, "error creating session")
- // }
-
sess, err := o.sess.NewSession(c, c)
if err != nil {
o.log.Printf("error creating login session: %v", err)
@@ -311,16 +306,6 @@ func (o *Auth) validateSession(c echo.Context) (*simplesessions.Session, models.
return nil, models.User{}, echo.NewHTTPError(http.StatusInternalServerError, err.Error())
}
- // If it's an OIDC session, validate the claim.
- if vars["oidc_token"] != "" {
- if !o.cfg.OIDC.Enabled {
- return nil, models.User{}, echo.NewHTTPError(http.StatusForbidden, "OIDC aut his not enabled.")
- }
- if _, err := o.verifyOIDC(vars["oidc_token"].(string), c); err != nil {
- return nil, models.User{}, err
- }
- }
-
// Fetch user details from the database.
user, err := o.cb.GetUser(userID)
if err != nil {
@@ -330,24 +315,6 @@ func (o *Auth) validateSession(c echo.Context) (*simplesessions.Session, models.
return sess, user, err
}
-func (o *Auth) verifyOIDC(token string, c echo.Context) (models.User, error) {
- idTk, err := o.verifier.Verify(c.Request().Context(), token)
- if err != nil {
- return models.User{}, err
- }
-
- var user models.User
- if err := idTk.Claims(&user); err != nil {
- return user, echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("error verifying OIDC claim: %v", user))
- }
-
- if user.ID < 1 {
- return user, echo.NewHTTPError(http.StatusForbidden, fmt.Sprintf("invalid user ID in OIDC: %v", user))
- }
-
- return user, err
-}
-
// parseAuthHeader parses the Authorization header and returns the api_key and access_token.
func parseAuthHeader(h string) (string, string, error) {
const authBasic = "Basic"
diff --git a/internal/core/users.go b/internal/core/users.go
index f46de061..038e95c9 100644
--- a/internal/core/users.go
+++ b/internal/core/users.go
@@ -3,7 +3,9 @@ package core
import (
"database/sql"
"encoding/json"
+ "errors"
"net/http"
+ "strings"
"github.com/knadh/listmonk/internal/utils"
"github.com/knadh/listmonk/models"
@@ -20,7 +22,7 @@ func (c *Core) GetUsers() ([]models.User, error) {
// GetUser retrieves a specific user based on any one given identifier.
func (c *Core) GetUser(id int, username, email string) (models.User, error) {
- out, err := c.getUsers(id, username, email)
+ out, err := c.getUsers(id, username, strings.ToLower(email))
if err != nil {
return models.User{}, echo.NewHTTPError(http.StatusInternalServerError,
c.i18n.Ts("globals.messages.errorFetching", "name", "{globals.terms.users}", "error", pqErrMsg(err)))
@@ -92,6 +94,16 @@ func (c *Core) UpdateUserProfile(id int, u models.User) (models.User, error) {
return c.GetUser(id, "", "")
}
+// UpdateUserLogin updates a user's record post-login.
+func (c *Core) UpdateUserLogin(id int, avatar string) error {
+ if _, err := c.q.UpdateUserLogin.Exec(id, avatar); err != nil {
+ return echo.NewHTTPError(http.StatusInternalServerError,
+ c.i18n.Ts("globals.messages.errorUpdating", "name", "{globals.terms.user}", "error", pqErrMsg(err)))
+ }
+
+ return nil
+}
+
// DeleteUsers deletes a given user.
func (c *Core) DeleteUsers(ids []int) error {
res, err := c.q.DeleteUsers.Exec(pq.Array(ids))
@@ -129,6 +141,10 @@ func (c *Core) getUsers(id int, username, email string) ([]models.User, error) {
c.i18n.Ts("globals.messages.errorFetching", "name", "{globals.terms.users}", "error", pqErrMsg(err)))
}
+ if len(out) == 0 {
+ return nil, errors.New("user not found")
+ }
+
for n, u := range out {
if u.Password.String != "" {
u.HasPassword = true
diff --git a/models/models.go b/models/models.go
index 1e9b1e77..83fc1922 100644
--- a/models/models.go
+++ b/models/models.go
@@ -157,7 +157,7 @@ type User struct {
Name string `db:"name" json:"name"`
Type string `db:"type" json:"type"`
Status string `db:"status" json:"status"`
- Avatar null.String `db:"-" json:"avatar"`
+ Avatar null.String `db:"avatar" json:"avatar"`
LoggedInAt null.Time `db:"loggedin_at" json:"loggedin_at"`
// Filled post-retrieval.
diff --git a/models/queries.go b/models/queries.go
index 7b17cf19..bba8e2d8 100644
--- a/models/queries.go
+++ b/models/queries.go
@@ -111,6 +111,7 @@ type Queries struct {
CreateUser *sqlx.Stmt `query:"create-user"`
UpdateUser *sqlx.Stmt `query:"update-user"`
UpdateUserProfile *sqlx.Stmt `query:"update-user-profile"`
+ UpdateUserLogin *sqlx.Stmt `query:"update-user-login"`
DeleteUsers *sqlx.Stmt `query:"delete-users"`
GetUsers *sqlx.Stmt `query:"get-users"`
GetAPITokens *sqlx.Stmt `query:"get-api-tokens"`
diff --git a/queries.sql b/queries.sql
index 6036ac43..4bd40537 100644
--- a/queries.sql
+++ b/queries.sql
@@ -1104,10 +1104,13 @@ WITH u AS (
SELECT * FROM u WHERE CRYPT($2, password) = password;
-- name: update-user-profile
-UPDATE users SET name=$2, email=$3,
+UPDATE users SET name=$2, email=(CASE WHEN password_login THEN $3 ELSE email END),
password=(CASE WHEN $4 = TRUE THEN (CASE WHEN $5 != '' THEN CRYPT($5, GEN_SALT('bf')) ELSE password END) ELSE NULL END)
WHERE id=$1;
+-- name: update-user-login
+UPDATE users SET loggedin_at=NOW(), avatar=(CASE WHEN $2 != '' THEN $2 ELSE avatar END) WHERE id=$1;
+
-- name: get-roles
WITH mainroles AS (
SELECT ur.* FROM user_roles ur WHERE ur.parent_id IS NULL