2022-10-30 10:28:14 +02:00
|
|
|
package apis
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
2023-01-17 23:04:13 +02:00
|
|
|
"log"
|
|
|
|
"net/http"
|
2022-11-17 14:17:10 +02:00
|
|
|
"strings"
|
2022-10-30 10:28:14 +02:00
|
|
|
|
|
|
|
"github.com/labstack/echo/v5"
|
|
|
|
"github.com/pocketbase/dbx"
|
2023-01-17 23:04:13 +02:00
|
|
|
"github.com/pocketbase/pocketbase/core"
|
2022-10-30 10:28:14 +02:00
|
|
|
"github.com/pocketbase/pocketbase/daos"
|
|
|
|
"github.com/pocketbase/pocketbase/models"
|
|
|
|
"github.com/pocketbase/pocketbase/resolvers"
|
2023-01-17 23:04:13 +02:00
|
|
|
"github.com/pocketbase/pocketbase/tokens"
|
2022-10-30 10:28:14 +02:00
|
|
|
"github.com/pocketbase/pocketbase/tools/rest"
|
|
|
|
"github.com/pocketbase/pocketbase/tools/search"
|
|
|
|
)
|
|
|
|
|
2023-07-17 22:13:39 +02:00
|
|
|
const ContextRequestInfoKey = "requestInfo"
|
2022-10-30 10:28:14 +02:00
|
|
|
|
2023-07-17 22:13:39 +02:00
|
|
|
// Deprecated: Use RequestInfo instead.
|
|
|
|
func RequestData(c echo.Context) *models.RequestInfo {
|
|
|
|
log.Println("RequestInfo(c) is depracated and will be removed in the future! You can replace it with RequestInfo(c).")
|
|
|
|
return RequestInfo(c)
|
|
|
|
}
|
|
|
|
|
|
|
|
// RequestInfo exports cached common request data fields
|
2022-11-17 14:17:10 +02:00
|
|
|
// (query, body, logged auth state, etc.) from the provided context.
|
2023-07-17 22:13:39 +02:00
|
|
|
func RequestInfo(c echo.Context) *models.RequestInfo {
|
2022-11-18 13:32:32 +02:00
|
|
|
// return cached to avoid copying the body multiple times
|
2023-07-17 22:13:39 +02:00
|
|
|
if v := c.Get(ContextRequestInfoKey); v != nil {
|
|
|
|
if data, ok := v.(*models.RequestInfo); ok {
|
2023-05-28 16:36:56 +02:00
|
|
|
// refresh auth state
|
|
|
|
data.AuthRecord, _ = c.Get(ContextAuthRecordKey).(*models.Record)
|
|
|
|
data.Admin, _ = c.Get(ContextAdminKey).(*models.Admin)
|
2022-11-17 14:17:10 +02:00
|
|
|
return data
|
|
|
|
}
|
|
|
|
}
|
2022-10-30 10:28:14 +02:00
|
|
|
|
2023-07-17 22:13:39 +02:00
|
|
|
result := &models.RequestInfo{
|
2023-03-02 18:56:18 +02:00
|
|
|
Method: c.Request().Method,
|
|
|
|
Query: map[string]any{},
|
|
|
|
Data: map[string]any{},
|
2023-03-23 19:30:35 +02:00
|
|
|
Headers: map[string]any{},
|
2023-03-02 18:56:18 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
// extract the first value of all headers and normalizes the keys
|
|
|
|
// ("X-Token" is converted to "x_token")
|
|
|
|
for k, v := range c.Request().Header {
|
|
|
|
if len(v) > 0 {
|
|
|
|
result.Headers[strings.ToLower(strings.ReplaceAll(k, "-", "_"))] = v[0]
|
|
|
|
}
|
2022-11-17 14:17:10 +02:00
|
|
|
}
|
2022-10-30 10:28:14 +02:00
|
|
|
|
2022-11-17 14:17:10 +02:00
|
|
|
result.AuthRecord, _ = c.Get(ContextAuthRecordKey).(*models.Record)
|
|
|
|
result.Admin, _ = c.Get(ContextAdminKey).(*models.Admin)
|
|
|
|
echo.BindQueryParams(c, &result.Query)
|
|
|
|
rest.BindBody(c, &result.Data)
|
2022-10-30 10:28:14 +02:00
|
|
|
|
2023-07-17 22:13:39 +02:00
|
|
|
c.Set(ContextRequestInfoKey, result)
|
2022-10-30 10:28:14 +02:00
|
|
|
|
|
|
|
return result
|
|
|
|
}
|
|
|
|
|
2023-06-23 21:20:13 +02:00
|
|
|
// RecordAuthResponse writes standardised json record auth response
|
|
|
|
// into the specified request context.
|
2023-05-29 20:50:07 +02:00
|
|
|
func RecordAuthResponse(
|
|
|
|
app core.App,
|
|
|
|
c echo.Context,
|
|
|
|
authRecord *models.Record,
|
|
|
|
meta any,
|
|
|
|
finalizers ...func(token string) error,
|
|
|
|
) error {
|
2023-01-17 23:04:13 +02:00
|
|
|
token, tokenErr := tokens.NewRecordAuthToken(app, authRecord)
|
|
|
|
if tokenErr != nil {
|
|
|
|
return NewBadRequestError("Failed to create auth token.", tokenErr)
|
|
|
|
}
|
|
|
|
|
2023-01-27 22:19:08 +02:00
|
|
|
event := new(core.RecordAuthEvent)
|
|
|
|
event.HttpContext = c
|
|
|
|
event.Collection = authRecord.Collection()
|
|
|
|
event.Record = authRecord
|
|
|
|
event.Token = token
|
|
|
|
event.Meta = meta
|
2023-01-17 23:04:13 +02:00
|
|
|
|
|
|
|
return app.OnRecordAuthRequest().Trigger(event, func(e *core.RecordAuthEvent) error {
|
2023-07-20 09:40:03 +02:00
|
|
|
if e.HttpContext.Response().Committed {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2023-01-17 23:04:13 +02:00
|
|
|
// allow always returning the email address of the authenticated account
|
|
|
|
e.Record.IgnoreEmailVisibility(true)
|
|
|
|
|
|
|
|
// expand record relations
|
|
|
|
expands := strings.Split(c.QueryParam(expandQueryParam), ",")
|
|
|
|
if len(expands) > 0 {
|
|
|
|
// create a copy of the cached request data and adjust it to the current auth record
|
2023-07-17 22:13:39 +02:00
|
|
|
requestInfo := *RequestInfo(e.HttpContext)
|
|
|
|
requestInfo.Admin = nil
|
|
|
|
requestInfo.AuthRecord = e.Record
|
2023-01-17 23:04:13 +02:00
|
|
|
failed := app.Dao().ExpandRecord(
|
|
|
|
e.Record,
|
|
|
|
expands,
|
2023-07-17 22:13:39 +02:00
|
|
|
expandFetch(app.Dao(), &requestInfo),
|
2023-01-17 23:04:13 +02:00
|
|
|
)
|
|
|
|
if len(failed) > 0 && app.IsDebug() {
|
|
|
|
log.Println("Failed to expand relations: ", failed)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
result := map[string]any{
|
|
|
|
"token": e.Token,
|
|
|
|
"record": e.Record,
|
|
|
|
}
|
|
|
|
|
|
|
|
if e.Meta != nil {
|
|
|
|
result["meta"] = e.Meta
|
|
|
|
}
|
|
|
|
|
2023-05-29 20:50:07 +02:00
|
|
|
for _, f := range finalizers {
|
|
|
|
if err := f(e.Token); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-01-17 23:04:13 +02:00
|
|
|
return e.HttpContext.JSON(http.StatusOK, result)
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2022-11-17 14:17:10 +02:00
|
|
|
// EnrichRecord parses the request context and enrich the provided record:
|
2023-01-27 22:19:08 +02:00
|
|
|
// - expands relations (if defaultExpands and/or ?expand query param is set)
|
|
|
|
// - ensures that the emails of the auth record and its expanded auth relations
|
|
|
|
// are visibe only for the current logged admin, record owner or record with manage access
|
2022-11-17 14:17:10 +02:00
|
|
|
func EnrichRecord(c echo.Context, dao *daos.Dao, record *models.Record, defaultExpands ...string) error {
|
|
|
|
return EnrichRecords(c, dao, []*models.Record{record}, defaultExpands...)
|
|
|
|
}
|
|
|
|
|
|
|
|
// EnrichRecords parses the request context and enriches the provided records:
|
2023-01-27 22:19:08 +02:00
|
|
|
// - expands relations (if defaultExpands and/or ?expand query param is set)
|
|
|
|
// - ensures that the emails of the auth records and their expanded auth relations
|
|
|
|
// are visibe only for the current logged admin, record owner or record with manage access
|
2022-11-17 14:17:10 +02:00
|
|
|
func EnrichRecords(c echo.Context, dao *daos.Dao, records []*models.Record, defaultExpands ...string) error {
|
2023-07-17 22:13:39 +02:00
|
|
|
requestInfo := RequestInfo(c)
|
2022-11-17 14:17:10 +02:00
|
|
|
|
2023-07-17 22:13:39 +02:00
|
|
|
if err := autoIgnoreAuthRecordsEmailVisibility(dao, records, requestInfo); err != nil {
|
2022-11-30 17:23:00 +02:00
|
|
|
return fmt.Errorf("Failed to resolve email visibility: %w", err)
|
2022-11-17 14:17:10 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
expands := defaultExpands
|
2023-04-25 16:58:51 +02:00
|
|
|
if param := c.QueryParam(expandQueryParam); param != "" {
|
|
|
|
expands = append(expands, strings.Split(param, ",")...)
|
|
|
|
}
|
2022-11-17 14:17:10 +02:00
|
|
|
if len(expands) == 0 {
|
|
|
|
return nil // nothing to expand
|
|
|
|
}
|
|
|
|
|
2023-07-17 22:13:39 +02:00
|
|
|
errs := dao.ExpandRecords(records, expands, expandFetch(dao, requestInfo))
|
2022-11-17 14:17:10 +02:00
|
|
|
if len(errs) > 0 {
|
|
|
|
return fmt.Errorf("Failed to expand: %v", errs)
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2022-10-30 10:28:14 +02:00
|
|
|
// expandFetch is the records fetch function that is used to expand related records.
|
|
|
|
func expandFetch(
|
|
|
|
dao *daos.Dao,
|
2023-07-17 22:13:39 +02:00
|
|
|
requestInfo *models.RequestInfo,
|
2022-10-30 10:28:14 +02:00
|
|
|
) daos.ExpandFetchFunc {
|
|
|
|
return func(relCollection *models.Collection, relIds []string) ([]*models.Record, error) {
|
|
|
|
records, err := dao.FindRecordsByIds(relCollection.Id, relIds, func(q *dbx.SelectQuery) error {
|
2023-07-17 22:13:39 +02:00
|
|
|
if requestInfo.Admin != nil {
|
2022-10-30 10:28:14 +02:00
|
|
|
return nil // admins can access everything
|
|
|
|
}
|
|
|
|
|
|
|
|
if relCollection.ViewRule == nil {
|
|
|
|
return fmt.Errorf("Only admins can view collection %q records", relCollection.Name)
|
|
|
|
}
|
|
|
|
|
|
|
|
if *relCollection.ViewRule != "" {
|
2023-07-17 22:13:39 +02:00
|
|
|
resolver := resolvers.NewRecordFieldResolver(dao, relCollection, requestInfo, true)
|
2022-10-30 10:28:14 +02:00
|
|
|
expr, err := search.FilterData(*(relCollection.ViewRule)).BuildExpr(resolver)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
resolver.UpdateQuery(q)
|
|
|
|
q.AndWhere(expr)
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
})
|
|
|
|
|
|
|
|
if err == nil && len(records) > 0 {
|
2023-07-17 22:13:39 +02:00
|
|
|
autoIgnoreAuthRecordsEmailVisibility(dao, records, requestInfo)
|
2022-10-30 10:28:14 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
return records, err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// autoIgnoreAuthRecordsEmailVisibility ignores the email visibility check for
|
|
|
|
// the provided record if the current auth model is admin, owner or a "manager".
|
|
|
|
//
|
|
|
|
// Note: Expects all records to be from the same auth collection!
|
|
|
|
func autoIgnoreAuthRecordsEmailVisibility(
|
|
|
|
dao *daos.Dao,
|
|
|
|
records []*models.Record,
|
2023-07-17 22:13:39 +02:00
|
|
|
requestInfo *models.RequestInfo,
|
2022-10-30 10:28:14 +02:00
|
|
|
) error {
|
|
|
|
if len(records) == 0 || !records[0].Collection().IsAuth() {
|
|
|
|
return nil // nothing to check
|
|
|
|
}
|
|
|
|
|
2023-07-17 22:13:39 +02:00
|
|
|
if requestInfo.Admin != nil {
|
2022-10-30 10:28:14 +02:00
|
|
|
for _, rec := range records {
|
|
|
|
rec.IgnoreEmailVisibility(true)
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
collection := records[0].Collection()
|
|
|
|
|
|
|
|
mappedRecords := make(map[string]*models.Record, len(records))
|
2022-11-26 09:05:52 +02:00
|
|
|
recordIds := make([]any, len(records))
|
|
|
|
for i, rec := range records {
|
2022-10-30 10:28:14 +02:00
|
|
|
mappedRecords[rec.Id] = rec
|
2022-11-26 09:05:52 +02:00
|
|
|
recordIds[i] = rec.Id
|
2022-10-30 10:28:14 +02:00
|
|
|
}
|
|
|
|
|
2023-07-17 22:13:39 +02:00
|
|
|
if requestInfo != nil && requestInfo.AuthRecord != nil && mappedRecords[requestInfo.AuthRecord.Id] != nil {
|
|
|
|
mappedRecords[requestInfo.AuthRecord.Id].IgnoreEmailVisibility(true)
|
2022-10-30 10:28:14 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
authOptions := collection.AuthOptions()
|
|
|
|
if authOptions.ManageRule == nil || *authOptions.ManageRule == "" {
|
|
|
|
return nil // no manage rule to check
|
|
|
|
}
|
|
|
|
|
|
|
|
// fetch the ids of the managed records
|
|
|
|
// ---
|
|
|
|
managedIds := []string{}
|
|
|
|
|
|
|
|
query := dao.RecordQuery(collection).
|
|
|
|
Select(dao.DB().QuoteSimpleColumnName(collection.Name) + ".id").
|
|
|
|
AndWhere(dbx.In(dao.DB().QuoteSimpleColumnName(collection.Name)+".id", recordIds...))
|
|
|
|
|
2023-07-17 22:13:39 +02:00
|
|
|
resolver := resolvers.NewRecordFieldResolver(dao, collection, requestInfo, true)
|
2022-10-30 10:28:14 +02:00
|
|
|
expr, err := search.FilterData(*authOptions.ManageRule).BuildExpr(resolver)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
resolver.UpdateQuery(query)
|
|
|
|
query.AndWhere(expr)
|
|
|
|
|
|
|
|
if err := query.Column(&managedIds); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
// ---
|
|
|
|
|
|
|
|
// ignore the email visibility check for the managed records
|
|
|
|
for _, id := range managedIds {
|
|
|
|
if rec, ok := mappedRecords[id]; ok {
|
|
|
|
rec.IgnoreEmailVisibility(true)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// hasAuthManageAccess checks whether the client is allowed to have full
|
|
|
|
// [forms.RecordUpsert] auth management permissions
|
|
|
|
// (aka. allowing to change system auth fields without oldPassword).
|
|
|
|
func hasAuthManageAccess(
|
|
|
|
dao *daos.Dao,
|
|
|
|
record *models.Record,
|
2023-07-17 22:13:39 +02:00
|
|
|
requestInfo *models.RequestInfo,
|
2022-10-30 10:28:14 +02:00
|
|
|
) bool {
|
|
|
|
if !record.Collection().IsAuth() {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
manageRule := record.Collection().AuthOptions().ManageRule
|
|
|
|
|
|
|
|
if manageRule == nil || *manageRule == "" {
|
|
|
|
return false // only for admins (manageRule can't be empty)
|
|
|
|
}
|
|
|
|
|
2023-07-17 22:13:39 +02:00
|
|
|
if requestInfo == nil || requestInfo.AuthRecord == nil {
|
2022-10-30 10:28:14 +02:00
|
|
|
return false // no auth record
|
|
|
|
}
|
|
|
|
|
|
|
|
ruleFunc := func(q *dbx.SelectQuery) error {
|
2023-07-17 22:13:39 +02:00
|
|
|
resolver := resolvers.NewRecordFieldResolver(dao, record.Collection(), requestInfo, true)
|
2022-10-30 10:28:14 +02:00
|
|
|
expr, err := search.FilterData(*manageRule).BuildExpr(resolver)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
resolver.UpdateQuery(q)
|
|
|
|
q.AndWhere(expr)
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
_, findErr := dao.FindRecordById(record.Collection().Id, record.Id, ruleFunc)
|
|
|
|
|
|
|
|
return findErr == nil
|
|
|
|
}
|