Refactored user/volunteer/participant identity.

This commit is contained in:
Pen Anderson 2026-03-10 14:08:00 -05:00
parent e640bf8bed
commit 883ebd584f
28 changed files with 450 additions and 265 deletions

30
auth.go
View file

@ -12,10 +12,10 @@ import (
)
type Claims struct {
UserID int `json:"uid"`
Username string `json:"sub"`
Role string `json:"role"`
DeptIDs []int `json:"dept_ids,omitempty"`
ParticipantID int `json:"pid"`
Email string `json:"sub"`
Roles []string `json:"roles"`
DeptIDs []int `json:"dept_ids,omitempty"`
jwt.RegisteredClaims
}
@ -28,13 +28,13 @@ func checkPassword(hash, password string) bool {
return bcrypt.CompareHashAndPassword([]byte(hash), []byte(password)) == nil
}
func (app *App) signToken(u *User) (string, error) {
func (app *App) signToken(s *User) (string, error) {
expiry := time.Duration(app.tokenExpiry) * time.Hour
claims := Claims{
UserID: u.ID,
Username: u.Username,
Role: u.Role,
DeptIDs: u.DepartmentIDs,
ParticipantID: s.ID,
Email: s.Email,
Roles: s.Roles,
DeptIDs: s.DepartmentIDs,
RegisteredClaims: jwt.RegisteredClaims{
ExpiresAt: jwt.NewNumericDate(time.Now().Add(expiry)),
IssuedAt: jwt.NewNumericDate(time.Now()),
@ -88,7 +88,7 @@ func (app *App) requireAuth(next http.HandlerFunc, roles ...string) http.Handler
writeError(w, "unauthorized", http.StatusUnauthorized)
return
}
if len(roles) > 0 && !hasRole(claims.Role, roles) {
if len(roles) > 0 && !hasAnyRole(claims.Roles, roles) {
writeError(w, "forbidden", http.StatusForbidden)
return
}
@ -97,10 +97,12 @@ func (app *App) requireAuth(next http.HandlerFunc, roles ...string) http.Handler
}
}
func hasRole(role string, allowed []string) bool {
for _, r := range allowed {
if r == role {
return true
func hasAnyRole(roles []string, allowed []string) bool {
for _, r := range roles {
for _, a := range allowed {
if r == a {
return true
}
}
}
return false