424 lines
11 KiB
Go
424 lines
11 KiB
Go
package cabana
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
"encoding/json"
|
|
"errors"
|
|
"log/slog"
|
|
"net"
|
|
"net/http"
|
|
"strings"
|
|
"time"
|
|
|
|
"git.golem15.com/golem15/summercms/backpack"
|
|
"git.golem15.com/golem15/summercms/bouncer"
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
const (
|
|
// backendJWTBlacklistTable matches the framework migration in lagoon.
|
|
// It is not the frontend jwt_blacklist table.
|
|
backendJWTBlacklistTable = "backend_jwt_blacklist"
|
|
|
|
msgInvalidCredentials = "Invalid credentials"
|
|
msgUnauthenticated = "Unauthenticated"
|
|
msgForbidden = "Forbidden"
|
|
msgNotFound = "Not found"
|
|
msgServerError = "Server error"
|
|
)
|
|
|
|
// BackendUsers loads activated backend principals. It never reads frontend users.
|
|
type BackendUsers struct {
|
|
DB *gorm.DB
|
|
Registry *Registry
|
|
}
|
|
|
|
func (p BackendUsers) FindByID(ctx context.Context, id uint) (*bouncer.Principal, error) {
|
|
if p.DB == nil || id == 0 {
|
|
return nil, nil
|
|
}
|
|
var user BackendUser
|
|
err := p.DB.WithContext(ctx).Preload("Role").First(&user, id).Error
|
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
|
return nil, nil
|
|
}
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if !user.IsActivated {
|
|
return nil, nil
|
|
}
|
|
principal := principalFrom(user)
|
|
for code, allowed := range p.Registry.rolePermissions(user.Role.Code) {
|
|
if !allowed {
|
|
continue
|
|
}
|
|
if principal.PermissionGrants == nil {
|
|
principal.PermissionGrants = map[string]bool{}
|
|
}
|
|
principal.PermissionGrants[code] = true
|
|
}
|
|
return principal, nil
|
|
}
|
|
|
|
func principalFrom(user BackendUser) *bouncer.Principal {
|
|
principal := &bouncer.Principal{
|
|
ID: user.ID,
|
|
Backend: true,
|
|
IsSuperuser: user.IsSuperuser,
|
|
PermissionGrants: parseGrants(user.Role.Permissions),
|
|
}
|
|
if user.TokensValidAfter != nil {
|
|
principal.TokensValidAfter = *user.TokensValidAfter
|
|
}
|
|
return principal
|
|
}
|
|
|
|
func parseGrants(raw string) map[string]bool {
|
|
raw = strings.TrimSpace(raw)
|
|
if raw == "" || raw == "{}" || raw == "null" {
|
|
return nil
|
|
}
|
|
var decoded map[string]any
|
|
if err := json.Unmarshal([]byte(raw), &decoded); err != nil {
|
|
return nil
|
|
}
|
|
out := make(map[string]bool, len(decoded))
|
|
for code, value := range decoded {
|
|
if truthyGrant(value) {
|
|
out[code] = true
|
|
}
|
|
}
|
|
if len(out) == 0 {
|
|
return nil
|
|
}
|
|
return out
|
|
}
|
|
|
|
func truthyGrant(value any) bool {
|
|
switch v := value.(type) {
|
|
case bool:
|
|
return v
|
|
case float64:
|
|
return v == 1
|
|
case string:
|
|
return v == "1" || strings.EqualFold(v, "true")
|
|
case json.Number:
|
|
return v.String() == "1"
|
|
default:
|
|
return false
|
|
}
|
|
}
|
|
|
|
type loginBody struct {
|
|
Login string `json:"login"`
|
|
Email string `json:"email"`
|
|
Password string `json:"password"`
|
|
}
|
|
|
|
func (s *service) login(w http.ResponseWriter, r *http.Request) {
|
|
var body loginBody
|
|
dec := json.NewDecoder(http.MaxBytesReader(w, r.Body, 4096))
|
|
if err := dec.Decode(&body); err != nil {
|
|
WriteError(w, http.StatusUnauthorized, "unauthenticated", msgInvalidCredentials)
|
|
return
|
|
}
|
|
identifier := strings.TrimSpace(body.Login)
|
|
if identifier == "" {
|
|
identifier = strings.TrimSpace(body.Email)
|
|
}
|
|
if identifier == "" || body.Password == "" {
|
|
WriteError(w, http.StatusUnauthorized, "unauthenticated", msgInvalidCredentials)
|
|
return
|
|
}
|
|
db, err := s.db()
|
|
if err != nil {
|
|
WriteError(w, http.StatusInternalServerError, "error", msgServerError)
|
|
return
|
|
}
|
|
user, found, err := findBackendLogin(db.WithContext(r.Context()), identifier)
|
|
if err != nil {
|
|
WriteError(w, http.StatusInternalServerError, "error", msgServerError)
|
|
return
|
|
}
|
|
hash := dummyPasswordHash
|
|
if found && user.Password != "" {
|
|
hash = user.Password
|
|
}
|
|
ok := bouncer.CheckPassword(hash, body.Password)
|
|
if !found || !ok || !user.IsActivated {
|
|
id := uint(0)
|
|
if found {
|
|
id = user.ID
|
|
}
|
|
s.logAuth(r, "failed", id)
|
|
WriteError(w, http.StatusUnauthorized, "unauthenticated", msgInvalidCredentials)
|
|
return
|
|
}
|
|
now := time.Now().UTC()
|
|
if err := db.WithContext(r.Context()).Model(&BackendUser{}).Where("id = ?", user.ID).Update("last_login", now).Error; err != nil {
|
|
WriteError(w, http.StatusInternalServerError, "error", msgServerError)
|
|
return
|
|
}
|
|
if bouncer.NeedsRehash(user.Password, s.bcryptCost) {
|
|
if next, err := bouncer.HashPassword(s.bcryptCost, body.Password); err == nil {
|
|
_ = db.WithContext(r.Context()).Model(&BackendUser{}).Where("id = ?", user.ID).Update("password", next).Error
|
|
}
|
|
}
|
|
token, _, err := bouncer.MintAudience(s.secret, uitoa(user.ID), s.issuer, s.ttl, bouncer.AudienceBackend)
|
|
if err != nil {
|
|
WriteError(w, http.StatusInternalServerError, "error", msgServerError)
|
|
return
|
|
}
|
|
s.logAuth(r, "success", user.ID)
|
|
WriteData(w, http.StatusOK, map[string]string{
|
|
"access_token": token,
|
|
"token_type": "bearer",
|
|
}, map[string]any{})
|
|
}
|
|
|
|
func (s *service) refresh(w http.ResponseWriter, r *http.Request) {
|
|
raw := bearerToken(r)
|
|
if raw == "" {
|
|
s.logAuth(r, "failed", 0)
|
|
WriteError(w, http.StatusUnauthorized, "unauthenticated", msgUnauthenticated)
|
|
return
|
|
}
|
|
next, err := bouncer.RefreshAudience(s.secret, raw, bouncer.AudienceBackend, s.refreshTTL, s.bl, s.grace, s.issuer)
|
|
if err != nil {
|
|
s.logAuth(r, "failed", 0)
|
|
WriteError(w, http.StatusUnauthorized, "unauthenticated", msgUnauthenticated)
|
|
return
|
|
}
|
|
s.logAuth(r, "success", 0)
|
|
WriteData(w, http.StatusOK, map[string]string{
|
|
"access_token": next,
|
|
"token_type": "bearer",
|
|
}, map[string]any{})
|
|
}
|
|
|
|
func (s *service) logout(w http.ResponseWriter, r *http.Request) {
|
|
raw := bearerToken(r)
|
|
_, iat, exp, jti, err := bouncer.VerifyClaimsAudience(raw, s.secret, bouncer.AudienceBackend)
|
|
if err != nil || jti == "" {
|
|
WriteError(w, http.StatusUnauthorized, "unauthenticated", msgUnauthenticated)
|
|
return
|
|
}
|
|
if s.bl != nil {
|
|
expiresAt := iat.Add(s.refreshTTL).Add(time.Minute)
|
|
if until := exp.Add(time.Minute); until.After(expiresAt) {
|
|
expiresAt = until
|
|
}
|
|
if err := s.bl.Add(r.Context(), jti, expiresAt, time.Now()); err != nil {
|
|
WriteError(w, http.StatusInternalServerError, "error", msgServerError)
|
|
return
|
|
}
|
|
}
|
|
id := uint(0)
|
|
if principal, ok := bouncer.User(r.Context()); ok {
|
|
id = principal.ID
|
|
}
|
|
s.logAuth(r, "success", id)
|
|
WriteData(w, http.StatusOK, map[string]any{"status": "logged_out"}, map[string]any{})
|
|
}
|
|
|
|
func (s *service) me(w http.ResponseWriter, r *http.Request) {
|
|
principal, ok := bouncer.User(r.Context())
|
|
if !ok || principal == nil {
|
|
WriteError(w, http.StatusUnauthorized, "unauthenticated", msgUnauthenticated)
|
|
return
|
|
}
|
|
db, err := s.db()
|
|
if err != nil {
|
|
WriteError(w, http.StatusInternalServerError, "error", msgServerError)
|
|
return
|
|
}
|
|
var user BackendUser
|
|
err = db.WithContext(r.Context()).Preload("Role").First(&user, principal.ID).Error
|
|
if errors.Is(err, gorm.ErrRecordNotFound) || (err == nil && !user.IsActivated) {
|
|
WriteError(w, http.StatusUnauthorized, "unauthenticated", msgUnauthenticated)
|
|
return
|
|
}
|
|
if err != nil {
|
|
WriteError(w, http.StatusInternalServerError, "error", msgServerError)
|
|
return
|
|
}
|
|
WriteData(w, http.StatusOK, profileOf(user), map[string]any{})
|
|
}
|
|
|
|
func profileOf(user BackendUser) map[string]any {
|
|
data := map[string]any{
|
|
"id": user.ID,
|
|
"login": user.Login,
|
|
"email": user.Email,
|
|
"first_name": user.FirstName,
|
|
"last_name": user.LastName,
|
|
"is_superuser": user.IsSuperuser,
|
|
}
|
|
if user.Role.ID != 0 {
|
|
data["role"] = map[string]any{
|
|
"id": user.Role.ID,
|
|
"code": user.Role.Code,
|
|
"name": user.Role.Name,
|
|
}
|
|
}
|
|
return data
|
|
}
|
|
|
|
func bearerToken(r *http.Request) string {
|
|
if r == nil {
|
|
return ""
|
|
}
|
|
value := strings.TrimSpace(r.Header.Get("Authorization"))
|
|
token, ok := strings.CutPrefix(value, "Bearer ")
|
|
if !ok {
|
|
return ""
|
|
}
|
|
return strings.TrimSpace(token)
|
|
}
|
|
|
|
func (s *service) logAuth(r *http.Request, outcome string, adminID uint) {
|
|
remote := ""
|
|
method := ""
|
|
path := ""
|
|
if r != nil {
|
|
method = r.Method
|
|
if r.URL != nil {
|
|
path = r.URL.Path
|
|
}
|
|
remote = r.RemoteAddr
|
|
if host, _, err := net.SplitHostPort(remote); err == nil {
|
|
remote = host
|
|
}
|
|
}
|
|
args := []any{"outcome", outcome, "method", method, "path", path, "remote", remote}
|
|
if adminID != 0 {
|
|
args = append(args, "admin_id", adminID)
|
|
}
|
|
slog.Default().Info("admin.auth", args...)
|
|
}
|
|
|
|
func adminBlacklist(app *backpack.App) bouncer.BlacklistStore {
|
|
var sqlDB *sql.DB
|
|
if app != nil {
|
|
if db, ok := app.Lookup[*sql.DB](); ok {
|
|
sqlDB = db
|
|
} else if gdb, ok := app.Lookup[*gorm.DB](); ok && gdb != nil {
|
|
if db, err := gdb.DB(); err == nil {
|
|
sqlDB = db
|
|
}
|
|
}
|
|
}
|
|
if sqlDB == nil {
|
|
return nil
|
|
}
|
|
return bouncer.NewPostgresBlacklist(sqlDB, backendJWTBlacklistTable)
|
|
}
|
|
|
|
func findBackendLogin(db *gorm.DB, identifier string) (BackendUser, bool, error) {
|
|
email := strings.ToLower(identifier)
|
|
var user BackendUser
|
|
err := db.Preload("Role").Where("login = ? OR lower(email) = ?", identifier, email).First(&user).Error
|
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
|
return BackendUser{}, false, nil
|
|
}
|
|
if err != nil {
|
|
return BackendUser{}, false, err
|
|
}
|
|
return user, true, nil
|
|
}
|
|
|
|
func (s *service) db() (*gorm.DB, error) {
|
|
if s == nil || s.app == nil {
|
|
return nil, errors.New("cabana: database is not configured")
|
|
}
|
|
db, ok := s.app.Lookup[*gorm.DB]()
|
|
if !ok || db == nil {
|
|
return nil, errors.New("cabana: database is not configured")
|
|
}
|
|
return db, nil
|
|
}
|
|
|
|
func adminSecret(app *backpack.App) (string, error) {
|
|
secret := ""
|
|
if app != nil && app.Config != nil {
|
|
secret = strings.TrimSpace(app.Config.String("admin.jwt.secret"))
|
|
}
|
|
if secret == "" {
|
|
return "", errors.New("cabana: admin.jwt.secret is empty (set SUMMER_ADMIN__JWT__SECRET)")
|
|
}
|
|
return secret, nil
|
|
}
|
|
|
|
func adminTTL(app *backpack.App) time.Duration {
|
|
minutes := 60
|
|
if app != nil && app.Config != nil && app.Config.Int("admin.jwt.ttl") > 0 {
|
|
minutes = app.Config.Int("admin.jwt.ttl")
|
|
}
|
|
return time.Duration(minutes) * time.Minute
|
|
}
|
|
|
|
func adminRefreshTTL(app *backpack.App) time.Duration {
|
|
minutes := 20160
|
|
if app != nil && app.Config != nil && app.Config.Int("admin.jwt.refresh_ttl") > 0 {
|
|
minutes = app.Config.Int("admin.jwt.refresh_ttl")
|
|
}
|
|
return time.Duration(minutes) * time.Minute
|
|
}
|
|
|
|
func adminGrace(app *backpack.App) time.Duration {
|
|
seconds := 0
|
|
if app != nil && app.Config != nil && app.Config.Has("admin.jwt.blacklist_grace") {
|
|
seconds = app.Config.Int("admin.jwt.blacklist_grace")
|
|
}
|
|
if seconds < 0 {
|
|
seconds = 0
|
|
}
|
|
return time.Duration(seconds) * time.Second
|
|
}
|
|
|
|
func adminBcryptCost(app *backpack.App) int {
|
|
cost := 10
|
|
if app != nil && app.Config != nil && app.Config.Int("admin.password.bcrypt_cost") > 0 {
|
|
cost = app.Config.Int("admin.password.bcrypt_cost")
|
|
}
|
|
if cost < 4 || cost > 31 {
|
|
return 10
|
|
}
|
|
return cost
|
|
}
|
|
|
|
func adminLoginWindow(app *backpack.App) (int, int) {
|
|
maxAttempts, decayMinutes := 5, 1
|
|
if app != nil && app.Config != nil {
|
|
if n := app.Config.Int("admin.login.max_attempts"); n > 0 {
|
|
maxAttempts = n
|
|
}
|
|
if n := app.Config.Int("admin.login.decay_minutes"); n > 0 {
|
|
decayMinutes = n
|
|
}
|
|
}
|
|
return maxAttempts, decayMinutes
|
|
}
|
|
|
|
func adminIssuer(app *backpack.App) string {
|
|
base := ""
|
|
if app != nil && app.Config != nil {
|
|
base = strings.TrimRight(strings.TrimSpace(app.Config.String("app.url")), "/")
|
|
}
|
|
if base == "" {
|
|
return "/_admin/api/v1/auth/login"
|
|
}
|
|
return base + "/_admin/api/v1/auth/login"
|
|
}
|
|
|
|
// dummyPasswordHash keeps a missing-user login on the bcrypt path.
|
|
var dummyPasswordHash = func() string {
|
|
hash, err := bouncer.HashPassword(10, "cabana-invalid-credentials")
|
|
if err != nil {
|
|
return ""
|
|
}
|
|
return hash
|
|
}()
|