feat: add the management API behind the shared golem15.user API token
Serve /api/v1/bm (seed, quiz import, materials, courses, me) behind user.api_token, user.scope and user.permission. jz.bm now requires golem15.quizzes for the quiz import.
This commit is contained in:
436
controllers/api/manage.go
Normal file
436
controllers/api/manage.go
Normal file
@@ -0,0 +1,436 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"slices"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode"
|
||||
|
||||
quizzes "git.golem15.com/golem15/sm-quizzes-plugin/classes"
|
||||
usermodels "git.golem15.com/golem15/sm-user-plugin/models"
|
||||
"git.golem15.com/golem15/summercms/modules/bouncer"
|
||||
"git.golem15.com/golem15/summercms/modules/lagoon"
|
||||
"git.golem15.com/golem15/summercms/modules/surf"
|
||||
"git.golem15.com/golem15/summercms/modules/wire"
|
||||
"git.golem15.com/jakub/sm-bm-plugin/classes"
|
||||
"git.golem15.com/jakub/sm-bm-plugin/models"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// The management API (/api/v1/bm) is what the console commands do, over
|
||||
// HTTP: it runs behind golem15.user's shared API-token, scope, and permission
|
||||
// middleware, not the students' jwt.auth.
|
||||
|
||||
// flag reads a boolean query parameter: 1 and true are on.
|
||||
func flag(r *http.Request, name string) bool {
|
||||
v := r.URL.Query().Get(name)
|
||||
return v == "1" || v == "true"
|
||||
}
|
||||
|
||||
func writeInvalid(w http.ResponseWriter, message string) {
|
||||
wire.WriteJSON(w, http.StatusUnprocessableEntity, map[string]any{"message": message})
|
||||
}
|
||||
|
||||
// body reads the request body and answers 413 or 400 itself when it cannot.
|
||||
func body(w http.ResponseWriter, r *http.Request) ([]byte, bool) {
|
||||
raw, err := io.ReadAll(r.Body)
|
||||
var tooLarge *http.MaxBytesError
|
||||
switch {
|
||||
case errors.As(err, &tooLarge):
|
||||
wire.WriteJSON(w, http.StatusRequestEntityTooLarge, map[string]any{"error": true, "message": "Request body too large."})
|
||||
return nil, false
|
||||
case err != nil:
|
||||
wire.WriteJSON(w, http.StatusBadRequest, map[string]any{"error": true, "message": "Unreadable request body."})
|
||||
return nil, false
|
||||
}
|
||||
return raw, true
|
||||
}
|
||||
|
||||
type tokenJSON struct {
|
||||
ID uint `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Scopes []string `json:"scopes"`
|
||||
ExpiresAt *string `json:"expires_at"`
|
||||
}
|
||||
|
||||
// TokenInfo answers GET /me: the user and the token of the request, to
|
||||
// check a token without changing anything.
|
||||
func (h *Handlers) TokenInfo(w http.ResponseWriter, r *http.Request) {
|
||||
userID, ok := h.caller(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
out := map[string]any{"user_id": userID}
|
||||
cred, _ := bouncer.Credential(r.Context())
|
||||
if t, ok := cred.(*usermodels.APIToken); ok {
|
||||
name := ""
|
||||
if t.Name != nil {
|
||||
name = *t.Name
|
||||
}
|
||||
tj := tokenJSON{ID: t.ID, Name: name, Scopes: wire.Slice(t.Scopes.Get())}
|
||||
if t.ExpiresAt != nil {
|
||||
s := models.FormatDateTime(*t.ExpiresAt)
|
||||
tj.ExpiresAt = &s
|
||||
}
|
||||
out["token"] = tj
|
||||
}
|
||||
writeData(w, out)
|
||||
}
|
||||
|
||||
type seedCountsJSON struct {
|
||||
Created int `json:"created"`
|
||||
Updated int `json:"updated"`
|
||||
Unchanged int `json:"unchanged"`
|
||||
Deleted int `json:"deleted"`
|
||||
}
|
||||
|
||||
func newSeedCountsJSON(c classes.SeedCounts) seedCountsJSON {
|
||||
return seedCountsJSON{Created: c.Created, Updated: c.Updated, Unchanged: c.Unchanged, Deleted: c.Deleted}
|
||||
}
|
||||
|
||||
// ApplySeed answers POST /seed?dry_run=&prune=: bm:seed over HTTP. The body
|
||||
// is the seed document; the answer is the summary the command prints. A
|
||||
// document that does not parse or validate is a 422 and writes nothing.
|
||||
func (h *Handlers) ApplySeed(w http.ResponseWriter, r *http.Request) {
|
||||
raw, ok := body(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
file, err := classes.ParseSeed(bytes.NewReader(raw))
|
||||
if err == nil {
|
||||
err = file.Validate()
|
||||
}
|
||||
if err != nil {
|
||||
writeInvalid(w, err.Error())
|
||||
return
|
||||
}
|
||||
db, ok := h.db(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
opts := classes.SeedOptions{DryRun: flag(r, "dry_run"), Prune: flag(r, "prune")}
|
||||
sum, err := classes.SeedWith(r.Context(), db, file, opts)
|
||||
if err != nil {
|
||||
writeOpaque500(w)
|
||||
return
|
||||
}
|
||||
writeData(w, map[string]any{
|
||||
"dry_run": opts.DryRun,
|
||||
"prune": opts.Prune,
|
||||
"summary": map[string]seedCountsJSON{
|
||||
"meetings": newSeedCountsJSON(sum.Meetings),
|
||||
"courses": newSeedCountsJSON(sum.Courses),
|
||||
"class_sessions": newSeedCountsJSON(sum.ClassSessions),
|
||||
"deadlines": newSeedCountsJSON(sum.Deadlines),
|
||||
"readings": newSeedCountsJSON(sum.Readings),
|
||||
},
|
||||
"removed": wire.Slice(sum.Removed),
|
||||
})
|
||||
}
|
||||
|
||||
// ImportQuiz answers POST /quizzes?replace=: quizzes:import over HTTP. The
|
||||
// body is the quiz document of golem15.quizzes. An existing slug is a 409
|
||||
// unless replace is on.
|
||||
func (h *Handlers) ImportQuiz(w http.ResponseWriter, r *http.Request) {
|
||||
raw, ok := body(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
doc, err := quizzes.ParseImport(raw)
|
||||
if err != nil {
|
||||
writeInvalid(w, err.Error())
|
||||
return
|
||||
}
|
||||
db, ok := h.db(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
res, err := quizzes.Import(r.Context(), db, doc, flag(r, "replace"))
|
||||
if errors.Is(err, quizzes.ErrQuizExists) {
|
||||
wire.WriteJSON(w, http.StatusConflict, map[string]any{"error": true, "message": "A quiz with the slug " + doc.Slug + " already exists; pass replace=1 to replace its questions."})
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
writeOpaque500(w)
|
||||
return
|
||||
}
|
||||
writeData(w, map[string]any{
|
||||
"id": res.Quiz.ID,
|
||||
"slug": res.Quiz.Slug,
|
||||
"created": res.Created,
|
||||
"questions": res.Questions,
|
||||
"answers": res.Answers,
|
||||
})
|
||||
}
|
||||
|
||||
// managedMaterialJSON is a material as the management API shows it: drafts
|
||||
// too, so published_at may be null.
|
||||
type managedMaterialJSON struct {
|
||||
ID uint `json:"id"`
|
||||
CourseID *uint `json:"course_id"`
|
||||
Course *courseRef `json:"course"`
|
||||
Title string `json:"title"`
|
||||
Type string `json:"type"`
|
||||
Body *string `json:"body"`
|
||||
Source *string `json:"source"`
|
||||
URL *string `json:"url"`
|
||||
PublishedAt *string `json:"published_at"`
|
||||
Tags []tagJSON `json:"tags"`
|
||||
}
|
||||
|
||||
func newManagedMaterialJSON(m models.Material) managedMaterialJSON {
|
||||
out := managedMaterialJSON{
|
||||
ID: m.ID, CourseID: m.CourseID, Course: newCourseRef(m.Course), Title: m.Title, Type: m.Type,
|
||||
Body: m.Body, Source: m.Source, URL: m.URL, Tags: newTagsJSON(m.Tags),
|
||||
}
|
||||
if m.PublishedAt != nil {
|
||||
s := models.FormatDateTime(*m.PublishedAt)
|
||||
out.PublishedAt = &s
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// ManagedCourses answers GET /courses: every course, for the course_id of
|
||||
// a material.
|
||||
func (h *Handlers) ManagedCourses(w http.ResponseWriter, r *http.Request) {
|
||||
db, ok := h.db(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var rows []models.Course
|
||||
if err := db.Order("semester, sort_order, name, id").Find(&rows).Error; err != nil {
|
||||
writeOpaque500(w)
|
||||
return
|
||||
}
|
||||
out := make([]courseJSON, 0, len(rows))
|
||||
for _, c := range rows {
|
||||
out = append(out, newCourseJSON(c))
|
||||
}
|
||||
writeData(w, out)
|
||||
}
|
||||
|
||||
// ManagedMaterials answers GET /materials: every material, drafts
|
||||
// included, newest first.
|
||||
func (h *Handlers) ManagedMaterials(w http.ResponseWriter, r *http.Request) {
|
||||
db, ok := h.db(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var rows []models.Material
|
||||
if err := preloadMaterial(db).Order("jz_bm_materials.id DESC").Find(&rows).Error; err != nil {
|
||||
writeOpaque500(w)
|
||||
return
|
||||
}
|
||||
out := make([]managedMaterialJSON, 0, len(rows))
|
||||
for _, m := range rows {
|
||||
out = append(out, newManagedMaterialJSON(m))
|
||||
}
|
||||
writeData(w, out)
|
||||
}
|
||||
|
||||
// materialInput is the body of POST /materials.
|
||||
type materialInput struct {
|
||||
CourseID *uint `json:"course_id"`
|
||||
Title string `json:"title"`
|
||||
Type string `json:"type"`
|
||||
Body *string `json:"body"`
|
||||
Source *string `json:"source"`
|
||||
URL *string `json:"url"`
|
||||
PublishedAt *string `json:"published_at"`
|
||||
Tags *[]string `json:"tags"`
|
||||
}
|
||||
|
||||
// UpsertMaterial answers POST /materials: it creates the material, or
|
||||
// updates the one with the same title and course, so sending a document
|
||||
// twice changes nothing. body, source and url are replaced as sent.
|
||||
// published_at: absent publishes a new material now and keeps an existing
|
||||
// one as it is; null makes a draft; otherwise a timestamp as in the seed
|
||||
// file. tags: absent keeps them; otherwise the list of tag names replaces
|
||||
// them, and unknown tags are created.
|
||||
func (h *Handlers) UpsertMaterial(w http.ResponseWriter, r *http.Request) {
|
||||
raw, ok := body(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var in materialInput
|
||||
dec := json.NewDecoder(bytes.NewReader(raw))
|
||||
dec.DisallowUnknownFields()
|
||||
if err := dec.Decode(&in); err != nil {
|
||||
writeInvalid(w, "invalid JSON: "+err.Error())
|
||||
return
|
||||
}
|
||||
var keys map[string]json.RawMessage
|
||||
_ = json.Unmarshal(raw, &keys)
|
||||
_, hasPublishedAt := keys["published_at"]
|
||||
|
||||
in.Title = strings.TrimSpace(in.Title)
|
||||
errs := map[string][]string{}
|
||||
if in.Title == "" || len(in.Title) > 255 {
|
||||
errs["title"] = []string{"The title is required and may not be longer than 255 characters."}
|
||||
}
|
||||
if !slices.Contains(models.MaterialTypes, in.Type) {
|
||||
errs["type"] = []string{"The type must be one of: " + strings.Join(models.MaterialTypes, ", ") + "."}
|
||||
}
|
||||
if in.Source != nil && len(*in.Source) > 500 {
|
||||
errs["source"] = []string{"The source may not be longer than 500 characters."}
|
||||
}
|
||||
if in.URL != nil && len(*in.URL) > 2048 {
|
||||
errs["url"] = []string{"The url may not be longer than 2048 characters."}
|
||||
}
|
||||
var publishedAt *time.Time
|
||||
if in.PublishedAt != nil {
|
||||
t, err := models.ParseDateTime(*in.PublishedAt)
|
||||
if err != nil {
|
||||
errs["published_at"] = []string{"The published_at is not a valid date and time."}
|
||||
}
|
||||
publishedAt = &t
|
||||
}
|
||||
var tags []models.Tag
|
||||
if in.Tags != nil {
|
||||
for _, name := range *in.Tags {
|
||||
name = strings.TrimSpace(name)
|
||||
slug := slugify(name)
|
||||
if slug == "" || len(name) > 100 || len(slug) > 100 {
|
||||
errs["tags"] = []string{"Each tag must be a name of 1 to 100 characters."}
|
||||
break
|
||||
}
|
||||
if !slices.ContainsFunc(tags, func(t models.Tag) bool { return t.Slug == slug }) {
|
||||
tags = append(tags, models.Tag{Name: name, Slug: slug})
|
||||
}
|
||||
}
|
||||
}
|
||||
db, ok := h.db(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if in.CourseID != nil {
|
||||
var n int64
|
||||
if err := db.Model(&models.Course{}).Where("id = ?", *in.CourseID).Count(&n).Error; err != nil {
|
||||
writeOpaque500(w)
|
||||
return
|
||||
}
|
||||
if n == 0 {
|
||||
errs["course_id"] = []string{"The selected course_id is invalid."}
|
||||
}
|
||||
}
|
||||
if len(errs) > 0 {
|
||||
writeValidation(w, errs)
|
||||
return
|
||||
}
|
||||
|
||||
var m models.Material
|
||||
created := false
|
||||
err := lagoon.Transaction(r.Context(), db, func(_ context.Context, tx *gorm.DB) error {
|
||||
q := tx.Where("title = ?", in.Title)
|
||||
if in.CourseID != nil {
|
||||
q = q.Where("course_id = ?", *in.CourseID)
|
||||
} else {
|
||||
q = q.Where("course_id IS NULL")
|
||||
}
|
||||
res := q.Order("id").Limit(1).Find(&m)
|
||||
if res.Error != nil {
|
||||
return res.Error
|
||||
}
|
||||
created = res.RowsAffected == 0
|
||||
m.CourseID, m.Title, m.Type = in.CourseID, in.Title, in.Type
|
||||
m.Body, m.Source, m.URL = in.Body, in.Source, in.URL
|
||||
switch {
|
||||
case hasPublishedAt:
|
||||
m.PublishedAt = publishedAt
|
||||
case created:
|
||||
now := h.now()
|
||||
m.PublishedAt = &now
|
||||
}
|
||||
if err := tx.Omit("Course", "Tags").Save(&m).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if in.Tags == nil {
|
||||
return nil
|
||||
}
|
||||
if err := tx.Where("material_id = ?", m.ID).Delete(&models.MaterialTag{}).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
for _, t := range tags {
|
||||
var tag models.Tag
|
||||
res := tx.Where("slug = ?", t.Slug).Limit(1).Find(&tag)
|
||||
if res.Error != nil {
|
||||
return res.Error
|
||||
}
|
||||
if res.RowsAffected == 0 {
|
||||
tag = t
|
||||
if err := tx.Create(&tag).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if err := tx.Create(&models.MaterialTag{MaterialID: m.ID, TagID: tag.ID}).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
writeOpaque500(w)
|
||||
return
|
||||
}
|
||||
var out models.Material
|
||||
if err := preloadMaterial(db).First(&out, m.ID).Error; err != nil {
|
||||
writeOpaque500(w)
|
||||
return
|
||||
}
|
||||
status := http.StatusOK
|
||||
if created {
|
||||
status = http.StatusCreated
|
||||
}
|
||||
wire.WriteJSON(w, status, map[string]any{"data": newManagedMaterialJSON(out), "created": created})
|
||||
}
|
||||
|
||||
// DeleteMaterial answers DELETE /materials/{id}.
|
||||
func (h *Handlers) DeleteMaterial(w http.ResponseWriter, r *http.Request) {
|
||||
db, ok := h.db(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
id, ok := surf.IntParam(r, "id")
|
||||
if !ok {
|
||||
writeNotFound(w)
|
||||
return
|
||||
}
|
||||
res := db.Where("id = ?", id).Delete(&models.Material{})
|
||||
if res.Error != nil {
|
||||
writeOpaque500(w)
|
||||
return
|
||||
}
|
||||
if res.RowsAffected == 0 {
|
||||
writeNotFound(w)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
// polish maps the Polish letters slugify cannot fold by case alone.
|
||||
var polish = strings.NewReplacer("ą", "a", "ć", "c", "ę", "e", "ł", "l", "ń", "n", "ó", "o", "ś", "s", "ź", "z", "ż", "z")
|
||||
|
||||
// slugify turns a tag name into its slug: lower-case ASCII letters and
|
||||
// digits, with a hyphen for every run of anything else.
|
||||
func slugify(name string) string {
|
||||
var b strings.Builder
|
||||
hyphen := false
|
||||
for _, r := range polish.Replace(strings.ToLower(name)) {
|
||||
if r < unicode.MaxASCII && (unicode.IsLetter(r) || unicode.IsDigit(r)) {
|
||||
if hyphen && b.Len() > 0 {
|
||||
b.WriteByte('-')
|
||||
}
|
||||
hyphen = false
|
||||
b.WriteRune(r)
|
||||
continue
|
||||
}
|
||||
hyphen = true
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
3
go.mod
3
go.mod
@@ -3,6 +3,7 @@ module git.golem15.com/jakub/sm-bm-plugin
|
||||
go 1.27.0
|
||||
|
||||
require (
|
||||
git.golem15.com/golem15/sm-quizzes-plugin v0.0.0
|
||||
git.golem15.com/golem15/sm-user-plugin v0.0.0
|
||||
git.golem15.com/golem15/summercms v0.0.0
|
||||
github.com/go-gormigrate/gormigrate/v2 v2.1.7
|
||||
@@ -121,3 +122,5 @@ require (
|
||||
replace git.golem15.com/golem15/summercms => ../../../../summercms.go
|
||||
|
||||
replace git.golem15.com/golem15/sm-user-plugin => ../../golem15/user
|
||||
|
||||
replace git.golem15.com/golem15/sm-quizzes-plugin => ../../golem15/quizzes
|
||||
|
||||
65
management_token_test.go
Normal file
65
management_token_test.go
Normal file
@@ -0,0 +1,65 @@
|
||||
package bm_test
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
userclasses "git.golem15.com/golem15/sm-user-plugin/classes"
|
||||
"git.golem15.com/golem15/summercms/modules/surf"
|
||||
)
|
||||
|
||||
func TestManagementAPIUsesSharedTokenAndCurrentUserPermissions(t *testing.T) {
|
||||
app, plugins, db := migrated(t)
|
||||
|
||||
var userID uint
|
||||
if err := db.Raw(`
|
||||
INSERT INTO users (email, password, must_change_password)
|
||||
VALUES ('bm-shared-token@example.test', '', false)
|
||||
RETURNING id`).Scan(&userID).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var groupID uint
|
||||
if err := db.Raw(`
|
||||
INSERT INTO user_groups (name, code, permissions, created_at, updated_at)
|
||||
VALUES ('BM API', 'bm-api', '{"jz.bm.access_courses":1}', NOW(), NOW())
|
||||
RETURNING id`).Scan(&groupID).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := db.Exec(`INSERT INTO users_groups (user_id, user_group_id) VALUES (?, ?)`, userID, groupID).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
secret, token, err := userclasses.MintAPIToken("usr_", userID, "BM integration", []string{"read"}, nil, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := db.Create(token).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
handler, err := surf.Assemble(app, plugins)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
request := func(path string) *httptest.ResponseRecorder {
|
||||
req := httptest.NewRequest(http.MethodGet, path, nil)
|
||||
req.Header.Set("Authorization", "Bearer "+secret)
|
||||
rec := httptest.NewRecorder()
|
||||
handler.ServeHTTP(rec, req)
|
||||
return rec
|
||||
}
|
||||
|
||||
if rec := request("/api/v1/bm/courses"); rec.Code != http.StatusOK {
|
||||
t.Fatalf("permitted courses request = %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
if rec := request("/api/v1/bm/materials"); rec.Code != http.StatusForbidden {
|
||||
t.Fatalf("ungranted materials request = %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
if err := db.Model(&struct{}{}).Table("user_groups").Where("id = ?", groupID).Update("permissions", `{}`).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if rec := request("/api/v1/bm/courses"); rec.Code != http.StatusForbidden || !strings.Contains(rec.Body.String(), "Forbidden") {
|
||||
t.Fatalf("request after permission revocation = %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
}
|
||||
12
plugin.go
12
plugin.go
@@ -54,8 +54,9 @@ type Plugin struct {
|
||||
func (p *Plugin) ID() string { return "jz.bm" }
|
||||
|
||||
// Requires golem15.user: its users table holds the students, and its
|
||||
// jwt.auth middleware guards the API.
|
||||
func (p *Plugin) Requires() []string { return []string{"golem15.user"} }
|
||||
// jwt.auth middleware guards the API. golem15.quizzes holds the quizzes the
|
||||
// management API imports.
|
||||
func (p *Plugin) Requires() []string { return []string{"golem15.user", "golem15.quizzes"} }
|
||||
|
||||
func (p *Plugin) Register(app *backpack.App) error {
|
||||
p.app = app
|
||||
@@ -63,7 +64,8 @@ func (p *Plugin) Register(app *backpack.App) error {
|
||||
}
|
||||
|
||||
// Boot keeps the application, so route handlers and commands can reach its
|
||||
// services, such as the database, when they run.
|
||||
// services, such as the database, when they run. The management API uses the
|
||||
// shared user.api_token middleware owned by golem15.user.
|
||||
func (p *Plugin) Boot(app *backpack.App) error {
|
||||
p.app = app
|
||||
return nil
|
||||
@@ -83,8 +85,8 @@ func (p *Plugin) AdminControllers() []pact.AdminController {
|
||||
return generatedAdminControllers()
|
||||
}
|
||||
|
||||
// Commands returns the generated commands plus bm:seed, which needs the
|
||||
// database and so is built here with the plugin's withDB.
|
||||
// Commands returns the generated commands plus bm:seed. API tokens are
|
||||
// managed application-wide by golem15.user.
|
||||
func (p *Plugin) Commands() []bonfire.Command {
|
||||
return append(generatedCommands(), console.SeedCommand(p.withDB))
|
||||
}
|
||||
|
||||
@@ -4,8 +4,10 @@ import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
_ "git.golem15.com/golem15/sm-quizzes-plugin"
|
||||
_ "git.golem15.com/golem15/sm-user-plugin"
|
||||
"git.golem15.com/golem15/summercms/modules/backpack"
|
||||
"git.golem15.com/golem15/summercms/modules/bonfire"
|
||||
@@ -46,10 +48,11 @@ func testConfig(t *testing.T) *compass.Config {
|
||||
return cfg
|
||||
}
|
||||
|
||||
// activate boots golem15.user and jz.bm the way the generated main does.
|
||||
// activate boots the plugin and both declared dependencies the way the
|
||||
// generated main does.
|
||||
func activate(t *testing.T, app *backpack.App) []party.Plugin {
|
||||
t.Helper()
|
||||
plugins, err := party.Activate(app, []string{"golem15.user", "jz.bm"})
|
||||
plugins, err := party.Activate(app, []string{"golem15.user", "golem15.quizzes", "jz.bm"})
|
||||
if err != nil {
|
||||
t.Fatalf("Activate: %v", err)
|
||||
}
|
||||
@@ -70,7 +73,7 @@ func bmPlugin(t *testing.T, plugins []party.Plugin) *bm.Plugin {
|
||||
func TestPluginActivates(t *testing.T) {
|
||||
app := backpack.New(testConfig(t))
|
||||
p := bmPlugin(t, activate(t, app))
|
||||
if p.ID() != "jz.bm" || !slices.Equal(p.Requires(), []string{"golem15.user"}) {
|
||||
if p.ID() != "jz.bm" || !slices.Equal(p.Requires(), []string{"golem15.user", "golem15.quizzes"}) {
|
||||
t.Errorf("ID %q Requires %v", p.ID(), p.Requires())
|
||||
}
|
||||
if n := len(p.Models()); n != 10 {
|
||||
@@ -116,6 +119,13 @@ func TestRoutes(t *testing.T) {
|
||||
"PUT /_bm/api/v1/calendar-feed",
|
||||
"POST /_bm/api/v1/calendar-feed/rotate",
|
||||
"DELETE /_bm/api/v1/calendar-feed",
|
||||
"GET /api/v1/bm/me",
|
||||
"GET /api/v1/bm/courses",
|
||||
"GET /api/v1/bm/materials",
|
||||
"POST /api/v1/bm/materials",
|
||||
"DELETE /api/v1/bm/materials/{id}",
|
||||
"POST /api/v1/bm/seed",
|
||||
"POST /api/v1/bm/quizzes",
|
||||
}
|
||||
var got []string
|
||||
sawFeed := false
|
||||
@@ -141,7 +151,14 @@ func TestRoutes(t *testing.T) {
|
||||
continue
|
||||
}
|
||||
got = append(got, rt.Method+" "+rt.Pattern)
|
||||
if !slices.Contains(rt.Middleware, "jwt.auth") {
|
||||
if strings.HasPrefix(rt.Pattern, "/api/v1/bm/") {
|
||||
if !slices.Contains(rt.Middleware, "user.api_token") || !slices.ContainsFunc(rt.Middleware, func(name string) bool { return strings.HasPrefix(name, "user.scope:") }) {
|
||||
t.Errorf("%s %s is not behind the shared token and a scope: %v", rt.Method, rt.Pattern, rt.Middleware)
|
||||
}
|
||||
if rt.Pattern != "/api/v1/bm/me" && !slices.ContainsFunc(rt.Middleware, func(name string) bool { return strings.HasPrefix(name, "user.permission:") }) {
|
||||
t.Errorf("%s %s has no user permission check: %v", rt.Method, rt.Pattern, rt.Middleware)
|
||||
}
|
||||
} else if !slices.Contains(rt.Middleware, "jwt.auth") {
|
||||
t.Errorf("%s %s is not behind jwt.auth: %v", rt.Method, rt.Pattern, rt.Middleware)
|
||||
}
|
||||
}
|
||||
|
||||
40
routes.go
40
routes.go
@@ -4,9 +4,12 @@ import (
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
userclasses "git.golem15.com/golem15/sm-user-plugin/classes"
|
||||
usermiddleware "git.golem15.com/golem15/sm-user-plugin/middleware"
|
||||
"git.golem15.com/golem15/summercms/modules/pact"
|
||||
"git.golem15.com/golem15/summercms/modules/phrasebook"
|
||||
"git.golem15.com/golem15/summercms/modules/surf"
|
||||
"git.golem15.com/jakub/sm-bm-plugin/controllers"
|
||||
"git.golem15.com/jakub/sm-bm-plugin/controllers/api"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
@@ -21,6 +24,9 @@ var (
|
||||
const (
|
||||
bucketCalendarIP = "throttle:jz.bm.calendar-ip"
|
||||
bucketCalendarToken = "throttle:jz.bm.calendar-token"
|
||||
// bucketManage throttles the management API per token, or per client IP
|
||||
// for a request without one.
|
||||
bucketManage = "throttle:jz.bm.manage"
|
||||
)
|
||||
|
||||
// Buckets declares the rate limits of the public calendar feed.
|
||||
@@ -40,14 +46,28 @@ func (p *Plugin) Buckets() map[string]surf.Bucket {
|
||||
Decay: time.Minute,
|
||||
Key: func(r *http.Request) string { return "jz.bm.calendar.token|" + r.PathValue("token") },
|
||||
},
|
||||
"jz.bm.manage": {
|
||||
Max: 120,
|
||||
Decay: time.Minute,
|
||||
Key: func(r *http.Request) string {
|
||||
if secret := usermiddleware.BearerToken(r); secret != "" {
|
||||
return "jz.bm.manage.token|" + userclasses.HashAPIToken(secret)
|
||||
}
|
||||
return "jz.bm.manage.ip|" + surf.ClientIP(r, trusted)
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// APIPrefix is the path prefix of the student API.
|
||||
const APIPrefix = "/_bm/api/v1"
|
||||
|
||||
// Routes declares the student API. Every route needs a golem15.user JWT
|
||||
// (jwt.auth); students only read, except for their own reading progress.
|
||||
// ManagePrefix is the path prefix of the management API.
|
||||
const ManagePrefix = "/api/v1/bm"
|
||||
|
||||
// Routes declares the student API and the management API. Every student
|
||||
// route needs a golem15.user JWT (jwt.auth); students only read, except for
|
||||
// their own reading progress.
|
||||
func (p *Plugin) Routes(r pact.Router) error {
|
||||
h := p.handlers()
|
||||
r.Group(APIPrefix, surf.Use("jwt.auth", "locale.from-principal"), func(g pact.Router) {
|
||||
@@ -71,6 +91,22 @@ func (p *Plugin) Routes(r pact.Router) error {
|
||||
g.Post("/calendar-feed/rotate", h.RotateCalendarFeed, "throttle:10,1")
|
||||
g.Delete("/calendar-feed", h.DeleteCalendarFeed)
|
||||
})
|
||||
// The management API: what bm:seed and quizzes:import do, plus materials,
|
||||
// behind the application-wide user API token. Scope limits delegation;
|
||||
// user.permission checks the owner's current group permissions.
|
||||
r.Group(ManagePrefix, surf.Use(bucketManage, "user.api_token"), func(g pact.Router) {
|
||||
g.Get("/me", h.TokenInfo, "user.scope:read")
|
||||
g.Get("/courses", h.ManagedCourses, "user.scope:read", "user.permission:"+controllers.PermCourses)
|
||||
g.Get("/materials", h.ManagedMaterials, "user.scope:read", "user.permission:"+controllers.PermMaterials)
|
||||
g.Post("/materials", h.UpsertMaterial, "user.scope:write", "user.permission:"+controllers.PermMaterials)
|
||||
g.Delete("/materials/{id}", h.DeleteMaterial, "user.scope:write", "user.permission:"+controllers.PermMaterials)
|
||||
g.Where("id", "[0-9]+")
|
||||
g.Post("/seed", h.ApplySeed, "user.scope:write",
|
||||
"user.permission:"+controllers.PermCourses,
|
||||
"user.permission:"+controllers.PermSchedule,
|
||||
"user.permission:"+controllers.PermMaterials)
|
||||
g.Post("/quizzes", h.ImportQuiz, "user.scope:write", "user.permission:golem15.quizzes.access_quizzes")
|
||||
})
|
||||
// The calendar feed: public, because calendar clients fetch it without
|
||||
// credentials; the token in the path is the credential. ServeMux cannot
|
||||
// match a suffix inside a segment, so {token} carries the ".ics" and the
|
||||
|
||||
@@ -39,7 +39,7 @@ const defaultAdminPath = "/bmadmin"
|
||||
// reservedPrefixes are the path prefixes the student app never answers: the
|
||||
// APIs of the plugins and the public uploads. The admin path is added from
|
||||
// the configuration.
|
||||
var reservedPrefixes = []string{"/_user", "/_bm", "/_quizzes", "/storage"}
|
||||
var reservedPrefixes = []string{"/_user", "/_bm", "/_quizzes", "/api", "/storage"}
|
||||
|
||||
// errMissingIndex reports a tree without index.html (an unbuilt tree).
|
||||
var errMissingIndex = errors.New("jz.bm: public/index.html missing; run the frontend build (cd frontend && npm ci && npm run build)")
|
||||
|
||||
@@ -10,6 +10,7 @@ import (
|
||||
"testing"
|
||||
"testing/fstest"
|
||||
|
||||
_ "git.golem15.com/golem15/sm-quizzes-plugin"
|
||||
_ "git.golem15.com/golem15/sm-user-plugin"
|
||||
"git.golem15.com/golem15/summercms/modules/backpack"
|
||||
"git.golem15.com/golem15/summercms/modules/compass"
|
||||
@@ -219,7 +220,7 @@ func TestStaticThroughRouter(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
app := backpack.New(cfg)
|
||||
plugins, err := party.Activate(app, []string{"golem15.user", "jz.bm"})
|
||||
plugins, err := party.Activate(app, []string{"golem15.user", "golem15.quizzes", "jz.bm"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user