Compare commits
3 Commits
main
...
feature/au
| Author | SHA1 | Date | |
|---|---|---|---|
| e3fe20005b | |||
| 889f072390 | |||
| ff5c5f1b1d |
@ -15,6 +15,7 @@ POSTGRES_USER=admin
|
||||
POSTGRES_PASSWORD=admin
|
||||
TZ=Asia/Tokyo
|
||||
COMPOSE_PLATFORM=linux/arm64/v8
|
||||
ROOT_ADMIN_UID=1
|
||||
|
||||
# App runtime (inside Docker network)
|
||||
PGHOST=db
|
||||
|
||||
@ -1,61 +0,0 @@
|
||||
name: Build and Deploy
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
|
||||
jobs:
|
||||
build-and-deploy:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
run: |
|
||||
rm -rf /tmp/watch-party
|
||||
git clone https://gitea.home.arpa/nik/watch-party /tmp/watch-party
|
||||
|
||||
- name: Write deploy key
|
||||
run: |
|
||||
echo "${{ secrets.DEPLOY_KEY }}" > /tmp/deploy_key
|
||||
chmod 600 /tmp/deploy_key
|
||||
|
||||
- name: Log in to Gitea registry
|
||||
run: |
|
||||
echo "${{ secrets.REGISTRY_PASSWORD }}" | docker login gitea.home.arpa \
|
||||
--username ${{ secrets.REGISTRY_USERNAME }} \
|
||||
--password-stdin
|
||||
|
||||
- name: Inject CA into buildkit
|
||||
run: |
|
||||
cat /etc/ssl/certs/homelab-ca.pem | docker exec -i buildx_buildkit_multiarch0 \
|
||||
sh -c 'cat >> /etc/ssl/certs/ca-certificates.crt && cat >> /etc/ssl/cert.pem'
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
run: |
|
||||
docker buildx create --use --name multiarch || docker buildx use multiarch
|
||||
|
||||
- name: Build and push backend
|
||||
run: |
|
||||
docker buildx build \
|
||||
--platform linux/amd64,linux/arm64 \
|
||||
-t gitea.home.arpa/nik/watch-party-backend:latest \
|
||||
--push \
|
||||
/tmp/watch-party/backend
|
||||
|
||||
- name: Build and push frontend
|
||||
run: |
|
||||
docker buildx build \
|
||||
--platform linux/amd64,linux/arm64 \
|
||||
-t gitea.home.arpa/nik/watch-party-frontend:latest \
|
||||
--push \
|
||||
/tmp/watch-party/frontend
|
||||
|
||||
- name: Deploy to Mac Mini
|
||||
run: |
|
||||
ssh -o StrictHostKeyChecking=no \
|
||||
-i /tmp/deploy_key \
|
||||
${{ secrets.DEPLOY_USER }}@${{ secrets.DEPLOY_HOST }} \
|
||||
"export PATH=/usr/local/bin:/opt/homebrew/bin:\$PATH && \
|
||||
cd ~/repo/watch-party && \
|
||||
docker compose pull && \
|
||||
docker compose up -d"
|
||||
@ -49,8 +49,6 @@ Compose uses the same image for `api` and the one-off `migrate` job.
|
||||
- `POST /api/v1/shows` — create a new episode (expects `{ ep_num, ep_title, season_name, start_time, playback_length }`)
|
||||
- `GET /api/v1/danime?part_id=...` — scrape dアニメ episode metadata (returns `{ ep_num, ep_title, season_name, playback_length }`)
|
||||
- `POST /api/v1/oauth/firebase` — verify a Firebase ID token and echo back UID/email
|
||||
- `POST /api/v1/oauth/firebase/claim-admin` — set the `admin` custom claim for a given Firebase UID
|
||||
- `GET /api/v1/archive` — list archived items (auth + admin required)
|
||||
- `DELETE /api/v1/shows?id=...` — delete a show (guarded by Firebase auth when `AUTH_ENABLED=true`)
|
||||
- `GET /healthz` — health check
|
||||
|
||||
@ -61,15 +59,6 @@ curl -X POST http://localhost:8082/api/v1/oauth/firebase \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"id_token":"<firebase-id-token>"}'
|
||||
|
||||
# Claim Firebase admin for a specific UID (AUTH_ENABLED=true)
|
||||
curl -X POST http://localhost:8082/api/v1/oauth/firebase/claim-admin \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"uid":"<firebase-uid>"}'
|
||||
|
||||
# List archive (admin only)
|
||||
curl -X GET http://localhost:8082/api/v1/archive \
|
||||
-H "Authorization: Bearer <firebase-id-token>"
|
||||
|
||||
# Delete a show with auth
|
||||
curl -X DELETE "http://localhost:8082/api/v1/shows?id=123" \
|
||||
-H "Authorization: Bearer <firebase-id-token>"
|
||||
|
||||
@ -43,19 +43,19 @@ func main() {
|
||||
// 3) wiring
|
||||
episodeRepo := repo.NewEpisodeRepo(pool)
|
||||
episodeSvc := service.NewEpisodeService(episodeRepo)
|
||||
var authClient auth.AuthClient
|
||||
var authMgr auth.AdminManager
|
||||
if cfg.Auth.Enabled {
|
||||
v, err := auth.NewFirebaseAuth(ctx, cfg.Firebase)
|
||||
if err != nil {
|
||||
log.Fatalf("firebase auth init failed: %v", err)
|
||||
}
|
||||
authClient = v
|
||||
authMgr = v
|
||||
log.Printf("auth enabled (project: %s)", cfg.Firebase.ProjectID)
|
||||
} else {
|
||||
log.Printf("auth disabled (AUTH_ENABLED=false)")
|
||||
}
|
||||
|
||||
router := httpapi.NewRouter(episodeSvc, authClient, cfg.Auth.Enabled)
|
||||
router := httpapi.NewRouter(episodeSvc, authMgr, cfg.Auth.Enabled, cfg.Auth.RootUID)
|
||||
router.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
|
||||
|
||||
// 4) HTTP server with timeouts
|
||||
|
||||
@ -16,39 +16,6 @@ const docTemplate = `{
|
||||
"basePath": "{{.BasePath}}",
|
||||
"paths": {
|
||||
"/api/v1/archive": {
|
||||
"get": {
|
||||
"description": "List all rows from ` + "`" + `current_archive` + "`" + ` (admin only).",
|
||||
"produces": [
|
||||
"application/json"
|
||||
],
|
||||
"tags": [
|
||||
"archive"
|
||||
],
|
||||
"summary": "List archive",
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK",
|
||||
"schema": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "#/definitions/httpapi.ArchiveResponse"
|
||||
}
|
||||
}
|
||||
},
|
||||
"403": {
|
||||
"description": "admin only",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/httpapi.HTTPError"
|
||||
}
|
||||
},
|
||||
"500": {
|
||||
"description": "list failed",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/httpapi.HTTPError"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"post": {
|
||||
"description": "Move one or many IDs from ` + "`" + `current` + "`" + ` to ` + "`" + `current_archive` + "`" + `.",
|
||||
"consumes": [
|
||||
@ -269,58 +236,6 @@ const docTemplate = `{
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/oauth/firebase/claim-admin": {
|
||||
"post": {
|
||||
"description": "Set the \\\"admin\\\" custom claim for the given Firebase UID.",
|
||||
"consumes": [
|
||||
"application/json"
|
||||
],
|
||||
"produces": [
|
||||
"application/json"
|
||||
],
|
||||
"tags": [
|
||||
"auth"
|
||||
],
|
||||
"summary": "Claim Firebase admin",
|
||||
"parameters": [
|
||||
{
|
||||
"description": "Firebase UID",
|
||||
"name": "body",
|
||||
"in": "body",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"$ref": "#/definitions/httpapi.FirebaseAdminClaimReq"
|
||||
}
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/httpapi.FirebaseAdminClaimRes"
|
||||
}
|
||||
},
|
||||
"400": {
|
||||
"description": "invalid payload",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/httpapi.HTTPError"
|
||||
}
|
||||
},
|
||||
"500": {
|
||||
"description": "claim failed",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/httpapi.HTTPError"
|
||||
}
|
||||
},
|
||||
"503": {
|
||||
"description": "auth disabled",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/httpapi.HTTPError"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/shows": {
|
||||
"get": {
|
||||
"description": "List all rows from ` + "`" + `current` + "`" + ` table.",
|
||||
@ -394,14 +309,14 @@ const docTemplate = `{
|
||||
}
|
||||
},
|
||||
"delete": {
|
||||
"description": "Delete a row from ` + "`" + `current_archive` + "`" + ` by ID.",
|
||||
"description": "Delete a row from ` + "`" + `current` + "`" + ` by ID.",
|
||||
"produces": [
|
||||
"application/json"
|
||||
],
|
||||
"tags": [
|
||||
"shows"
|
||||
],
|
||||
"summary": "Delete archived show",
|
||||
"summary": "Delete show",
|
||||
"parameters": [
|
||||
{
|
||||
"type": "integer",
|
||||
@ -439,47 +354,6 @@ const docTemplate = `{
|
||||
}
|
||||
},
|
||||
"definitions": {
|
||||
"httpapi.ArchiveResponse": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"current_ep": {
|
||||
"type": "boolean",
|
||||
"example": false
|
||||
},
|
||||
"date_archived": {
|
||||
"type": "string",
|
||||
"example": "2024-03-01T15:04:05Z"
|
||||
},
|
||||
"date_created": {
|
||||
"type": "string",
|
||||
"example": "2024-02-01T15:04:05Z"
|
||||
},
|
||||
"ep_num": {
|
||||
"type": "integer",
|
||||
"example": 1
|
||||
},
|
||||
"ep_title": {
|
||||
"type": "string",
|
||||
"example": "Pilot"
|
||||
},
|
||||
"id": {
|
||||
"type": "integer",
|
||||
"example": 123
|
||||
},
|
||||
"playback_length": {
|
||||
"type": "string",
|
||||
"example": "00:24:00"
|
||||
},
|
||||
"season_name": {
|
||||
"type": "string",
|
||||
"example": "Season 1"
|
||||
},
|
||||
"start_time": {
|
||||
"type": "string",
|
||||
"example": "10:00:00"
|
||||
}
|
||||
}
|
||||
},
|
||||
"httpapi.CreateShowReq": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
@ -570,39 +444,6 @@ const docTemplate = `{
|
||||
}
|
||||
}
|
||||
},
|
||||
"httpapi.FirebaseAdminClaimReq": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"uid"
|
||||
],
|
||||
"properties": {
|
||||
"uid": {
|
||||
"type": "string",
|
||||
"example": "abc123"
|
||||
}
|
||||
}
|
||||
},
|
||||
"httpapi.FirebaseAdminClaimRes": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"admin": {
|
||||
"type": "boolean",
|
||||
"example": true
|
||||
},
|
||||
"custom_claims": {
|
||||
"type": "object",
|
||||
"additionalProperties": true
|
||||
},
|
||||
"email": {
|
||||
"type": "string",
|
||||
"example": "user@example.com"
|
||||
},
|
||||
"uid": {
|
||||
"type": "string",
|
||||
"example": "abc123"
|
||||
}
|
||||
}
|
||||
},
|
||||
"httpapi.FirebaseOAuthReq": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
@ -618,15 +459,6 @@ const docTemplate = `{
|
||||
"httpapi.FirebaseOAuthRes": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"admin": {
|
||||
"type": "boolean",
|
||||
"example": true
|
||||
},
|
||||
"custom_claims": {
|
||||
"description": "CustomClaims echoes back custom claims; only include non-sensitive claims.",
|
||||
"type": "object",
|
||||
"additionalProperties": true
|
||||
},
|
||||
"email": {
|
||||
"type": "string",
|
||||
"example": "user@example.com"
|
||||
|
||||
@ -14,39 +14,6 @@
|
||||
"basePath": "/",
|
||||
"paths": {
|
||||
"/api/v1/archive": {
|
||||
"get": {
|
||||
"description": "List all rows from `current_archive` (admin only).",
|
||||
"produces": [
|
||||
"application/json"
|
||||
],
|
||||
"tags": [
|
||||
"archive"
|
||||
],
|
||||
"summary": "List archive",
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK",
|
||||
"schema": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "#/definitions/httpapi.ArchiveResponse"
|
||||
}
|
||||
}
|
||||
},
|
||||
"403": {
|
||||
"description": "admin only",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/httpapi.HTTPError"
|
||||
}
|
||||
},
|
||||
"500": {
|
||||
"description": "list failed",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/httpapi.HTTPError"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"post": {
|
||||
"description": "Move one or many IDs from `current` to `current_archive`.",
|
||||
"consumes": [
|
||||
@ -267,58 +234,6 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/oauth/firebase/claim-admin": {
|
||||
"post": {
|
||||
"description": "Set the \\\"admin\\\" custom claim for the given Firebase UID.",
|
||||
"consumes": [
|
||||
"application/json"
|
||||
],
|
||||
"produces": [
|
||||
"application/json"
|
||||
],
|
||||
"tags": [
|
||||
"auth"
|
||||
],
|
||||
"summary": "Claim Firebase admin",
|
||||
"parameters": [
|
||||
{
|
||||
"description": "Firebase UID",
|
||||
"name": "body",
|
||||
"in": "body",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"$ref": "#/definitions/httpapi.FirebaseAdminClaimReq"
|
||||
}
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/httpapi.FirebaseAdminClaimRes"
|
||||
}
|
||||
},
|
||||
"400": {
|
||||
"description": "invalid payload",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/httpapi.HTTPError"
|
||||
}
|
||||
},
|
||||
"500": {
|
||||
"description": "claim failed",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/httpapi.HTTPError"
|
||||
}
|
||||
},
|
||||
"503": {
|
||||
"description": "auth disabled",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/httpapi.HTTPError"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/shows": {
|
||||
"get": {
|
||||
"description": "List all rows from `current` table.",
|
||||
@ -392,14 +307,14 @@
|
||||
}
|
||||
},
|
||||
"delete": {
|
||||
"description": "Delete a row from `current_archive` by ID.",
|
||||
"description": "Delete a row from `current` by ID.",
|
||||
"produces": [
|
||||
"application/json"
|
||||
],
|
||||
"tags": [
|
||||
"shows"
|
||||
],
|
||||
"summary": "Delete archived show",
|
||||
"summary": "Delete show",
|
||||
"parameters": [
|
||||
{
|
||||
"type": "integer",
|
||||
@ -437,47 +352,6 @@
|
||||
}
|
||||
},
|
||||
"definitions": {
|
||||
"httpapi.ArchiveResponse": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"current_ep": {
|
||||
"type": "boolean",
|
||||
"example": false
|
||||
},
|
||||
"date_archived": {
|
||||
"type": "string",
|
||||
"example": "2024-03-01T15:04:05Z"
|
||||
},
|
||||
"date_created": {
|
||||
"type": "string",
|
||||
"example": "2024-02-01T15:04:05Z"
|
||||
},
|
||||
"ep_num": {
|
||||
"type": "integer",
|
||||
"example": 1
|
||||
},
|
||||
"ep_title": {
|
||||
"type": "string",
|
||||
"example": "Pilot"
|
||||
},
|
||||
"id": {
|
||||
"type": "integer",
|
||||
"example": 123
|
||||
},
|
||||
"playback_length": {
|
||||
"type": "string",
|
||||
"example": "00:24:00"
|
||||
},
|
||||
"season_name": {
|
||||
"type": "string",
|
||||
"example": "Season 1"
|
||||
},
|
||||
"start_time": {
|
||||
"type": "string",
|
||||
"example": "10:00:00"
|
||||
}
|
||||
}
|
||||
},
|
||||
"httpapi.CreateShowReq": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
@ -568,39 +442,6 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"httpapi.FirebaseAdminClaimReq": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"uid"
|
||||
],
|
||||
"properties": {
|
||||
"uid": {
|
||||
"type": "string",
|
||||
"example": "abc123"
|
||||
}
|
||||
}
|
||||
},
|
||||
"httpapi.FirebaseAdminClaimRes": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"admin": {
|
||||
"type": "boolean",
|
||||
"example": true
|
||||
},
|
||||
"custom_claims": {
|
||||
"type": "object",
|
||||
"additionalProperties": true
|
||||
},
|
||||
"email": {
|
||||
"type": "string",
|
||||
"example": "user@example.com"
|
||||
},
|
||||
"uid": {
|
||||
"type": "string",
|
||||
"example": "abc123"
|
||||
}
|
||||
}
|
||||
},
|
||||
"httpapi.FirebaseOAuthReq": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
@ -616,15 +457,6 @@
|
||||
"httpapi.FirebaseOAuthRes": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"admin": {
|
||||
"type": "boolean",
|
||||
"example": true
|
||||
},
|
||||
"custom_claims": {
|
||||
"description": "CustomClaims echoes back custom claims; only include non-sensitive claims.",
|
||||
"type": "object",
|
||||
"additionalProperties": true
|
||||
},
|
||||
"email": {
|
||||
"type": "string",
|
||||
"example": "user@example.com"
|
||||
|
||||
@ -1,35 +1,5 @@
|
||||
basePath: /
|
||||
definitions:
|
||||
httpapi.ArchiveResponse:
|
||||
properties:
|
||||
current_ep:
|
||||
example: false
|
||||
type: boolean
|
||||
date_archived:
|
||||
example: "2024-03-01T15:04:05Z"
|
||||
type: string
|
||||
date_created:
|
||||
example: "2024-02-01T15:04:05Z"
|
||||
type: string
|
||||
ep_num:
|
||||
example: 1
|
||||
type: integer
|
||||
ep_title:
|
||||
example: Pilot
|
||||
type: string
|
||||
id:
|
||||
example: 123
|
||||
type: integer
|
||||
playback_length:
|
||||
example: "00:24:00"
|
||||
type: string
|
||||
season_name:
|
||||
example: Season 1
|
||||
type: string
|
||||
start_time:
|
||||
example: "10:00:00"
|
||||
type: string
|
||||
type: object
|
||||
httpapi.CreateShowReq:
|
||||
properties:
|
||||
ep_num:
|
||||
@ -96,29 +66,6 @@ definitions:
|
||||
example: フルーツバスケット 2nd season
|
||||
type: string
|
||||
type: object
|
||||
httpapi.FirebaseAdminClaimReq:
|
||||
properties:
|
||||
uid:
|
||||
example: abc123
|
||||
type: string
|
||||
required:
|
||||
- uid
|
||||
type: object
|
||||
httpapi.FirebaseAdminClaimRes:
|
||||
properties:
|
||||
admin:
|
||||
example: true
|
||||
type: boolean
|
||||
custom_claims:
|
||||
additionalProperties: true
|
||||
type: object
|
||||
email:
|
||||
example: user@example.com
|
||||
type: string
|
||||
uid:
|
||||
example: abc123
|
||||
type: string
|
||||
type: object
|
||||
httpapi.FirebaseOAuthReq:
|
||||
properties:
|
||||
id_token:
|
||||
@ -129,14 +76,6 @@ definitions:
|
||||
type: object
|
||||
httpapi.FirebaseOAuthRes:
|
||||
properties:
|
||||
admin:
|
||||
example: true
|
||||
type: boolean
|
||||
custom_claims:
|
||||
additionalProperties: true
|
||||
description: CustomClaims echoes back custom claims; only include non-sensitive
|
||||
claims.
|
||||
type: object
|
||||
email:
|
||||
example: user@example.com
|
||||
type: string
|
||||
@ -207,28 +146,6 @@ info:
|
||||
version: "1.0"
|
||||
paths:
|
||||
/api/v1/archive:
|
||||
get:
|
||||
description: List all rows from `current_archive` (admin only).
|
||||
produces:
|
||||
- application/json
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
schema:
|
||||
items:
|
||||
$ref: '#/definitions/httpapi.ArchiveResponse'
|
||||
type: array
|
||||
"403":
|
||||
description: admin only
|
||||
schema:
|
||||
$ref: '#/definitions/httpapi.HTTPError'
|
||||
"500":
|
||||
description: list failed
|
||||
schema:
|
||||
$ref: '#/definitions/httpapi.HTTPError'
|
||||
summary: List archive
|
||||
tags:
|
||||
- archive
|
||||
post:
|
||||
consumes:
|
||||
- application/json
|
||||
@ -373,43 +290,9 @@ paths:
|
||||
summary: Verify Firebase ID token
|
||||
tags:
|
||||
- auth
|
||||
/api/v1/oauth/firebase/claim-admin:
|
||||
post:
|
||||
consumes:
|
||||
- application/json
|
||||
description: Set the \"admin\" custom claim for the given Firebase UID.
|
||||
parameters:
|
||||
- description: Firebase UID
|
||||
in: body
|
||||
name: body
|
||||
required: true
|
||||
schema:
|
||||
$ref: '#/definitions/httpapi.FirebaseAdminClaimReq'
|
||||
produces:
|
||||
- application/json
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
schema:
|
||||
$ref: '#/definitions/httpapi.FirebaseAdminClaimRes'
|
||||
"400":
|
||||
description: invalid payload
|
||||
schema:
|
||||
$ref: '#/definitions/httpapi.HTTPError'
|
||||
"500":
|
||||
description: claim failed
|
||||
schema:
|
||||
$ref: '#/definitions/httpapi.HTTPError'
|
||||
"503":
|
||||
description: auth disabled
|
||||
schema:
|
||||
$ref: '#/definitions/httpapi.HTTPError'
|
||||
summary: Claim Firebase admin
|
||||
tags:
|
||||
- auth
|
||||
/api/v1/shows:
|
||||
delete:
|
||||
description: Delete a row from `current_archive` by ID.
|
||||
description: Delete a row from `current` by ID.
|
||||
parameters:
|
||||
- description: Show ID
|
||||
format: int64
|
||||
@ -434,7 +317,7 @@ paths:
|
||||
description: delete failed
|
||||
schema:
|
||||
$ref: '#/definitions/httpapi.HTTPError'
|
||||
summary: Delete archived show
|
||||
summary: Delete show
|
||||
tags:
|
||||
- shows
|
||||
get:
|
||||
|
||||
@ -16,10 +16,10 @@ type TokenVerifier interface {
|
||||
Verify(ctx context.Context, token string) (*fbauth.Token, error)
|
||||
}
|
||||
|
||||
// AuthClient can verify tokens and mutate Firebase custom claims.
|
||||
type AuthClient interface {
|
||||
// AdminManager can set admin claims.
|
||||
type AdminManager interface {
|
||||
TokenVerifier
|
||||
SetAdminClaim(ctx context.Context, uid string) (string, map[string]interface{}, error)
|
||||
SetAdmin(ctx context.Context, uid string, admin bool) error
|
||||
}
|
||||
|
||||
// FirebaseAuth verifies Firebase ID tokens.
|
||||
@ -53,19 +53,9 @@ func (f *FirebaseAuth) Verify(ctx context.Context, token string) (*fbauth.Token,
|
||||
return f.client.VerifyIDToken(ctx, token)
|
||||
}
|
||||
|
||||
// SetAdminClaim sets the "admin" custom claim while preserving existing claims.
|
||||
func (f *FirebaseAuth) SetAdminClaim(ctx context.Context, uid string) (string, map[string]interface{}, error) {
|
||||
user, err := f.client.GetUser(ctx, uid)
|
||||
if err != nil {
|
||||
return "", nil, fmt.Errorf("get user: %w", err)
|
||||
}
|
||||
claims := make(map[string]interface{}, len(user.CustomClaims)+1)
|
||||
for k, v := range user.CustomClaims {
|
||||
claims[k] = v
|
||||
}
|
||||
claims["admin"] = true
|
||||
if err := f.client.SetCustomUserClaims(ctx, uid, claims); err != nil {
|
||||
return "", nil, fmt.Errorf("set custom claims: %w", err)
|
||||
}
|
||||
return user.Email, claims, nil
|
||||
// SetAdmin sets or clears the custom claim "admin" for a given uid.
|
||||
func (f *FirebaseAuth) SetAdmin(ctx context.Context, uid string, admin bool) error {
|
||||
return f.client.SetCustomUserClaims(ctx, uid, map[string]interface{}{
|
||||
"admin": admin,
|
||||
})
|
||||
}
|
||||
|
||||
@ -23,6 +23,7 @@ type Config struct {
|
||||
|
||||
type AuthConfig struct {
|
||||
Enabled bool
|
||||
RootUID string
|
||||
}
|
||||
|
||||
type FirebaseConfig struct {
|
||||
@ -50,6 +51,7 @@ func Load() Config {
|
||||
GinMode: getenv("GIN_MODE", "release"),
|
||||
Auth: AuthConfig{
|
||||
Enabled: getenvBool("AUTH_ENABLED", false),
|
||||
RootUID: getenv("ROOT_ADMIN_UID", ""),
|
||||
},
|
||||
Firebase: FirebaseConfig{
|
||||
ProjectID: getenv("FIREBASE_PROJECT_ID", ""),
|
||||
|
||||
@ -26,19 +26,6 @@ type Episode struct {
|
||||
DateCreated time.Time `json:"date_created"`
|
||||
}
|
||||
|
||||
// ArchiveEpisode represents a row in the current_archive table.
|
||||
type ArchiveEpisode struct {
|
||||
Id int `json:"id"`
|
||||
EpNum int `json:"ep_num"`
|
||||
EpTitle string `json:"ep_title"`
|
||||
SeasonName string `json:"season_name"`
|
||||
StartTime string `json:"start_time"`
|
||||
PlaybackLength string `json:"playback_length"`
|
||||
CurrentEp bool `json:"current_ep"`
|
||||
DateCreated time.Time `json:"date_created"`
|
||||
DateArchived time.Time `json:"date_archived"`
|
||||
}
|
||||
|
||||
// NewShowInput is the payload needed to create a new show/episode.
|
||||
type NewShowInput struct {
|
||||
EpNum int `json:"ep_num"`
|
||||
@ -62,6 +49,5 @@ type Repository interface {
|
||||
Create(ctx context.Context, in NewShowInput) (Episode, error)
|
||||
MoveToArchive(ctx context.Context, ids []int64) (MoveResult, error)
|
||||
ListAll(ctx context.Context) ([]Episode, error)
|
||||
ListArchive(ctx context.Context) ([]ArchiveEpisode, error)
|
||||
Delete(ctx context.Context, id int64) error
|
||||
}
|
||||
|
||||
@ -9,6 +9,5 @@ type UseCases interface {
|
||||
Create(ctx context.Context, in NewShowInput) (Episode, error)
|
||||
MoveToArchive(ctx context.Context, ids []int64) (MoveResult, error)
|
||||
ListAll(ctx context.Context) ([]Episode, error)
|
||||
ListArchive(ctx context.Context) ([]ArchiveEpisode, error)
|
||||
Delete(ctx context.Context, id int64) error
|
||||
}
|
||||
|
||||
@ -15,7 +15,7 @@ import (
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func NewRouter(svc episode.UseCases, authClient auth.AuthClient, authEnabled bool) *gin.Engine {
|
||||
func NewRouter(svc episode.UseCases, authMgr auth.AdminManager, authEnabled bool, rootUID string) *gin.Engine {
|
||||
r := gin.New()
|
||||
r.Use(gin.Logger(), gin.Recovery())
|
||||
|
||||
@ -29,16 +29,20 @@ func NewRouter(svc episode.UseCases, authClient auth.AuthClient, authEnabled boo
|
||||
v1.POST("/current", setCurrentHandler(svc))
|
||||
v1.POST("/shows", createShowHandler(svc))
|
||||
v1.GET("/shows", listShowsHandler(svc))
|
||||
v1.POST("/oauth/firebase", oauthFirebaseHandler(authClient, authEnabled))
|
||||
v1.POST("/oauth/firebase/claim-admin", claimFirebaseAdminHandler(authClient, authEnabled))
|
||||
v1.POST("/oauth/firebase", oauthFirebaseHandler(verifier, authEnabled))
|
||||
v1.GET("/danime", getDanimeHandler())
|
||||
|
||||
if authEnabled && authClient != nil {
|
||||
if authEnabled && authMgr != nil {
|
||||
protected := v1.Group("/")
|
||||
protected.Use(AuthMiddleware(authClient))
|
||||
protected.Use(AuthMiddleware(authMgr), RequireAdmin())
|
||||
protected.DELETE("/shows", deleteShowsHandler(svc))
|
||||
protected.POST("/archive", moveToArchiveHandler(svc))
|
||||
protected.GET("/archive", AdminOnly(), listArchiveHandler(svc))
|
||||
|
||||
if rootUID != "" {
|
||||
admin := v1.Group("/admin")
|
||||
admin.Use(AuthMiddleware(authMgr), RequireRootUID(rootUID))
|
||||
admin.POST("/grant", setAdminHandler(authMgr))
|
||||
}
|
||||
} else {
|
||||
v1.DELETE("/shows", deleteShowsHandler(svc))
|
||||
v1.POST("/archive", moveToArchiveHandler(svc))
|
||||
@ -47,6 +51,38 @@ func NewRouter(svc episode.UseCases, authClient auth.AuthClient, authEnabled boo
|
||||
return r
|
||||
}
|
||||
|
||||
// setAdminHandler godoc
|
||||
// @Summary Grant/revoke admin
|
||||
// @Description Set the custom claim "admin" for a user. Requires root admin UID.
|
||||
// @Tags admin
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param body body SetAdminReq true "UID and desired admin flag"
|
||||
// @Success 204 {string} string "no content"
|
||||
// @Failure 400 {object} HTTPError "invalid payload"
|
||||
// @Failure 403 {object} HTTPError "forbidden"
|
||||
// @Failure 500 {object} HTTPError "failed to set claim"
|
||||
// @Router /api/v1/admin/grant [post]
|
||||
func setAdminHandler(authMgr auth.AdminManager) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
var req SetAdminReq
|
||||
if err := c.ShouldBindJSON(&req); err != nil || strings.TrimSpace(req.UID) == "" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid payload"})
|
||||
return
|
||||
}
|
||||
admin := true
|
||||
if req.Admin != nil {
|
||||
admin = *req.Admin
|
||||
}
|
||||
if err := authMgr.SetAdmin(c.Request.Context(), req.UID, admin); err != nil {
|
||||
log.Printf("set admin failed for uid=%s: %v", req.UID, err)
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to set claim"})
|
||||
return
|
||||
}
|
||||
c.Status(http.StatusNoContent)
|
||||
}
|
||||
}
|
||||
|
||||
// GET /healthz
|
||||
func healthzHandler(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, gin.H{"status": "ok"})
|
||||
@ -270,8 +306,8 @@ func listShowsHandler(svc episode.UseCases) gin.HandlerFunc {
|
||||
}
|
||||
|
||||
// deleteShowHandler godoc
|
||||
// @Summary Delete archived show
|
||||
// @Description Delete a row from `current_archive` by ID.
|
||||
// @Summary Delete show
|
||||
// @Description Delete a row from `current` by ID.
|
||||
// @Tags shows
|
||||
// @Produce json
|
||||
// @Param id query int64 true "Show ID"
|
||||
@ -335,93 +371,11 @@ func oauthFirebaseHandler(verifier auth.TokenVerifier, authEnabled bool) gin.Han
|
||||
return
|
||||
}
|
||||
email, _ := token.Claims["email"].(string)
|
||||
admin, _ := token.Claims["admin"].(bool)
|
||||
c.JSON(http.StatusOK, FirebaseOAuthRes{
|
||||
UID: token.UID,
|
||||
Email: email,
|
||||
Issuer: token.Issuer,
|
||||
Expires: token.Expires,
|
||||
Admin: admin,
|
||||
CustomClaims: map[string]interface{}{
|
||||
"admin": admin,
|
||||
},
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// claimFirebaseAdminHandler godoc
|
||||
// @Summary Claim Firebase admin
|
||||
// @Description Set the \"admin\" custom claim for the given Firebase UID.
|
||||
// @Tags auth
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param body body FirebaseAdminClaimReq true "Firebase UID"
|
||||
// @Success 200 {object} FirebaseAdminClaimRes
|
||||
// @Failure 400 {object} HTTPError "invalid payload"
|
||||
// @Failure 503 {object} HTTPError "auth disabled"
|
||||
// @Failure 500 {object} HTTPError "claim failed"
|
||||
// @Router /api/v1/oauth/firebase/claim-admin [post]
|
||||
func claimFirebaseAdminHandler(client auth.AuthClient, authEnabled bool) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
if !authEnabled || client == nil {
|
||||
c.JSON(http.StatusServiceUnavailable, gin.H{"error": "auth disabled"})
|
||||
return
|
||||
}
|
||||
var req FirebaseAdminClaimReq
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid payload"})
|
||||
return
|
||||
}
|
||||
uid := strings.TrimSpace(req.UID)
|
||||
if uid == "" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "uid is required"})
|
||||
return
|
||||
}
|
||||
email, claims, err := client.SetAdminClaim(c.Request.Context(), uid)
|
||||
if err != nil {
|
||||
log.Printf("set admin claim failed for uid=%s: %v", uid, err)
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "claim failed"})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, FirebaseAdminClaimRes{
|
||||
UID: uid,
|
||||
Email: email,
|
||||
Admin: true,
|
||||
CustomClaims: claims,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// listArchiveHandler godoc
|
||||
// @Summary List archive
|
||||
// @Description List all rows from `current_archive` (admin only).
|
||||
// @Tags archive
|
||||
// @Produce json
|
||||
// @Success 200 {array} ArchiveResponse
|
||||
// @Failure 403 {object} HTTPError "admin only"
|
||||
// @Failure 500 {object} HTTPError "list failed"
|
||||
// @Router /api/v1/archive [get]
|
||||
func listArchiveHandler(svc episode.UseCases) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
items, err := svc.ListArchive(c.Request.Context())
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "list failed"})
|
||||
return
|
||||
}
|
||||
res := make([]ArchiveResponse, 0, len(items))
|
||||
for _, it := range items {
|
||||
res = append(res, ArchiveResponse{
|
||||
ID: it.Id,
|
||||
EpNum: it.EpNum,
|
||||
EpTitle: it.EpTitle,
|
||||
SeasonName: it.SeasonName,
|
||||
StartTime: it.StartTime,
|
||||
PlaybackLength: it.PlaybackLength,
|
||||
CurrentEp: it.CurrentEp,
|
||||
DateCreated: it.DateCreated,
|
||||
DateArchived: it.DateArchived,
|
||||
})
|
||||
}
|
||||
c.JSON(http.StatusOK, res)
|
||||
}
|
||||
}
|
||||
|
||||
@ -10,9 +10,6 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
fbauth "firebase.google.com/go/v4/auth"
|
||||
|
||||
"watch-party-backend/internal/auth"
|
||||
"watch-party-backend/internal/core/episode"
|
||||
"watch-party-backend/internal/danime"
|
||||
httpapi "watch-party-backend/internal/http"
|
||||
@ -39,8 +36,6 @@ type fakeSvc struct {
|
||||
lastMove []int64
|
||||
lastDelID int64
|
||||
lastCreate episode.NewShowInput
|
||||
archiveRes []episode.ArchiveEpisode
|
||||
archiveErr error
|
||||
}
|
||||
|
||||
func (f *fakeSvc) GetCurrent(ctx context.Context) (episode.Episode, error) {
|
||||
@ -60,9 +55,6 @@ func (f *fakeSvc) ListAll(ctx context.Context) ([]episode.Episode, error) {
|
||||
}
|
||||
return f.listRes, f.listErr
|
||||
}
|
||||
func (f *fakeSvc) ListArchive(ctx context.Context) ([]episode.ArchiveEpisode, error) {
|
||||
return f.archiveRes, f.archiveErr
|
||||
}
|
||||
func (f *fakeSvc) Delete(ctx context.Context, id int64) error {
|
||||
f.lastDelID = id
|
||||
return f.deleteErr
|
||||
@ -75,12 +67,8 @@ func (f *fakeSvc) Create(ctx context.Context, in episode.NewShowInput) (episode.
|
||||
// ---- helpers ----
|
||||
|
||||
func newRouterWithSvc(svc episode.UseCases) *gin.Engine {
|
||||
return newRouterWithOpts(svc, nil, false)
|
||||
}
|
||||
|
||||
func newRouterWithOpts(svc episode.UseCases, authClient auth.AuthClient, authEnabled bool) *gin.Engine {
|
||||
gin.SetMode(gin.TestMode)
|
||||
return httpapi.NewRouter(svc, authClient, authEnabled)
|
||||
return httpapi.NewRouter(svc, nil, false)
|
||||
}
|
||||
|
||||
func doJSON(t *testing.T, r *gin.Engine, method, path string, body any) *httptest.ResponseRecorder {
|
||||
@ -98,30 +86,6 @@ func doJSON(t *testing.T, r *gin.Engine, method, path string, body any) *httptes
|
||||
return w
|
||||
}
|
||||
|
||||
type fakeAuthClient struct {
|
||||
token *fbauth.Token
|
||||
verifyErr error
|
||||
claimErr error
|
||||
claims map[string]interface{}
|
||||
email string
|
||||
lastUID string
|
||||
}
|
||||
|
||||
func (f *fakeAuthClient) Verify(_ context.Context, _ string) (*fbauth.Token, error) {
|
||||
return f.token, f.verifyErr
|
||||
}
|
||||
|
||||
func (f *fakeAuthClient) SetAdminClaim(_ context.Context, uid string) (string, map[string]interface{}, error) {
|
||||
f.lastUID = uid
|
||||
if f.claimErr != nil {
|
||||
return "", nil, f.claimErr
|
||||
}
|
||||
if f.claims != nil {
|
||||
return f.email, f.claims, nil
|
||||
}
|
||||
return f.email, map[string]interface{}{"admin": true}, nil
|
||||
}
|
||||
|
||||
// ---- tests ----
|
||||
|
||||
func TestHealthz_OK(t *testing.T) {
|
||||
@ -435,104 +399,6 @@ func TestListShows_OK(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestClaimFirebaseAdmin_Disabled(t *testing.T) {
|
||||
r := newRouterWithSvc(&fakeSvc{})
|
||||
w := doJSON(t, r, http.MethodPost, "/api/v1/oauth/firebase/claim-admin", map[string]any{"uid": "uid-x"})
|
||||
if w.Code != http.StatusServiceUnavailable {
|
||||
t.Fatalf("expected 503, got %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClaimFirebaseAdmin_InvalidPayload(t *testing.T) {
|
||||
client := &fakeAuthClient{}
|
||||
r := newRouterWithOpts(&fakeSvc{}, client, true)
|
||||
w := doJSON(t, r, http.MethodPost, "/api/v1/oauth/firebase/claim-admin", nil)
|
||||
if w.Code != http.StatusBadRequest {
|
||||
t.Fatalf("expected 400, got %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClaimFirebaseAdmin_ClaimError(t *testing.T) {
|
||||
client := &fakeAuthClient{
|
||||
claimErr: errors.New("cannot set"),
|
||||
}
|
||||
r := newRouterWithOpts(&fakeSvc{}, client, true)
|
||||
w := doJSON(t, r, http.MethodPost, "/api/v1/oauth/firebase/claim-admin", map[string]any{"uid": "uid-2"})
|
||||
if w.Code != http.StatusInternalServerError {
|
||||
t.Fatalf("expected 500, got %d", w.Code)
|
||||
}
|
||||
if client.lastUID != "uid-2" {
|
||||
t.Fatalf("expected claim to run on uid-2, got %s", client.lastUID)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClaimFirebaseAdmin_OK(t *testing.T) {
|
||||
client := &fakeAuthClient{
|
||||
email: "user@example.com",
|
||||
claims: map[string]interface{}{"admin": true, "role": "owner"},
|
||||
}
|
||||
r := newRouterWithOpts(&fakeSvc{}, client, true)
|
||||
w := doJSON(t, r, http.MethodPost, "/api/v1/oauth/firebase/claim-admin", map[string]any{"uid": "uid-3"})
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("expected 200, got %d", w.Code)
|
||||
}
|
||||
var body map[string]any
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil {
|
||||
t.Fatalf("json: %v", err)
|
||||
}
|
||||
if body["uid"] != "uid-3" || body["admin"] != true {
|
||||
t.Fatalf("unexpected body: %+v", body)
|
||||
}
|
||||
claims, ok := body["custom_claims"].(map[string]any)
|
||||
if !ok || claims["role"] != "owner" {
|
||||
t.Fatalf("claims not returned as expected: %+v", body["custom_claims"])
|
||||
}
|
||||
if client.lastUID != "uid-3" {
|
||||
t.Fatalf("expected claim to run on uid-3, got %s", client.lastUID)
|
||||
}
|
||||
if body["email"] != "user@example.com" {
|
||||
t.Fatalf("expected email propagated, got %v", body["email"])
|
||||
}
|
||||
}
|
||||
|
||||
func TestListArchive_AdminRequired(t *testing.T) {
|
||||
svc := &fakeSvc{}
|
||||
client := &fakeAuthClient{token: &fbauth.Token{UID: "uid-1", Claims: map[string]interface{}{"admin": false}}}
|
||||
r := newRouterWithOpts(svc, client, true)
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/v1/archive", nil)
|
||||
req.Header.Set("Authorization", "Bearer tok")
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, req)
|
||||
if w.Code != http.StatusForbidden {
|
||||
t.Fatalf("expected 403, got %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestListArchive_OK(t *testing.T) {
|
||||
now := time.Now().UTC()
|
||||
svc := &fakeSvc{
|
||||
archiveRes: []episode.ArchiveEpisode{
|
||||
{Id: 1, EpNum: 1, EpTitle: "Pilot", SeasonName: "S1", StartTime: "10:00:00", PlaybackLength: "00:24:00", DateCreated: now, DateArchived: now},
|
||||
},
|
||||
}
|
||||
client := &fakeAuthClient{token: &fbauth.Token{UID: "uid-1", Claims: map[string]interface{}{"admin": true}}}
|
||||
r := newRouterWithOpts(svc, client, true)
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/v1/archive", nil)
|
||||
req.Header.Set("Authorization", "Bearer tok")
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, req)
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())
|
||||
}
|
||||
var items []episode.ArchiveEpisode
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &items); err != nil {
|
||||
t.Fatalf("json: %v", err)
|
||||
}
|
||||
if len(items) != 1 || items[0].EpTitle != "Pilot" {
|
||||
t.Fatalf("unexpected items: %+v", items)
|
||||
}
|
||||
}
|
||||
|
||||
func TestListShows_Error(t *testing.T) {
|
||||
svc := &fakeSvc{listErr: errors.New("query failed")}
|
||||
r := newRouterWithSvc(svc)
|
||||
|
||||
@ -4,9 +4,9 @@ import (
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
fbauth "firebase.google.com/go/v4/auth"
|
||||
"watch-party-backend/internal/auth"
|
||||
|
||||
fbauth "firebase.google.com/go/v4/auth"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
@ -33,22 +33,42 @@ func AuthMiddleware(verifier auth.TokenVerifier) gin.HandlerFunc {
|
||||
}
|
||||
}
|
||||
|
||||
// AdminOnly ensures the firebaseToken context value has admin=true claim.
|
||||
func AdminOnly() gin.HandlerFunc {
|
||||
// RequireAdmin enforces a custom claim "admin": true on the Firebase token.
|
||||
func RequireAdmin() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
val, ok := c.Get("firebaseToken")
|
||||
if !ok {
|
||||
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "missing token"})
|
||||
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
|
||||
return
|
||||
}
|
||||
token, ok := val.(*fbauth.Token)
|
||||
if !ok || token == nil {
|
||||
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "missing token"})
|
||||
if !ok {
|
||||
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
|
||||
return
|
||||
}
|
||||
admin, _ := token.Claims["admin"].(bool)
|
||||
if !admin {
|
||||
c.AbortWithStatusJSON(http.StatusForbidden, gin.H{"error": "admin only"})
|
||||
if isAdmin, ok := token.Claims["admin"].(bool); !ok || !isAdmin {
|
||||
c.AbortWithStatusJSON(http.StatusForbidden, gin.H{"error": "forbidden"})
|
||||
return
|
||||
}
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
// RequireRootUID enforces that the caller's UID matches the configured root admin UID.
|
||||
func RequireRootUID(rootUID string) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
val, ok := c.Get("firebaseToken")
|
||||
if !ok {
|
||||
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
|
||||
return
|
||||
}
|
||||
token, ok := val.(*fbauth.Token)
|
||||
if !ok || token.UID == "" {
|
||||
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
|
||||
return
|
||||
}
|
||||
if token.UID != rootUID {
|
||||
c.AbortWithStatusJSON(http.StatusForbidden, gin.H{"error": "forbidden"})
|
||||
return
|
||||
}
|
||||
c.Next()
|
||||
|
||||
@ -69,54 +69,3 @@ func TestAuthMiddleware_Success(t *testing.T) {
|
||||
t.Fatalf("expected status %d, got %d", http.StatusOK, w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAdminOnly_MissingToken(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
r := gin.New()
|
||||
r.Use(AdminOnly())
|
||||
r.GET("/", func(c *gin.Context) {})
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/", nil)
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusUnauthorized {
|
||||
t.Fatalf("expected status %d, got %d", http.StatusUnauthorized, w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAdminOnly_Forbidden(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
r := gin.New()
|
||||
r.Use(func(c *gin.Context) {
|
||||
c.Set("firebaseToken", &fbauth.Token{Claims: map[string]interface{}{"admin": false}})
|
||||
})
|
||||
r.Use(AdminOnly())
|
||||
r.GET("/", func(c *gin.Context) {})
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/", nil)
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusForbidden {
|
||||
t.Fatalf("expected status %d, got %d", http.StatusForbidden, w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAdminOnly_Success(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
r := gin.New()
|
||||
r.Use(func(c *gin.Context) {
|
||||
c.Set("firebaseToken", &fbauth.Token{Claims: map[string]interface{}{"admin": true}})
|
||||
})
|
||||
r.Use(AdminOnly())
|
||||
r.GET("/", func(c *gin.Context) { c.Status(http.StatusOK) })
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/", nil)
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("expected status %d, got %d", http.StatusOK, w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
@ -69,33 +69,10 @@ type FirebaseOAuthRes struct {
|
||||
Email string `json:"email,omitempty" example:"user@example.com"`
|
||||
Issuer string `json:"issuer,omitempty" example:"https://securetoken.google.com/<project>"`
|
||||
Expires int64 `json:"expires,omitempty" example:"1700000000"`
|
||||
Admin bool `json:"admin,omitempty" example:"true"`
|
||||
// CustomClaims echoes back custom claims; only include non-sensitive claims.
|
||||
CustomClaims map[string]interface{} `json:"custom_claims,omitempty"`
|
||||
}
|
||||
|
||||
// FirebaseAdminClaimReq is the request body for POST /api/v1/oauth/firebase/claim-admin.
|
||||
type FirebaseAdminClaimReq struct {
|
||||
UID string `json:"uid" binding:"required" example:"abc123"`
|
||||
}
|
||||
|
||||
// FirebaseAdminClaimRes is the response body for POST /api/v1/oauth/firebase/claim-admin.
|
||||
type FirebaseAdminClaimRes struct {
|
||||
UID string `json:"uid" example:"abc123"`
|
||||
Email string `json:"email,omitempty" example:"user@example.com"`
|
||||
Admin bool `json:"admin" example:"true"`
|
||||
CustomClaims map[string]interface{} `json:"custom_claims,omitempty"`
|
||||
}
|
||||
|
||||
// ArchiveResponse represents a row from current_archive.
|
||||
type ArchiveResponse struct {
|
||||
ID int `json:"id" example:"123"`
|
||||
EpNum int `json:"ep_num" example:"1"`
|
||||
EpTitle string `json:"ep_title" example:"Pilot"`
|
||||
SeasonName string `json:"season_name" example:"Season 1"`
|
||||
StartTime string `json:"start_time" example:"10:00:00"`
|
||||
PlaybackLength string `json:"playback_length" example:"00:24:00"`
|
||||
CurrentEp bool `json:"current_ep" example:"false"`
|
||||
DateCreated time.Time `json:"date_created" example:"2024-02-01T15:04:05Z"`
|
||||
DateArchived time.Time `json:"date_archived" example:"2024-03-01T15:04:05Z"`
|
||||
// SetAdminReq is the request body for POST /api/v1/admin/grant.
|
||||
type SetAdminReq struct {
|
||||
UID string `json:"uid" binding:"required" example:"abc123"`
|
||||
Admin *bool `json:"admin,omitempty" example:"true"`
|
||||
}
|
||||
|
||||
@ -112,38 +112,6 @@ RETURNING
|
||||
return e, nil
|
||||
}
|
||||
|
||||
func (r *pgxEpisodeRepo) ListArchive(ctx context.Context) ([]episode.ArchiveEpisode, error) {
|
||||
const q = `
|
||||
SELECT
|
||||
id,
|
||||
ep_num,
|
||||
ep_title,
|
||||
season_name,
|
||||
to_char(start_time, 'HH24:MI:SS') AS start_time,
|
||||
to_char(playback_length, 'HH24:MI:SS') AS playback_length,
|
||||
current_ep,
|
||||
date_created,
|
||||
date_archived
|
||||
FROM current_archive
|
||||
ORDER BY date_archived DESC, id DESC;
|
||||
`
|
||||
rows, err := r.pool.Query(ctx, q)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var out []episode.ArchiveEpisode
|
||||
for rows.Next() {
|
||||
var e episode.ArchiveEpisode
|
||||
if err := rows.Scan(&e.Id, &e.EpNum, &e.EpTitle, &e.SeasonName, &e.StartTime, &e.PlaybackLength, &e.CurrentEp, &e.DateCreated, &e.DateArchived); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, e)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
func (r *pgxEpisodeRepo) SetCurrent(ctx context.Context, id int64, startHHMMSS string) error {
|
||||
tx, err := r.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
@ -290,7 +258,7 @@ func (r *pgxEpisodeRepo) MoveToArchive(ctx context.Context, ids []int64) (episod
|
||||
}
|
||||
|
||||
func (r *pgxEpisodeRepo) Delete(ctx context.Context, id int64) error {
|
||||
cmdTag, err := r.pool.Exec(ctx, `DELETE FROM current_archive WHERE id = $1`, id)
|
||||
cmdTag, err := r.pool.Exec(ctx, `DELETE FROM current WHERE id = $1`, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@ -19,7 +19,7 @@ func TestPGXEpisodeRepo_Delete(t *testing.T) {
|
||||
t.Run("not found", func(t *testing.T) {
|
||||
fp := &fakePool{
|
||||
execFn: func(ctx context.Context, sql string, args ...any) (pgconn.CommandTag, error) {
|
||||
if sql != `DELETE FROM current_archive WHERE id = $1` {
|
||||
if sql != `DELETE FROM current WHERE id = $1` {
|
||||
t.Fatalf("unexpected sql: %s", sql)
|
||||
}
|
||||
return pgconn.NewCommandTag("DELETE 0"), nil
|
||||
@ -32,13 +32,9 @@ func TestPGXEpisodeRepo_Delete(t *testing.T) {
|
||||
})
|
||||
|
||||
t.Run("ok", func(t *testing.T) {
|
||||
var (
|
||||
gotSQL string
|
||||
gotID int64
|
||||
)
|
||||
var gotID int64
|
||||
fp := &fakePool{
|
||||
execFn: func(ctx context.Context, sql string, args ...any) (pgconn.CommandTag, error) {
|
||||
gotSQL = sql
|
||||
gotID = args[0].(int64)
|
||||
return pgconn.NewCommandTag("DELETE 1"), nil
|
||||
},
|
||||
@ -47,9 +43,6 @@ func TestPGXEpisodeRepo_Delete(t *testing.T) {
|
||||
if err := repo.Delete(context.Background(), 22); err != nil {
|
||||
t.Fatalf("unexpected err: %v", err)
|
||||
}
|
||||
if gotSQL != `DELETE FROM current_archive WHERE id = $1` {
|
||||
t.Fatalf("expected archive delete sql, got %s", gotSQL)
|
||||
}
|
||||
if gotID != 22 {
|
||||
t.Fatalf("expected id 22, got %d", gotID)
|
||||
}
|
||||
|
||||
@ -24,12 +24,6 @@ func (s *Service) ListAll(ctx context.Context) ([]episode.Episode, error) {
|
||||
return s.repo.ListAll(c)
|
||||
}
|
||||
|
||||
func (s *Service) ListArchive(ctx context.Context) ([]episode.ArchiveEpisode, error) {
|
||||
c, cancel := context.WithTimeout(ctx, 5*time.Second)
|
||||
defer cancel()
|
||||
return s.repo.ListArchive(c)
|
||||
}
|
||||
|
||||
func (s *Service) GetCurrent(ctx context.Context) (episode.Episode, error) {
|
||||
c, cancel := context.WithTimeout(ctx, 3*time.Second)
|
||||
defer cancel()
|
||||
|
||||
@ -22,14 +22,12 @@ type fakeRepo struct {
|
||||
id int64
|
||||
start string
|
||||
}
|
||||
moveCalls [][]int64
|
||||
listRes []episode.Episode
|
||||
listErr error
|
||||
createRes episode.Episode
|
||||
createErr error
|
||||
createIn []episode.NewShowInput
|
||||
archiveRes []episode.ArchiveEpisode
|
||||
archiveErr error
|
||||
moveCalls [][]int64
|
||||
listRes []episode.Episode
|
||||
listErr error
|
||||
createRes episode.Episode
|
||||
createErr error
|
||||
createIn []episode.NewShowInput
|
||||
}
|
||||
|
||||
func (f *fakeRepo) GetCurrent(ctx context.Context) (episode.Episode, error) {
|
||||
@ -49,9 +47,6 @@ func (f *fakeRepo) MoveToArchive(ctx context.Context, ids []int64) (episode.Move
|
||||
func (f *fakeRepo) ListAll(ctx context.Context) ([]episode.Episode, error) {
|
||||
return f.listRes, f.listErr
|
||||
}
|
||||
func (f *fakeRepo) ListArchive(ctx context.Context) ([]episode.ArchiveEpisode, error) {
|
||||
return f.archiveRes, f.archiveErr
|
||||
}
|
||||
func (f *fakeRepo) Delete(ctx context.Context, id int64) error {
|
||||
return nil
|
||||
}
|
||||
@ -182,28 +177,6 @@ func TestEpisodeService_ListAll_Error(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestEpisodeService_ListArchive(t *testing.T) {
|
||||
fr := &fakeRepo{
|
||||
archiveRes: []episode.ArchiveEpisode{{Id: 1}, {Id: 2}},
|
||||
}
|
||||
svc := service.NewEpisodeService(fr)
|
||||
got, err := svc.ListArchive(context.Background())
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected: %v", err)
|
||||
}
|
||||
if len(got) != 2 || got[0].Id != 1 {
|
||||
t.Fatalf("bad archive list: %+v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEpisodeService_ListArchive_Error(t *testing.T) {
|
||||
fr := &fakeRepo{archiveErr: errors.New("down")}
|
||||
svc := service.NewEpisodeService(fr)
|
||||
if _, err := svc.ListArchive(context.Background()); err == nil {
|
||||
t.Fatal("expected error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestEpisodeService_Create_Validation(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
|
||||
@ -1,8 +1,21 @@
|
||||
name: watch-party
|
||||
|
||||
services:
|
||||
# Frontend (Vite built → nginx). Only public-facing service on LAN.
|
||||
web:
|
||||
image: gitea.home.arpa/nik/watch-party-frontend:latest
|
||||
build:
|
||||
context: ./frontend
|
||||
dockerfile: Dockerfile
|
||||
args:
|
||||
PUBLIC_BASE_PATH: ${PUBLIC_BASE_PATH}
|
||||
FRONTEND_MODE: ${FRONTEND_MODE:-production}
|
||||
VITE_AUTH_ENABLED: ${VITE_AUTH_ENABLED:-true}
|
||||
VITE_FIREBASE_API_KEY: ${VITE_FIREBASE_API_KEY}
|
||||
VITE_FIREBASE_AUTH_DOMAIN: ${VITE_FIREBASE_AUTH_DOMAIN}
|
||||
VITE_FIREBASE_PROJECT_ID: ${VITE_FIREBASE_PROJECT_ID}
|
||||
VITE_FIREBASE_APP_ID: ${VITE_FIREBASE_APP_ID}
|
||||
VITE_BACKEND_ORIGIN: ${VITE_BACKEND_ORIGIN:-/api}
|
||||
image: watchparty-frontend:prod
|
||||
container_name: watchparty-frontend
|
||||
environment:
|
||||
BACKEND_ORIGIN: ${BACKEND_ORIGIN}
|
||||
@ -19,6 +32,7 @@ services:
|
||||
timeout: 5s
|
||||
retries: 5
|
||||
|
||||
# Backend DB (internal only)
|
||||
db:
|
||||
image: postgres:16-alpine
|
||||
platform: ${COMPOSE_PLATFORM}
|
||||
@ -28,7 +42,7 @@ services:
|
||||
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
|
||||
TZ: ${TZ}
|
||||
ports:
|
||||
- "${POSTGRES_PORT:-5432}:5432"
|
||||
- "${POSTGRES_PORT:-5432}:5432" ####### TEMPORARY EXPOSE #########
|
||||
volumes:
|
||||
- pgdata:/var/lib/postgresql/data
|
||||
command: >
|
||||
@ -48,8 +62,12 @@ services:
|
||||
restart: unless-stopped
|
||||
networks: [internal]
|
||||
|
||||
# One-off migration job (idempotent)
|
||||
migrate:
|
||||
image: gitea.home.arpa/nik/watch-party-backend:latest
|
||||
build:
|
||||
context: ./backend
|
||||
dockerfile: Dockerfile
|
||||
image: watchparty-backend:latest
|
||||
entrypoint: ["/app/migrate"]
|
||||
env_file:
|
||||
- ./.env
|
||||
@ -61,8 +79,9 @@ services:
|
||||
restart: "no"
|
||||
networks: [internal]
|
||||
|
||||
# API server (internal port only; reached via web → proxy)
|
||||
api:
|
||||
image: gitea.home.arpa/nik/watch-party-backend:latest
|
||||
image: watchparty-backend:latest
|
||||
env_file:
|
||||
- ./.env
|
||||
depends_on:
|
||||
@ -82,11 +101,11 @@ services:
|
||||
timeout: 5s
|
||||
retries: 10
|
||||
ports:
|
||||
- "${APP_PORT:-8082}:8082"
|
||||
- "${APP_PORT:-8082}:8082" ####### TEMPORARY EXPOSE #########
|
||||
|
||||
networks:
|
||||
internal:
|
||||
driver: bridge
|
||||
|
||||
volumes:
|
||||
pgdata:
|
||||
pgdata:
|
||||
|
||||
22
frontend/package-lock.json
generated
22
frontend/package-lock.json
generated
@ -11,8 +11,7 @@
|
||||
"firebase": "^12.6.0",
|
||||
"react": "^19.1.1",
|
||||
"react-dom": "^19.1.1",
|
||||
"react-router-dom": "^7.9.5",
|
||||
"react-snowfall": "^2.4.0"
|
||||
"react-router-dom": "^7.9.5"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/js": "^9.36.0",
|
||||
@ -4216,12 +4215,6 @@
|
||||
"react": "^19.1.1"
|
||||
}
|
||||
},
|
||||
"node_modules/react-fast-compare": {
|
||||
"version": "3.2.2",
|
||||
"resolved": "https://registry.npmjs.org/react-fast-compare/-/react-fast-compare-3.2.2.tgz",
|
||||
"integrity": "sha512-nsO+KSNgo1SbJqJEYRE9ERzo7YtYbou/OqjSQKxV7jcKox7+usiUVZOAC+XnDOABXggQTno0Y1CpVnuWEc1boQ==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/react-refresh": {
|
||||
"version": "0.17.0",
|
||||
"resolved": "https://registry.npmjs.org/react-refresh/-/react-refresh-0.17.0.tgz",
|
||||
@ -4270,19 +4263,6 @@
|
||||
"react-dom": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/react-snowfall": {
|
||||
"version": "2.4.0",
|
||||
"resolved": "https://registry.npmjs.org/react-snowfall/-/react-snowfall-2.4.0.tgz",
|
||||
"integrity": "sha512-KAPMiGnxt11PEgC2pTVrTQsvk5jt1kLUtG+ZamiKLphTZ7GiYT1Aa5kX6jp4jKWq1kqJHchnGT9CDm4g86A5Gg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"react-fast-compare": "^3.2.2"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"react": "^16.8 || 17.x || 18.x || 19.x",
|
||||
"react-dom": "^16.8 || 17.x || 18.x || 19.x"
|
||||
}
|
||||
},
|
||||
"node_modules/require-directory": {
|
||||
"version": "2.1.1",
|
||||
"resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz",
|
||||
|
||||
@ -15,8 +15,7 @@
|
||||
"firebase": "^12.6.0",
|
||||
"react": "^19.1.1",
|
||||
"react-dom": "^19.1.1",
|
||||
"react-router-dom": "^7.9.5",
|
||||
"react-snowfall": "^2.4.0"
|
||||
"react-router-dom": "^7.9.5"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/js": "^9.36.0",
|
||||
|
||||
@ -2,21 +2,17 @@ import React from "react";
|
||||
import { Link, NavLink, Route, Routes, useLocation } from "react-router-dom";
|
||||
import Timer from "./components/Timer";
|
||||
import ShowsPage from "./pages/ShowsPage";
|
||||
import ArchivePage from "./pages/ArchivePage";
|
||||
import TimeSyncNotice from "./components/TimeSyncNotice";
|
||||
import { ToastViewport } from "./components/Toasts";
|
||||
import DebugOverlay from "./components/DebugOverlay";
|
||||
import AuthStatus from "./components/AuthStatus";
|
||||
import { useAuth } from "./auth/AuthProvider";
|
||||
import "./index.css";
|
||||
import Snowfall from "react-snowfall";
|
||||
|
||||
const TIME_SYNC_OFF_THRESHOLD = 100;
|
||||
|
||||
export default function App() {
|
||||
const [open, setOpen] = React.useState(false);
|
||||
const loc = useLocation();
|
||||
const { isAdmin } = useAuth();
|
||||
|
||||
// close sidebar on route change
|
||||
React.useEffect(() => setOpen(false), [loc.pathname]);
|
||||
@ -30,10 +26,6 @@ export default function App() {
|
||||
|
||||
return (
|
||||
<div className={`site ${open ? "sidebar-open" : ""}`}>
|
||||
<Snowfall
|
||||
snowflakeCount={140}
|
||||
style={{ position: "fixed", width: "100vw", height: "100vh", pointerEvents: "none", zIndex: 2 }}
|
||||
/>
|
||||
{/* Top-left header (outside the card) */}
|
||||
<header className="site-header">
|
||||
|
||||
@ -54,7 +46,6 @@ export default function App() {
|
||||
<nav className="sidebar-nav" onClick={() => setOpen(false)}>
|
||||
<NavLink end to="/" className="navlink">Timer</NavLink>
|
||||
<NavLink to="/shows" className="navlink">Shows</NavLink>
|
||||
{isAdmin && <NavLink to="/archive" className="navlink">Archive</NavLink>}
|
||||
</nav>
|
||||
<div className="sidebar-auth">
|
||||
<div className="sidebar-auth-title">管理用サインイン</div>
|
||||
@ -77,7 +68,6 @@ export default function App() {
|
||||
<Routes>
|
||||
<Route path="/" element={<Timer />} />
|
||||
<Route path="/shows" element={<ShowsPage />} />
|
||||
<Route path="/archive" element={<ArchivePage />} />
|
||||
</Routes>
|
||||
|
||||
<div className="footer">
|
||||
|
||||
@ -34,8 +34,6 @@ export type FirebaseAuthResponse = {
|
||||
email?: string;
|
||||
issuer?: string;
|
||||
expires?: number;
|
||||
admin?: boolean;
|
||||
custom_claims?: Record<string, unknown>;
|
||||
};
|
||||
|
||||
export type ArchiveResult = {
|
||||
@ -46,15 +44,3 @@ export type ArchiveResult = {
|
||||
deleted: number;
|
||||
skipped: number;
|
||||
};
|
||||
|
||||
export type ArchiveItem = {
|
||||
id: number;
|
||||
ep_num: number;
|
||||
ep_title: string;
|
||||
season_name: string;
|
||||
start_time: string;
|
||||
playback_length: string;
|
||||
current_ep: boolean;
|
||||
date_created: string;
|
||||
date_archived: string;
|
||||
};
|
||||
|
||||
@ -1,8 +1,8 @@
|
||||
import { API_ENDPOINT } from "./endpoint";
|
||||
import { ApiError, apiFetch } from "./client";
|
||||
import type { ArchiveItem, ArchiveResult, DanimeEpisode, ScheduleResponse, ShowItem, TimeResponse } from "./types";
|
||||
import type { ArchiveResult, DanimeEpisode, ScheduleResponse, ShowItem, TimeResponse } from "./types";
|
||||
|
||||
export type { DanimeEpisode, ScheduleResponse, ShowItem, TimeResponse, ArchiveItem } from "./types";
|
||||
export type { DanimeEpisode, ScheduleResponse, ShowItem, TimeResponse } from "./types";
|
||||
|
||||
function asNumber(v: unknown, fallback = 0) {
|
||||
const n = typeof v === "number" ? v : Number(v);
|
||||
@ -52,33 +52,6 @@ function normalizeShows(data: unknown): ShowItem[] {
|
||||
});
|
||||
}
|
||||
|
||||
function normalizeArchive(data: unknown): ArchiveItem[] {
|
||||
if (!Array.isArray(data)) {
|
||||
throw new ApiError("Archive payload is not an array", { url: API_ENDPOINT.v1.ARCHIVE, data });
|
||||
}
|
||||
return data.map((item) => {
|
||||
if (!item || typeof item !== "object") {
|
||||
throw new ApiError("Bad archive item", { url: API_ENDPOINT.v1.ARCHIVE, data: item });
|
||||
}
|
||||
const obj = item as Record<string, unknown>;
|
||||
const id = asNumber(obj.id, NaN);
|
||||
if (!Number.isFinite(id)) {
|
||||
throw new ApiError("Archive item missing id", { url: API_ENDPOINT.v1.ARCHIVE, data: item });
|
||||
}
|
||||
return {
|
||||
id,
|
||||
ep_num: asNumber(obj.ep_num, 0),
|
||||
ep_title: asString(obj.ep_title, "不明"),
|
||||
season_name: asString(obj.season_name, "不明"),
|
||||
start_time: asString(obj.start_time, ""),
|
||||
playback_length: asString(obj.playback_length, ""),
|
||||
current_ep: Boolean(obj.current_ep),
|
||||
date_created: asString(obj.date_created, ""),
|
||||
date_archived: asString(obj.date_archived, ""),
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
function normalizeDanimeEpisode(data: unknown): DanimeEpisode {
|
||||
if (!data || typeof data !== "object") {
|
||||
throw new ApiError("Bad danime payload", { url: API_ENDPOINT.v1.DANIME, data });
|
||||
@ -164,22 +137,6 @@ export async function createShow(payload: {
|
||||
});
|
||||
}
|
||||
|
||||
export async function deleteArchiveShow(id: number, idToken: string) {
|
||||
if (!idToken) {
|
||||
throw new ApiError("Missing auth token for delete");
|
||||
}
|
||||
const url = `${API_ENDPOINT.v1.SHOWS}?id=${encodeURIComponent(id)}`;
|
||||
await apiFetch<void>(url, {
|
||||
method: "DELETE",
|
||||
headers: {
|
||||
"Authorization": `Bearer ${idToken}`,
|
||||
},
|
||||
timeoutMs: 10_000,
|
||||
expect: "void",
|
||||
logLabel: "delete archived show",
|
||||
});
|
||||
}
|
||||
|
||||
export async function archiveShow(id: number, idToken: string) {
|
||||
if (!idToken) {
|
||||
throw new ApiError("Missing auth token for archive");
|
||||
@ -196,18 +153,3 @@ export async function archiveShow(id: number, idToken: string) {
|
||||
logLabel: "archive show",
|
||||
});
|
||||
}
|
||||
|
||||
export async function fetchArchive(idToken: string) {
|
||||
if (!idToken) {
|
||||
throw new ApiError("Missing auth token for archive list");
|
||||
}
|
||||
const data = await apiFetch<ArchiveItem[]>(API_ENDPOINT.v1.ARCHIVE, {
|
||||
method: "GET",
|
||||
headers: {
|
||||
"Authorization": `Bearer ${idToken}`,
|
||||
},
|
||||
timeoutMs: 12_000,
|
||||
logLabel: "fetch archive",
|
||||
});
|
||||
return normalizeArchive(data);
|
||||
}
|
||||
|
||||
@ -13,7 +13,6 @@ type AuthContextShape = {
|
||||
user: User | null;
|
||||
idToken: string | null;
|
||||
backendClaims: FirebaseAuthResponse | null;
|
||||
isAdmin: boolean;
|
||||
verifying: boolean;
|
||||
signingIn: boolean;
|
||||
error: string | null;
|
||||
@ -30,7 +29,6 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
|
||||
const [user, setUser] = React.useState<User | null>(null);
|
||||
const [idToken, setIdToken] = React.useState<string | null>(null);
|
||||
const [backendClaims, setBackendClaims] = React.useState<FirebaseAuthResponse | null>(null);
|
||||
const isAdmin = Boolean(backendClaims?.admin ?? backendClaims?.custom_claims?.admin);
|
||||
const [verifying, setVerifying] = React.useState(false);
|
||||
const [signingIn, setSigningIn] = React.useState(false);
|
||||
const [error, setError] = React.useState<string | null>(null);
|
||||
@ -80,17 +78,12 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
|
||||
try {
|
||||
await signInWithPopup(auth, provider);
|
||||
} catch (err: any) {
|
||||
// Avoid redirect fallback to prevent navigation/404; surface a clearer popup-blocked message.
|
||||
const code = err?.code ?? "";
|
||||
// Common cases where redirect works better
|
||||
const redirectable = [
|
||||
"auth/popup-blocked",
|
||||
"auth/operation-not-supported-in-this-environment",
|
||||
"auth/unauthorized-domain",
|
||||
];
|
||||
if (redirectable.includes(code)) {
|
||||
const { signInWithRedirect } = await import("firebase/auth");
|
||||
await signInWithRedirect(auth, provider);
|
||||
return; // navigation will happen
|
||||
if (code === "auth/popup-blocked") {
|
||||
setError("ポップアップがブロックされました。ブラウザで許可してください。");
|
||||
console.error("signin popup blocked:", err);
|
||||
return;
|
||||
}
|
||||
const msg = err instanceof Error ? err.message : String(err);
|
||||
setError(msg); // keep the message for the UI
|
||||
@ -134,14 +127,13 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
|
||||
user,
|
||||
idToken,
|
||||
backendClaims,
|
||||
isAdmin,
|
||||
verifying,
|
||||
signingIn,
|
||||
error,
|
||||
signInWithGoogle,
|
||||
signOut,
|
||||
refreshToken,
|
||||
}), [enabled, status, user, idToken, backendClaims, isAdmin, verifying, signingIn, error, signInWithGoogle, signOut, refreshToken]);
|
||||
}), [enabled, status, user, idToken, backendClaims, verifying, signingIn, error, signInWithGoogle, signOut, refreshToken]);
|
||||
|
||||
return (
|
||||
<AuthContext.Provider value={value}>
|
||||
|
||||
@ -1,7 +1,7 @@
|
||||
import { useAuth } from "../auth/AuthProvider";
|
||||
|
||||
export default function AuthStatus() {
|
||||
const { enabled, status, user, verifying, signingIn, signInWithGoogle, signOut, error, isAdmin } = useAuth();
|
||||
const { enabled, status, user, verifying, signingIn, signInWithGoogle, signOut, error } = useAuth();
|
||||
|
||||
if (!enabled) {
|
||||
return <div className="auth-chip muted">Auth off</div>;
|
||||
@ -24,10 +24,7 @@ export default function AuthStatus() {
|
||||
<div className="auth-chip signed-in">
|
||||
{user.photoURL && <img src={user.photoURL} alt="" className="auth-avatar" referrerPolicy="no-referrer" />}
|
||||
<div className="auth-meta">
|
||||
<div className="auth-name">
|
||||
{user.displayName || user.email || user.uid}
|
||||
{isAdmin && <span style={{ marginLeft: 6, color: "#6de3a2", fontWeight: 700, fontSize: 11 }}>ADMIN</span>}
|
||||
</div>
|
||||
<div className="auth-name">{user.displayName || user.email || user.uid}</div>
|
||||
{verifying && (
|
||||
<div className="auth-subtle">
|
||||
確認中…
|
||||
|
||||
@ -70,7 +70,7 @@ html, body, #root {
|
||||
border-radius: 16px;
|
||||
padding: 28px 32px;
|
||||
box-shadow: 0 10px 30px rgba(0,0,0,0.25);
|
||||
max-width: 1280px;
|
||||
max-width: 720px;
|
||||
width: 100%;
|
||||
text-align: center;
|
||||
container-type: inline-size;
|
||||
@ -503,85 +503,6 @@ kbd {
|
||||
background: var(--accent); color:#0b0f14; border:none;
|
||||
}
|
||||
.primary:disabled { opacity:0.5; cursor:not-allowed; }
|
||||
.archive-table {
|
||||
display: grid;
|
||||
gap: 6px;
|
||||
text-align: left;
|
||||
}
|
||||
.archive-header,
|
||||
.archive-row {
|
||||
display: grid;
|
||||
grid-template-columns: 70px 80px 1fr 1fr 90px 90px 150px 150px;
|
||||
gap: 10px;
|
||||
align-items: center;
|
||||
padding: 10px 12px;
|
||||
border-radius: 10px;
|
||||
}
|
||||
.archive-scroll {
|
||||
width: 100%;
|
||||
overflow: auto;
|
||||
}
|
||||
.archive-table {
|
||||
min-width: 1040px;
|
||||
}
|
||||
.archive-header {
|
||||
font-weight: 800;
|
||||
color: var(--subtle);
|
||||
background: rgba(255,255,255,0.04);
|
||||
border: 1px solid rgba(255,255,255,0.08);
|
||||
}
|
||||
.archive-head-btn {
|
||||
all: unset;
|
||||
cursor: pointer;
|
||||
font-weight: 800;
|
||||
color: var(--subtle);
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
}
|
||||
.archive-head-btn:hover { color: var(--text); }
|
||||
.archive-row {
|
||||
background: rgba(255,255,255,0.03);
|
||||
border: 1px solid rgba(255,255,255,0.05);
|
||||
cursor: pointer;
|
||||
transition: background 120ms ease, border-color 120ms ease, box-shadow 160ms ease;
|
||||
}
|
||||
.archive-row:hover { background: rgba(255,255,255,0.05); }
|
||||
.archive-row span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.archive-row.selected {
|
||||
border-color: rgba(121,192,255,0.7);
|
||||
background: linear-gradient(135deg, rgba(121,192,255,0.10), rgba(121,192,255,0.04));
|
||||
box-shadow: 0 10px 28px rgba(121,192,255,0.14);
|
||||
}
|
||||
.archive-row:focus-visible {
|
||||
outline: 2px solid var(--accent);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
@media (max-width: 820px) {
|
||||
.archive-header,
|
||||
.archive-row {
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
row-gap: 6px;
|
||||
}
|
||||
.archive-header span:nth-child(3),
|
||||
.archive-row span:nth-child(3) { grid-column: span 2; }
|
||||
.archive-header span:nth-child(4),
|
||||
.archive-row span:nth-child(4) { grid-column: span 2; }
|
||||
.archive-table { min-width: 100%; }
|
||||
}
|
||||
.archive-detail-actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
flex-wrap: wrap;
|
||||
justify-content: flex-end;
|
||||
}
|
||||
.archive-detail-bar {
|
||||
position: sticky;
|
||||
bottom: 10px;
|
||||
z-index: 5;
|
||||
}
|
||||
|
||||
.scrape-card {
|
||||
padding: 14px;
|
||||
border-radius: 14px;
|
||||
|
||||
@ -1,255 +0,0 @@
|
||||
import React from "react";
|
||||
import { deleteArchiveShow, fetchArchive } from "../api/watchparty";
|
||||
import type { ArchiveItem } from "../api/types";
|
||||
import { useAuth } from "../auth/AuthProvider";
|
||||
import { toastError, toastInfo } from "../utils/toastBus";
|
||||
import { logApiError } from "../utils/logger";
|
||||
|
||||
type SortKey = "id" | "ep_num" | "ep_title" | "season_name" | "start_time" | "playback_length" | "date_created" | "date_archived";
|
||||
type SortDir = "asc" | "desc" | null;
|
||||
|
||||
function formatTimestamp(ts: string) {
|
||||
if (!ts) return "";
|
||||
const d = new Date(ts);
|
||||
if (Number.isNaN(d.getTime())) return ts;
|
||||
return d.toLocaleString("ja-JP", { timeZone: "Asia/Tokyo" });
|
||||
}
|
||||
|
||||
export default function ArchivePage() {
|
||||
const { enabled, idToken, isAdmin, verifying } = useAuth();
|
||||
const [items, setItems] = React.useState<ArchiveItem[]>([]);
|
||||
const [loading, setLoading] = React.useState(true);
|
||||
const [error, setError] = React.useState<string | null>(null);
|
||||
const [sort, setSort] = React.useState<{ key: SortKey | null; dir: SortDir }>({ key: null, dir: null });
|
||||
const [selectedId, setSelectedId] = React.useState<number | null>(null);
|
||||
const [deletingId, setDeletingId] = React.useState<number | null>(null);
|
||||
|
||||
const load = React.useCallback(async () => {
|
||||
if (!idToken) {
|
||||
setError("サインインが必要です");
|
||||
return;
|
||||
}
|
||||
setError(null);
|
||||
try {
|
||||
setLoading(true);
|
||||
const data = await fetchArchive(idToken);
|
||||
setItems(data);
|
||||
setSelectedId((prev) => (prev != null && data.some((it) => it.id === prev) ? prev : null));
|
||||
} catch (e: unknown) {
|
||||
const msg = e instanceof Error ? e.message : "アーカイブを取得できませんでした。";
|
||||
setError(msg);
|
||||
logApiError("fetch archive", e);
|
||||
toastError("アーカイブを取得できませんでした", msg);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [idToken]);
|
||||
|
||||
React.useEffect(() => {
|
||||
if (enabled && isAdmin && idToken) {
|
||||
load().catch(() => { });
|
||||
} else {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [enabled, isAdmin, idToken, load]);
|
||||
|
||||
const sortedItems = React.useMemo(() => {
|
||||
const { key, dir } = sort;
|
||||
if (!key || !dir) return items;
|
||||
const next = [...items];
|
||||
next.sort((a, b) => {
|
||||
let av: string | number = "";
|
||||
let bv: string | number = "";
|
||||
switch (key) {
|
||||
case "id":
|
||||
case "ep_num":
|
||||
av = a[key];
|
||||
bv = b[key];
|
||||
break;
|
||||
case "date_created":
|
||||
case "date_archived":
|
||||
av = new Date(a[key]).getTime();
|
||||
bv = new Date(b[key]).getTime();
|
||||
break;
|
||||
default:
|
||||
av = (a as Record<string, unknown>)[key] as string | number | undefined ?? "";
|
||||
bv = (b as Record<string, unknown>)[key] as string | number | undefined ?? "";
|
||||
}
|
||||
if (av === bv) return 0;
|
||||
const asc = av > bv ? 1 : -1;
|
||||
return dir === "asc" ? asc : -asc;
|
||||
});
|
||||
return next;
|
||||
}, [items, sort]);
|
||||
|
||||
function toggleSort(key: SortKey) {
|
||||
setSort((prev) => {
|
||||
if (prev.key !== key) return { key, dir: "asc" };
|
||||
if (prev.dir === "asc") return { key, dir: "desc" };
|
||||
if (prev.dir === "desc") return { key: null, dir: null };
|
||||
return { key, dir: "asc" };
|
||||
});
|
||||
}
|
||||
|
||||
const sortIndicator = (key: SortKey) => {
|
||||
if (sort.key !== key) return "";
|
||||
if (sort.dir === "asc") return "▲";
|
||||
if (sort.dir === "desc") return "▼";
|
||||
return "";
|
||||
};
|
||||
|
||||
const selectedItem = React.useMemo(
|
||||
() => items.find((it) => it.id === selectedId) ?? null,
|
||||
[items, selectedId],
|
||||
);
|
||||
|
||||
const handleSelect = React.useCallback((id: number) => {
|
||||
setSelectedId((prev) => (prev === id ? null : id));
|
||||
}, []);
|
||||
|
||||
async function handleDeleteSelected() {
|
||||
if (!selectedItem) return;
|
||||
if (!enabled) {
|
||||
toastError("認証が無効です", "管理者に確認してください");
|
||||
return;
|
||||
}
|
||||
if (!idToken) {
|
||||
toastError("サインインしてください", "削除には管理者サインインが必要です");
|
||||
return;
|
||||
}
|
||||
try {
|
||||
setDeletingId(selectedItem.id);
|
||||
await deleteArchiveShow(selectedItem.id, idToken);
|
||||
toastInfo("アーカイブを削除しました");
|
||||
setItems((prev) => prev.filter((it) => it.id !== selectedItem.id));
|
||||
setSelectedId((prev) => (prev === selectedItem.id ? null : prev));
|
||||
} catch (e: unknown) {
|
||||
const msg = e instanceof Error ? e.message : "削除に失敗しました。";
|
||||
toastError("削除に失敗しました", msg);
|
||||
logApiError("delete archived show", e);
|
||||
} finally {
|
||||
setDeletingId(null);
|
||||
}
|
||||
}
|
||||
|
||||
if (!enabled) {
|
||||
return <div className="subtle">認証が無効です。</div>;
|
||||
}
|
||||
if (!isAdmin) {
|
||||
return <div className="subtle">管理者のみアクセスできます。</div>;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="shows-page">
|
||||
<h2 className="h1" style={{ marginBottom: 8 }}>アーカイブ一覧</h2>
|
||||
<div className="subtle" style={{ marginTop: 0, display: "flex", flexDirection: "column", gap: 4 }}>
|
||||
<span>削除済みのエピソードを表示します。最新のアーカイブが上に表示されます。</span>
|
||||
<button className="link-btn" disabled={loading} onClick={() => load().catch(() => { })}>
|
||||
再読み込み
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{loading && <div className="subtle">読み込み中…</div>}
|
||||
{error && (
|
||||
<div className="timer-status" style={{ color: "#f88" }}>
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
{!loading && !error && items.length === 0 && (
|
||||
<div className="subtle">アーカイブは空です。</div>
|
||||
)}
|
||||
|
||||
{items.length > 0 && (
|
||||
<div className="archive-scroll">
|
||||
<div className="archive-table">
|
||||
<div className="archive-header">
|
||||
<button className="archive-head-btn" onClick={() => toggleSort("id")}>
|
||||
ID {sortIndicator("id")}
|
||||
</button>
|
||||
<button className="archive-head-btn" onClick={() => toggleSort("ep_num")}>
|
||||
話数 {sortIndicator("ep_num")}
|
||||
</button>
|
||||
<button className="archive-head-btn" onClick={() => toggleSort("ep_title")}>
|
||||
タイトル {sortIndicator("ep_title")}
|
||||
</button>
|
||||
<button className="archive-head-btn" onClick={() => toggleSort("season_name")}>
|
||||
シーズン {sortIndicator("season_name")}
|
||||
</button>
|
||||
<button className="archive-head-btn" onClick={() => toggleSort("start_time")}>
|
||||
開始時刻 {sortIndicator("start_time")}
|
||||
</button>
|
||||
<button className="archive-head-btn" onClick={() => toggleSort("playback_length")}>
|
||||
再生時間 {sortIndicator("playback_length")}
|
||||
</button>
|
||||
<button className="archive-head-btn" onClick={() => toggleSort("date_created")}>
|
||||
登録 {sortIndicator("date_created")}
|
||||
</button>
|
||||
<button className="archive-head-btn" onClick={() => toggleSort("date_archived")}>
|
||||
アーカイブ {sortIndicator("date_archived")}
|
||||
</button>
|
||||
</div>
|
||||
{sortedItems.map((it) => (
|
||||
<div
|
||||
key={it.id}
|
||||
className={`archive-row ${selectedId === it.id ? "selected" : ""}`}
|
||||
role="button"
|
||||
tabIndex={0}
|
||||
aria-pressed={selectedId === it.id}
|
||||
onClick={() => handleSelect(it.id)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === "Enter" || e.key === " ") {
|
||||
e.preventDefault();
|
||||
handleSelect(it.id);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<span>#{it.id}</span>
|
||||
<span>第{it.ep_num}話</span>
|
||||
<span>{it.ep_title}</span>
|
||||
<span>{it.season_name}</span>
|
||||
<span>{it.start_time.slice(0, 5)}</span>
|
||||
<span>{it.playback_length.slice(0, 5)}</span>
|
||||
<span className="subtle">{formatTimestamp(it.date_created)}</span>
|
||||
<span className="subtle">{formatTimestamp(it.date_archived)}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{selectedItem && (
|
||||
<div className="selection-bar archive-detail-bar">
|
||||
<div className="selection-meta">
|
||||
<div className="selection-count">1件選択中</div>
|
||||
<div className="selection-title">
|
||||
第{selectedItem.ep_num}話:{selectedItem.ep_title}
|
||||
</div>
|
||||
<div className="selection-note">
|
||||
シーズン {selectedItem.season_name} ・ 開始 {selectedItem.start_time.slice(0, 5)} ・ 再生 {selectedItem.playback_length.slice(0, 5)} ・ ID #{selectedItem.id}
|
||||
</div>
|
||||
<div className="selection-note">
|
||||
アーカイブ日時 {formatTimestamp(selectedItem.date_archived)}
|
||||
</div>
|
||||
<div className="selection-note">
|
||||
{idToken
|
||||
? (verifying ? "トークン確認中…" : "サインイン済み")
|
||||
: "削除には管理者サインインが必要です"}
|
||||
</div>
|
||||
</div>
|
||||
<div className="archive-detail-actions">
|
||||
<button className="link-btn" type="button" onClick={() => setSelectedId(null)}>
|
||||
選択をクリア
|
||||
</button>
|
||||
<button
|
||||
className="danger-btn"
|
||||
disabled={deletingId === selectedItem.id || verifying || !idToken}
|
||||
onClick={() => handleDeleteSelected().catch(() => { })}
|
||||
>
|
||||
{deletingId === selectedItem.id ? "削除中…" : "完全に削除"}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Loading…
x
Reference in New Issue
Block a user