2022-07-06 23:19:05 +02:00
|
|
|
package apis
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"log"
|
2022-08-20 04:56:56 +02:00
|
|
|
"net"
|
2022-07-06 23:19:05 +02:00
|
|
|
"net/http"
|
|
|
|
"strings"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/labstack/echo/v5"
|
|
|
|
"github.com/pocketbase/pocketbase/core"
|
|
|
|
"github.com/pocketbase/pocketbase/models"
|
2022-10-30 10:28:14 +02:00
|
|
|
"github.com/pocketbase/pocketbase/tokens"
|
|
|
|
"github.com/pocketbase/pocketbase/tools/list"
|
2022-07-06 23:19:05 +02:00
|
|
|
"github.com/pocketbase/pocketbase/tools/routine"
|
2022-10-30 10:28:14 +02:00
|
|
|
"github.com/pocketbase/pocketbase/tools/security"
|
2022-07-06 23:19:05 +02:00
|
|
|
"github.com/pocketbase/pocketbase/tools/types"
|
|
|
|
"github.com/spf13/cast"
|
|
|
|
)
|
|
|
|
|
|
|
|
// Common request context keys used by the middlewares and api handlers.
|
|
|
|
const (
|
|
|
|
ContextAdminKey string = "admin"
|
2022-10-30 10:28:14 +02:00
|
|
|
ContextAuthRecordKey string = "authRecord"
|
2022-07-06 23:19:05 +02:00
|
|
|
ContextCollectionKey string = "collection"
|
|
|
|
)
|
|
|
|
|
|
|
|
// RequireGuestOnly middleware requires a request to NOT have a valid
|
2022-10-30 10:28:14 +02:00
|
|
|
// Authorization header.
|
2022-07-06 23:19:05 +02:00
|
|
|
//
|
2022-10-30 10:28:14 +02:00
|
|
|
// This middleware is the opposite of [apis.RequireAdminOrRecordAuth()].
|
2022-07-06 23:19:05 +02:00
|
|
|
func RequireGuestOnly() echo.MiddlewareFunc {
|
|
|
|
return func(next echo.HandlerFunc) echo.HandlerFunc {
|
|
|
|
return func(c echo.Context) error {
|
2022-10-30 10:28:14 +02:00
|
|
|
err := NewBadRequestError("The request can be accessed only by guests.", nil)
|
2022-07-06 23:19:05 +02:00
|
|
|
|
2022-10-30 10:28:14 +02:00
|
|
|
record, _ := c.Get(ContextAuthRecordKey).(*models.Record)
|
|
|
|
if record != nil {
|
2022-07-06 23:19:05 +02:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
admin, _ := c.Get(ContextAdminKey).(*models.Admin)
|
|
|
|
if admin != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
return next(c)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-10-30 10:28:14 +02:00
|
|
|
// RequireRecordAuth middleware requires a request to have
|
|
|
|
// a valid record auth Authorization header.
|
|
|
|
//
|
|
|
|
// The auth record could be from any collection.
|
|
|
|
//
|
|
|
|
// You can further filter the allowed record auth collections by
|
|
|
|
// specifying their names.
|
|
|
|
//
|
|
|
|
// Example:
|
2023-02-18 19:33:42 +02:00
|
|
|
//
|
|
|
|
// apis.RequireRecordAuth()
|
|
|
|
//
|
2022-10-30 10:28:14 +02:00
|
|
|
// Or:
|
2023-02-18 19:33:42 +02:00
|
|
|
//
|
|
|
|
// apis.RequireRecordAuth("users", "supervisors")
|
2022-10-30 10:28:14 +02:00
|
|
|
//
|
|
|
|
// To restrict the auth record only to the loaded context collection,
|
|
|
|
// use [apis.RequireSameContextRecordAuth()] instead.
|
|
|
|
func RequireRecordAuth(optCollectionNames ...string) echo.MiddlewareFunc {
|
|
|
|
return func(next echo.HandlerFunc) echo.HandlerFunc {
|
|
|
|
return func(c echo.Context) error {
|
|
|
|
record, _ := c.Get(ContextAuthRecordKey).(*models.Record)
|
|
|
|
if record == nil {
|
|
|
|
return NewUnauthorizedError("The request requires valid record authorization token to be set.", nil)
|
|
|
|
}
|
|
|
|
|
|
|
|
// check record collection name
|
|
|
|
if len(optCollectionNames) > 0 && !list.ExistInSlice(record.Collection().Name, optCollectionNames) {
|
|
|
|
return NewForbiddenError("The authorized record model is not allowed to perform this action.", nil)
|
|
|
|
}
|
|
|
|
|
|
|
|
return next(c)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// RequireSameContextRecordAuth middleware requires a request to have
|
|
|
|
// a valid record Authorization header.
|
|
|
|
//
|
|
|
|
// The auth record must be from the same collection already loaded in the context.
|
|
|
|
func RequireSameContextRecordAuth() echo.MiddlewareFunc {
|
2022-07-06 23:19:05 +02:00
|
|
|
return func(next echo.HandlerFunc) echo.HandlerFunc {
|
|
|
|
return func(c echo.Context) error {
|
2022-10-30 10:28:14 +02:00
|
|
|
record, _ := c.Get(ContextAuthRecordKey).(*models.Record)
|
|
|
|
if record == nil {
|
|
|
|
return NewUnauthorizedError("The request requires valid record authorization token to be set.", nil)
|
|
|
|
}
|
|
|
|
|
|
|
|
collection, _ := c.Get(ContextCollectionKey).(*models.Collection)
|
|
|
|
if collection == nil || record.Collection().Id != collection.Id {
|
|
|
|
return NewForbiddenError(fmt.Sprintf("The request requires auth record from %s collection.", record.Collection().Name), nil)
|
2022-07-06 23:19:05 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
return next(c)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// RequireAdminAuth middleware requires a request to have
|
2022-10-30 10:28:14 +02:00
|
|
|
// a valid admin Authorization header.
|
2022-07-06 23:19:05 +02:00
|
|
|
func RequireAdminAuth() echo.MiddlewareFunc {
|
|
|
|
return func(next echo.HandlerFunc) echo.HandlerFunc {
|
|
|
|
return func(c echo.Context) error {
|
|
|
|
admin, _ := c.Get(ContextAdminKey).(*models.Admin)
|
|
|
|
if admin == nil {
|
2022-10-30 10:28:14 +02:00
|
|
|
return NewUnauthorizedError("The request requires valid admin authorization token to be set.", nil)
|
2022-07-06 23:19:05 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
return next(c)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-07-18 00:03:09 +02:00
|
|
|
// RequireAdminAuthOnlyIfAny middleware requires a request to have
|
2022-10-30 10:28:14 +02:00
|
|
|
// a valid admin Authorization header ONLY if the application has
|
|
|
|
// at least 1 existing Admin model.
|
2022-07-10 10:46:21 +02:00
|
|
|
func RequireAdminAuthOnlyIfAny(app core.App) echo.MiddlewareFunc {
|
|
|
|
return func(next echo.HandlerFunc) echo.HandlerFunc {
|
|
|
|
return func(c echo.Context) error {
|
|
|
|
totalAdmins, err := app.Dao().TotalAdmins()
|
|
|
|
if err != nil {
|
2022-10-30 10:28:14 +02:00
|
|
|
return NewBadRequestError("Failed to fetch admins info.", err)
|
2022-07-10 10:46:21 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
admin, _ := c.Get(ContextAdminKey).(*models.Admin)
|
|
|
|
|
|
|
|
if admin != nil || totalAdmins == 0 {
|
|
|
|
return next(c)
|
|
|
|
}
|
|
|
|
|
2022-10-30 10:28:14 +02:00
|
|
|
return NewUnauthorizedError("The request requires valid admin authorization token to be set.", nil)
|
2022-07-10 10:46:21 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-10-30 10:28:14 +02:00
|
|
|
// RequireAdminOrRecordAuth middleware requires a request to have
|
|
|
|
// a valid admin or record Authorization header set.
|
|
|
|
//
|
|
|
|
// You can further filter the allowed auth record collections by providing their names.
|
2022-07-06 23:19:05 +02:00
|
|
|
//
|
|
|
|
// This middleware is the opposite of [apis.RequireGuestOnly()].
|
2022-10-30 10:28:14 +02:00
|
|
|
func RequireAdminOrRecordAuth(optCollectionNames ...string) echo.MiddlewareFunc {
|
2022-07-06 23:19:05 +02:00
|
|
|
return func(next echo.HandlerFunc) echo.HandlerFunc {
|
|
|
|
return func(c echo.Context) error {
|
|
|
|
admin, _ := c.Get(ContextAdminKey).(*models.Admin)
|
2022-10-30 10:28:14 +02:00
|
|
|
record, _ := c.Get(ContextAuthRecordKey).(*models.Record)
|
2022-07-06 23:19:05 +02:00
|
|
|
|
2022-10-30 10:28:14 +02:00
|
|
|
if admin == nil && record == nil {
|
|
|
|
return NewUnauthorizedError("The request requires admin or record authorization token to be set.", nil)
|
|
|
|
}
|
|
|
|
|
|
|
|
if record != nil && len(optCollectionNames) > 0 && !list.ExistInSlice(record.Collection().Name, optCollectionNames) {
|
|
|
|
return NewForbiddenError("The authorized record model is not allowed to perform this action.", nil)
|
2022-07-06 23:19:05 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
return next(c)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// RequireAdminOrOwnerAuth middleware requires a request to have
|
2022-10-30 10:28:14 +02:00
|
|
|
// a valid admin or auth record owner Authorization header set.
|
2022-07-06 23:19:05 +02:00
|
|
|
//
|
2022-10-30 10:28:14 +02:00
|
|
|
// This middleware is similar to [apis.RequireAdminOrRecordAuth()] but
|
|
|
|
// for the auth record token expects to have the same id as the path
|
|
|
|
// parameter ownerIdParam (default to "id" if empty).
|
2022-07-06 23:19:05 +02:00
|
|
|
func RequireAdminOrOwnerAuth(ownerIdParam string) echo.MiddlewareFunc {
|
|
|
|
return func(next echo.HandlerFunc) echo.HandlerFunc {
|
|
|
|
return func(c echo.Context) error {
|
2022-10-30 10:28:14 +02:00
|
|
|
admin, _ := c.Get(ContextAdminKey).(*models.Admin)
|
|
|
|
if admin != nil {
|
|
|
|
return next(c)
|
2022-07-06 23:19:05 +02:00
|
|
|
}
|
|
|
|
|
2022-10-30 10:28:14 +02:00
|
|
|
record, _ := c.Get(ContextAuthRecordKey).(*models.Record)
|
|
|
|
if record == nil {
|
|
|
|
return NewUnauthorizedError("The request requires admin or record authorization token to be set.", nil)
|
|
|
|
}
|
2022-07-06 23:19:05 +02:00
|
|
|
|
2022-10-30 10:28:14 +02:00
|
|
|
if ownerIdParam == "" {
|
|
|
|
ownerIdParam = "id"
|
2022-07-06 23:19:05 +02:00
|
|
|
}
|
2022-10-30 10:28:14 +02:00
|
|
|
ownerId := c.PathParam(ownerIdParam)
|
2022-07-06 23:19:05 +02:00
|
|
|
|
2022-10-30 10:28:14 +02:00
|
|
|
// note: it is "safe" to compare only the record id since the auth
|
|
|
|
// record ids are treated as unique across all auth collections
|
|
|
|
if record.Id != ownerId {
|
|
|
|
return NewForbiddenError("You are not allowed to perform this request.", nil)
|
2022-07-06 23:19:05 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
return next(c)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// LoadAuthContext middleware reads the Authorization request header
|
2022-10-30 10:28:14 +02:00
|
|
|
// and loads the token related record or admin instance into the
|
2022-07-06 23:19:05 +02:00
|
|
|
// request's context.
|
|
|
|
//
|
2022-10-30 10:28:14 +02:00
|
|
|
// This middleware is expected to be already registered by default for all routes.
|
2022-07-06 23:19:05 +02:00
|
|
|
func LoadAuthContext(app core.App) echo.MiddlewareFunc {
|
|
|
|
return func(next echo.HandlerFunc) echo.HandlerFunc {
|
|
|
|
return func(c echo.Context) error {
|
|
|
|
token := c.Request().Header.Get("Authorization")
|
2022-10-30 10:28:14 +02:00
|
|
|
if token == "" {
|
|
|
|
return next(c)
|
|
|
|
}
|
2022-07-06 23:19:05 +02:00
|
|
|
|
2022-10-30 10:28:14 +02:00
|
|
|
// the schema is not required and it is only for
|
|
|
|
// compatibility with the defaults of some HTTP clients
|
|
|
|
token = strings.TrimPrefix(token, "Bearer ")
|
|
|
|
|
|
|
|
claims, _ := security.ParseUnverifiedJWT(token)
|
|
|
|
tokenType := cast.ToString(claims["type"])
|
|
|
|
|
|
|
|
switch tokenType {
|
|
|
|
case tokens.TypeAdmin:
|
|
|
|
admin, err := app.Dao().FindAdminByToken(
|
|
|
|
token,
|
|
|
|
app.Settings().AdminAuthToken.Secret,
|
|
|
|
)
|
|
|
|
if err == nil && admin != nil {
|
|
|
|
c.Set(ContextAdminKey, admin)
|
|
|
|
}
|
|
|
|
case tokens.TypeAuthRecord:
|
|
|
|
record, err := app.Dao().FindAuthRecordByToken(
|
|
|
|
token,
|
|
|
|
app.Settings().RecordAuthToken.Secret,
|
|
|
|
)
|
|
|
|
if err == nil && record != nil {
|
|
|
|
c.Set(ContextAuthRecordKey, record)
|
2022-07-06 23:19:05 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return next(c)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// LoadCollectionContext middleware finds the collection with related
|
|
|
|
// path identifier and loads it into the request context.
|
2022-10-30 10:28:14 +02:00
|
|
|
//
|
|
|
|
// Set optCollectionTypes to further filter the found collection by its type.
|
|
|
|
func LoadCollectionContext(app core.App, optCollectionTypes ...string) echo.MiddlewareFunc {
|
2022-07-06 23:19:05 +02:00
|
|
|
return func(next echo.HandlerFunc) echo.HandlerFunc {
|
|
|
|
return func(c echo.Context) error {
|
|
|
|
if param := c.PathParam("collection"); param != "" {
|
|
|
|
collection, err := app.Dao().FindCollectionByNameOrId(param)
|
|
|
|
if err != nil || collection == nil {
|
2022-10-30 10:28:14 +02:00
|
|
|
return NewNotFoundError("", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
if len(optCollectionTypes) > 0 && !list.ExistInSlice(collection.Type, optCollectionTypes) {
|
2023-02-18 19:33:42 +02:00
|
|
|
return NewBadRequestError("Unsupported collection type.", nil)
|
2022-07-06 23:19:05 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
c.Set(ContextCollectionKey, collection)
|
|
|
|
}
|
|
|
|
|
|
|
|
return next(c)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// ActivityLogger middleware takes care to save the request information
|
|
|
|
// into the logs database.
|
|
|
|
//
|
|
|
|
// The middleware does nothing if the app logs retention period is zero
|
|
|
|
// (aka. app.Settings().Logs.MaxDays = 0).
|
|
|
|
func ActivityLogger(app core.App) echo.MiddlewareFunc {
|
|
|
|
return func(next echo.HandlerFunc) echo.HandlerFunc {
|
|
|
|
return func(c echo.Context) error {
|
|
|
|
err := next(c)
|
|
|
|
|
|
|
|
// no logs retention
|
|
|
|
if app.Settings().Logs.MaxDays == 0 {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
httpRequest := c.Request()
|
|
|
|
httpResponse := c.Response()
|
|
|
|
status := httpResponse.Status
|
|
|
|
meta := types.JsonMap{}
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
switch v := err.(type) {
|
2022-07-10 08:13:44 +02:00
|
|
|
case *echo.HTTPError:
|
2022-07-06 23:19:05 +02:00
|
|
|
status = v.Code
|
|
|
|
meta["errorMessage"] = v.Message
|
|
|
|
meta["errorDetails"] = fmt.Sprint(v.Internal)
|
2022-10-30 10:28:14 +02:00
|
|
|
case *ApiError:
|
2022-07-06 23:19:05 +02:00
|
|
|
status = v.Code
|
|
|
|
meta["errorMessage"] = v.Message
|
|
|
|
meta["errorDetails"] = fmt.Sprint(v.RawData())
|
|
|
|
default:
|
|
|
|
status = http.StatusBadRequest
|
|
|
|
meta["errorMessage"] = v.Error()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
requestAuth := models.RequestAuthGuest
|
2022-10-30 10:28:14 +02:00
|
|
|
if c.Get(ContextAuthRecordKey) != nil {
|
|
|
|
requestAuth = models.RequestAuthRecord
|
2022-07-06 23:19:05 +02:00
|
|
|
} else if c.Get(ContextAdminKey) != nil {
|
|
|
|
requestAuth = models.RequestAuthAdmin
|
|
|
|
}
|
|
|
|
|
2022-08-20 04:56:56 +02:00
|
|
|
ip, _, _ := net.SplitHostPort(httpRequest.RemoteAddr)
|
|
|
|
|
2022-07-06 23:19:05 +02:00
|
|
|
model := &models.Request{
|
|
|
|
Url: httpRequest.URL.RequestURI(),
|
|
|
|
Method: strings.ToLower(httpRequest.Method),
|
|
|
|
Status: status,
|
|
|
|
Auth: requestAuth,
|
2022-08-20 04:56:56 +02:00
|
|
|
UserIp: realUserIp(httpRequest, ip),
|
|
|
|
RemoteIp: ip,
|
2022-07-06 23:19:05 +02:00
|
|
|
Referer: httpRequest.Referer(),
|
|
|
|
UserAgent: httpRequest.UserAgent(),
|
|
|
|
Meta: meta,
|
|
|
|
}
|
|
|
|
// set timestamp fields before firing a new go routine
|
|
|
|
model.RefreshCreated()
|
|
|
|
model.RefreshUpdated()
|
|
|
|
|
|
|
|
routine.FireAndForget(func() {
|
2022-12-11 01:39:13 +02:00
|
|
|
if err := app.LogsDao().SaveRequest(model); err != nil && app.IsDebug() {
|
|
|
|
log.Println("Log save failed:", err)
|
2022-07-06 23:19:05 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
// Delete old request logs
|
|
|
|
// ---
|
|
|
|
now := time.Now()
|
|
|
|
lastLogsDeletedAt := cast.ToTime(app.Cache().Get("lastLogsDeletedAt"))
|
2022-07-10 08:13:44 +02:00
|
|
|
daysDiff := now.Sub(lastLogsDeletedAt).Hours() * 24
|
2022-07-06 23:19:05 +02:00
|
|
|
|
|
|
|
if daysDiff > float64(app.Settings().Logs.MaxDays) {
|
|
|
|
deleteErr := app.LogsDao().DeleteOldRequests(now.AddDate(0, 0, -1*app.Settings().Logs.MaxDays))
|
|
|
|
if deleteErr == nil {
|
|
|
|
app.Cache().Set("lastLogsDeletedAt", now)
|
|
|
|
} else if app.IsDebug() {
|
|
|
|
log.Println("Logs delete failed:", deleteErr)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
})
|
|
|
|
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2022-08-18 14:27:45 +02:00
|
|
|
|
2022-08-20 04:56:56 +02:00
|
|
|
// Returns the "real" user IP from common proxy headers (or fallbackIp if none is found).
|
2022-08-18 14:27:45 +02:00
|
|
|
//
|
2022-08-20 06:57:17 +02:00
|
|
|
// The returned IP value shouldn't be trusted if not behind a trusted reverse proxy!
|
2022-08-20 04:56:56 +02:00
|
|
|
func realUserIp(r *http.Request, fallbackIp string) string {
|
|
|
|
if ip := r.Header.Get("CF-Connecting-IP"); ip != "" {
|
|
|
|
return ip
|
2022-08-18 14:27:45 +02:00
|
|
|
}
|
|
|
|
|
2022-08-20 06:57:17 +02:00
|
|
|
if ip := r.Header.Get("X-Real-IP"); ip != "" {
|
2022-08-20 04:56:56 +02:00
|
|
|
return ip
|
|
|
|
}
|
|
|
|
|
2022-08-20 06:57:17 +02:00
|
|
|
if ipsList := r.Header.Get("X-Forwarded-For"); ipsList != "" {
|
|
|
|
ips := strings.Split(ipsList, ",")
|
|
|
|
// extract the rightmost ip
|
2022-08-20 07:01:54 +02:00
|
|
|
for i := len(ips) - 1; i >= 0; i-- {
|
|
|
|
ip := strings.TrimSpace(ips[i])
|
|
|
|
if ip != "" {
|
|
|
|
return ip
|
2022-08-20 06:57:17 +02:00
|
|
|
}
|
|
|
|
}
|
2022-08-18 14:27:45 +02:00
|
|
|
}
|
|
|
|
|
2022-08-20 04:56:56 +02:00
|
|
|
return fallbackIp
|
2022-08-18 14:27:45 +02:00
|
|
|
}
|