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:
@@ -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