Phase 9c: Parent accounts, magic-link login + parent timetable view
CI / go-lint (push) Has been skipped
CI / python-lint (push) Has been skipped
CI / nodejs-lint (push) Has been skipped
CI / test-go-school (push) Successful in 31s
CI / test-go-edu-search (push) Successful in 30s
CI / test-python-klausur (push) Failing after 2m36s
CI / test-python-agent-core (push) Successful in 21s
CI / test-nodejs-website (push) Successful in 26s
CI / go-lint (push) Has been skipped
CI / python-lint (push) Has been skipped
CI / nodejs-lint (push) Has been skipped
CI / test-go-school (push) Successful in 31s
CI / test-go-edu-search (push) Successful in 30s
CI / test-python-klausur (push) Failing after 2m36s
CI / test-python-agent-core (push) Successful in 21s
CI / test-nodejs-website (push) Successful in 26s
Backend (school-service):
- parent_account, parent_child, parent_magic_link, parent_session
tables. Tokens are sha256-hashed in DB; raw goes back exactly
once to the inviting teacher.
- InviteParent upserts the parent account, links a child to a tt_
class, mints a 7-day magic link. Returns the link path so the
teacher can paste it into Matrix/Email.
- RedeemMagicLink validates + marks used + mints a 30-day session,
sets HttpOnly bp_parent_session cookie.
- ParentSessionMiddleware reads the cookie and resolves the parent.
Lives in its own router group /api/v1/parent — totally separate
from the teacher JWT path.
- ParentMe returns the account + list of children (with class name).
- ParentTimetable returns the latest completed tt_solution's lessons
for the requested child's class, with full authorization check
(parent must own a child in that class).
Frontend (studio-v2):
- lib/calendar/subject-i18n.ts maps 22 German subject names to 8
parent locales (de/en/tr/ar/uk/ru/pl/fr). Falls back to German
for custom subjects.
- ParentManager component on the Schulkalender page lets the teacher
invite parents via email + child name + class + language. Newly
minted magic-link is shown with a copy-to-clipboard button.
- app/api/parent/[...path]/route.ts proxies parent-side endpoints
via the cookie so HttpOnly survives the Next.js round-trip.
- /eltern/login?token=… redeems and redirects to /eltern.
- /eltern shows a Wochengrid with German days + translated subject
names in the parent's preferred language. Headings and weekday
labels also localised (de/en/tr/ar/uk/ru/pl/fr).
Tests:
- 3 new Go unit tests (random token, hash stability, invite-request
validator). 83 subtests gesamt.
- studio-v2: e2e/eltern.spec.ts mit 7 tests across ParentManager,
/eltern/login, /eltern overview, subject-i18n end-to-end.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -258,6 +258,31 @@ func main() {
|
||||
api.POST("/calendar/events", handler.CreateSchoolEvent)
|
||||
api.DELETE("/calendar/events/:id", handler.DeleteSchoolEvent)
|
||||
api.POST("/calendar/school-year-rollover", handler.RolloverSchoolYear)
|
||||
|
||||
// Phase 9c: parent invitations (teacher side).
|
||||
api.GET("/calendar/parents", handler.ListParentInvites)
|
||||
api.POST("/calendar/parents/invite", handler.InviteParent)
|
||||
api.DELETE("/calendar/parents/children/:id", handler.DeleteParentInvite)
|
||||
}
|
||||
|
||||
// Phase 9c: parent-side endpoints. Auth is the parent session cookie,
|
||||
// NOT the teacher JWT. /parent/auth/redeem creates the cookie; the
|
||||
// other routes require it via ParentSessionMiddleware.
|
||||
parentAPI := router.Group("/api/v1/parent")
|
||||
{
|
||||
parentAPI.POST("/auth/redeem", handler.RedeemMagicLink)
|
||||
|
||||
authed := parentAPI.Group("/")
|
||||
authed.Use(middleware.ParentSessionMiddleware(func(ctx context.Context, token string) (string, string, string, error) {
|
||||
p, err := handler.ParentService().ParentFromSession(ctx, token)
|
||||
if err != nil {
|
||||
return "", "", "", err
|
||||
}
|
||||
return p.ID.String(), p.Email, p.PreferredLanguage, nil
|
||||
}))
|
||||
authed.GET("/me", handler.ParentMe)
|
||||
authed.GET("/me/timetable", handler.ParentTimetable)
|
||||
authed.POST("/auth/logout", handler.ParentLogout)
|
||||
}
|
||||
|
||||
// Start server
|
||||
|
||||
@@ -224,6 +224,9 @@ func Migrate(db *DB) error {
|
||||
// Append calendar migrations (see calendar_migrations.go).
|
||||
migrations = append(migrations, CalendarMigrations()...)
|
||||
|
||||
// Append parent migrations (Phase 9c — see parent_migrations.go).
|
||||
migrations = append(migrations, ParentMigrations()...)
|
||||
|
||||
for _, migration := range migrations {
|
||||
_, err := db.Pool.Exec(ctx, migration)
|
||||
if err != nil {
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
package database
|
||||
|
||||
// ParentMigrations creates the four parent-side tables for Phase 9c:
|
||||
//
|
||||
// parent_account — one row per invited parent (email, language)
|
||||
// parent_child — kids linked to a parent and a tt_class
|
||||
// parent_magic_link — one-shot invite tokens, hashed
|
||||
// parent_session — active browser sessions after redeeming a link
|
||||
//
|
||||
// The teacher owns the invite (created_by_user_id on account); parent sees
|
||||
// only data scoped to their own children's class via tt_class.id.
|
||||
func ParentMigrations() []string {
|
||||
return []string{
|
||||
`CREATE TABLE IF NOT EXISTS parent_account (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
created_by_user_id UUID NOT NULL,
|
||||
email VARCHAR(255) NOT NULL,
|
||||
preferred_language VARCHAR(8) DEFAULT 'de',
|
||||
created_at TIMESTAMPTZ DEFAULT NOW(),
|
||||
UNIQUE(created_by_user_id, email)
|
||||
)`,
|
||||
|
||||
`CREATE TABLE IF NOT EXISTS parent_child (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
parent_id UUID NOT NULL REFERENCES parent_account(id) ON DELETE CASCADE,
|
||||
tt_class_id UUID NOT NULL REFERENCES tt_class(id) ON DELETE CASCADE,
|
||||
first_name VARCHAR(100) NOT NULL,
|
||||
last_name VARCHAR(100) NOT NULL,
|
||||
created_at TIMESTAMPTZ DEFAULT NOW()
|
||||
)`,
|
||||
|
||||
`CREATE TABLE IF NOT EXISTS parent_magic_link (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
parent_id UUID NOT NULL REFERENCES parent_account(id) ON DELETE CASCADE,
|
||||
token_hash VARCHAR(64) NOT NULL UNIQUE,
|
||||
expires_at TIMESTAMPTZ NOT NULL,
|
||||
used_at TIMESTAMPTZ,
|
||||
created_at TIMESTAMPTZ DEFAULT NOW()
|
||||
)`,
|
||||
|
||||
`CREATE TABLE IF NOT EXISTS parent_session (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
parent_id UUID NOT NULL REFERENCES parent_account(id) ON DELETE CASCADE,
|
||||
token_hash VARCHAR(64) NOT NULL UNIQUE,
|
||||
expires_at TIMESTAMPTZ NOT NULL,
|
||||
created_at TIMESTAMPTZ DEFAULT NOW()
|
||||
)`,
|
||||
|
||||
`CREATE INDEX IF NOT EXISTS idx_parent_account_owner ON parent_account(created_by_user_id)`,
|
||||
`CREATE INDEX IF NOT EXISTS idx_parent_child_parent ON parent_child(parent_id)`,
|
||||
`CREATE INDEX IF NOT EXISTS idx_parent_child_class ON parent_child(tt_class_id)`,
|
||||
}
|
||||
}
|
||||
@@ -18,6 +18,7 @@ type Handler struct {
|
||||
aiService *services.AIService
|
||||
timetableService *services.TimetableService
|
||||
calendarService *services.CalendarService
|
||||
parentService *services.ParentService
|
||||
solverServiceURL string
|
||||
}
|
||||
|
||||
@@ -31,6 +32,7 @@ func NewHandler(db *pgxpool.Pool, llmGatewayURL, solverServiceURL string) *Handl
|
||||
aiService := services.NewAIService(llmGatewayURL)
|
||||
timetableService := services.NewTimetableService(db)
|
||||
calendarService := services.NewCalendarService(db)
|
||||
parentService := services.NewParentService(db)
|
||||
|
||||
return &Handler{
|
||||
classService: classService,
|
||||
@@ -41,6 +43,7 @@ func NewHandler(db *pgxpool.Pool, llmGatewayURL, solverServiceURL string) *Handl
|
||||
aiService: aiService,
|
||||
timetableService: timetableService,
|
||||
calendarService: calendarService,
|
||||
parentService: parentService,
|
||||
solverServiceURL: solverServiceURL,
|
||||
}
|
||||
}
|
||||
@@ -51,6 +54,12 @@ func (h *Handler) CalendarService() *services.CalendarService {
|
||||
return h.calendarService
|
||||
}
|
||||
|
||||
// ParentService exposes the parent service so the parent-session middleware
|
||||
// in main.go can resolve session cookies.
|
||||
func (h *Handler) ParentService() *services.ParentService {
|
||||
return h.parentService
|
||||
}
|
||||
|
||||
// Health returns the service health status
|
||||
func (h *Handler) Health(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
|
||||
@@ -0,0 +1,140 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/breakpilot/school-service/internal/middleware"
|
||||
"github.com/breakpilot/school-service/internal/models"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// ---------- Teacher-side (uses JWT/dev auth from existing middleware) ----------
|
||||
|
||||
func (h *Handler) InviteParent(c *gin.Context) {
|
||||
uid := getUserID(c)
|
||||
if uid == "" {
|
||||
respondError(c, http.StatusUnauthorized, "User not authenticated")
|
||||
return
|
||||
}
|
||||
var req models.InviteParentRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
respondError(c, http.StatusBadRequest, "Invalid request: "+err.Error())
|
||||
return
|
||||
}
|
||||
out, err := h.parentService.InviteParent(c.Request.Context(), uid, &req)
|
||||
if err != nil {
|
||||
respondError(c, http.StatusInternalServerError, "Failed to invite parent: "+err.Error())
|
||||
return
|
||||
}
|
||||
respondCreated(c, out)
|
||||
}
|
||||
|
||||
func (h *Handler) ListParentInvites(c *gin.Context) {
|
||||
uid := getUserID(c)
|
||||
if uid == "" {
|
||||
respondError(c, http.StatusUnauthorized, "User not authenticated")
|
||||
return
|
||||
}
|
||||
items, err := h.parentService.ListInvites(c.Request.Context(), uid)
|
||||
if err != nil {
|
||||
respondError(c, http.StatusInternalServerError, "Failed to list invites: "+err.Error())
|
||||
return
|
||||
}
|
||||
if items == nil {
|
||||
items = []models.ParentInviteListItem{}
|
||||
}
|
||||
respondSuccess(c, items)
|
||||
}
|
||||
|
||||
func (h *Handler) DeleteParentInvite(c *gin.Context) {
|
||||
uid := getUserID(c)
|
||||
if uid == "" {
|
||||
respondError(c, http.StatusUnauthorized, "User not authenticated")
|
||||
return
|
||||
}
|
||||
if err := h.parentService.DeleteInvite(c.Request.Context(), c.Param("id"), uid); err != nil {
|
||||
respondError(c, http.StatusInternalServerError, "Failed to delete invite: "+err.Error())
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"message": "Invite removed"})
|
||||
}
|
||||
|
||||
// ---------- Parent-side (uses ParentSessionMiddleware) ----------
|
||||
|
||||
func (h *Handler) RedeemMagicLink(c *gin.Context) {
|
||||
var req models.RedeemMagicLinkRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
respondError(c, http.StatusBadRequest, "Invalid request: "+err.Error())
|
||||
return
|
||||
}
|
||||
session, parent, err := h.parentService.RedeemMagicLink(c.Request.Context(), req.Token)
|
||||
if err != nil {
|
||||
respondError(c, http.StatusUnauthorized, err.Error())
|
||||
return
|
||||
}
|
||||
// HttpOnly + Lax → cookie survives a fresh redirect from /eltern/login but
|
||||
// isn't sent on cross-site CSRF requests.
|
||||
c.SetSameSite(http.SameSiteLaxMode)
|
||||
c.SetCookie(middleware.ParentSessionCookieName, session,
|
||||
60*60*24*30, "/", "", false, true)
|
||||
respondSuccess(c, parent)
|
||||
}
|
||||
|
||||
func (h *Handler) ParentMe(c *gin.Context) {
|
||||
parentID := c.GetString("parent_id")
|
||||
children, err := h.parentService.ListChildren(c.Request.Context(), parentID)
|
||||
if err != nil {
|
||||
respondError(c, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
if children == nil {
|
||||
children = []models.ParentChild{}
|
||||
}
|
||||
respondSuccess(c, gin.H{
|
||||
"parent": gin.H{
|
||||
"id": parentID,
|
||||
"email": c.GetString("parent_email"),
|
||||
"preferred_language": c.GetString("parent_language"),
|
||||
},
|
||||
"children": children,
|
||||
})
|
||||
}
|
||||
|
||||
// ParentTimetable returns the latest completed timetable lessons for the
|
||||
// given child's class. Authorization: parent must own a child in that class.
|
||||
func (h *Handler) ParentTimetable(c *gin.Context) {
|
||||
parentID := c.GetString("parent_id")
|
||||
classID := c.Query("class_id")
|
||||
if classID == "" {
|
||||
respondError(c, http.StatusBadRequest, "class_id required")
|
||||
return
|
||||
}
|
||||
ok, err := h.parentService.ChildBelongsToParent(c.Request.Context(), parentID, classID)
|
||||
if err != nil {
|
||||
respondError(c, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
if !ok {
|
||||
respondError(c, http.StatusForbidden, "Not allowed")
|
||||
return
|
||||
}
|
||||
// Need the teacher's user_id to find the right solution. We re-derive it
|
||||
// from parent_account.created_by_user_id via a small extra query.
|
||||
teacherID, err := h.parentService.TeacherOfParent(c.Request.Context(), parentID)
|
||||
if err != nil {
|
||||
respondError(c, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
lessons, err := h.parentService.LatestCompletedSolutionLessonsForClass(c.Request.Context(), classID, teacherID)
|
||||
if err != nil {
|
||||
respondError(c, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
respondSuccess(c, lessons)
|
||||
}
|
||||
|
||||
func (h *Handler) ParentLogout(c *gin.Context) {
|
||||
c.SetSameSite(http.SameSiteLaxMode)
|
||||
c.SetCookie(middleware.ParentSessionCookieName, "", -1, "/", "", false, true)
|
||||
c.JSON(http.StatusOK, gin.H{"message": "Logged out"})
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// ParentResolver is the minimum the middleware needs from the parent
|
||||
// service. Defined as interface so handlers can pass their own service
|
||||
// without import cycles.
|
||||
type ParentResolver interface {
|
||||
ParentFromSession(ctx context.Context, token string) (parent interface{}, err error)
|
||||
}
|
||||
|
||||
// ParentSessionCookieName is the name of the HttpOnly cookie that carries
|
||||
// the parent's session token after redeem. Exported so handlers can set it.
|
||||
const ParentSessionCookieName = "bp_parent_session"
|
||||
|
||||
// ParentSessionMiddleware reads the parent session cookie and resolves it
|
||||
// to a parent_account. Stores parent_id (string) in the Gin context for
|
||||
// downstream handlers. Aborts with 401 if the cookie is missing or the
|
||||
// session expired.
|
||||
func ParentSessionMiddleware(resolve func(ctx context.Context, token string) (string, string, string, error)) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
token, err := c.Cookie(ParentSessionCookieName)
|
||||
if err != nil || token == "" {
|
||||
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Parent session required"})
|
||||
return
|
||||
}
|
||||
parentID, email, lang, err := resolve(c.Request.Context(), token)
|
||||
if err != nil {
|
||||
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Invalid or expired session"})
|
||||
return
|
||||
}
|
||||
c.Set("parent_id", parentID)
|
||||
c.Set("parent_email", email)
|
||||
c.Set("parent_language", lang)
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type ParentAccount struct {
|
||||
ID uuid.UUID `json:"id" db:"id"`
|
||||
CreatedByUserID uuid.UUID `json:"created_by_user_id" db:"created_by_user_id"`
|
||||
Email string `json:"email" db:"email"`
|
||||
PreferredLanguage string `json:"preferred_language" db:"preferred_language"`
|
||||
CreatedAt time.Time `json:"created_at" db:"created_at"`
|
||||
}
|
||||
|
||||
type ParentChild struct {
|
||||
ID uuid.UUID `json:"id" db:"id"`
|
||||
ParentID uuid.UUID `json:"parent_id" db:"parent_id"`
|
||||
TTClassID uuid.UUID `json:"tt_class_id" db:"tt_class_id"`
|
||||
FirstName string `json:"first_name" db:"first_name"`
|
||||
LastName string `json:"last_name" db:"last_name"`
|
||||
CreatedAt time.Time `json:"created_at" db:"created_at"`
|
||||
// Joined for display
|
||||
ClassName string `json:"class_name,omitempty"`
|
||||
}
|
||||
|
||||
// Request DTOs
|
||||
|
||||
// InviteParentRequest is what the teacher posts to invite one parent for one
|
||||
// child. The endpoint creates the account if it doesn't exist, the child
|
||||
// row, and a fresh magic_link. Same parent can be invited for several
|
||||
// children (re-using the account).
|
||||
type InviteParentRequest struct {
|
||||
Email string `json:"email" binding:"required,email"`
|
||||
PreferredLanguage string `json:"preferred_language"`
|
||||
ChildFirstName string `json:"child_first_name" binding:"required"`
|
||||
ChildLastName string `json:"child_last_name" binding:"required"`
|
||||
TTClassID string `json:"tt_class_id" binding:"required,uuid"`
|
||||
}
|
||||
|
||||
// InviteParentResponse carries the freshly-minted magic-link path so the
|
||||
// teacher can copy it into Matrix/Email manually (mass-send comes from the
|
||||
// notification worker in Phase 9d).
|
||||
type InviteParentResponse struct {
|
||||
Parent ParentAccount `json:"parent"`
|
||||
Child ParentChild `json:"child"`
|
||||
MagicToken string `json:"magic_token"`
|
||||
MagicURL string `json:"magic_url"`
|
||||
ExpiresAt time.Time `json:"expires_at"`
|
||||
}
|
||||
|
||||
// ParentInviteListItem is the teacher-facing list row — one entry per
|
||||
// (parent, child) pair, with the joined class name.
|
||||
type ParentInviteListItem struct {
|
||||
ParentID uuid.UUID `json:"parent_id"`
|
||||
Email string `json:"email"`
|
||||
PreferredLanguage string `json:"preferred_language"`
|
||||
ChildID uuid.UUID `json:"child_id"`
|
||||
ChildFirstName string `json:"child_first_name"`
|
||||
ChildLastName string `json:"child_last_name"`
|
||||
ClassID uuid.UUID `json:"class_id"`
|
||||
ClassName string `json:"class_name"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
// RedeemMagicLinkRequest is what /parent/auth/redeem expects.
|
||||
type RedeemMagicLinkRequest struct {
|
||||
Token string `json:"token" binding:"required"`
|
||||
}
|
||||
|
||||
// ParentMe is what /parent/me returns: the account + every linked child.
|
||||
type ParentMe struct {
|
||||
Parent ParentAccount `json:"parent"`
|
||||
Children []ParentChild `json:"children"`
|
||||
}
|
||||
@@ -0,0 +1,209 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/breakpilot/school-service/internal/models"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// RedeemMagicLink validates a one-shot link, marks it used, mints a session
|
||||
// token. Returns the raw session token; caller (HTTP handler) sets it as
|
||||
// HttpOnly cookie.
|
||||
func (s *ParentService) RedeemMagicLink(ctx context.Context, token string) (sessionToken string, parent *models.ParentAccount, err error) {
|
||||
hash := hashToken(token)
|
||||
|
||||
tx, err := s.db.Begin(ctx)
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
defer tx.Rollback(ctx)
|
||||
|
||||
var (
|
||||
linkID uuid.UUID
|
||||
parentID uuid.UUID
|
||||
expiresAt time.Time
|
||||
usedAt *time.Time
|
||||
)
|
||||
if err := tx.QueryRow(ctx, `
|
||||
SELECT id, parent_id, expires_at, used_at
|
||||
FROM parent_magic_link
|
||||
WHERE token_hash = $1
|
||||
`, hash).Scan(&linkID, &parentID, &expiresAt, &usedAt); err != nil {
|
||||
return "", nil, fmt.Errorf("invalid token")
|
||||
}
|
||||
if usedAt != nil {
|
||||
return "", nil, fmt.Errorf("token already used")
|
||||
}
|
||||
if time.Now().After(expiresAt) {
|
||||
return "", nil, fmt.Errorf("token expired")
|
||||
}
|
||||
|
||||
// Mark used.
|
||||
if _, err := tx.Exec(ctx, `UPDATE parent_magic_link SET used_at = NOW() WHERE id = $1`, linkID); err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
|
||||
// Mint session token.
|
||||
raw, h, err := randomToken()
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
sessionExpires := time.Now().Add(parentSessionTTL)
|
||||
if _, err := tx.Exec(ctx, `
|
||||
INSERT INTO parent_session (parent_id, token_hash, expires_at)
|
||||
VALUES ($1, $2, $3)
|
||||
`, parentID, h, sessionExpires); err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
|
||||
// Fetch the account so callers (UI) get the email + language back.
|
||||
var p models.ParentAccount
|
||||
if err := tx.QueryRow(ctx, `
|
||||
SELECT id, created_by_user_id, email, preferred_language, created_at
|
||||
FROM parent_account WHERE id = $1
|
||||
`, parentID).Scan(&p.ID, &p.CreatedByUserID, &p.Email, &p.PreferredLanguage, &p.CreatedAt); err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
return raw, &p, nil
|
||||
}
|
||||
|
||||
// ParentFromSession resolves a session token back to the parent account.
|
||||
// Returns error on missing/expired session. Called by ParentSession
|
||||
// middleware.
|
||||
func (s *ParentService) ParentFromSession(ctx context.Context, sessionToken string) (*models.ParentAccount, error) {
|
||||
hash := hashToken(sessionToken)
|
||||
var p models.ParentAccount
|
||||
var expiresAt time.Time
|
||||
if err := s.db.QueryRow(ctx, `
|
||||
SELECT pa.id, pa.created_by_user_id, pa.email, pa.preferred_language, pa.created_at, ps.expires_at
|
||||
FROM parent_session ps
|
||||
JOIN parent_account pa ON pa.id = ps.parent_id
|
||||
WHERE ps.token_hash = $1
|
||||
`, hash).Scan(&p.ID, &p.CreatedByUserID, &p.Email, &p.PreferredLanguage, &p.CreatedAt, &expiresAt); err != nil {
|
||||
return nil, fmt.Errorf("invalid session")
|
||||
}
|
||||
if time.Now().After(expiresAt) {
|
||||
return nil, fmt.Errorf("session expired")
|
||||
}
|
||||
return &p, nil
|
||||
}
|
||||
|
||||
// ListChildren returns all parent_child rows for a parent, joined with the
|
||||
// class name from tt_class.
|
||||
func (s *ParentService) ListChildren(ctx context.Context, parentID string) ([]models.ParentChild, error) {
|
||||
rows, err := s.db.Query(ctx, `
|
||||
SELECT pc.id, pc.parent_id, pc.tt_class_id, pc.first_name, pc.last_name, pc.created_at, cl.name
|
||||
FROM parent_child pc
|
||||
JOIN tt_class cl ON cl.id = pc.tt_class_id
|
||||
WHERE pc.parent_id = $1
|
||||
ORDER BY pc.last_name, pc.first_name
|
||||
`, parentID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var out []models.ParentChild
|
||||
for rows.Next() {
|
||||
var c models.ParentChild
|
||||
if err := rows.Scan(&c.ID, &c.ParentID, &c.TTClassID, &c.FirstName, &c.LastName, &c.CreatedAt, &c.ClassName); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, c)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// TeacherOfParent returns the created_by_user_id of the teacher who invited
|
||||
// this parent. Used to scope timetable + calendar queries.
|
||||
func (s *ParentService) TeacherOfParent(ctx context.Context, parentID string) (string, error) {
|
||||
var uid string
|
||||
err := s.db.QueryRow(ctx,
|
||||
`SELECT created_by_user_id::text FROM parent_account WHERE id = $1`, parentID,
|
||||
).Scan(&uid)
|
||||
return uid, err
|
||||
}
|
||||
|
||||
// ChildBelongsToParent checks whether a tt_class is one this parent has a
|
||||
// child in. Used by the timetable + calendar handlers as authorization.
|
||||
func (s *ParentService) ChildBelongsToParent(ctx context.Context, parentID, classID string) (bool, error) {
|
||||
var ok bool
|
||||
err := s.db.QueryRow(ctx, `
|
||||
SELECT EXISTS(SELECT 1 FROM parent_child
|
||||
WHERE parent_id = $1 AND tt_class_id = $2)
|
||||
`, parentID, classID).Scan(&ok)
|
||||
return ok, err
|
||||
}
|
||||
|
||||
// LatestCompletedSolutionLessonsForClass returns the lessons of the most
|
||||
// recent COMPLETED tt_solution where the given class has rows, owned by
|
||||
// the teacher that originally invited the parent. Joined with subject + room
|
||||
// + teacher names so the parent UI can render directly.
|
||||
func (s *ParentService) LatestCompletedSolutionLessonsForClass(ctx context.Context, classID, teacherUserID string) ([]LessonExport, error) {
|
||||
// Find latest completed solution by the teacher that has at least one
|
||||
// lesson in this class.
|
||||
var solutionID string
|
||||
if err := s.db.QueryRow(ctx, `
|
||||
SELECT s.id::text
|
||||
FROM tt_solution s
|
||||
JOIN tt_lesson l ON l.solution_id = s.id
|
||||
WHERE s.created_by_user_id = $1
|
||||
AND s.status = 'completed'
|
||||
AND l.class_id = $2::uuid
|
||||
ORDER BY s.created_at DESC
|
||||
LIMIT 1
|
||||
`, teacherUserID, classID).Scan(&solutionID); err != nil {
|
||||
return nil, nil // no plan yet — parent UI shows empty grid
|
||||
}
|
||||
|
||||
// Re-use the existing export shape with a stricter filter (class only).
|
||||
rows, err := s.db.Query(ctx, `
|
||||
SELECT l.day_of_week, l.period_index,
|
||||
to_char(p.start_time, 'HH24:MI') AS st,
|
||||
to_char(p.end_time, 'HH24:MI') AS et,
|
||||
cl.name, sub.name, sub.short_code,
|
||||
t.last_name || ', ' || t.first_name,
|
||||
COALESCE(r.name, ''),
|
||||
l.pinned
|
||||
FROM tt_lesson l
|
||||
JOIN tt_solution s ON l.solution_id = s.id
|
||||
JOIN tt_class cl ON l.class_id = cl.id
|
||||
JOIN tt_subject sub ON l.subject_id = sub.id
|
||||
JOIN tt_teacher t ON l.teacher_id = t.id
|
||||
LEFT JOIN tt_room r ON l.room_id = r.id
|
||||
LEFT JOIN tt_period p
|
||||
ON p.day_of_week = l.day_of_week
|
||||
AND p.period_index = l.period_index
|
||||
AND p.created_by_user_id = s.created_by_user_id
|
||||
WHERE s.id = $1::uuid AND l.class_id = $2::uuid
|
||||
ORDER BY l.day_of_week, l.period_index
|
||||
`, solutionID, classID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var out []LessonExport
|
||||
for rows.Next() {
|
||||
var le LessonExport
|
||||
var st, et *string
|
||||
if err := rows.Scan(&le.DayOfWeek, &le.PeriodIndex, &st, &et,
|
||||
&le.ClassName, &le.SubjectName, &le.SubjectCode,
|
||||
&le.TeacherName, &le.RoomName, &le.Pinned); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if st != nil {
|
||||
le.StartTime = *st
|
||||
}
|
||||
if et != nil {
|
||||
le.EndTime = *et
|
||||
}
|
||||
out = append(out, le)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/breakpilot/school-service/internal/models"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
// ParentService owns the parent_* tables. Magic-link tokens are random
|
||||
// 32-byte values; only the SHA-256 hash is stored in the DB. The raw token
|
||||
// goes back to the teacher exactly once (when they invite a parent) so
|
||||
// they can paste it into a Matrix message or email. After redeem, a
|
||||
// browser session (own table, separate token) carries the parent through
|
||||
// the API.
|
||||
type ParentService struct {
|
||||
db *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewParentService(db *pgxpool.Pool) *ParentService {
|
||||
return &ParentService{db: db}
|
||||
}
|
||||
|
||||
const (
|
||||
magicLinkTTL = 7 * 24 * time.Hour
|
||||
parentSessionTTL = 30 * 24 * time.Hour
|
||||
parentCookieName = "bp_parent_session"
|
||||
tokenLen = 32 // raw bytes; URL-safe base64 encoded
|
||||
)
|
||||
|
||||
func randomToken() (raw string, hash string, err error) {
|
||||
buf := make([]byte, tokenLen)
|
||||
if _, err := rand.Read(buf); err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
raw = base64.RawURLEncoding.EncodeToString(buf)
|
||||
h := sha256.Sum256([]byte(raw))
|
||||
hash = hex.EncodeToString(h[:])
|
||||
return raw, hash, nil
|
||||
}
|
||||
|
||||
func hashToken(raw string) string {
|
||||
h := sha256.Sum256([]byte(raw))
|
||||
return hex.EncodeToString(h[:])
|
||||
}
|
||||
|
||||
// InviteParent upserts the parent account, creates a fresh child row, and
|
||||
// issues a magic-link. Caller (teacher) is the owner; child must belong to
|
||||
// one of their tt_class rows.
|
||||
func (s *ParentService) InviteParent(ctx context.Context, userID string, req *models.InviteParentRequest) (*models.InviteParentResponse, error) {
|
||||
tx, err := s.db.Begin(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer tx.Rollback(ctx)
|
||||
|
||||
// 1. Verify class ownership.
|
||||
var owned bool
|
||||
if err := tx.QueryRow(ctx,
|
||||
`SELECT EXISTS(SELECT 1 FROM tt_class WHERE id = $1 AND created_by_user_id = $2)`,
|
||||
req.TTClassID, userID,
|
||||
).Scan(&owned); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !owned {
|
||||
return nil, fmt.Errorf("tt_class_id not found or not owned by user")
|
||||
}
|
||||
|
||||
lang := req.PreferredLanguage
|
||||
if lang == "" {
|
||||
lang = "de"
|
||||
}
|
||||
|
||||
// 2. Upsert parent_account.
|
||||
var parent models.ParentAccount
|
||||
if err := tx.QueryRow(ctx, `
|
||||
INSERT INTO parent_account (created_by_user_id, email, preferred_language)
|
||||
VALUES ($1, $2, $3)
|
||||
ON CONFLICT (created_by_user_id, email) DO UPDATE
|
||||
SET preferred_language = EXCLUDED.preferred_language
|
||||
RETURNING id, created_by_user_id, email, preferred_language, created_at
|
||||
`, userID, req.Email, lang).Scan(
|
||||
&parent.ID, &parent.CreatedByUserID, &parent.Email, &parent.PreferredLanguage, &parent.CreatedAt,
|
||||
); err != nil {
|
||||
return nil, fmt.Errorf("upsert parent: %w", err)
|
||||
}
|
||||
|
||||
// 3. Insert child.
|
||||
var child models.ParentChild
|
||||
if err := tx.QueryRow(ctx, `
|
||||
INSERT INTO parent_child (parent_id, tt_class_id, first_name, last_name)
|
||||
VALUES ($1, $2::uuid, $3, $4)
|
||||
RETURNING id, parent_id, tt_class_id, first_name, last_name, created_at
|
||||
`, parent.ID, req.TTClassID, req.ChildFirstName, req.ChildLastName).Scan(
|
||||
&child.ID, &child.ParentID, &child.TTClassID, &child.FirstName, &child.LastName, &child.CreatedAt,
|
||||
); err != nil {
|
||||
return nil, fmt.Errorf("insert child: %w", err)
|
||||
}
|
||||
|
||||
// 4. Mint a magic-link token (raw goes back, hash goes to DB).
|
||||
raw, hash, err := randomToken()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("token gen: %w", err)
|
||||
}
|
||||
expiresAt := time.Now().Add(magicLinkTTL)
|
||||
if _, err := tx.Exec(ctx, `
|
||||
INSERT INTO parent_magic_link (parent_id, token_hash, expires_at)
|
||||
VALUES ($1, $2, $3)
|
||||
`, parent.ID, hash, expiresAt); err != nil {
|
||||
return nil, fmt.Errorf("insert magic link: %w", err)
|
||||
}
|
||||
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &models.InviteParentResponse{
|
||||
Parent: parent,
|
||||
Child: child,
|
||||
MagicToken: raw,
|
||||
MagicURL: "/eltern/login?token=" + raw,
|
||||
ExpiresAt: expiresAt,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (s *ParentService) ListInvites(ctx context.Context, userID string) ([]models.ParentInviteListItem, error) {
|
||||
rows, err := s.db.Query(ctx, `
|
||||
SELECT pa.id, pa.email, pa.preferred_language,
|
||||
pc.id, pc.first_name, pc.last_name,
|
||||
cl.id, cl.name, pc.created_at
|
||||
FROM parent_account pa
|
||||
JOIN parent_child pc ON pc.parent_id = pa.id
|
||||
JOIN tt_class cl ON cl.id = pc.tt_class_id
|
||||
WHERE pa.created_by_user_id = $1
|
||||
ORDER BY pa.email, pc.last_name
|
||||
`, userID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var out []models.ParentInviteListItem
|
||||
for rows.Next() {
|
||||
var it models.ParentInviteListItem
|
||||
if err := rows.Scan(&it.ParentID, &it.Email, &it.PreferredLanguage,
|
||||
&it.ChildID, &it.ChildFirstName, &it.ChildLastName,
|
||||
&it.ClassID, &it.ClassName, &it.CreatedAt); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, it)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// DeleteInvite removes one child row (parent stays if other children still
|
||||
// exist for the same teacher).
|
||||
func (s *ParentService) DeleteInvite(ctx context.Context, childID, userID string) error {
|
||||
res, err := s.db.Exec(ctx, `
|
||||
DELETE FROM parent_child pc
|
||||
USING parent_account pa
|
||||
WHERE pc.id = $1 AND pc.parent_id = pa.id AND pa.created_by_user_id = $2
|
||||
`, childID, userID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if res.RowsAffected() == 0 {
|
||||
return fmt.Errorf("child not found or not owned")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/breakpilot/school-service/internal/models"
|
||||
)
|
||||
|
||||
func TestRandomToken_Hashable(t *testing.T) {
|
||||
raw, hash, err := randomToken()
|
||||
if err != nil {
|
||||
t.Fatalf("randomToken error: %v", err)
|
||||
}
|
||||
if len(raw) < 30 {
|
||||
t.Errorf("raw token suspiciously short: %d", len(raw))
|
||||
}
|
||||
if len(hash) != 64 {
|
||||
t.Errorf("sha256 hex hash must be 64 chars, got %d", len(hash))
|
||||
}
|
||||
if hashToken(raw) != hash {
|
||||
t.Errorf("hashToken(raw) must equal the hash randomToken returned")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRandomToken_NonRepeating(t *testing.T) {
|
||||
// 16 iterations, all raw tokens must differ.
|
||||
seen := map[string]struct{}{}
|
||||
for i := 0; i < 16; i++ {
|
||||
raw, _, err := randomToken()
|
||||
if err != nil {
|
||||
t.Fatalf("iter %d: %v", i, err)
|
||||
}
|
||||
if _, dup := seen[raw]; dup {
|
||||
t.Fatalf("duplicate raw token at iter %d", i)
|
||||
}
|
||||
seen[raw] = struct{}{}
|
||||
}
|
||||
}
|
||||
|
||||
func TestHashToken_StableHexLowercase(t *testing.T) {
|
||||
h := hashToken("hello world")
|
||||
if strings.ToLower(h) != h {
|
||||
t.Errorf("hash should be lowercase hex")
|
||||
}
|
||||
if len(h) != 64 {
|
||||
t.Errorf("expected 64-char hash, got %d", len(h))
|
||||
}
|
||||
}
|
||||
|
||||
func TestInviteParentRequest_Validation(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
req models.InviteParentRequest
|
||||
wantErr bool
|
||||
}{
|
||||
{"valid", models.InviteParentRequest{
|
||||
Email: "a@b.de", ChildFirstName: "Max", ChildLastName: "Mueller",
|
||||
TTClassID: "00000000-0000-0000-0000-000000000001",
|
||||
}, false},
|
||||
{"bad email", models.InviteParentRequest{
|
||||
Email: "not-an-email", ChildFirstName: "Max", ChildLastName: "Mueller",
|
||||
TTClassID: "00000000-0000-0000-0000-000000000001",
|
||||
}, true},
|
||||
{"missing child", models.InviteParentRequest{
|
||||
Email: "a@b.de", TTClassID: "00000000-0000-0000-0000-000000000001",
|
||||
}, true},
|
||||
{"bad class uuid", models.InviteParentRequest{
|
||||
Email: "a@b.de", ChildFirstName: "Max", ChildLastName: "Mueller",
|
||||
TTClassID: "not-a-uuid",
|
||||
}, true},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if (validate.Struct(tt.req) != nil) != tt.wantErr {
|
||||
t.Errorf("unexpected validation outcome for %s", tt.name)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user