website/pkg/middleware/authentication.go

163 lines
4.8 KiB
Go
Raw Permalink Normal View History

package middleware
import (
"context"
"net/http"
"net/url"
"time"
2022-08-26 04:21:46 +00:00
"code.nonshy.com/nonshy/website/pkg/config"
"code.nonshy.com/nonshy/website/pkg/controller/photo"
"code.nonshy.com/nonshy/website/pkg/log"
"code.nonshy.com/nonshy/website/pkg/models"
"code.nonshy.com/nonshy/website/pkg/session"
"code.nonshy.com/nonshy/website/pkg/templates"
)
// LoginRequired middleware.
func LoginRequired(handler http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// User must be logged in.
user, err := session.CurrentUser(r)
if err != nil {
log.Error("LoginRequired: %s", err)
session.FlashError(w, r, "You must be signed in to view this page.")
templates.Redirect(w, "/login?next="+url.QueryEscape(r.URL.String()))
return
}
// Are they banned?
if user.Status == models.UserStatusBanned {
session.LogoutUser(w, r)
session.FlashError(w, r, "Your account has been banned and you are now logged out.")
templates.Redirect(w, "/")
return
}
// Is their account disabled?
if DisabledAccount(user, w, r) {
return
}
// Is the site under a Maintenance Mode restriction?
if MaintenanceMode(user, w, r) {
return
}
// Ping LastLoginAt for long lived sessions, but not if impersonated.
2024-04-26 01:55:02 +00:00
var pingLastLoginAt bool
if time.Since(user.LastLoginAt) > config.LastLoginAtCooldown && !session.Impersonated(r) {
user.LastLoginAt = time.Now()
2024-04-26 01:55:02 +00:00
pingLastLoginAt = true
if err := user.Save(); err != nil {
log.Error("LoginRequired: couldn't refresh LastLoginAt for user %s: %s", user.Username, err)
}
}
2024-04-26 01:55:02 +00:00
// Log the last visit of their current IP address.
if err := models.PingIPAddress(r, user, pingLastLoginAt); err != nil {
log.Error("LoginRequired: couldn't ping user %s IP address: %s", user.Username, err)
}
// Ask the user for their birthdate?
if AgeGate(user, w, r) {
return
}
// Stick the CurrentUser in the request context so future calls to session.CurrentUser can read it.
ctx := context.WithValue(r.Context(), session.CurrentUserKey, user)
handler.ServeHTTP(w, r.WithContext(ctx))
})
}
// AdminRequired middleware.
Admin Groups & Permissions Add a permission system for admin users so you can lock down specific admins to a narrower set of features instead of them all having omnipotent powers. * New page: Admin Dashboard -> Admin Permissions Management * Permissions are handled in the form of 'scopes' relevant to each feature or action on the site. Scopes are assigned to Groups, and in turn, admin user accounts are placed in those Groups. * The Superusers group (scope '*') has wildcard permission to all scopes. The permissions dashboard has a create-once action to initialize the Superusers for the first admin who clicks on it, and places that admin in the group. The following are the exhaustive list of permission changes on the site: * Moderator scopes: * Chat room (enter the room with Operator permission) * Forums (can edit or delete user posts on the forum) * Photo Gallery (can see all private/friends-only photos on the site gallery or user profile pages) * Certification photos (with nuanced sub-action permissions) * Approve: has access to the Pending tab to act on incoming pictures * List: can paginate thru past approved/rejected photos * View: can bring up specific user cert photo from their profile * The minimum requirement is Approve or else no cert photo page will load for your admin user. * User Actions (each action individually scoped) * Impersonate * Ban * Delete * Promote to admin * Inner circle whitelist: no longer are admins automatically part of the inner circle unless they have a specialized scope attached. The AdminRequired decorator may also apply scopes on an entire admin route. The following routes have scopes to limit them: * Forum Admin (manage forums and their settings) * Remove from inner circle
2023-08-02 03:39:48 +00:00
func AdminRequired(scope string, handler http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// User must be logged in.
currentUser, err := session.CurrentUser(r)
if err != nil {
log.Error("AdminRequired: %s", err)
session.FlashError(w, r, "You must be signed in to view this page.")
templates.Redirect(w, "/login?next="+url.QueryEscape(r.URL.String()))
return
}
// Stick the CurrentUser in the request context so future calls to session.CurrentUser can read it.
ctx := context.WithValue(r.Context(), session.CurrentUserKey, currentUser)
// Admin required.
if !currentUser.IsAdmin {
errhandler := templates.MakeErrorPage("Admin Required", "You do not have permission for this page.", http.StatusForbidden)
errhandler.ServeHTTP(w, r.WithContext(ctx))
return
}
Admin Groups & Permissions Add a permission system for admin users so you can lock down specific admins to a narrower set of features instead of them all having omnipotent powers. * New page: Admin Dashboard -> Admin Permissions Management * Permissions are handled in the form of 'scopes' relevant to each feature or action on the site. Scopes are assigned to Groups, and in turn, admin user accounts are placed in those Groups. * The Superusers group (scope '*') has wildcard permission to all scopes. The permissions dashboard has a create-once action to initialize the Superusers for the first admin who clicks on it, and places that admin in the group. The following are the exhaustive list of permission changes on the site: * Moderator scopes: * Chat room (enter the room with Operator permission) * Forums (can edit or delete user posts on the forum) * Photo Gallery (can see all private/friends-only photos on the site gallery or user profile pages) * Certification photos (with nuanced sub-action permissions) * Approve: has access to the Pending tab to act on incoming pictures * List: can paginate thru past approved/rejected photos * View: can bring up specific user cert photo from their profile * The minimum requirement is Approve or else no cert photo page will load for your admin user. * User Actions (each action individually scoped) * Impersonate * Ban * Delete * Promote to admin * Inner circle whitelist: no longer are admins automatically part of the inner circle unless they have a specialized scope attached. The AdminRequired decorator may also apply scopes on an entire admin route. The following routes have scopes to limit them: * Forum Admin (manage forums and their settings) * Remove from inner circle
2023-08-02 03:39:48 +00:00
// Ensure the admin scope.
if scope != "" && !currentUser.HasAdminScope(scope) {
errhandler := templates.MakeErrorPage(
"Admin Scope Required",
"Missing required admin scope: "+scope,
http.StatusForbidden,
)
errhandler.ServeHTTP(w, r.WithContext(ctx))
return
}
handler.ServeHTTP(w, r.WithContext(ctx))
})
}
// CertRequired middleware: like LoginRequired but user must also have their verification pic certified.
func CertRequired(handler http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// User must be logged in.
currentUser, err := session.CurrentUser(r)
if err != nil {
log.Error("LoginRequired: %s", err)
session.FlashError(w, r, "You must be signed in to view this page.")
templates.Redirect(w, "/login?next="+url.QueryEscape(r.URL.String()))
return
}
2024-04-26 01:55:02 +00:00
// Log the last visit of their current IP address.
if err := models.PingIPAddress(r, currentUser, false); err != nil {
log.Error("CertRequired: couldn't ping user %s IP address: %s", currentUser.Username, err)
}
// Are they banned?
if currentUser.Status == models.UserStatusBanned {
2023-03-10 00:57:38 +00:00
session.LogoutUser(w, r)
session.FlashError(w, r, "Your account has been banned and you are now logged out.")
templates.Redirect(w, "/")
return
}
// Is their account disabled?
if DisabledAccount(currentUser, w, r) {
return
}
// Is the site under a Maintenance Mode restriction?
if MaintenanceMode(currentUser, w, r) {
return
}
// User must be certified.
if !currentUser.Certified || currentUser.ProfilePhoto.ID == 0 {
log.Error("CertRequired: user is not certified")
photo.CertificationRequiredError().ServeHTTP(w, r)
return
}
// Ask the user for their birthdate?
if AgeGate(currentUser, w, r) {
return
}
handler.ServeHTTP(w, r)
})
}