Compare commits
595 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 4353acebf9 | |||
| 89f86b9fe4 | |||
| ceb2a09f48 | |||
| 094276d3cc | |||
| 59b56ed3d7 | |||
| 0a5b07de5d | |||
| b05c36ac81 | |||
| 9323befdd9 | |||
| 61142c0d0e | |||
| 623ab72916 | |||
| 3716ff5085 | |||
| dffe057772 | |||
| 3319a304ce | |||
| c303dd51e8 | |||
| b1dfbe4c2f | |||
| 54badefc51 | |||
| 15a8ab41fd | |||
| 77f07e9329 | |||
| 72c0c2d18e | |||
| 95d8bc4065 | |||
| 3856ba25bb | |||
| 9e1ba4f851 | |||
| b0efd32f7a | |||
| 9ed8a2b199 | |||
| ad4e5a7506 | |||
| d4b4dc628f | |||
| fe46e4268d | |||
| 1f3b9c6712 | |||
| 5295516b67 | |||
| ee0baafc59 | |||
| c63bc47089 | |||
| 147dc28440 | |||
| c031b1e863 | |||
| b1d16670d5 | |||
| ba1f010166 | |||
| ad64005a80 | |||
| 8805fa53e6 | |||
| 633d4a0f30 | |||
| b23c51b386 | |||
| 835bdf5abb | |||
| a1b63de251 | |||
| 97b1ae5b03 | |||
| dc98206737 | |||
| 40332a71db | |||
| 125cd0d003 | |||
| 83868ffe2f | |||
| 9ddd50f7e4 | |||
| bec36fc99f | |||
| ea50488e99 | |||
| 8614c2232c | |||
| 07fc5e6519 | |||
| 3c8d344ddd | |||
| edf8bd54af | |||
| 2b7c9b0138 | |||
| aef9b4ed7f | |||
| ee3f6ae13b | |||
| 5025a42bf7 | |||
| 0a7a89045b | |||
| ddefd3a95e | |||
| 978e4473b5 | |||
| 8c5996e4ec | |||
| f50d7c0c51 | |||
| 4ce8dd297a | |||
| 85a4eb90fd | |||
| e32da68cbd | |||
| b54a80d251 | |||
| 2ac6c51fe5 | |||
| 23cd9cb680 | |||
| a63f1a8dd9 | |||
| 954a0118ba | |||
| ee46088985 | |||
| 3742d71535 | |||
| 486239aeb9 | |||
| 2c5ae6fbb9 | |||
| f9889a93fb | |||
| 4a93e4e8cb | |||
| e1b6e43e52 | |||
| 999c66dbbf | |||
| f5997892c4 | |||
| 7ca96315e2 | |||
| f3622396e7 | |||
| 56cf60c570 | |||
| 2618415aa1 | |||
| dfae2c2bc6 | |||
| bbeedd1888 | |||
| 201965b4b1 | |||
| 1468c459ba | |||
| 088de43f09 | |||
| 1fa222e9c4 | |||
| 6aceb40595 | |||
| 431a82eca1 | |||
| 85a07fcca7 | |||
| 1f524f2358 | |||
| 48a025b915 | |||
| c652ae0ead | |||
| 9a6d2e8e3a | |||
| fc0911acf8 | |||
| f77802325a | |||
| 74c9a5fbcd | |||
| 703c03fbee | |||
| 6f95b8c26c | |||
| 7250c427b9 | |||
| 04a7ea80f9 | |||
| c0a5cd56c8 | |||
| 908ab08815 | |||
| 52ab609597 | |||
| fafcfbf4e6 | |||
| f07602553c | |||
| 56f497c5f1 | |||
| d2663bff81 | |||
| b52cf1f741 | |||
| 308e086263 | |||
| 7f7736282f | |||
| 67b0f32456 | |||
| 25b40c03b0 | |||
| 28793bba68 | |||
| 4ae91142f8 | |||
| c92879fbd3 | |||
| a0bb080586 | |||
| fc75bcdfc3 | |||
| 9877f63aed | |||
| 0c98c6b453 | |||
| 831ea6a3bc | |||
| 9c44a0ebfa | |||
| a840ad4594 | |||
| 08ac238d0a | |||
| 7d967a47ae | |||
| 9b7495e005 | |||
| e1ad4219a5 | |||
| cc4503ad28 | |||
| 424336340b | |||
| a8308a5c02 | |||
| 02a46e083d | |||
| 98fd6dd8e1 | |||
| 3a30fea862 | |||
| 7d6d2f5688 | |||
| b5074e4e46 | |||
| a1d941f049 | |||
| 80171713e0 | |||
| c0301dcbf4 | |||
| cbecb9323c | |||
| 4272618b3f | |||
| fe07a148f1 | |||
| 0ec4190e2e | |||
| 0ec3787150 | |||
| 59faf73f04 | |||
| 3e0c4fd73e | |||
| 33af088560 | |||
| 5ea4ef3cf3 | |||
| 33483cf32d | |||
| cd00bc13d4 | |||
| 26ec9666b9 | |||
| f672c1daa6 | |||
| 5f1f0f253d | |||
| 888c4ab209 | |||
| 551d9cc66f | |||
| 9045402c9a | |||
| 0817443e79 | |||
| a4c624802b | |||
| 79cf4100a1 | |||
| fe9486e5fa | |||
| bcf2745ab6 | |||
| c4f16eb76c | |||
| 5925ea8406 | |||
| 6613f1b088 | |||
| 3ea9d5b121 | |||
| 0891be197f | |||
| 2b25d81144 | |||
| 50c09904a9 | |||
| 7aa37b2447 | |||
| d239857d9a | |||
| 3974ba5de5 | |||
| 5cef7fdd18 | |||
| 092f007ed3 | |||
| edf3a43950 | |||
| 45d78c0dce | |||
| d63f67a2af | |||
| ad00eae251 | |||
| 2c35543e73 | |||
| 7c75736719 | |||
| 9c2a0d272a | |||
| 4912e2bccf | |||
| f8c8abd70b | |||
| 7726adeff0 | |||
| e05fd64760 | |||
| 4280444d70 | |||
| 6491184402 | |||
| 171abb3161 | |||
| e179def3cc | |||
| bc6c48bb24 | |||
| 57845a5508 | |||
| 10ff6b118c | |||
| 2288309395 | |||
| a19e7c40a2 | |||
| de56cd0dce | |||
| 8ddec6ed8b | |||
| d9e00dc0db | |||
| 6c30e2c2ed | |||
| 329d224846 | |||
| 734868abc2 | |||
| f554f463b3 | |||
| fa4c83812d | |||
| 8cc5685428 | |||
| 7bf1e5c0f9 | |||
| 7037106bff | |||
| eca36c70a2 | |||
| 7b8d8bd92b | |||
| 397d33a95a | |||
| 08c2e4530e | |||
| 9ec0e2e7c0 | |||
| aacfcd517e | |||
| 27ff51e7a1 | |||
| 821d3296ea | |||
| 46ed1bc276 | |||
| 8711f967a1 | |||
| 5c8aed5793 | |||
| c40f34d3de | |||
| ef2ae00ff2 | |||
| 608bbd50e7 | |||
| e3024e6ffd | |||
| b4978c0869 | |||
| cd1d50474f | |||
| 8097a0cb53 | |||
| e081b56a44 | |||
| c2309af3e0 | |||
| 32fc939c7a | |||
| 4c081601e0 | |||
| 85170b883f | |||
| c018604e5d | |||
| 9c8b5e9fd6 | |||
| 151e1bf50f | |||
| c5a8ffc08c | |||
| d4a15dbe74 | |||
| 0790a1ddad | |||
| f8881d5bd6 | |||
| 6b3ead747b | |||
| dadef81158 | |||
| 644ea22b5f | |||
| f4da354ae7 | |||
| a59f41463f | |||
| 9872ad3aef | |||
| d0880ccb03 | |||
| 237eeea5a6 | |||
| 41bf6ff884 | |||
| 991aa98f98 | |||
| 86fa1046d5 | |||
| 3397807670 | |||
| cdda709886 | |||
| 023bb97e66 | |||
| cf38305f28 | |||
| 0e3674b2b0 | |||
| 3ccb8154eb | |||
| b5ac18121d | |||
| b613f8fbc7 | |||
| cacaffa5c3 | |||
| 691e3aba09 | |||
| 70a0caa11f | |||
| e808e529cd | |||
| 05a5307e22 | |||
| 2a2c23d116 | |||
| a092d98523 | |||
| b5f06af126 | |||
| 6cb43428d1 | |||
| df7dbffbff | |||
| 94421a6b12 | |||
| 7805e89bfe | |||
| 3079eaa2e5 | |||
| 2151147f2d | |||
| 3e69579f5a | |||
| 808ed1d2f1 | |||
| b40e085d28 | |||
| d603567e21 | |||
| c6fdd38e84 | |||
| ae181cf92f | |||
| 1be974afbb | |||
| 4c0baf242b | |||
| b12621b994 | |||
| 4701edc12e | |||
| d29aab7c70 | |||
| 41f80fc898 | |||
| 0f7551ab5b | |||
| 7c58749806 | |||
| 050ed37819 | |||
| 83a4344a01 | |||
| 9b50f3d6b7 | |||
| e945bc9413 | |||
| 3b720ed56e | |||
| ce8587b24d | |||
| fe772b52d6 | |||
| f29b77998b | |||
| f843e4c25c | |||
| ea20446a79 | |||
| 41f9b6d45d | |||
| 7b5916d3b9 | |||
| 657c205a4d | |||
| 1c8f686c19 | |||
| a0f38053d3 | |||
| cb012186d9 | |||
| fe7d45dd12 | |||
| c05ae5b0b9 | |||
| dab012c3d1 | |||
| 32492c5a91 | |||
| 2add85eccf | |||
| 5edfb44776 | |||
| eedb0fe49c | |||
| 3c7dc2013f | |||
| 617e778a48 | |||
| e3c3c4c951 | |||
| 0e3b50d1b6 | |||
| bd8b885f7f | |||
| 3cdc0ea715 | |||
| a2ff9eae3f | |||
| 3f7631cd95 | |||
| 53b8764ed7 | |||
| 082d8ab205 | |||
| 749100c92a | |||
| 3798662722 | |||
| fa1397cb8c | |||
| cc1ddfd42c | |||
| 049837f9d6 | |||
| 29dc2a3cf1 | |||
| d2cba449b0 | |||
| e0bd19a74d | |||
| 0ab8cbde7f | |||
| 3a8d53f492 | |||
| 804a964ba0 | |||
| d2cd1aa933 | |||
| d7ecf83d32 | |||
| ebb2ce6065 | |||
| 1931d73b60 | |||
| 0d5ce48dcc | |||
| 4872ef71f8 | |||
| b83f4272b5 | |||
| 5df64992c4 | |||
| 7e5e004270 | |||
| 09ce2b80d0 | |||
| 476fcce13f | |||
| c030e87213 | |||
| e6dd89e969 | |||
| e85a68a386 | |||
| 0acce6ab08 | |||
| 92a1c7a2df | |||
| edc57bfbbe | |||
| 37d4e1cb61 | |||
| 0d36a273bb | |||
| a19e218e40 | |||
| 61c53fb24e | |||
| dc8cf9a9a2 | |||
| 16b3ab039a | |||
| 6a6c2cd34d | |||
| 856d53343c | |||
| d9da98c355 | |||
| 892e47d017 | |||
| 007e46edb9 | |||
| 542887c2e5 | |||
| 4651783d4d | |||
| b706eeb5d3 | |||
| 40ee67171d | |||
| 6033461be1 | |||
| f3c2cee362 | |||
| 0da45e699a | |||
| 97455ab047 | |||
| fbd7b67016 | |||
| 3424bd22ee | |||
| 77a4bfd499 | |||
| 64ceb20431 | |||
| e0204aeeee | |||
| 7df481f7ea | |||
| 03bd6cef93 | |||
| da5ae0ef10 | |||
| 7c7498385f | |||
| 1ae63890ff | |||
| 5f1affafd8 | |||
| 8315c11d34 | |||
| 0043f2aaf4 | |||
| d494eda301 | |||
| a59a4232ff | |||
| 77326a91ca | |||
| 0d95eab86a | |||
| f3482a9a78 | |||
| 68a9dc5749 | |||
| 8c87f1537b | |||
| 97e54355fb | |||
| 9a75f1c929 | |||
| bce5f749b1 | |||
| 584cfb11df | |||
| f327f4cbcd | |||
| 14c4bc17f3 | |||
| 3d0a4564b6 | |||
| e85d1bf72a | |||
| bd3aa6206b | |||
| a971eee7b9 | |||
| 8e8dd358bf | |||
| ee1aa7e5cb | |||
| f446335e81 | |||
| d91ab436e8 | |||
| 0745b11745 | |||
| 97589a7c5f | |||
| 9f04da6956 | |||
| 62e6a67cb7 | |||
| b2ce011545 | |||
| 2f0fd7e360 | |||
| ae93755dbb | |||
| b2626918d3 | |||
| 41628b0578 | |||
| 8826fb7a12 | |||
| f29e9db99d | |||
| 81416737e8 | |||
| d2e97567a9 | |||
| 69538b86ea | |||
| f6f1c31369 | |||
| b76e45cb54 | |||
| 5b5e431b08 | |||
| 07759a0e40 | |||
| 31fd64c83c | |||
| 775c5159ea | |||
| 8f297e25c4 | |||
| ccb65b892b | |||
| 52f8f1f738 | |||
| e731e7b47c | |||
| 2bccb1a439 | |||
| df10fc677e | |||
| 8c690155bf | |||
| 1b1e4f715d | |||
| 68eb9ba552 | |||
| 7040865154 | |||
| 013be18d98 | |||
| 3c2a79a31a | |||
| f20472ca26 | |||
| a1e9fb6ffc | |||
| 87f4526220 | |||
| 665ce5a6e7 | |||
| d42a11680f | |||
| 8c41dd626d | |||
| 38dd74b893 | |||
| 775e417e55 | |||
| fc1bf53412 | |||
| 5d6c061f1c | |||
| 45e835a51a | |||
| afc00090cf | |||
| 59750dea15 | |||
| 2fe32e9a69 | |||
| 5f8c8c5508 | |||
| fb739f221d | |||
| b5399aaa9b | |||
| a4595e2ab2 | |||
| 0911711a37 | |||
| f2c7594b23 | |||
| 32355fabad | |||
| c127fd829d | |||
| cab5b0d795 | |||
| ba95aad3c6 | |||
| c1be7d6785 | |||
| 0024686dc2 | |||
| 96b8b77792 | |||
| 9d2726b3d3 | |||
| 8d6ddd257d | |||
| e0865b81b6 | |||
| d4404e39bd | |||
| 8611206396 | |||
| 39d2244e1e | |||
| eb626be22c | |||
| aaaf59817b | |||
| 2a4d38813f | |||
| ad9c6d63d3 | |||
| 8c77b30de6 | |||
| e51347d0a1 | |||
| 71e7179145 | |||
| bda76ff513 | |||
| 097ce2c205 | |||
| 1d8be3d840 | |||
| aebb8e66cb | |||
| ed2a278da2 | |||
| db2f5da66a | |||
| 19f8facc49 | |||
| b03760ab01 | |||
| 526dcd8dfc | |||
| 5b2561b6f1 | |||
| 3a6d06192a | |||
| 4b64b80b20 | |||
| ff89f96e31 | |||
| 465f997752 | |||
| 6948aaa92a | |||
| 4c7b49a5f6 | |||
| 6368f1027f | |||
| d64e7d08de | |||
| eb3751cb52 | |||
| 9fda54bd06 | |||
| 0d77a3a0a8 | |||
| 0618b78725 | |||
| 0178e71c67 | |||
| aa9b3a0227 | |||
| 410a33fecf | |||
| 05ebaaeedb | |||
| 84d0f63d36 | |||
| 6a4b549d9f | |||
| f3604b438b | |||
| 531831e84b | |||
| 90bb21e38b | |||
| 2f1a137342 | |||
| adf576fbe1 | |||
| 4264026bbe | |||
| 24b4a314a9 | |||
| ba825823a0 | |||
| fb16b7bbb8 | |||
| 8404125ff0 | |||
| 61ad2d61c1 | |||
| 9fd6b44487 | |||
| 9fe10bcce2 | |||
| f2abb40987 | |||
| 3697344cd0 | |||
| 4aa0ff705f | |||
| dc482e614a | |||
| 448882cfef | |||
| 7f9cb33a40 | |||
| 798f6211e0 | |||
| b992b151d3 | |||
| 87b8414e44 | |||
| ee13556c5c | |||
| afeb35a446 | |||
| ab324f1928 | |||
| 78ab0ad2e9 | |||
| 49c77785e7 | |||
| 1d826accdc | |||
| ceefe4f5a7 | |||
| e9171c7115 | |||
| 758c085467 | |||
| ecbc48815d | |||
| e91b138154 | |||
| dad1787aad | |||
| 909e760447 | |||
| 41857ec499 | |||
| f7a8765f58 | |||
| 214f120f7a | |||
| f26becad1d | |||
| 67ff415840 | |||
| 88659f1fa6 | |||
| c1e10f14a3 | |||
| 0881a0fa71 | |||
| e91209f7cb | |||
| 828d6bc456 | |||
| f945573f09 | |||
| 296430e4d7 | |||
| 7b517fa290 | |||
| 2c9a56f217 | |||
| 986b101040 | |||
| 0c283717cb | |||
| 4029559954 | |||
| 9c943bc69a | |||
| 29a8ff914c | |||
| a73d217273 | |||
| 1b4b497fdf | |||
| 827eb4819b | |||
| 086a4ca342 | |||
| 6de64a1df1 | |||
| 3074748bbc | |||
| 934d6ddc58 | |||
| a699a0477b | |||
| ed0243ec39 | |||
| ac31798bf5 | |||
| 65d796b9f0 | |||
| 6389b9df3f | |||
| 87d1761091 | |||
| fda132eed4 | |||
| 1cadce196b | |||
| 840b8870ec | |||
| ad495a92c4 | |||
| b428543452 | |||
| 6492cb9ec8 | |||
| 0e0a0b91d1 | |||
| f8fb1c3f4b | |||
| b108f6fe1c | |||
| 61299a33c4 | |||
| 96542d7e35 | |||
| ee855a3502 | |||
| 02c407d431 | |||
| 62617f627f | |||
| 1cbeb75094 | |||
| baa08e9ec9 | |||
| 8d85454ef6 | |||
| 596bba2c1b | |||
| 055de06315 | |||
| ccf59d1d4d | |||
| 4e052966d3 | |||
| ba2c021c45 | |||
| 519518ed6c | |||
| 8a0a4436b0 | |||
| 9854ca2f59 | |||
| 0c989ce086 | |||
| 35e360dcf7 | |||
| a209796b16 | |||
| 7c79052681 | |||
| d560453982 | |||
| ecb3263267 | |||
| 4d929a71ce |
@@ -1,286 +0,0 @@
|
||||
# Security Scan Report - Wedding Photo Sharing Application
|
||||
**Date**: July 13, 2025
|
||||
**Scanner**: Claude Security Audit with --security --validate flags
|
||||
**Overall Risk Level**: MEDIUM-HIGH
|
||||
|
||||
## Executive Summary
|
||||
|
||||
The wedding photo sharing application demonstrates strong security fundamentals with comprehensive input validation, proper authentication mechanisms, and good file security practices. However, several critical issues require immediate attention, particularly around hardcoded secrets, token storage, and Content Security Policy configuration.
|
||||
|
||||
### Security Score: 6.5/10
|
||||
|
||||
**Strengths**: Excellent input validation, parameterized queries, file security, rate limiting
|
||||
**Critical Issues**: Hardcoded JWT secrets, localStorage token storage, weak CSP, console logging in production
|
||||
|
||||
---
|
||||
|
||||
## 🔴 CRITICAL FINDINGS (Immediate Action Required)
|
||||
|
||||
### 1. Hardcoded JWT Secret in Development
|
||||
- **Location**: Backend `.env` file
|
||||
- **Risk**: Token forgery, authentication bypass
|
||||
- **Impact**: Complete authentication compromise
|
||||
- **Remediation**:
|
||||
```bash
|
||||
# Generate secure secret
|
||||
openssl rand -base64 32
|
||||
# Never commit to repository
|
||||
echo ".env" >> .gitignore
|
||||
```
|
||||
|
||||
### 2. Gallery Tokens in localStorage
|
||||
- **Location**: Frontend `api.ts` and auth contexts
|
||||
- **Risk**: XSS token theft
|
||||
- **Impact**: Gallery access compromise
|
||||
- **Remediation**: Move to httpOnly cookies:
|
||||
```typescript
|
||||
Cookies.set(`gallery_token_${slug}`, token, {
|
||||
httpOnly: true,
|
||||
secure: true,
|
||||
sameSite: 'strict'
|
||||
});
|
||||
```
|
||||
|
||||
### 3. Weak Content Security Policy
|
||||
- **Location**: Frontend `nginx.conf`
|
||||
- **Risk**: XSS, code injection
|
||||
- **Current**: `unsafe-inline` and `unsafe-eval` allowed
|
||||
- **Remediation**: Implement strict CSP (see detailed recommendations below)
|
||||
|
||||
---
|
||||
|
||||
## 🟠 HIGH SEVERITY FINDINGS
|
||||
|
||||
### 1. Console Logging in Production
|
||||
- **Locations**: 61 instances across frontend
|
||||
- **Risk**: Information disclosure
|
||||
- **Impact**: Leaking sensitive data, debugging info
|
||||
- **Remediation**: Implement environment-aware logging
|
||||
|
||||
### 2. Token Revocation Vulnerability
|
||||
- **Location**: Backend `tokenRevocation.js`
|
||||
- **Risk**: Token manipulation
|
||||
- **Impact**: Bypass revocation checks
|
||||
- **Remediation**: Verify token signature before decoding
|
||||
|
||||
### 3. Source Maps in Production
|
||||
- **Location**: Frontend build configuration
|
||||
- **Risk**: Source code exposure
|
||||
- **Impact**: Reveals application structure
|
||||
- **Remediation**: Disable in production builds
|
||||
|
||||
### 4. Missing Security Headers
|
||||
- **Location**: nginx configuration
|
||||
- **Missing**: HSTS, Permissions-Policy
|
||||
- **Impact**: Various client-side attacks
|
||||
- **Remediation**: Add comprehensive security headers
|
||||
|
||||
---
|
||||
|
||||
## 🟡 MEDIUM SEVERITY FINDINGS
|
||||
|
||||
### 1. Rate Limiting Bypass Potential
|
||||
- **Location**: Backend rate limiter
|
||||
- **Risk**: DoS attacks
|
||||
- **Current**: JWT validation in rate limiter
|
||||
- **Remediation**: Use IP-based limiting only
|
||||
|
||||
### 2. Incomplete SQL Injection Protection
|
||||
- **Location**: Complex dashboard queries
|
||||
- **Risk**: Potential injection in edge cases
|
||||
- **Current**: Mostly parameterized
|
||||
- **Remediation**: Use query builder exclusively
|
||||
|
||||
### 3. Session Management
|
||||
- **Issue**: No gallery token invalidation on password change
|
||||
- **Risk**: Persistent access after compromise
|
||||
- **Remediation**: Implement token revocation
|
||||
|
||||
### 4. Path Traversal in Gallery Slugs
|
||||
- **Location**: Frontend gallery routes
|
||||
- **Risk**: Directory traversal attempts
|
||||
- **Remediation**: Validate and sanitize slugs
|
||||
|
||||
---
|
||||
|
||||
## 🟢 LOW SEVERITY FINDINGS
|
||||
|
||||
### 1. Verbose Error Messages
|
||||
- **Location**: Multiple API endpoints
|
||||
- **Risk**: Information disclosure
|
||||
- **Remediation**: Generic client errors, detailed server logs
|
||||
|
||||
### 2. Weak Gallery Passwords
|
||||
- **Current**: zxcvbn score 2/4 allowed
|
||||
- **Risk**: Brute force attacks
|
||||
- **Remediation**: Increase to score 3/4
|
||||
|
||||
### 3. Missing File Size Validation
|
||||
- **Location**: Frontend upload components
|
||||
- **Risk**: DoS via large uploads
|
||||
- **Remediation**: Add client-side size checks
|
||||
|
||||
---
|
||||
|
||||
## ✅ SECURITY STRENGTHS
|
||||
|
||||
### Authentication & Authorization
|
||||
- JWT with proper expiration (24h/7d)
|
||||
- Token type validation
|
||||
- IP tracking and validation
|
||||
- Password change detection
|
||||
- Token revocation system
|
||||
- Bcrypt with 12 rounds
|
||||
- zxcvbn password strength checking
|
||||
|
||||
### Input Validation & SQL Security
|
||||
- express-validator on all endpoints
|
||||
- Parameterized queries via Knex
|
||||
- SQL injection protection utilities
|
||||
- Path traversal prevention
|
||||
- Comprehensive input sanitization
|
||||
|
||||
### File Security
|
||||
- Magic number verification
|
||||
- MIME type validation
|
||||
- Safe filename generation
|
||||
- Directory traversal protection
|
||||
- File extension whitelist
|
||||
|
||||
### Rate Limiting & DoS Protection
|
||||
- General: 100 req/15min
|
||||
- Auth endpoints: 5 req/15min
|
||||
- Account lockout after failed attempts
|
||||
- Suspicious activity detection
|
||||
|
||||
### Frontend Security
|
||||
- React's built-in XSS protection
|
||||
- DOMPurify for HTML content
|
||||
- No eval() or innerHTML usage
|
||||
- Proper error boundaries
|
||||
- ReCAPTCHA integration
|
||||
|
||||
---
|
||||
|
||||
## 📊 DEPENDENCY ANALYSIS
|
||||
|
||||
### Current Status
|
||||
- **Backend**: 0 vulnerabilities (691 packages)
|
||||
- **Frontend**: 0 vulnerabilities (434 packages)
|
||||
|
||||
### Recommended Updates
|
||||
1. **bcrypt** 5.1.1 → 6.0.0 (performance, compatibility)
|
||||
2. **helmet** 7.2.0 → 8.1.0 (new security features)
|
||||
3. **@tiptap** 2.x → 3.x (security improvements)
|
||||
|
||||
### Supply Chain Assessment
|
||||
- All major dependencies from trusted sources
|
||||
- No typosquatting detected
|
||||
- Regular maintenance observed
|
||||
- MIT/ISC/Apache licenses only
|
||||
|
||||
---
|
||||
|
||||
## 🛠️ REMEDIATION PLAN
|
||||
|
||||
### Phase 1: Critical (Within 24 hours)
|
||||
1. Replace hardcoded JWT secret with secure random value
|
||||
2. Move gallery tokens from localStorage to httpOnly cookies
|
||||
3. Implement strict CSP without unsafe-eval
|
||||
4. Remove or wrap console.log statements
|
||||
|
||||
### Phase 2: High Priority (Within 1 week)
|
||||
1. Disable source maps in production
|
||||
2. Add missing security headers (HSTS, Permissions-Policy)
|
||||
3. Fix token revocation vulnerability
|
||||
4. Update critical dependencies (bcrypt, helmet)
|
||||
|
||||
### Phase 3: Medium Priority (Within 1 month)
|
||||
1. Implement comprehensive logging strategy
|
||||
2. Add gallery slug validation
|
||||
3. Enhance rate limiting logic
|
||||
4. Implement session invalidation on password change
|
||||
|
||||
### Phase 4: Ongoing
|
||||
1. Weekly dependency scanning
|
||||
2. Implement security testing in CI/CD
|
||||
3. Regular penetration testing
|
||||
4. Security awareness training
|
||||
|
||||
---
|
||||
|
||||
## 🔒 RECOMMENDED CSP CONFIGURATION
|
||||
|
||||
```nginx
|
||||
add_header Content-Security-Policy "
|
||||
default-src 'self';
|
||||
script-src 'self' 'nonce-{RANDOM}' https://www.google.com/recaptcha/ https://www.gstatic.com/recaptcha/;
|
||||
style-src 'self' 'unsafe-inline';
|
||||
img-src 'self' data: blob: https:;
|
||||
font-src 'self';
|
||||
connect-src 'self' https://analytics.domain.com;
|
||||
frame-src https://www.google.com/recaptcha/;
|
||||
object-src 'none';
|
||||
base-uri 'self';
|
||||
form-action 'self';
|
||||
frame-ancestors 'none';
|
||||
upgrade-insecure-requests;
|
||||
" always;
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🚀 SECURITY IMPROVEMENTS ROADMAP
|
||||
|
||||
### Immediate Implementation
|
||||
```bash
|
||||
# 1. Generate secure secrets
|
||||
openssl rand -base64 32 > jwt-secret.txt
|
||||
|
||||
# 2. Update dependencies
|
||||
cd backend && npm install bcrypt@^6.0.0 helmet@^8.1.0
|
||||
cd ../frontend && npm update
|
||||
|
||||
# 3. Add security scanning
|
||||
npm install -D npm-audit-resolver
|
||||
```
|
||||
|
||||
### CI/CD Integration
|
||||
```yaml
|
||||
# Add to CI pipeline
|
||||
- name: Security Scan
|
||||
run: |
|
||||
npm audit --audit-level=moderate
|
||||
npm run test:security
|
||||
```
|
||||
|
||||
### Monitoring & Alerting
|
||||
1. Implement fail2ban for repeated auth failures
|
||||
2. Set up log analysis for suspicious patterns
|
||||
3. Configure alerts for security events
|
||||
4. Regular vulnerability scanning
|
||||
|
||||
---
|
||||
|
||||
## 📋 COMPLIANCE CHECKLIST
|
||||
|
||||
- [ ] OWASP Top 10 addressed
|
||||
- [ ] GDPR compliance (data minimization, right to erasure)
|
||||
- [ ] Security headers implemented
|
||||
- [ ] Dependency scanning automated
|
||||
- [ ] Incident response plan documented
|
||||
- [ ] Security documentation maintained
|
||||
- [ ] Regular security reviews scheduled
|
||||
|
||||
---
|
||||
|
||||
## 🎯 CONCLUSION
|
||||
|
||||
The wedding photo sharing application has a solid security foundation with excellent input validation and authentication mechanisms. However, operational security practices need immediate attention. The critical issues around secret management and token storage must be addressed before production deployment.
|
||||
|
||||
Implementing the recommended fixes will raise the security score from 6.5/10 to approximately 8.5/10, providing a robust and secure platform for wedding photo sharing.
|
||||
|
||||
---
|
||||
|
||||
*Generated by Claude Security Scanner v1.0*
|
||||
*Next scan recommended: After Phase 1 remediation completion*
|
||||
-114
@@ -1,114 +0,0 @@
|
||||
kind: pipeline
|
||||
type: docker
|
||||
name: default
|
||||
|
||||
steps:
|
||||
# Build Backend Docker Image
|
||||
- name: build-backend
|
||||
image: plugins/docker
|
||||
settings:
|
||||
repo: registry.local.nothaft.cloud/picpeak-backend
|
||||
tags:
|
||||
- latest
|
||||
- ${DRONE_COMMIT_SHA:0:8}
|
||||
- ${DRONE_BRANCH}-latest
|
||||
dockerfile: backend/Dockerfile
|
||||
context: backend/
|
||||
registry: registry.local.nothaft.cloud
|
||||
build_args:
|
||||
- VERSION=${DRONE_TAG:-dev}
|
||||
|
||||
# Build Frontend Docker Image
|
||||
- name: build-frontend
|
||||
image: plugins/docker
|
||||
settings:
|
||||
repo: registry.local.nothaft.cloud/picpeak-frontend
|
||||
tags:
|
||||
- latest
|
||||
- ${DRONE_COMMIT_SHA:0:8}
|
||||
- ${DRONE_BRANCH}-latest
|
||||
dockerfile: frontend/Dockerfile
|
||||
context: frontend/
|
||||
registry: registry.local.nothaft.cloud
|
||||
build_args:
|
||||
- VERSION=${DRONE_TAG:-dev}
|
||||
- VITE_API_URL=${VITE_API_URL:-/api}
|
||||
|
||||
trigger:
|
||||
branch:
|
||||
- main
|
||||
- develop
|
||||
event:
|
||||
- push
|
||||
- pull_request
|
||||
|
||||
---
|
||||
kind: pipeline
|
||||
type: docker
|
||||
name: release
|
||||
|
||||
steps:
|
||||
# Build Backend Release
|
||||
- name: build-backend-release
|
||||
image: plugins/docker
|
||||
settings:
|
||||
repo: registry.local.nothaft.cloud/picpeak-backend
|
||||
tags:
|
||||
- ${DRONE_TAG}
|
||||
- latest
|
||||
dockerfile: backend/Dockerfile
|
||||
context: backend/
|
||||
registry: registry.local.nothaft.cloud
|
||||
|
||||
# Build Frontend Release
|
||||
- name: build-frontend-release
|
||||
image: plugins/docker
|
||||
settings:
|
||||
repo: registry.local.nothaft.cloud/picpeak-frontend
|
||||
tags:
|
||||
- ${DRONE_TAG}
|
||||
- latest
|
||||
dockerfile: frontend/Dockerfile
|
||||
context: frontend/
|
||||
registry: registry.local.nothaft.cloud
|
||||
|
||||
# -------- NEW: Publish Docker images to GitHub Container Registry --------
|
||||
- name: push-backend-ghcr
|
||||
image: plugins/docker
|
||||
settings:
|
||||
repo: ghcr.io/the-luap/picpeak-backend
|
||||
tags:
|
||||
- ${DRONE_TAG}
|
||||
- latest
|
||||
dockerfile: backend/Dockerfile
|
||||
context: backend/
|
||||
registry: ghcr.io
|
||||
username:
|
||||
from_secret: GITHUB_USERNAME
|
||||
password:
|
||||
from_secret: GITHUB_TOKEN
|
||||
build_args:
|
||||
- VERSION=${DRONE_TAG}
|
||||
|
||||
- name: push-frontend-ghcr
|
||||
image: plugins/docker
|
||||
settings:
|
||||
repo: ghcr.io/the-luap/picpeak-frontend
|
||||
tags:
|
||||
- ${DRONE_TAG}
|
||||
- latest
|
||||
dockerfile: frontend/Dockerfile
|
||||
context: frontend/
|
||||
registry: ghcr.io
|
||||
username:
|
||||
from_secret: GITHUB_USERNAME
|
||||
password:
|
||||
from_secret: GITHUB_TOKEN
|
||||
build_args:
|
||||
- VERSION=${DRONE_TAG}
|
||||
- VITE_API_URL=${VITE_API_URL:-/api}
|
||||
|
||||
|
||||
trigger:
|
||||
event:
|
||||
- tag
|
||||
+111
-37
@@ -1,47 +1,121 @@
|
||||
# PicPeak Development Environment Configuration
|
||||
# Copy this file to .env for local development
|
||||
# PicPeak Environment Configuration
|
||||
# Copy this file to .env and update with your values
|
||||
|
||||
# SECURITY WARNING: This configuration is for development only!
|
||||
# For production, use .env.production.example
|
||||
# Environment
|
||||
NODE_ENV=production
|
||||
|
||||
# JWT Secret (Change in production!)
|
||||
# Generate secure secret with: openssl rand -base64 32
|
||||
JWT_SECRET=dev-secret-DO-NOT-USE-IN-PRODUCTION
|
||||
# JWT Secret (generate with: openssl rand -base64 64)
|
||||
JWT_SECRET=your_very_long_random_jwt_secret_here
|
||||
|
||||
# Application URLs (Docker Compose development setup)
|
||||
ADMIN_URL=http://localhost:3005
|
||||
FRONTEND_URL=http://localhost:3005
|
||||
BACKEND_URL=http://localhost:3001
|
||||
# Auth cookie Secure flag
|
||||
# unset - default: follows NODE_ENV (production=true, dev=false)
|
||||
# true - always set Secure (HTTPS-only cookies; breaks plain-HTTP access)
|
||||
# false - never set Secure (allows HTTP; cookies not protected on HTTPS)
|
||||
# auto - decide per request: Secure on HTTPS, not on HTTP
|
||||
#
|
||||
# Use COOKIE_SECURE=auto if your deployment is reachable over both HTTPS
|
||||
# (via reverse proxy like Nginx Proxy Manager, Traefik, Caddy) AND plain
|
||||
# HTTP (e.g. LAN access at http://192.168.x.x:3010). The backend reads
|
||||
# req.secure from Express, which respects the X-Forwarded-Proto header
|
||||
# when the proxy is in the trust list.
|
||||
#
|
||||
# Requirements for auto mode:
|
||||
# 1. Your reverse proxy MUST send X-Forwarded-Proto: https on HTTPS
|
||||
# requests. Standard configs for NPM/Traefik/Caddy do this by default.
|
||||
# 2. The proxy must be on a trusted IP range. By default PicPeak trusts
|
||||
# loopback and private networks (127.0.0.1, 10.x, 172.16-31.x,
|
||||
# 192.168.x, link-local). Proxies outside those ranges need custom
|
||||
# trust proxy configuration.
|
||||
# COOKIE_SECURE=auto
|
||||
|
||||
# Database Configuration (SQLite for development)
|
||||
DATABASE_CLIENT=sqlite3
|
||||
DATABASE_PATH=./data/photo_sharing.db
|
||||
# Cookie SameSite attribute (Lax | Strict | None). Default: Lax
|
||||
# COOKIE_SAMESITE=Lax
|
||||
|
||||
# Email Configuration (Mailhog for development)
|
||||
# Access Mailhog UI at: http://localhost:8025
|
||||
SMTP_HOST=mailhog
|
||||
SMTP_PORT=1025
|
||||
# Cookie Domain — set this if serving auth cookies across subdomains.
|
||||
# Leave unset for same-origin setups.
|
||||
# COOKIE_DOMAIN=.example.com
|
||||
|
||||
# Database Configuration (PostgreSQL)
|
||||
DATABASE_CLIENT=pg
|
||||
DB_USER=picpeak
|
||||
# IMPORTANT: Avoid $ character in passwords - Docker Compose interprets it as variable substitution
|
||||
# If you must use $, escape it as $$ (e.g., Pass$$word instead of Pass$word)
|
||||
DB_PASSWORD=your_secure_postgres_password_here
|
||||
DB_NAME=picpeak_prod
|
||||
|
||||
# Redis Configuration
|
||||
# IMPORTANT: Same warning applies - avoid $ or escape as $$
|
||||
REDIS_PASSWORD=your_secure_redis_password_here
|
||||
|
||||
# Admin Account (initial setup)
|
||||
ADMIN_USERNAME=admin
|
||||
ADMIN_EMAIL=admin@yourdomain.com
|
||||
ADMIN_PASSWORD=your_secure_admin_password_here
|
||||
|
||||
# Email Configuration
|
||||
# For Gmail: use app-specific password
|
||||
# For SendGrid: SMTP_USER=apikey, SMTP_PASS=your-api-key
|
||||
SMTP_HOST=smtp.gmail.com
|
||||
SMTP_PORT=587
|
||||
SMTP_SECURE=false
|
||||
SMTP_USER=
|
||||
SMTP_PASS=
|
||||
EMAIL_FROM=noreply@localhost
|
||||
SMTP_USER=your-email@gmail.com
|
||||
SMTP_PASS=your-app-specific-password
|
||||
EMAIL_FROM=noreply@yourdomain.com
|
||||
|
||||
# Backend Port Configuration
|
||||
PORT=3001
|
||||
# Application URLs
|
||||
# Use full origin with scheme, no trailing slash.
|
||||
# Admin UI is served by the frontend at /admin.
|
||||
FRONTEND_URL=https://yourdomain.com
|
||||
ADMIN_URL=https://yourdomain.com
|
||||
|
||||
# Optional: Umami Analytics Backend Config
|
||||
# NOTE: Primary configuration through Admin UI > Settings > Analytics
|
||||
# These are fallback values for server-side tracking
|
||||
# UMAMI_URL=https://analytics.example.com
|
||||
# UMAMI_WEBSITE_ID=your-website-id
|
||||
# UMAMI_HASH_SALT=your-hash-salt
|
||||
# API URL for email assets (logos, images in notification emails)
|
||||
# This must be the publicly accessible URL where email recipients can load images.
|
||||
# If not set, defaults to http://localhost:3001 which will show broken images in emails.
|
||||
API_URL=https://yourdomain.com/api
|
||||
|
||||
# Development Features
|
||||
NODE_ENV=development
|
||||
LOG_LEVEL=debug
|
||||
# Frontend API base
|
||||
# For pre-built images and production behind a reverse proxy, keep '/api'.
|
||||
# If you rebuild the frontend yourself, you may set a full URL at build time.
|
||||
VITE_API_URL=/api
|
||||
|
||||
# Admin Setup Notes:
|
||||
# 1. Run 'npm run migrate' in backend folder
|
||||
# 2. Admin credentials will be auto-generated
|
||||
# 3. Check ADMIN_CREDENTIALS.txt for login details
|
||||
# 4. Change password on first login (required)
|
||||
# Port Configuration (optional)
|
||||
# BACKEND_PORT=3001
|
||||
# FRONTEND_PORT=3000
|
||||
# DB_PORT=5432
|
||||
# REDIS_PORT=6379
|
||||
|
||||
# Release Channel
|
||||
# Options: 'stable' (default), 'beta', or specific version like 'v2.3.0'
|
||||
# 'stable' uses the :stable tag (same as :latest on main)
|
||||
# 'beta' uses the :beta tag for pre-release versions
|
||||
PICPEAK_CHANNEL=stable
|
||||
|
||||
# Update Check Configuration
|
||||
# Set to 'false' to disable update notifications in admin UI
|
||||
UPDATE_CHECK_ENABLED=true
|
||||
|
||||
# Timezone
|
||||
TZ=UTC
|
||||
|
||||
# Runtime user mapping for Docker (optional)
|
||||
# Set these to your host user's UID/GID to avoid permission issues on bind mounts.
|
||||
# Run `id -u` and `id -g` on host to get values. Defaults to 1001.
|
||||
PUID=1001
|
||||
PGID=1001
|
||||
|
||||
# Analytics (Optional - Umami)
|
||||
VITE_UMAMI_URL=
|
||||
VITE_UMAMI_WEBSITE_ID=
|
||||
VITE_UMAMI_SHARE_URL=
|
||||
|
||||
# Storage variables (host paths)
|
||||
# These control where data is stored on the host. Defaults are local folders.
|
||||
APP_STORAGE=./storage
|
||||
APP_DATA=./data
|
||||
LOGS=./logs
|
||||
|
||||
# Note on FRONTEND_API_URL (documentation only):
|
||||
# When using pre-built frontend images, runtime env vars cannot override the built JS.
|
||||
# Do NOT rely on FRONTEND_API_URL in Compose. Instead, keep VITE_API_URL=/api and
|
||||
# let the frontend Nginx proxy /api to the backend. Only if you rebuild the frontend
|
||||
# should you change VITE_API_URL at build time.
|
||||
|
||||
@@ -1,100 +0,0 @@
|
||||
# PicPeak Production Configuration
|
||||
# Copy this file to .env and update with your production values
|
||||
|
||||
# ============================================
|
||||
# CRITICAL SECURITY - MUST CHANGE ALL VALUES!
|
||||
# ============================================
|
||||
|
||||
# JWT Secret - REQUIRED (minimum 32 characters)
|
||||
# Generate with: openssl rand -base64 32
|
||||
JWT_SECRET=CHANGE-THIS-PRODUCTION-SECRET-USE-OPENSSL-COMMAND
|
||||
|
||||
# Application URLs - REQUIRED (your actual domain)
|
||||
FRONTEND_URL=https://your-domain.com
|
||||
BACKEND_URL=https://your-domain.com
|
||||
ADMIN_URL=https://your-domain.com
|
||||
|
||||
# ============================================
|
||||
# DATABASE CONFIGURATION - REQUIRED
|
||||
# ============================================
|
||||
|
||||
# PostgreSQL Configuration (Recommended for production)
|
||||
DATABASE_CLIENT=pg
|
||||
DB_HOST=postgres # or your database host
|
||||
DB_PORT=5432
|
||||
DB_NAME=picpeak
|
||||
DB_USER=picpeak
|
||||
DB_PASSWORD=CHANGE-THIS-SECURE-DATABASE-PASSWORD
|
||||
|
||||
# ============================================
|
||||
# EMAIL CONFIGURATION - REQUIRED
|
||||
# ============================================
|
||||
|
||||
# Example: Gmail with App Password
|
||||
# SMTP_HOST=smtp.gmail.com
|
||||
# SMTP_PORT=587
|
||||
# SMTP_SECURE=false
|
||||
# SMTP_USER=your-email@gmail.com
|
||||
# SMTP_PASS=your-16-char-app-password
|
||||
# EMAIL_FROM=Your Name <your-email@gmail.com>
|
||||
|
||||
# Example: SendGrid
|
||||
SMTP_HOST=smtp.sendgrid.net
|
||||
SMTP_PORT=587
|
||||
SMTP_SECURE=false
|
||||
SMTP_USER=apikey
|
||||
SMTP_PASS=YOUR-SENDGRID-API-KEY
|
||||
EMAIL_FROM=PicPeak <noreply@your-domain.com>
|
||||
|
||||
# ============================================
|
||||
# ADMIN SETUP - AUTO-GENERATED
|
||||
# ============================================
|
||||
# NOTE: Admin credentials are automatically generated during setup
|
||||
# DO NOT set ADMIN_EMAIL or ADMIN_PASSWORD anymore!
|
||||
# Run 'npm run migrate' and check ADMIN_CREDENTIALS.txt
|
||||
|
||||
# ============================================
|
||||
# OPTIONAL CONFIGURATION
|
||||
# ============================================
|
||||
|
||||
# Umami Analytics (Optional - Fallback values)
|
||||
# Primary config via Admin UI > Settings > Analytics
|
||||
# UMAMI_URL=https://analytics.your-domain.com
|
||||
# UMAMI_WEBSITE_ID=your-website-id
|
||||
# UMAMI_HASH_SALT=your-hash-salt
|
||||
|
||||
# Frontend Analytics (Optional - Fallback values)
|
||||
# VITE_UMAMI_URL=https://analytics.your-domain.com
|
||||
# VITE_UMAMI_WEBSITE_ID=your-website-id
|
||||
# VITE_UMAMI_SHARE_URL=https://analytics.your-domain.com/share/xyz/gallery
|
||||
|
||||
# ============================================
|
||||
# PERFORMANCE & SECURITY TUNING
|
||||
# ============================================
|
||||
|
||||
NODE_ENV=production
|
||||
PORT=3001
|
||||
LOG_LEVEL=info
|
||||
|
||||
# Security Settings (Defaults are secure)
|
||||
BCRYPT_ROUNDS=12
|
||||
SESSION_TIMEOUT_MINUTES=60
|
||||
RATE_LIMIT_WINDOW_MS=900000 # 15 minutes
|
||||
RATE_LIMIT_MAX_REQUESTS=100 # per window
|
||||
|
||||
# Connection Pool (Adjust based on load)
|
||||
DB_POOL_MIN=5
|
||||
DB_POOL_MAX=25
|
||||
|
||||
# ============================================
|
||||
# DOCKER COMPOSE SPECIFIC
|
||||
# ============================================
|
||||
|
||||
# Traefik Configuration (if using Traefik)
|
||||
DOMAIN=your-domain.com
|
||||
LETSENCRYPT_EMAIL=admin@your-domain.com
|
||||
|
||||
# Volume Paths (Docker)
|
||||
STORAGE_PATH=/app/storage
|
||||
EVENTS_PATH=/app/storage/events
|
||||
ARCHIVE_PATH=/app/storage/events/archived
|
||||
@@ -1,12 +0,0 @@
|
||||
# Files to exclude from GitHub mirror
|
||||
.env* export-ignore
|
||||
docker-compose.prod.yml export-ignore
|
||||
.claudedocs/ export-ignore
|
||||
backend/data/ export-ignore
|
||||
backend/storage/ export-ignore
|
||||
backend/.env* export-ignore
|
||||
frontend/.env* export-ignore
|
||||
secrets/ export-ignore
|
||||
*.key export-ignore
|
||||
*.pem export-ignore
|
||||
.gitea/ export-ignore
|
||||
@@ -1,99 +0,0 @@
|
||||
name: Mirror to GitHub
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
workflow_dispatch: # Allow manual triggering
|
||||
|
||||
jobs:
|
||||
mirror:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v3
|
||||
with:
|
||||
fetch-depth: 0 # Full history for proper mirroring
|
||||
|
||||
- name: Setup Git
|
||||
run: |
|
||||
git config --global user.name "the-luap"
|
||||
git config --global user.email "paul-nothaft@hotmail.de"
|
||||
|
||||
- name: Remove sensitive files and directories
|
||||
run: |
|
||||
echo "Current files before cleanup:"
|
||||
ls -la | head -10 || true
|
||||
echo "..."
|
||||
|
||||
# Remove sensitive files/directories if they exist
|
||||
echo "Removing sensitive files..."
|
||||
rm -rf .env || true
|
||||
rm -rf backend/.env* || true
|
||||
rm -rf frontend/.env* || true
|
||||
rm -rf docker-compose.prod.yml || true
|
||||
rm -rf .claudedocs/ || true
|
||||
rm -rf backend/data/ || true
|
||||
rm -rf backend/storage/ || true
|
||||
rm -rf .gitea/ || true
|
||||
rm -rf scripts/install-gitea-runner.sh || true
|
||||
rm -rf .drone* || true
|
||||
rm -rf .github-mirror-exclude || true
|
||||
rm -rf .gitattributes-github || true
|
||||
rm -rf photo-sharing-prd.md || true
|
||||
rm -rf CLAUDE.md || true
|
||||
rm -rf PRODUCTION_DEPLOYMENT_GUIDE.md || true
|
||||
rm -rf logs/ || true
|
||||
rm -rf frontend/.claudedocs/ || true
|
||||
rm -rf test-maintenance.sh || true
|
||||
rm -rf storage/ || true
|
||||
|
||||
echo "Sensitive files removal completed"
|
||||
|
||||
# Add and commit the cleanup if there are changes
|
||||
git add -A
|
||||
if ! git diff --cached --quiet; then
|
||||
git commit -m "chore: remove sensitive files for GitHub mirror"
|
||||
echo "✅ Committed cleanup of sensitive files"
|
||||
else
|
||||
echo "✅ No sensitive files to remove"
|
||||
fi
|
||||
|
||||
echo "Final file structure (top level):"
|
||||
ls -la | head -10 || true
|
||||
|
||||
- name: Check GitHub token
|
||||
env:
|
||||
GITHUBTOKEN: ${{ secrets.GITHUBTOKEN }}
|
||||
run: |
|
||||
if [ -z "$GITHUBTOKEN" ]; then
|
||||
echo "ERROR: GITHUBTOKEN secret is not set!"
|
||||
exit 1
|
||||
else
|
||||
echo "GitHub token is available (length: ${#GITHUBTOKEN})"
|
||||
fi
|
||||
|
||||
- name: Push to GitHub
|
||||
env:
|
||||
GITHUBTOKEN: ${{ secrets.GITHUBTOKEN }}
|
||||
run: |
|
||||
# Remove existing github remote if it exists
|
||||
git remote remove github || true
|
||||
|
||||
# Add GitHub remote
|
||||
git remote add github https://x-access-token:${GITHUBTOKEN}@github.com/the-luap/picpeak.git
|
||||
|
||||
# Verify remote was added
|
||||
echo "GitHub remote added:"
|
||||
git remote -v
|
||||
|
||||
# Push to GitHub main branch
|
||||
echo "Pushing to GitHub..."
|
||||
git push github main --force
|
||||
echo "✅ Push to GitHub completed!"
|
||||
|
||||
- name: Workflow completed
|
||||
run: |
|
||||
echo "✅ Mirror to GitHub workflow completed successfully!"
|
||||
echo "📊 Repository mirrored to: https://github.com/the-luap/picpeak"
|
||||
echo "🔒 Sensitive files have been removed from the mirror"
|
||||
@@ -1,52 +0,0 @@
|
||||
name: Test and Lint
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [ main, develop ]
|
||||
pull_request:
|
||||
branches: [ main ]
|
||||
|
||||
jobs:
|
||||
backend-test:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v3
|
||||
with:
|
||||
node-version: '18'
|
||||
|
||||
- name: Install backend dependencies
|
||||
working-directory: ./backend
|
||||
run: npm ci
|
||||
|
||||
- name: Run backend linting
|
||||
working-directory: ./backend
|
||||
run: npm run lint || true # Continue on lint errors for now
|
||||
|
||||
- name: Run backend tests
|
||||
working-directory: ./backend
|
||||
run: npm test || true # Continue on test failures for now
|
||||
|
||||
frontend-test:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v3
|
||||
with:
|
||||
node-version: '18'
|
||||
|
||||
- name: Install frontend dependencies
|
||||
working-directory: ./frontend
|
||||
run: npm ci --legacy-peer-deps
|
||||
|
||||
- name: Run frontend linting
|
||||
working-directory: ./frontend
|
||||
run: npm run lint || true # Continue on lint errors for now
|
||||
|
||||
- name: Build frontend
|
||||
working-directory: ./frontend
|
||||
run: npm run build
|
||||
@@ -1,267 +0,0 @@
|
||||
name: Version and Release
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [ main ]
|
||||
paths-ignore:
|
||||
- '**.md'
|
||||
- '.gitea/**'
|
||||
- '.drone.yml'
|
||||
|
||||
jobs:
|
||||
version-bump:
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
new_version: ${{ steps.version.outputs.new_version }}
|
||||
version_changed: ${{ steps.version.outputs.version_changed }}
|
||||
component_changed: ${{ steps.version.outputs.component_changed }}
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
with:
|
||||
fetch-depth: 0
|
||||
token: ${{ secrets.GITEA_TOKEN || github.token }}
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v3
|
||||
with:
|
||||
node-version: '18'
|
||||
|
||||
- name: Configure Git
|
||||
run: |
|
||||
git config --global user.name 'Gitea Actions Bot'
|
||||
git config --global user.email 'actions@gitea.local'
|
||||
|
||||
- name: Detect changes and bump version
|
||||
id: version
|
||||
run: |
|
||||
set -e # Exit on error
|
||||
|
||||
echo "=== Debug Info ==="
|
||||
echo "GitHub event before: ${{ github.event.before }}"
|
||||
echo "GitHub SHA: ${{ github.sha }}"
|
||||
echo "Current directory: $(pwd)"
|
||||
echo "Git log (last 5): $(git log --oneline -5)"
|
||||
|
||||
# Get the commit range for changed files
|
||||
if [ "${{ github.event.before }}" != "0000000000000000000000000000000000000000" ] && [ "${{ github.event.before }}" != "" ]; then
|
||||
COMMIT_RANGE="${{ github.event.before }}..${{ github.sha }}"
|
||||
echo "Using commit range: $COMMIT_RANGE"
|
||||
CHANGED_FILES=$(git diff --name-only $COMMIT_RANGE || echo "")
|
||||
else
|
||||
# First commit or no previous commit, check against HEAD~1 if it exists
|
||||
if git rev-parse HEAD~1 >/dev/null 2>&1; then
|
||||
COMMIT_RANGE="HEAD~1..HEAD"
|
||||
echo "Using commit range: $COMMIT_RANGE"
|
||||
CHANGED_FILES=$(git diff --name-only $COMMIT_RANGE || echo "")
|
||||
else
|
||||
echo "First commit detected, checking all files"
|
||||
CHANGED_FILES=$(git ls-files)
|
||||
fi
|
||||
fi
|
||||
|
||||
echo "Changed files:"
|
||||
echo "$CHANGED_FILES"
|
||||
|
||||
# Check what changed (using echo to pipe to grep to avoid grep exit codes)
|
||||
BACKEND_CHANGED=$(echo "$CHANGED_FILES" | grep -c '^backend/' || echo "0")
|
||||
FRONTEND_CHANGED=$(echo "$CHANGED_FILES" | grep -c '^frontend/' || echo "0")
|
||||
ROOT_CHANGED=$(echo "$CHANGED_FILES" | grep -c -E '^(package\.json|docker-compose|Dockerfile|scripts/)' || echo "0")
|
||||
|
||||
echo "Backend files changed: $BACKEND_CHANGED"
|
||||
echo "Frontend files changed: $FRONTEND_CHANGED"
|
||||
echo "Root files changed: $ROOT_CHANGED"
|
||||
|
||||
# Get current versions
|
||||
BACKEND_VERSION=$(node -p "require('./backend/package.json').version" 2>/dev/null || echo "1.0.0")
|
||||
FRONTEND_VERSION=$(node -p "require('./frontend/package.json').version" 2>/dev/null || echo "1.0.0")
|
||||
|
||||
echo "Current backend version: $BACKEND_VERSION"
|
||||
echo "Current frontend version: $FRONTEND_VERSION"
|
||||
|
||||
# Determine what to update based on changes
|
||||
BACKEND_UPDATE=false
|
||||
FRONTEND_UPDATE=false
|
||||
COMPONENT_CHANGED="none"
|
||||
|
||||
if [ "$ROOT_CHANGED" -gt 0 ]; then
|
||||
# Root changes affect both components
|
||||
BACKEND_UPDATE=true
|
||||
FRONTEND_UPDATE=true
|
||||
COMPONENT_CHANGED="both"
|
||||
SOURCE_VERSION=$BACKEND_VERSION
|
||||
echo "Root changes detected - updating both components"
|
||||
elif [ "$BACKEND_CHANGED" -gt 0 ] && [ "$FRONTEND_CHANGED" -gt 0 ]; then
|
||||
# Both components changed
|
||||
BACKEND_UPDATE=true
|
||||
FRONTEND_UPDATE=true
|
||||
COMPONENT_CHANGED="both"
|
||||
# Use the higher version as source
|
||||
if [ "$(printf '%s\n' "$BACKEND_VERSION" "$FRONTEND_VERSION" | sort -V | tail -n1)" = "$BACKEND_VERSION" ]; then
|
||||
SOURCE_VERSION=$BACKEND_VERSION
|
||||
else
|
||||
SOURCE_VERSION=$FRONTEND_VERSION
|
||||
fi
|
||||
echo "Both backend and frontend changed - updating both"
|
||||
elif [ "$BACKEND_CHANGED" -gt 0 ]; then
|
||||
# Only backend changed
|
||||
BACKEND_UPDATE=true
|
||||
COMPONENT_CHANGED="backend"
|
||||
SOURCE_VERSION=$BACKEND_VERSION
|
||||
echo "Only backend changed - updating backend"
|
||||
elif [ "$FRONTEND_CHANGED" -gt 0 ]; then
|
||||
# Only frontend changed
|
||||
FRONTEND_UPDATE=true
|
||||
COMPONENT_CHANGED="frontend"
|
||||
SOURCE_VERSION=$FRONTEND_VERSION
|
||||
echo "Only frontend changed - updating frontend"
|
||||
else
|
||||
echo "No relevant changes detected"
|
||||
echo "version_changed=false" >> $GITHUB_OUTPUT
|
||||
echo "component_changed=none" >> $GITHUB_OUTPUT
|
||||
echo "new_version=" >> $GITHUB_OUTPUT
|
||||
exit 0
|
||||
fi
|
||||
|
||||
echo "Component changed: $COMPONENT_CHANGED"
|
||||
echo "Source version: $SOURCE_VERSION"
|
||||
echo "Backend update: $BACKEND_UPDATE"
|
||||
echo "Frontend update: $FRONTEND_UPDATE"
|
||||
|
||||
# Calculate new version
|
||||
IFS='.' read -r -a version_parts <<< "$SOURCE_VERSION"
|
||||
MAJOR="${version_parts[0]}"
|
||||
MINOR="${version_parts[1]}"
|
||||
PATCH="${version_parts[2]}"
|
||||
|
||||
# Increment patch version
|
||||
NEW_PATCH=$((PATCH + 1))
|
||||
NEW_VERSION="$MAJOR.$MINOR.$NEW_PATCH"
|
||||
|
||||
echo "New version: $NEW_VERSION"
|
||||
echo "new_version=$NEW_VERSION" >> $GITHUB_OUTPUT
|
||||
echo "component_changed=$COMPONENT_CHANGED" >> $GITHUB_OUTPUT
|
||||
|
||||
# Update versions in package.json files
|
||||
if [ "$BACKEND_UPDATE" = true ]; then
|
||||
echo "Updating backend version to $NEW_VERSION"
|
||||
cd backend && npm version $NEW_VERSION --no-git-tag-version
|
||||
cd ..
|
||||
fi
|
||||
|
||||
if [ "$FRONTEND_UPDATE" = true ]; then
|
||||
echo "Updating frontend version to $NEW_VERSION"
|
||||
cd frontend && npm version $NEW_VERSION --no-git-tag-version
|
||||
cd ..
|
||||
fi
|
||||
|
||||
# Check if there are changes to commit
|
||||
if [[ -n $(git status --porcelain) ]]; then
|
||||
echo "version_changed=true" >> $GITHUB_OUTPUT
|
||||
else
|
||||
echo "version_changed=false" >> $GITHUB_OUTPUT
|
||||
fi
|
||||
|
||||
- name: Commit version bump
|
||||
if: steps.version.outputs.version_changed == 'true'
|
||||
run: |
|
||||
set -e # Exit on any error
|
||||
|
||||
# First, ensure we have the latest changes
|
||||
echo "Fetching latest changes..."
|
||||
git fetch origin main
|
||||
|
||||
# Check if we're behind and need to update
|
||||
LOCAL=$(git rev-parse HEAD)
|
||||
REMOTE=$(git rev-parse origin/main)
|
||||
|
||||
if [ "$LOCAL" != "$REMOTE" ]; then
|
||||
echo "Local is behind remote, pulling changes..."
|
||||
git pull origin main --no-rebase
|
||||
fi
|
||||
|
||||
COMPONENT="${{ steps.version.outputs.component_changed }}"
|
||||
|
||||
if [ "$COMPONENT" = "both" ]; then
|
||||
git add backend/package.json backend/package-lock.json frontend/package.json frontend/package-lock.json
|
||||
git commit -m "chore: bump version to ${{ steps.version.outputs.new_version }} (backend + frontend)"
|
||||
elif [ "$COMPONENT" = "backend" ]; then
|
||||
git add backend/package.json backend/package-lock.json
|
||||
git commit -m "chore: bump backend version to ${{ steps.version.outputs.new_version }}"
|
||||
elif [ "$COMPONENT" = "frontend" ]; then
|
||||
git add frontend/package.json frontend/package-lock.json
|
||||
git commit -m "chore: bump frontend version to ${{ steps.version.outputs.new_version }}"
|
||||
fi
|
||||
|
||||
# Pull latest changes before pushing to avoid conflicts
|
||||
echo "Pulling latest changes from origin/main..."
|
||||
if ! git pull --rebase origin main; then
|
||||
echo "Rebase failed, attempting to resolve..."
|
||||
# If rebase fails, abort and try a regular merge
|
||||
git rebase --abort || true
|
||||
git pull origin main --no-rebase
|
||||
fi
|
||||
|
||||
# Push the changes with retry logic
|
||||
echo "Pushing version bump..."
|
||||
PUSH_SUCCESS=false
|
||||
|
||||
for i in 1 2 3; do
|
||||
echo "Push attempt $i of 3..."
|
||||
|
||||
# Try to push
|
||||
if git push origin main 2>&1; then
|
||||
echo "Successfully pushed version bump on attempt $i"
|
||||
PUSH_SUCCESS=true
|
||||
break
|
||||
else
|
||||
echo "Push failed on attempt $i"
|
||||
|
||||
if [ $i -lt 3 ]; then
|
||||
echo "Waiting 5 seconds before retry..."
|
||||
sleep 5
|
||||
|
||||
echo "Pulling latest changes..."
|
||||
git fetch origin main
|
||||
|
||||
# Try rebase first, fall back to merge
|
||||
if ! git rebase origin/main; then
|
||||
echo "Rebase failed, trying merge..."
|
||||
git rebase --abort 2>/dev/null || true
|
||||
git pull origin main --no-rebase
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
done
|
||||
|
||||
if [ "$PUSH_SUCCESS" = "false" ]; then
|
||||
echo "ERROR: Failed to push after 3 attempts"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: Create Git tag
|
||||
if: steps.version.outputs.version_changed == 'true'
|
||||
run: |
|
||||
COMPONENT="${{ steps.version.outputs.component_changed }}"
|
||||
|
||||
if [ "$COMPONENT" = "both" ]; then
|
||||
TAG_MESSAGE="Release v${{ steps.version.outputs.new_version }} (backend + frontend)"
|
||||
elif [ "$COMPONENT" = "backend" ]; then
|
||||
TAG_MESSAGE="Release v${{ steps.version.outputs.new_version }} (backend)"
|
||||
elif [ "$COMPONENT" = "frontend" ]; then
|
||||
TAG_MESSAGE="Release v${{ steps.version.outputs.new_version }} (frontend)"
|
||||
fi
|
||||
|
||||
git tag -a "v${{ steps.version.outputs.new_version }}" -m "$TAG_MESSAGE"
|
||||
git push origin "v${{ steps.version.outputs.new_version }}"
|
||||
|
||||
trigger-drone:
|
||||
needs: version-bump
|
||||
if: needs.version-bump.outputs.version_changed == 'true'
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Trigger Drone Build
|
||||
run: |
|
||||
echo "Version bumped to ${{ needs.version-bump.outputs.new_version }}"
|
||||
echo "Component(s) changed: ${{ needs.version-bump.outputs.component_changed }}"
|
||||
echo "Drone will automatically trigger on the new tag"
|
||||
# Drone CI will automatically trigger on the tag push event
|
||||
@@ -1,24 +0,0 @@
|
||||
# Exclude patterns for GitHub mirror
|
||||
.env
|
||||
.env.*
|
||||
.env*
|
||||
docker-compose.prod.yml
|
||||
docker-compose.traefik.yml
|
||||
.claudedocs/
|
||||
backend/data/
|
||||
backend/storage/
|
||||
backend/.env*
|
||||
frontend/.env*
|
||||
secrets/
|
||||
*.key
|
||||
*.pem
|
||||
.gitea/
|
||||
node_modules/
|
||||
dist/
|
||||
build/
|
||||
*.log
|
||||
.DS_Store
|
||||
deploy/
|
||||
certbot/
|
||||
nginx/
|
||||
photo-sharing-prd.md
|
||||
@@ -9,7 +9,7 @@ assignees: ''
|
||||
|
||||
⚠️ **IMPORTANT: For serious security vulnerabilities, please DO NOT create a public issue.**
|
||||
|
||||
Instead, please email security@example.com with the details.
|
||||
Instead, please use [GitHub Private Vulnerability Reporting](https://github.com/the-luap/picpeak/security/advisories/new) or email **info@picpeak.app** with the details.
|
||||
|
||||
For minor security improvements or questions, you can use this template:
|
||||
|
||||
|
||||
@@ -0,0 +1,213 @@
|
||||
# Docker Build and Push Workflow
|
||||
|
||||
This GitHub Actions workflow automatically builds and pushes Docker images for both the backend and frontend to GitHub Container Registry (ghcr.io).
|
||||
|
||||
## Features
|
||||
|
||||
- 🔧 **Automatic builds** on push to main/develop branches, PRs, and releases
|
||||
- 🏗️ **Multi-architecture support** (linux/amd64 and linux/arm64)
|
||||
- 🏷️ **Smart tagging** based on branches, versions, and commits
|
||||
- 🔒 **Security scanning** with Trivy vulnerability scanner
|
||||
- 💾 **Build caching** for faster subsequent builds
|
||||
- 📊 **Build summaries** in GitHub Actions UI
|
||||
|
||||
## Authentication
|
||||
|
||||
The workflow uses the built-in `GITHUB_TOKEN` for authentication with GitHub Container Registry. No additional setup or personal access tokens are required.
|
||||
|
||||
### Required Permissions
|
||||
|
||||
The workflow automatically sets the necessary permissions:
|
||||
- `contents: read` - To checkout the repository
|
||||
- `packages: write` - To push images to ghcr.io
|
||||
- `security-events: write` - To upload security scan results
|
||||
|
||||
## Image Tags
|
||||
|
||||
Images are automatically tagged based on the trigger event:
|
||||
|
||||
| Event | Tags Generated |
|
||||
|-------|---------------|
|
||||
| Push to main | `latest`, `main`, `main-<short-sha>` |
|
||||
| Push to develop | `develop`, `develop-<short-sha>` |
|
||||
| Pull Request | `pr-<number>` |
|
||||
| Release (v1.2.3) | `1.2.3`, `1.2`, `1`, `latest` |
|
||||
| Manual trigger | Based on branch + optional push |
|
||||
|
||||
## Usage
|
||||
|
||||
### Pull Images
|
||||
|
||||
Once published, images can be pulled using:
|
||||
|
||||
```bash
|
||||
# Pull backend image
|
||||
docker pull ghcr.io/the-luap/picpeak/backend:latest
|
||||
|
||||
# Pull frontend image
|
||||
docker pull ghcr.io/the-luap/picpeak/frontend:latest
|
||||
|
||||
# Pull specific version
|
||||
docker pull ghcr.io/the-luap/picpeak/backend:v1.0.0
|
||||
|
||||
# Pull for specific architecture
|
||||
docker pull --platform linux/arm64 ghcr.io/the-luap/picpeak/backend:latest
|
||||
```
|
||||
|
||||
### Using in Docker Compose
|
||||
|
||||
```yaml
|
||||
version: '3.8'
|
||||
|
||||
services:
|
||||
backend:
|
||||
image: ghcr.io/the-luap/picpeak/backend:latest
|
||||
environment:
|
||||
- NODE_ENV=production
|
||||
ports:
|
||||
- "3001:3000"
|
||||
|
||||
frontend:
|
||||
image: ghcr.io/the-luap/picpeak/frontend:latest
|
||||
ports:
|
||||
- "80:80"
|
||||
```
|
||||
|
||||
### Using in Kubernetes
|
||||
|
||||
```yaml
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata:
|
||||
name: picpeak-backend
|
||||
spec:
|
||||
replicas: 3
|
||||
template:
|
||||
spec:
|
||||
containers:
|
||||
- name: backend
|
||||
image: ghcr.io/the-luap/picpeak/backend:latest
|
||||
imagePullPolicy: Always
|
||||
```
|
||||
|
||||
## Manual Workflow Trigger
|
||||
|
||||
You can manually trigger the workflow from the Actions tab:
|
||||
|
||||
1. Go to Actions → "Build and Push Docker Images"
|
||||
2. Click "Run workflow"
|
||||
3. Select branch and whether to push images
|
||||
4. Click "Run workflow"
|
||||
|
||||
## Security Scanning
|
||||
|
||||
The workflow includes Trivy vulnerability scanning that:
|
||||
- Scans for CRITICAL and HIGH severity vulnerabilities
|
||||
- Uploads results to GitHub Security tab
|
||||
- Available under Security → Code scanning alerts
|
||||
|
||||
## Build Optimization
|
||||
|
||||
The workflow uses several optimization techniques:
|
||||
|
||||
1. **GitHub Actions Cache**: Speeds up builds by caching layers
|
||||
2. **Multi-stage builds**: Reduces final image size
|
||||
3. **Parallel builds**: Backend and frontend build simultaneously
|
||||
4. **Smart rebuilds**: Only rebuilds changed components
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Permission Denied Errors
|
||||
|
||||
If you encounter permission errors when pushing images:
|
||||
|
||||
1. **First-time setup**: The first push creates a private package. You may need to:
|
||||
- Go to your package settings at `https://github.com/users/YOUR_USERNAME/packages`
|
||||
- Link the package to your repository
|
||||
- Set package visibility (public/private)
|
||||
|
||||
2. **Organization repositories**: Ensure the organization allows GitHub Actions to create packages
|
||||
|
||||
### Build Failures
|
||||
|
||||
Check the workflow logs in the Actions tab for detailed error messages. Common issues:
|
||||
- Missing dependencies in package.json
|
||||
- Dockerfile syntax errors
|
||||
- Network issues during package installation
|
||||
|
||||
### Image Not Found
|
||||
|
||||
If images aren't visible after successful push:
|
||||
- Check package visibility settings
|
||||
- Ensure you're authenticated to pull private images:
|
||||
```bash
|
||||
echo $GITHUB_TOKEN | docker login ghcr.io -u YOUR_USERNAME --password-stdin
|
||||
```
|
||||
|
||||
## Package Management
|
||||
|
||||
### View Packages
|
||||
|
||||
Your Docker images are available at:
|
||||
- Backend: `https://github.com/users/the-luap/packages/container/package/picpeak%2Fbackend`
|
||||
- Frontend: `https://github.com/users/the-luap/packages/container/package/picpeak%2Ffrontend`
|
||||
|
||||
### Delete Old Versions
|
||||
|
||||
To save storage, you can delete old versions:
|
||||
1. Go to package settings
|
||||
2. Click on "Manage versions"
|
||||
3. Select versions to delete
|
||||
4. Click "Delete selected versions"
|
||||
|
||||
### Set Retention Policy
|
||||
|
||||
Configure automatic cleanup in package settings:
|
||||
1. Go to package settings
|
||||
2. Click on "Manage Actions access"
|
||||
3. Set retention days for untagged versions
|
||||
|
||||
## Best Practices
|
||||
|
||||
1. **Use semantic versioning** for releases (e.g., v1.2.3)
|
||||
2. **Test images locally** before pushing to production
|
||||
3. **Monitor security alerts** from Trivy scans
|
||||
4. **Clean up old images** regularly to save storage
|
||||
5. **Use specific tags** in production (avoid `latest`)
|
||||
|
||||
## Advanced Configuration
|
||||
|
||||
### Custom Registry
|
||||
|
||||
To use a different registry, update the workflow:
|
||||
|
||||
```yaml
|
||||
env:
|
||||
REGISTRY: docker.io # or your custom registry
|
||||
BACKEND_IMAGE_NAME: yourusername/picpeak-backend
|
||||
```
|
||||
|
||||
### Additional Platforms
|
||||
|
||||
To build for more platforms:
|
||||
|
||||
```yaml
|
||||
platforms: linux/amd64,linux/arm64,linux/arm/v7
|
||||
```
|
||||
|
||||
### Custom Build Arguments
|
||||
|
||||
Add build arguments in the workflow:
|
||||
|
||||
```yaml
|
||||
build-args: |
|
||||
NODE_VERSION=20
|
||||
API_URL=${{ secrets.API_URL }}
|
||||
```
|
||||
|
||||
## Related Documentation
|
||||
|
||||
- [GitHub Container Registry Docs](https://docs.github.com/en/packages/working-with-a-github-packages-registry/working-with-the-container-registry)
|
||||
- [Docker Build Action](https://github.com/docker/build-push-action)
|
||||
- [Trivy Security Scanner](https://github.com/aquasecurity/trivy)
|
||||
- [Multi-platform Builds](https://docs.docker.com/build/building/multi-platform/)
|
||||
@@ -0,0 +1,297 @@
|
||||
name: Build and Push Docker Images
|
||||
|
||||
# This workflow is triggered by:
|
||||
# - Push to main/develop branches (builds 'latest' or branch-tagged images)
|
||||
# - Version tags from Release Please (e.g., v1.2.0 -> builds versioned images)
|
||||
# - GitHub Releases (created by Release Please)
|
||||
# - Manual workflow dispatch
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [ main, beta ]
|
||||
tags: [ 'v*.*.*', 'v*.*.*-beta.*' ] # Triggered by Release Please tags (stable and beta)
|
||||
pull_request:
|
||||
branches: [ main, beta ]
|
||||
release:
|
||||
types: [ published ] # Triggered when Release Please creates a release
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
push:
|
||||
description: 'Push images to registry'
|
||||
required: false
|
||||
default: 'false'
|
||||
type: choice
|
||||
options:
|
||||
- 'true'
|
||||
- 'false'
|
||||
|
||||
env:
|
||||
REGISTRY: ghcr.io
|
||||
BACKEND_IMAGE_NAME: ${{ github.repository }}/backend
|
||||
FRONTEND_IMAGE_NAME: ${{ github.repository }}/frontend
|
||||
|
||||
jobs:
|
||||
build-backend:
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
packages: write
|
||||
security-events: write
|
||||
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Determine build context
|
||||
id: context
|
||||
run: |
|
||||
# Determine if this is a beta or stable release
|
||||
if [[ "${{ github.ref }}" == refs/tags/v*-beta* ]] || [[ "${{ github.ref }}" == refs/heads/beta ]]; then
|
||||
echo "channel=beta" >> $GITHUB_OUTPUT
|
||||
echo "is_prerelease=true" >> $GITHUB_OUTPUT
|
||||
else
|
||||
echo "channel=stable" >> $GITHUB_OUTPUT
|
||||
echo "is_prerelease=false" >> $GITHUB_OUTPUT
|
||||
fi
|
||||
|
||||
- name: Determine build platforms
|
||||
id: platforms
|
||||
run: |
|
||||
# Only build ARM64 for tagged releases (v*.*.*)
|
||||
# QEMU emulation is too slow/unreliable for npm operations on regular builds
|
||||
if [[ "${{ github.ref }}" == refs/tags/v* ]]; then
|
||||
echo "platforms=linux/amd64,linux/arm64" >> $GITHUB_OUTPUT
|
||||
echo "skip_qemu=false" >> $GITHUB_OUTPUT
|
||||
else
|
||||
echo "platforms=linux/amd64" >> $GITHUB_OUTPUT
|
||||
echo "skip_qemu=true" >> $GITHUB_OUTPUT
|
||||
fi
|
||||
|
||||
- name: Set up QEMU
|
||||
if: steps.platforms.outputs.skip_qemu != 'true'
|
||||
uses: docker/setup-qemu-action@v3
|
||||
with:
|
||||
platforms: arm64
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
|
||||
- name: Log in to Container Registry
|
||||
if: github.event_name != 'pull_request' || github.event.inputs.push == 'true'
|
||||
id: login-ghcr
|
||||
continue-on-error: true
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
registry: ${{ env.REGISTRY }}
|
||||
username: ${{ github.actor }}
|
||||
password: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Extract metadata for Backend
|
||||
id: meta-backend
|
||||
uses: docker/metadata-action@v5
|
||||
with:
|
||||
images: ${{ env.REGISTRY }}/${{ env.BACKEND_IMAGE_NAME }}
|
||||
labels: |
|
||||
org.opencontainers.image.title=PicPeak Backend
|
||||
org.opencontainers.image.description=PicPeak photo sharing platform backend service
|
||||
org.opencontainers.image.vendor=PicPeak
|
||||
maintainer=${{ github.repository_owner }}
|
||||
tags: |
|
||||
type=ref,event=branch
|
||||
type=ref,event=pr
|
||||
type=semver,pattern={{version}}
|
||||
type=semver,pattern={{major}}.{{minor}},enable=${{ steps.context.outputs.is_prerelease == 'false' }}
|
||||
type=semver,pattern={{major}},enable=${{ steps.context.outputs.is_prerelease == 'false' }}
|
||||
type=sha,format=short
|
||||
type=raw,value=latest,enable={{is_default_branch}}
|
||||
type=raw,value=stable,enable=${{ github.ref == 'refs/heads/main' || (startsWith(github.ref, 'refs/tags/v') && steps.context.outputs.is_prerelease == 'false') }}
|
||||
type=raw,value=beta,enable=${{ github.ref == 'refs/heads/beta' || steps.context.outputs.is_prerelease == 'true' }}
|
||||
|
||||
- name: Build and push Backend Docker image
|
||||
uses: docker/build-push-action@v5
|
||||
with:
|
||||
context: ./backend
|
||||
file: ./backend/Dockerfile
|
||||
# Always build; only push when registry login succeeded
|
||||
push: ${{ (github.event_name != 'pull_request' || github.event.inputs.push == 'true') && steps.login-ghcr.outcome == 'success' }}
|
||||
tags: ${{ steps.meta-backend.outputs.tags }}
|
||||
labels: ${{ steps.meta-backend.outputs.labels }}
|
||||
platforms: ${{ steps.platforms.outputs.platforms }}
|
||||
cache-from: type=gha,scope=backend
|
||||
cache-to: type=gha,mode=max,scope=backend
|
||||
build-args: |
|
||||
CACHEBUST=${{ github.run_number }}
|
||||
BUILD_DATE=${{ github.event.head_commit.timestamp }}
|
||||
VCS_REF=${{ github.sha }}
|
||||
VERSION=${{ steps.meta-backend.outputs.version }}
|
||||
|
||||
- name: Run Trivy vulnerability scanner
|
||||
if: github.event_name != 'pull_request' && steps.login-ghcr.outcome == 'success'
|
||||
uses: aquasecurity/trivy-action@master
|
||||
with:
|
||||
image-ref: ${{ env.REGISTRY }}/${{ env.BACKEND_IMAGE_NAME }}:${{ steps.meta-backend.outputs.version }}
|
||||
format: 'sarif'
|
||||
output: 'trivy-backend.sarif'
|
||||
severity: 'CRITICAL,HIGH'
|
||||
timeout: '10m'
|
||||
|
||||
- name: Upload Trivy scan results to GitHub Security tab
|
||||
if: github.event_name != 'pull_request' && steps.login-ghcr.outcome == 'success'
|
||||
uses: github/codeql-action/upload-sarif@v4
|
||||
with:
|
||||
sarif_file: 'trivy-backend.sarif'
|
||||
category: 'backend-vulnerabilities'
|
||||
|
||||
build-frontend:
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
packages: write
|
||||
security-events: write
|
||||
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Determine build context
|
||||
id: context
|
||||
run: |
|
||||
# Determine if this is a beta or stable release
|
||||
if [[ "${{ github.ref }}" == refs/tags/v*-beta* ]] || [[ "${{ github.ref }}" == refs/heads/beta ]]; then
|
||||
echo "channel=beta" >> $GITHUB_OUTPUT
|
||||
echo "is_prerelease=true" >> $GITHUB_OUTPUT
|
||||
else
|
||||
echo "channel=stable" >> $GITHUB_OUTPUT
|
||||
echo "is_prerelease=false" >> $GITHUB_OUTPUT
|
||||
fi
|
||||
|
||||
- name: Determine build platforms
|
||||
id: platforms
|
||||
run: |
|
||||
# Only build ARM64 for tagged releases (v*.*.*)
|
||||
# QEMU emulation is too slow/unreliable for npm operations on regular builds
|
||||
if [[ "${{ github.ref }}" == refs/tags/v* ]]; then
|
||||
echo "platforms=linux/amd64,linux/arm64" >> $GITHUB_OUTPUT
|
||||
echo "skip_qemu=false" >> $GITHUB_OUTPUT
|
||||
else
|
||||
echo "platforms=linux/amd64" >> $GITHUB_OUTPUT
|
||||
echo "skip_qemu=true" >> $GITHUB_OUTPUT
|
||||
fi
|
||||
|
||||
- name: Set up QEMU
|
||||
if: steps.platforms.outputs.skip_qemu != 'true'
|
||||
uses: docker/setup-qemu-action@v3
|
||||
with:
|
||||
platforms: arm64
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
|
||||
- name: Log in to Container Registry
|
||||
if: github.event_name != 'pull_request' || github.event.inputs.push == 'true'
|
||||
id: login-ghcr
|
||||
continue-on-error: true
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
registry: ${{ env.REGISTRY }}
|
||||
username: ${{ github.actor }}
|
||||
password: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Extract metadata for Frontend
|
||||
id: meta-frontend
|
||||
uses: docker/metadata-action@v5
|
||||
with:
|
||||
images: ${{ env.REGISTRY }}/${{ env.FRONTEND_IMAGE_NAME }}
|
||||
labels: |
|
||||
org.opencontainers.image.title=PicPeak Frontend
|
||||
org.opencontainers.image.description=PicPeak photo sharing platform frontend application
|
||||
org.opencontainers.image.vendor=PicPeak
|
||||
maintainer=${{ github.repository_owner }}
|
||||
tags: |
|
||||
type=ref,event=branch
|
||||
type=ref,event=pr
|
||||
type=semver,pattern={{version}}
|
||||
type=semver,pattern={{major}}.{{minor}},enable=${{ steps.context.outputs.is_prerelease == 'false' }}
|
||||
type=semver,pattern={{major}},enable=${{ steps.context.outputs.is_prerelease == 'false' }}
|
||||
type=sha,format=short
|
||||
type=raw,value=latest,enable={{is_default_branch}}
|
||||
type=raw,value=stable,enable=${{ github.ref == 'refs/heads/main' || (startsWith(github.ref, 'refs/tags/v') && steps.context.outputs.is_prerelease == 'false') }}
|
||||
type=raw,value=beta,enable=${{ github.ref == 'refs/heads/beta' || steps.context.outputs.is_prerelease == 'true' }}
|
||||
|
||||
- name: Build and push Frontend Docker image
|
||||
uses: docker/build-push-action@v5
|
||||
with:
|
||||
context: ./frontend
|
||||
file: ./frontend/Dockerfile
|
||||
# Always build; only push when registry login succeeded
|
||||
push: ${{ (github.event_name != 'pull_request' || github.event.inputs.push == 'true') && steps.login-ghcr.outcome == 'success' }}
|
||||
tags: ${{ steps.meta-frontend.outputs.tags }}
|
||||
labels: ${{ steps.meta-frontend.outputs.labels }}
|
||||
platforms: ${{ steps.platforms.outputs.platforms }}
|
||||
cache-from: type=gha,scope=frontend
|
||||
cache-to: type=gha,mode=max,scope=frontend
|
||||
build-args: |
|
||||
CACHEBUST=${{ github.run_number }}
|
||||
BUILD_DATE=${{ github.event.head_commit.timestamp }}
|
||||
VCS_REF=${{ github.sha }}
|
||||
VERSION=${{ steps.meta-frontend.outputs.version }}
|
||||
|
||||
- name: Run Trivy vulnerability scanner
|
||||
if: github.event_name != 'pull_request' && steps.login-ghcr.outcome == 'success'
|
||||
uses: aquasecurity/trivy-action@master
|
||||
with:
|
||||
image-ref: ${{ env.REGISTRY }}/${{ env.FRONTEND_IMAGE_NAME }}:${{ steps.meta-frontend.outputs.version }}
|
||||
format: 'sarif'
|
||||
output: 'trivy-frontend.sarif'
|
||||
severity: 'CRITICAL,HIGH'
|
||||
timeout: '10m'
|
||||
|
||||
- name: Upload Trivy scan results to GitHub Security tab
|
||||
if: github.event_name != 'pull_request' && steps.login-ghcr.outcome == 'success'
|
||||
uses: github/codeql-action/upload-sarif@v4
|
||||
with:
|
||||
sarif_file: 'trivy-frontend.sarif'
|
||||
category: 'frontend-vulnerabilities'
|
||||
|
||||
# Note: The publish-manifest job is not needed since docker/build-push-action@v5
|
||||
# automatically creates multi-arch manifests when building for multiple platforms.
|
||||
# The images are already properly tagged and include all architectures.
|
||||
|
||||
summary:
|
||||
needs: [build-backend, build-frontend]
|
||||
if: always()
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
steps:
|
||||
- name: Build Summary
|
||||
run: |
|
||||
echo "## 🐳 Docker Build Summary" >> $GITHUB_STEP_SUMMARY
|
||||
echo "" >> $GITHUB_STEP_SUMMARY
|
||||
|
||||
if [[ "${{ needs.build-backend.result }}" == "success" ]]; then
|
||||
echo "✅ **Backend**: Successfully built" >> $GITHUB_STEP_SUMMARY
|
||||
else
|
||||
echo "❌ **Backend**: Build failed" >> $GITHUB_STEP_SUMMARY
|
||||
fi
|
||||
|
||||
if [[ "${{ needs.build-frontend.result }}" == "success" ]]; then
|
||||
echo "✅ **Frontend**: Successfully built" >> $GITHUB_STEP_SUMMARY
|
||||
else
|
||||
echo "❌ **Frontend**: Build failed" >> $GITHUB_STEP_SUMMARY
|
||||
fi
|
||||
|
||||
echo "" >> $GITHUB_STEP_SUMMARY
|
||||
echo "### 📦 Images" >> $GITHUB_STEP_SUMMARY
|
||||
echo "- Backend: \`${{ env.REGISTRY }}/${{ env.BACKEND_IMAGE_NAME }}\`" >> $GITHUB_STEP_SUMMARY
|
||||
echo "- Frontend: \`${{ env.REGISTRY }}/${{ env.FRONTEND_IMAGE_NAME }}\`" >> $GITHUB_STEP_SUMMARY
|
||||
|
||||
echo "" >> $GITHUB_STEP_SUMMARY
|
||||
echo "### 🏷️ Tags" >> $GITHUB_STEP_SUMMARY
|
||||
echo "Images are tagged based on:" >> $GITHUB_STEP_SUMMARY
|
||||
echo "- Branch name (for branch pushes)" >> $GITHUB_STEP_SUMMARY
|
||||
echo "- PR number (for pull requests)" >> $GITHUB_STEP_SUMMARY
|
||||
echo "- Version tags (for releases)" >> $GITHUB_STEP_SUMMARY
|
||||
echo "- Short SHA with branch prefix" >> $GITHUB_STEP_SUMMARY
|
||||
echo "- \`latest\` (for main branch)" >> $GITHUB_STEP_SUMMARY
|
||||
@@ -0,0 +1,37 @@
|
||||
name: Release Please (Beta)
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [beta]
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
pull-requests: write
|
||||
|
||||
jobs:
|
||||
release-please:
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
release_created: ${{ steps.release.outputs.release_created }}
|
||||
tag_name: ${{ steps.release.outputs.tag_name }}
|
||||
version: ${{ steps.release.outputs.version }}
|
||||
steps:
|
||||
- name: Run Release Please
|
||||
uses: googleapis/release-please-action@v4
|
||||
id: release
|
||||
with:
|
||||
token: ${{ secrets.GITHUB_TOKEN }}
|
||||
config-file: release-please-config-beta.json
|
||||
manifest-file: .release-please-manifest-beta.json
|
||||
target-branch: beta
|
||||
|
||||
- name: Output Release Info
|
||||
if: ${{ steps.release.outputs.release_created }}
|
||||
run: |
|
||||
echo "## Beta Release Created!" >> $GITHUB_STEP_SUMMARY
|
||||
echo "" >> $GITHUB_STEP_SUMMARY
|
||||
echo "**Tag:** ${{ steps.release.outputs.tag_name }}" >> $GITHUB_STEP_SUMMARY
|
||||
echo "**Version:** ${{ steps.release.outputs.version }}" >> $GITHUB_STEP_SUMMARY
|
||||
echo "" >> $GITHUB_STEP_SUMMARY
|
||||
echo "Docker images will be built and tagged with this beta version." >> $GITHUB_STEP_SUMMARY
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
name: Release Please
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
pull-requests: write
|
||||
|
||||
jobs:
|
||||
release-please:
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
release_created: ${{ steps.release.outputs.release_created }}
|
||||
tag_name: ${{ steps.release.outputs.tag_name }}
|
||||
version: ${{ steps.release.outputs.major }}.${{ steps.release.outputs.minor }}.${{ steps.release.outputs.patch }}
|
||||
steps:
|
||||
- name: Run Release Please
|
||||
uses: googleapis/release-please-action@v4
|
||||
id: release
|
||||
with:
|
||||
token: ${{ secrets.GITHUB_TOKEN }}
|
||||
config-file: release-please-config.json
|
||||
manifest-file: .release-please-manifest.json
|
||||
|
||||
- name: Output Release Info
|
||||
if: ${{ steps.release.outputs.release_created }}
|
||||
run: |
|
||||
echo "## Release Created! " >> $GITHUB_STEP_SUMMARY
|
||||
echo "" >> $GITHUB_STEP_SUMMARY
|
||||
echo "**Tag:** ${{ steps.release.outputs.tag_name }}" >> $GITHUB_STEP_SUMMARY
|
||||
echo "**Version:** ${{ steps.release.outputs.major }}.${{ steps.release.outputs.minor }}.${{ steps.release.outputs.patch }}" >> $GITHUB_STEP_SUMMARY
|
||||
echo "" >> $GITHUB_STEP_SUMMARY
|
||||
echo "Docker images will be built and tagged with this version." >> $GITHUB_STEP_SUMMARY
|
||||
|
||||
+56
-1
@@ -11,6 +11,9 @@ yarn-error.log*
|
||||
.env.test.local
|
||||
.env.production.local
|
||||
|
||||
# Docker override file
|
||||
docker-compose.override.yml
|
||||
|
||||
# Security - Never commit credentials
|
||||
ADMIN_CREDENTIALS.txt
|
||||
ADMIN_PASSWORD_RESET.txt
|
||||
@@ -59,4 +62,56 @@ test-archiver/
|
||||
!data/.gitkeep
|
||||
!logs/.gitkeep
|
||||
|
||||
PRODUCTION_DEPLOYMENT_GUIDE.md
|
||||
# development files
|
||||
backend/.swarm/
|
||||
.claudedocs/
|
||||
backend/data/
|
||||
backend/docs/
|
||||
backend/logs/
|
||||
logs/
|
||||
storage/
|
||||
data/
|
||||
certbot/
|
||||
|
||||
# Ignore local contributor guide copy
|
||||
AGENTS.md
|
||||
CLAUDE.md
|
||||
|
||||
# Working/planning documents (not for release)
|
||||
BUGS_AND_FEATURES.md
|
||||
frontend/TEST_PLAN.md
|
||||
docs/REFACTORING_PLAN.md
|
||||
docs/MULTIPLE_ADMINISTRATORS_PLAN.md
|
||||
docs/*_PLAN.md
|
||||
docs/test-*.md
|
||||
docs/feature-*.md
|
||||
|
||||
# Scaffolding documentation (local development reference)
|
||||
docs/DATABASE_SCHEMA.md
|
||||
docs/BACKEND_SERVICES.md
|
||||
docs/API_ROUTES.md
|
||||
docs/FRONTEND_ARCHITECTURE.md
|
||||
docs/DEVELOPER_ONBOARDING.md
|
||||
docs/ENVIRONMENT_VARIABLES.md
|
||||
|
||||
# Local backup directory (from testing)
|
||||
backup/
|
||||
|
||||
# Local artifacts from browser tooling
|
||||
.playwright-mcp/
|
||||
|
||||
# Local SQLite files in backend
|
||||
backend/*.sqlite*
|
||||
backend/*.db
|
||||
|
||||
# Test files and artifacts
|
||||
test-images/
|
||||
test-logo*.jpg
|
||||
test-logo*.png
|
||||
test-results/
|
||||
|
||||
# Development docker compose
|
||||
docker-compose.dev.yml
|
||||
|
||||
# New layout development files
|
||||
new-layouts/
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
{
|
||||
".": "3.28.3-beta.0"
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
{
|
||||
".": "2.6.1"
|
||||
}
|
||||
@@ -1,152 +0,0 @@
|
||||
# Backup Version Tracking Implementation
|
||||
|
||||
## Overview
|
||||
Version tracking has been added to the backup system to ensure safe restoration by tracking application versions, Node.js versions, and database schema versions at the time of backup.
|
||||
|
||||
## Implementation Details
|
||||
|
||||
### 1. Database Schema Changes (Migration 034)
|
||||
|
||||
Added version tracking columns to backup tables:
|
||||
|
||||
#### `database_backup_runs` table:
|
||||
- `app_version` - Application version from package.json
|
||||
- `node_version` - Node.js runtime version
|
||||
- `db_schema_version` - Latest migration name
|
||||
- `environment_info` - JSON with additional environment details
|
||||
|
||||
#### `backup_runs` table:
|
||||
- `app_version` - Application version
|
||||
- `node_version` - Node.js version
|
||||
- `db_schema_version` - Database schema version
|
||||
- `manifest_info` - Summary of manifest information
|
||||
|
||||
#### New `restore_history` table:
|
||||
Tracks all restore attempts with comprehensive version information:
|
||||
- Backup versions vs current versions
|
||||
- Compatibility check results
|
||||
- Warnings and errors
|
||||
- Restore outcome
|
||||
|
||||
### 2. Version Information Captured
|
||||
|
||||
During each backup, the system now records:
|
||||
- **Application Version**: From `package.json` (e.g., "1.0.77")
|
||||
- **Node.js Version**: Runtime version (e.g., "v18.17.0")
|
||||
- **Database Schema**: Latest migration file (e.g., "034_add_version_to_backups.js")
|
||||
- **Environment Info**: Platform, architecture, environment mode
|
||||
|
||||
### 3. Backup Services Updated
|
||||
|
||||
#### Database Backup Service (`databaseBackup.js`):
|
||||
- Records version info when creating backups
|
||||
- Includes versions in statistics JSON
|
||||
- New method: `checkVersionCompatibility()` for restore safety
|
||||
- New method: `getCurrentSchemaVersion()` to track migrations
|
||||
|
||||
#### File Backup Service (`backupService.js`):
|
||||
- Records version info in backup_runs table
|
||||
- Integrates with manifest system
|
||||
- Stores manifest summary with version details
|
||||
|
||||
### 4. Existing Manifest System
|
||||
|
||||
The `backupManifest.js` already provides comprehensive version tracking:
|
||||
- Application version and Node.js version
|
||||
- System information (OS, platform, architecture)
|
||||
- Database schema version
|
||||
- Detailed file and database metadata
|
||||
|
||||
### 5. Version Compatibility Checking
|
||||
|
||||
When restoring, the system can now:
|
||||
- Compare backup version vs current version
|
||||
- Detect major/minor version differences
|
||||
- Identify schema mismatches
|
||||
- Provide warnings and recommendations
|
||||
|
||||
### 6. Configuration Settings
|
||||
|
||||
New backup settings for version control:
|
||||
- `backup_require_version_match` - Enforce exact version matching
|
||||
- `backup_allow_minor_version_mismatch` - Allow same major version
|
||||
- `backup_warn_on_version_mismatch` - Show warnings on mismatch
|
||||
- `backup_check_schema_compatibility` - Validate schema versions
|
||||
|
||||
## Usage
|
||||
|
||||
### Creating Backups
|
||||
Backups automatically capture version information - no changes needed to existing backup workflows.
|
||||
|
||||
### Checking Version Before Restore
|
||||
|
||||
1. **For Database Backups**:
|
||||
```javascript
|
||||
const compatibility = await databaseBackupService.checkVersionCompatibility({
|
||||
app_version: '1.0.75',
|
||||
node_version: 'v16.14.0',
|
||||
db_schema_version: '032_add_feedback.js'
|
||||
});
|
||||
|
||||
if (!compatibility.compatible) {
|
||||
console.error('Version mismatch:', compatibility.errors);
|
||||
}
|
||||
```
|
||||
|
||||
2. **For File Backups**:
|
||||
Check the manifest file which contains all version information:
|
||||
```bash
|
||||
cat /backup/path/manifest-backup-20250122-123456.json | jq '.application'
|
||||
```
|
||||
|
||||
### Restore History
|
||||
All restore attempts are logged in the `restore_history` table with:
|
||||
- Version compatibility results
|
||||
- Warnings encountered
|
||||
- Success/failure status
|
||||
- Who performed the restore
|
||||
|
||||
## Best Practices
|
||||
|
||||
1. **Always Check Compatibility**: Before restoring, verify version compatibility
|
||||
2. **Document Version Changes**: Keep changelog updated with breaking changes
|
||||
3. **Test Restores**: Regularly test restore procedures in staging
|
||||
4. **Monitor Warnings**: Even if compatible, review warnings before proceeding
|
||||
5. **Keep Backups Organized**: Label backups with version info in filename
|
||||
|
||||
## Migration Instructions
|
||||
|
||||
1. Run the new migration:
|
||||
```bash
|
||||
cd backend
|
||||
npm run migrate
|
||||
```
|
||||
|
||||
2. Existing backups will show "unknown" for version fields
|
||||
3. New backups will automatically include version information
|
||||
4. The system remains backward compatible with old backups
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Version Mismatch Errors
|
||||
- Check current app version: `cat backend/package.json | grep version`
|
||||
- Check Node version: `node --version`
|
||||
- Check latest migration: `SELECT name FROM knex_migrations ORDER BY id DESC LIMIT 1`
|
||||
|
||||
### Restore Failures
|
||||
- Review `restore_history` table for detailed error messages
|
||||
- Check version compatibility warnings
|
||||
- Consider using same version environment for critical restores
|
||||
|
||||
## Future Enhancements
|
||||
|
||||
1. **Automated Version Matching**: Docker containers with specific versions
|
||||
2. **Migration Rollback**: Support for downgrading schema safely
|
||||
3. **Version Matrix**: Compatibility matrix for different version combinations
|
||||
4. **Restore Wizard**: UI for guided restore with compatibility checks
|
||||
|
||||
---
|
||||
|
||||
**Implementation Date**: January 2025
|
||||
**Current Version**: 1.0.77
|
||||
**Status**: Production Ready
|
||||
+1345
File diff suppressed because it is too large
Load Diff
@@ -1,365 +0,0 @@
|
||||
# CLAUDE.md
|
||||
|
||||
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
|
||||
|
||||
## Product Overview
|
||||
|
||||
A secure photo sharing platform designed for weddings and events, enabling photographers to share time-limited, password-protected galleries. The platform features automatic expiration, archiving, and a scrappbook.de-inspired modern, minimalist UI.
|
||||
|
||||
## Architecture Overview
|
||||
|
||||
- **Backend**: Node.js/Express API with SQLite/PostgreSQL, file-based photo storage
|
||||
- **Frontend**: React SPA with scrappbook.de-style design (requires implementation)
|
||||
- **Storage**: File-based with active/archived separation
|
||||
- **Services**: Background workers for email, archiving, file watching, and expiration monitoring
|
||||
- **Analytics**: Umami integration for engagement tracking
|
||||
|
||||
## Essential Commands
|
||||
|
||||
### Backend Development
|
||||
```bash
|
||||
cd backend
|
||||
npm install # Install dependencies
|
||||
npm run migrate # Initialize database schema
|
||||
npm run dev # Start with hot-reload (port 3001)
|
||||
npm test # Run Jest tests
|
||||
npm run lint # ESLint checks
|
||||
```
|
||||
|
||||
### Running a Single Test
|
||||
```bash
|
||||
cd backend
|
||||
npm test -- path/to/test.test.js
|
||||
npm test -- --testNamePattern="test name"
|
||||
```
|
||||
|
||||
### Production
|
||||
```bash
|
||||
docker-compose -f docker-compose.prod.yml up -d # Production deployment
|
||||
pm2 start ecosystem.config.js # Alternative: PM2 deployment
|
||||
```
|
||||
|
||||
**⚠️ CRITICAL PRODUCTION NOTICE:**
|
||||
- Production runs on a SEPARATE SERVER - never assume local changes affect production
|
||||
- ALWAYS request production server details before any troubleshooting
|
||||
- NO trial-and-error approaches in production - data loss is unacceptable
|
||||
- Every change must be thoroughly analyzed and tested locally first
|
||||
|
||||
## Key Product Requirements (from PRD)
|
||||
|
||||
### Core Features
|
||||
1. **File-Based System**: Drop photos in folders → automatic gallery creation
|
||||
2. **Automatic Expiration**: Default 30 days, with 7-day warning emails
|
||||
3. **Password Protection**: Secure access with customizable passwords
|
||||
4. **Automatic Archiving**: ZIP compression and storage after expiration
|
||||
5. **Email Notifications**: Creation, warning, and expiration notifications
|
||||
6. **Analytics**: Umami tracking for views, downloads, and engagement
|
||||
|
||||
### Folder Structure
|
||||
```
|
||||
/events/
|
||||
├── active/
|
||||
│ ├── wedding-smith-jones-2024-06-15/
|
||||
│ │ ├── collages/
|
||||
│ │ └── individual/
|
||||
│ └── birthday-emma-2024-07-20/
|
||||
└── archived/
|
||||
└── wedding-smith-jones-2024-06-15.zip
|
||||
```
|
||||
|
||||
## Frontend Implementation Requirements
|
||||
|
||||
### Design Style (scrappbook.de-inspired)
|
||||
- **Color Palette**: Primary green (#5C8762), neutral backgrounds
|
||||
- **Typography**: Clean, modern sans-serif (Noto Sans or similar)
|
||||
- **Layout**: Minimalist, modular sections with grid-based photo displays
|
||||
- **Aesthetic**: Professional yet approachable, photographer-focused
|
||||
|
||||
### Key Frontend Components to Build
|
||||
1. **Landing Page**: Password entry with event preview
|
||||
2. **Gallery View**:
|
||||
- Responsive photo grid with lazy loading
|
||||
- Toggle between collages/individual photos
|
||||
- Prominent expiration banner
|
||||
- Download urgency indicators
|
||||
3. **Photo Lightbox**: Full-screen viewing with zoom
|
||||
4. **Mobile-First**: Responsive design with touch gestures
|
||||
5. **Personalization**: Dynamic theming per event type
|
||||
|
||||
### User Experience Priorities
|
||||
- Clear expiration warnings (sticky banner)
|
||||
- One-click "Download All" for urgent galleries
|
||||
- Smooth image loading with skeleton screens
|
||||
- Intuitive navigation between photo categories
|
||||
- Professional presentation matching photographer branding
|
||||
|
||||
## Key Architecture Patterns
|
||||
|
||||
### Authentication Flow
|
||||
- JWT-based with separate tokens for admin and gallery access
|
||||
- Gallery tokens include event-specific claims
|
||||
- Auth middleware: `backend/src/middleware/auth.js`
|
||||
- `adminAuth` - Admin panel protection
|
||||
- `photoAuth` - Protected photo access
|
||||
- `verifyGalleryAccess` - Gallery-specific validation
|
||||
|
||||
### Database Schema (Knex/SQLite)
|
||||
Main tables:
|
||||
- `events` - Gallery metadata with expiration, custom messages, themes
|
||||
- `photos` - Photo records linked to events
|
||||
- `access_logs` - IP-based usage tracking
|
||||
- `email_queue` - Async email processing
|
||||
- `admin_users` - Admin authentication
|
||||
|
||||
### Service Architecture
|
||||
Background services run as separate processes:
|
||||
- **emailService**: Processes email queue with retry logic
|
||||
- **archiveService**: Creates ZIP archives of expired events
|
||||
- **expirationChecker**: Cron job for expiration warnings
|
||||
- **fileWatcher**: Monitors for new photo uploads
|
||||
- **backupService**: Scheduled backups with checksum-based change detection
|
||||
|
||||
### API Structure
|
||||
- `/api/admin/*` - Admin panel endpoints (requires adminAuth)
|
||||
- `/api/gallery/*` - Public gallery endpoints
|
||||
- `/api/auth/*` - Authentication endpoints
|
||||
- Rate limiting: 100 req/15min (general), 5 req/15min (auth)
|
||||
|
||||
## Critical Implementation Notes
|
||||
|
||||
1. **Security**: All gallery access requires valid JWT with event-specific claims
|
||||
2. **Expiration**: Events auto-expire based on `expires_at`, with 7-day email warnings
|
||||
3. **Email Queue**: Async processing with retry logic, check `email_queue` table
|
||||
4. **File Processing**: Sharp library for thumbnail generation (300x300)
|
||||
5. **Frontend Status**: Only skeleton exists - requires full implementation based on PRD
|
||||
6. **Umami Analytics**: Track password entries, downloads, views, expiration warnings
|
||||
|
||||
## Troubleshooting Guidelines
|
||||
|
||||
### Before ANY Production Troubleshooting:
|
||||
1. **ALWAYS request specific details**:
|
||||
- Production server URL/IP
|
||||
- Current error messages/logs
|
||||
- Recent changes or deployments
|
||||
- Affected users/galleries
|
||||
- Time of issue occurrence
|
||||
|
||||
2. **Thorough Analysis Required**:
|
||||
- Use detailed thinking/analysis for EVERY troubleshooting task
|
||||
- Review all related code before suggesting changes
|
||||
- Consider all potential side effects
|
||||
- Never make assumptions about production environment
|
||||
|
||||
3. **Safe Troubleshooting Steps**:
|
||||
- First, reproduce issue in local/dev environment
|
||||
- Analyze logs without modifying production
|
||||
- Create detailed action plan before any changes
|
||||
- Always have rollback strategy ready
|
||||
- Document every step taken
|
||||
|
||||
### Common Issues & Safe Approaches:
|
||||
- **Email not sending**: Check email_queue table, SMTP settings, service status
|
||||
- **Photos not loading**: Verify file permissions, storage paths, nginx config
|
||||
- **Gallery access issues**: Check JWT tokens, expiration dates, access_logs
|
||||
- **Performance problems**: Analyze with monitoring tools first, never experiment
|
||||
|
||||
### Data Safety Rules:
|
||||
- NEVER delete or modify production data without explicit backup confirmation
|
||||
- ALWAYS verify backups exist before any data operations
|
||||
- NO direct database modifications without transaction safety
|
||||
- Log all actions for audit trail
|
||||
|
||||
## Environment Variables
|
||||
|
||||
### Backend (.env)
|
||||
- `JWT_SECRET` - Token signing
|
||||
- `ADMIN_URL`, `FRONTEND_URL` - CORS origins
|
||||
- `SMTP_*` - Email configuration
|
||||
- `DB_*` - PostgreSQL credentials (production)
|
||||
- `UMAMI_URL` - Umami instance URL (for server-side tracking)
|
||||
- `UMAMI_WEBSITE_ID` - Website ID from Umami
|
||||
|
||||
### Frontend (.env)
|
||||
- `VITE_API_URL` - Backend API URL
|
||||
- `VITE_UMAMI_URL` - Umami analytics URL
|
||||
- `VITE_UMAMI_WEBSITE_ID` - Website ID from Umami
|
||||
- `VITE_UMAMI_SHARE_URL` - (Optional) Public share URL for embedded dashboard
|
||||
|
||||
## Testing Approach
|
||||
- Jest with Supertest for API testing
|
||||
- Test files in `__tests__` directories
|
||||
- Database migrations run before tests
|
||||
- Mock email sending in tests
|
||||
|
||||
## Umami Analytics Integration
|
||||
|
||||
The frontend includes comprehensive Umami analytics integration for tracking user behavior and gallery performance.
|
||||
|
||||
### Tracked Events:
|
||||
- **Gallery Events**:
|
||||
- `gallery_password_entry` - Password attempts (success/failure)
|
||||
- `gallery_photo_view` - Individual photo views
|
||||
- `gallery_photo_download` - Single photo downloads
|
||||
- `gallery_bulk_download` - Bulk/all photo downloads
|
||||
- `gallery_expired` - Expired gallery access attempts
|
||||
- **Admin Events**:
|
||||
- `admin_login` - Admin authentication
|
||||
- `admin_event_created` - New event creation
|
||||
- `admin_event_archived` - Event archiving
|
||||
- `admin_event_deleted` - Event deletion
|
||||
- `admin_settings_updated` - Settings changes
|
||||
- **User Behavior**:
|
||||
- Search queries (with debouncing)
|
||||
- Expiration warning views
|
||||
- Page views with automatic tracking
|
||||
|
||||
### Setup:
|
||||
1. Install Umami (self-hosted or cloud)
|
||||
2. Create a website in Umami dashboard
|
||||
3. Set environment variables:
|
||||
```
|
||||
VITE_UMAMI_URL=https://your-umami-instance.com
|
||||
VITE_UMAMI_WEBSITE_ID=your-website-id
|
||||
VITE_UMAMI_SHARE_URL=https://your-umami-instance.com/share/...
|
||||
```
|
||||
|
||||
### Analytics Dashboard:
|
||||
- Admin panel includes analytics page at `/admin/analytics`
|
||||
- Summary view with key metrics
|
||||
- Option to embed full Umami dashboard
|
||||
- Real-time event tracking
|
||||
|
||||
## Accessibility & Performance Features
|
||||
|
||||
### Accessibility (WCAG 2.1 AA Compliance)
|
||||
- **Error Boundaries**: Graceful error handling with recovery options
|
||||
- **Skip Links**: Skip to main content for keyboard navigation
|
||||
- **ARIA Labels**: Proper labeling for screen readers
|
||||
- **Focus Management**: Focus trap in modals, visible focus indicators
|
||||
- **Keyboard Navigation**: Full keyboard support in gallery lightbox (arrows, escape, +/-, d for download)
|
||||
- **Loading States**: Skeleton screens instead of spinners for better UX
|
||||
- **Offline Support**: Visual indicator when offline
|
||||
- **Form Validation**: Accessible error messages with aria-describedby
|
||||
|
||||
### Performance Optimizations
|
||||
- **Lazy Loading**: Images load on scroll with Intersection Observer
|
||||
- **Skeleton Screens**: Instant visual feedback during loading
|
||||
- **Error Recovery**: Component-level error boundaries prevent full page crashes
|
||||
- **Optimistic Updates**: Immediate UI updates with background sync
|
||||
- **Debounced Search**: Prevents excessive API calls
|
||||
- **Analytics**: Non-blocking Umami integration
|
||||
|
||||
### Component Library Enhancements
|
||||
- `<ErrorBoundary>` - Catches and displays errors gracefully
|
||||
- `<PageErrorBoundary>` - Full-page error recovery
|
||||
- `<Skeleton>` - Flexible skeleton loader with variants
|
||||
- `<OfflineIndicator>` - Network status monitoring
|
||||
- `<SkipLink>` - Accessibility navigation
|
||||
- `useFocusTrap` - Modal focus management hook
|
||||
- `useOnlineStatus` - Network status hook
|
||||
|
||||
## Theme System & Branding
|
||||
|
||||
### Theme Features
|
||||
- **Dynamic Theming**: CSS variables for runtime theme switching
|
||||
- **Preset Themes**: Default, Wedding, Birthday, Corporate, Minimal
|
||||
- **Customization Options**:
|
||||
- Primary/Accent/Background/Text colors
|
||||
- Font family selection
|
||||
- Border radius (none, sm, md, lg)
|
||||
- Custom logo upload
|
||||
- Custom CSS injection
|
||||
- **Event-Specific Themes**: Override global theme per gallery
|
||||
- **Live Preview**: Real-time theme changes in admin panel
|
||||
|
||||
### Theme Context API
|
||||
```typescript
|
||||
const { theme, setTheme, setThemeByName } = useTheme();
|
||||
```
|
||||
|
||||
### Branding Settings
|
||||
- Company name, tagline, and support email
|
||||
- Custom footer text
|
||||
- Optional watermarking on downloads
|
||||
- Logo upload for gallery header
|
||||
|
||||
### CSS Variables
|
||||
```css
|
||||
--color-primary: #5C8762;
|
||||
--color-primary-light: #7aa583;
|
||||
--color-primary-dark: #4a6f4f;
|
||||
--color-accent: #22c55e;
|
||||
--color-background: #fafafa;
|
||||
--color-text: #171717;
|
||||
--font-family: 'Inter', sans-serif;
|
||||
--border-radius: 0.5rem;
|
||||
```
|
||||
|
||||
## Backup Service
|
||||
|
||||
### Overview
|
||||
The backup service provides automated, scheduled backups of all photo data with checksum-based change detection to minimize transfer overhead.
|
||||
|
||||
### Features
|
||||
- **Multiple Destinations**: Local directory, remote server (rsync), S3-compatible storage
|
||||
- **Change Detection**: SHA256 checksums track file changes, only modified files are backed up
|
||||
- **Scheduled Execution**: Configurable cron-based scheduling (default: 2 AM daily)
|
||||
- **Email Notifications**: Alerts on backup failure, optional success notifications
|
||||
- **Retention Management**: Automatic cleanup of old backup runs based on retention policy
|
||||
- **Progress Tracking**: Database storage of backup history, file states, and statistics
|
||||
|
||||
### Configuration
|
||||
Backup settings are stored in `app_settings` table with `backup_` prefix:
|
||||
- `backup_enabled`: Enable/disable the service
|
||||
- `backup_schedule`: Cron expression (e.g., '0 2 * * *')
|
||||
- `backup_destination_type`: 'local', 'rsync', or 's3'
|
||||
- `backup_retention_days`: How long to keep backup history
|
||||
- `backup_include_archived`: Whether to backup archived events
|
||||
- `backup_exclude_patterns`: File patterns to exclude
|
||||
|
||||
### API Endpoints
|
||||
- `GET /api/admin/backup/config` - Get current configuration
|
||||
- `PUT /api/admin/backup/config` - Update configuration
|
||||
- `GET /api/admin/backup/status` - Get backup status and history
|
||||
- `POST /api/admin/backup/run` - Trigger manual backup
|
||||
- `POST /api/admin/backup/test-connection` - Test destination connectivity
|
||||
|
||||
### Testing
|
||||
Run backup service test: `npm run test-backup`
|
||||
|
||||
### Database Tables
|
||||
- `backup_runs`: Tracks each backup execution with statistics
|
||||
- `backup_file_states`: Stores file checksums for change detection
|
||||
|
||||
## Success Metrics (from PRD)
|
||||
- Time to generate gallery: <2 minutes
|
||||
- Guest satisfaction: >90%
|
||||
- System uptime: 99.9%
|
||||
- Email delivery rate: >98%
|
||||
- Successful archiving: 100%
|
||||
|
||||
## Documentation & Development Practices
|
||||
|
||||
### Documentation Guidelines:
|
||||
- **NEVER create new documentation files for simple tasks**
|
||||
- **ALWAYS update existing documentation (like this CLAUDE.md)**
|
||||
- Only create new .md files when explicitly requested
|
||||
- Avoid creating temporary scripts for one-off tasks
|
||||
|
||||
### Development Best Practices:
|
||||
- Test all changes thoroughly in local environment first
|
||||
- Use version control for all changes
|
||||
- Keep commits atomic and well-described
|
||||
- Review impact on all integrated services
|
||||
- Consider backward compatibility
|
||||
- Update tests when changing functionality
|
||||
|
||||
### Production Deployment Checklist:
|
||||
- [ ] All tests passing locally
|
||||
- [ ] Linting and type checks pass
|
||||
- [ ] Database migrations tested with rollback plan
|
||||
- [ ] Environment variables documented
|
||||
- [ ] Backup strategy confirmed
|
||||
- [ ] Monitoring alerts configured
|
||||
- [ ] Rollback procedure documented
|
||||
- [ ] Stakeholders notified of maintenance window
|
||||
+1
-1
@@ -20,7 +20,7 @@ We are committed to providing a welcoming and inspiring community for all photog
|
||||
|
||||
## Enforcement
|
||||
|
||||
Instances of unacceptable behavior may be reported to the project team at conduct@example.com. All complaints will be reviewed and investigated promptly and fairly.
|
||||
Instances of unacceptable behavior may be reported by [opening an issue](https://github.com/the-luap/picpeak/issues/new?labels=conduct) on GitHub. All complaints will be reviewed and investigated promptly and fairly.
|
||||
|
||||
## Attribution
|
||||
|
||||
|
||||
+3
-3
@@ -153,8 +153,8 @@ picpeak/
|
||||
|
||||
## 📮 Contact
|
||||
|
||||
- Create an issue for bugs or features
|
||||
- Join discussions for questions
|
||||
- Email: picpeak@example.com for security issues
|
||||
- Create an [issue](https://github.com/the-luap/picpeak/issues) for bugs or features
|
||||
- Join [discussions](https://github.com/the-luap/picpeak/discussions) for questions
|
||||
- Security issues: Open a [security issue](https://github.com/the-luap/picpeak/issues/new?labels=security) on GitHub
|
||||
|
||||
Thank you for contributing! 🎉
|
||||
-220
@@ -1,220 +0,0 @@
|
||||
# 🚀 PicPeak Deployment Guide
|
||||
|
||||
This guide will help you deploy PicPeak in production. The entire process takes about 10-15 minutes.
|
||||
|
||||
## 📋 Prerequisites
|
||||
|
||||
- A server with Docker and Docker Compose installed
|
||||
- A domain name (for SSL certificates)
|
||||
- SMTP credentials for sending emails
|
||||
- Basic command line knowledge
|
||||
|
||||
## 🏃 Quick Deploy (Recommended)
|
||||
|
||||
### 1. Clone and Configure
|
||||
|
||||
```bash
|
||||
# Clone the repository
|
||||
git clone https://github.com/the-luap/picpeak.git
|
||||
cd picpeak
|
||||
|
||||
# Copy environment template
|
||||
cp .env.production.example .env
|
||||
|
||||
# Generate a secure JWT secret
|
||||
echo "JWT_SECRET=$(openssl rand -base64 32)" >> .env
|
||||
|
||||
# Edit configuration
|
||||
nano .env
|
||||
```
|
||||
|
||||
### 2. Required Environment Variables
|
||||
|
||||
Edit your `.env` file with these essential settings:
|
||||
|
||||
```env
|
||||
# Application URLs
|
||||
FRONTEND_URL=https://your-domain.com
|
||||
BACKEND_URL=https://your-domain.com
|
||||
|
||||
# Email Configuration (Required for notifications)
|
||||
SMTP_HOST=smtp.gmail.com
|
||||
SMTP_PORT=587
|
||||
SMTP_USER=your-email@gmail.com
|
||||
SMTP_PASS=your-app-password
|
||||
SMTP_FROM=your-email@gmail.com
|
||||
|
||||
# Admin Configuration
|
||||
ADMIN_EMAIL=admin@your-domain.com
|
||||
ADMIN_PASSWORD=your-secure-password
|
||||
|
||||
# Database (PostgreSQL for production)
|
||||
DATABASE_CLIENT=pg
|
||||
DB_HOST=postgres
|
||||
DB_NAME=picpeak
|
||||
DB_USER=picpeak
|
||||
DB_PASSWORD=secure-db-password
|
||||
```
|
||||
|
||||
### 3. Deploy with Docker Compose
|
||||
|
||||
```bash
|
||||
# Start all services
|
||||
docker-compose -f docker-compose.prod.yml up -d
|
||||
|
||||
# Check logs
|
||||
docker-compose logs -f
|
||||
|
||||
# Access your site at https://your-domain.com
|
||||
```
|
||||
|
||||
## 🔧 Configuration Options
|
||||
|
||||
### Storage Settings
|
||||
|
||||
```env
|
||||
# Storage paths (default: ./storage)
|
||||
STORAGE_PATH=./storage
|
||||
ARCHIVE_PATH=./storage/archives
|
||||
|
||||
# Gallery expiration (days)
|
||||
DEFAULT_EXPIRATION_DAYS=30
|
||||
WARNING_DAYS_BEFORE_EXPIRY=7
|
||||
```
|
||||
|
||||
### Security Settings
|
||||
|
||||
```env
|
||||
# Session timeout (minutes)
|
||||
SESSION_TIMEOUT=60
|
||||
|
||||
# Rate limiting
|
||||
RATE_LIMIT_WINDOW_MS=900000 # 15 minutes
|
||||
RATE_LIMIT_MAX_REQUESTS=100
|
||||
```
|
||||
|
||||
### Analytics (Optional)
|
||||
|
||||
```env
|
||||
# Umami Analytics
|
||||
VITE_UMAMI_URL=https://analytics.your-domain.com
|
||||
VITE_UMAMI_WEBSITE_ID=your-website-id
|
||||
```
|
||||
|
||||
## 🔒 SSL/TLS Setup
|
||||
|
||||
The production Docker Compose includes automatic SSL via Let's Encrypt:
|
||||
|
||||
1. **Ensure your domain points to your server**
|
||||
2. **Update nginx configuration**:
|
||||
```bash
|
||||
nano nginx/nginx.conf
|
||||
# Replace your-domain.com with your actual domain
|
||||
```
|
||||
3. **Start services** - Certbot will automatically obtain certificates
|
||||
|
||||
## 📁 Directory Structure
|
||||
|
||||
After deployment, your directory structure will be:
|
||||
|
||||
```
|
||||
picpeak/
|
||||
├── backend/ # API server
|
||||
├── frontend/ # React app
|
||||
├── storage/ # Photo storage
|
||||
│ ├── events/ # Active galleries
|
||||
│ │ ├── active/ # Current photos
|
||||
│ │ └── archived/ # Expired galleries
|
||||
│ ├── thumbnails/ # Generated thumbnails
|
||||
│ └── uploads/ # User uploads
|
||||
├── data/ # Database files
|
||||
└── logs/ # Application logs
|
||||
```
|
||||
|
||||
## 🔄 Maintenance
|
||||
|
||||
### Backup
|
||||
|
||||
```bash
|
||||
# Backup database and photos
|
||||
./scripts/backup.sh
|
||||
|
||||
# Backups are stored in ./backups/
|
||||
```
|
||||
|
||||
### Update
|
||||
|
||||
```bash
|
||||
# Pull latest changes
|
||||
git pull
|
||||
|
||||
# Rebuild and restart
|
||||
docker-compose -f docker-compose.prod.yml up -d --build
|
||||
```
|
||||
|
||||
### Logs
|
||||
|
||||
```bash
|
||||
# View all logs
|
||||
docker-compose logs
|
||||
|
||||
# View specific service
|
||||
docker-compose logs backend
|
||||
docker-compose logs frontend
|
||||
```
|
||||
|
||||
## 🚨 Troubleshooting
|
||||
|
||||
### Common Issues
|
||||
|
||||
**Photos not appearing:**
|
||||
- Check storage permissions: `chmod -R 755 storage/`
|
||||
- Verify file watcher is running: `docker-compose logs backend | grep watcher`
|
||||
|
||||
**Email not sending:**
|
||||
- Test SMTP settings: Admin Panel → Settings → Email → Send Test
|
||||
- Check email queue: Admin Panel → System → Email Queue
|
||||
|
||||
**Can't access admin panel:**
|
||||
- Default login: Use email/password from `.env`
|
||||
- Reset password: `docker exec picpeak-backend npm run reset-admin`
|
||||
|
||||
### Health Check
|
||||
|
||||
```bash
|
||||
# Check service status
|
||||
docker-compose ps
|
||||
|
||||
# Test backend API
|
||||
curl https://your-domain.com/api/health
|
||||
|
||||
# Check disk space
|
||||
df -h storage/
|
||||
```
|
||||
|
||||
## 🐳 Alternative Deployment Methods
|
||||
|
||||
### Using Docker Swarm
|
||||
|
||||
For high availability deployments, see [Docker Swarm Setup](deploy/README.md).
|
||||
|
||||
### Manual Installation
|
||||
|
||||
If you prefer not to use Docker:
|
||||
|
||||
1. Install Node.js 18+
|
||||
2. Install PostgreSQL
|
||||
3. Clone repository
|
||||
4. Install dependencies: `npm install` in both `/backend` and `/frontend`
|
||||
5. Build frontend: `cd frontend && npm run build`
|
||||
6. Start services with PM2
|
||||
|
||||
## 📞 Support
|
||||
|
||||
- 📘 [Documentation](https://github.com/the-luap/picpeak)
|
||||
- 🐛 [Report Issues](https://github.com/the-luap/picpeak/issues)
|
||||
- 💬 [Discussions](https://github.com/the-luap/picpeak/discussions)
|
||||
|
||||
---
|
||||
|
||||
**Need help?** Open an issue on GitHub and we'll assist you!
|
||||
@@ -0,0 +1,799 @@
|
||||
# 🚀 PicPeak Deployment Guide
|
||||
|
||||
This guide covers multiple deployment options for PicPeak, from simple local setups to production-ready configurations.
|
||||
|
||||
## 📋 Table of Contents
|
||||
|
||||
- [Quick Start](#-quick-start)
|
||||
- [Prerequisites](#prerequisites)
|
||||
- [Configuration](#-configuration)
|
||||
- [Deployment](#-deployment)
|
||||
- [First Login](#-first-login)
|
||||
- [Release Channels](#-release-channels)
|
||||
- [Reverse Proxy Setup](#-reverse-proxy-setup)
|
||||
- [External Media Library](#external-media-library)
|
||||
- [Maintenance](#-maintenance)
|
||||
- [Troubleshooting](#-troubleshooting)
|
||||
|
||||
## 🚀 Quick Start
|
||||
|
||||
### Option 1: Automated Setup Script (Easiest)
|
||||
|
||||
For the simplest installation, use our unified setup script:
|
||||
|
||||
```bash
|
||||
curl -fsSL https://raw.githubusercontent.com/the-luap/picpeak/main/scripts/picpeak-setup.sh -o picpeak-setup.sh && \
|
||||
chmod +x picpeak-setup.sh && \
|
||||
sudo ./picpeak-setup.sh
|
||||
```
|
||||
|
||||
This script handles Docker/Native installation choice, OS detection, dependencies, database setup, and optional SSL.
|
||||
|
||||
👉 **See [SIMPLE_SETUP.md](./SIMPLE_SETUP.md) for detailed instructions.**
|
||||
|
||||
### Option 2: Docker with Pre-built Images (Recommended)
|
||||
|
||||
```bash
|
||||
# Clone repository for configuration files
|
||||
git clone https://github.com/the-luap/picpeak.git
|
||||
cd picpeak
|
||||
|
||||
# Copy and configure environment
|
||||
cp .env.example .env
|
||||
nano .env # Edit with your values
|
||||
|
||||
# Create required directories
|
||||
mkdir -p events/active events/archived data logs backup storage
|
||||
chmod -R 755 events data logs backup storage
|
||||
|
||||
# Deploy using pre-built images
|
||||
docker compose -f docker-compose.production.yml up -d
|
||||
|
||||
# Check logs
|
||||
docker compose -f docker-compose.production.yml logs -f
|
||||
```
|
||||
|
||||
**Available image tags:**
|
||||
| Channel | Tags | Description |
|
||||
|---------|------|-------------|
|
||||
| Stable | `stable`, `latest`, `v2.3.0` | Production-ready releases |
|
||||
| Beta | `beta`, `v2.3.0-beta.1` | Early access to new features |
|
||||
| Branch | `main`, `beta` | Latest from each branch |
|
||||
|
||||
To select a channel, set `PICPEAK_CHANNEL` in your `.env` file (see [Release Channels](#release-channels) section)
|
||||
|
||||
### Option 3: Build from Source
|
||||
|
||||
```bash
|
||||
git clone https://github.com/the-luap/picpeak.git
|
||||
cd picpeak
|
||||
cp .env.example .env
|
||||
nano .env # Edit with your values
|
||||
|
||||
mkdir -p events/active events/archived data logs backup storage
|
||||
chmod -R 755 events data logs backup storage
|
||||
|
||||
docker compose build
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- Docker and Docker Compose installed
|
||||
- Domain name (for production)
|
||||
- SMTP server credentials for emails
|
||||
- At least 2GB RAM and 20GB storage
|
||||
|
||||
## 🔧 Configuration
|
||||
|
||||
### Essential Environment Variables
|
||||
|
||||
Generate secure values:
|
||||
```bash
|
||||
# JWT Secret
|
||||
openssl rand -base64 64
|
||||
|
||||
# Database Password (avoid $ character - see warning below)
|
||||
openssl rand -base64 32 | tr -d '$'
|
||||
|
||||
# Redis Password (avoid $ character - see warning below)
|
||||
openssl rand -base64 32 | tr -d '$'
|
||||
```
|
||||
|
||||
⚠️ **PASSWORD WARNING**: Docker Compose interprets `$` as variable substitution. Either:
|
||||
- Avoid `$` in passwords (recommended - use the commands above)
|
||||
- Escape `$` as `$$` (e.g., `Pass$$word` instead of `Pass$word`)
|
||||
- Quote the entire value: `DB_PASSWORD='Pass$word'` (less reliable)
|
||||
|
||||
### Public Landing Page
|
||||
|
||||
- `npm run migrate` now seeds three general settings: `general_public_site_enabled`, `general_public_site_html`, and `general_public_site_custom_css` so existing installs stay disabled by default.
|
||||
- Configure the feature from **Admin → CMS Pages**. The landing page panel exposes the toggle, HTML editor, optional CSS overrides, preview, and a reset-to-default action.
|
||||
- All HTML and CSS submitted through the UI is sanitized server-side. Scripts, inline event handlers, disallowed attributes, `@import` rules, and `javascript:` URLs are stripped before content is cached or rendered.
|
||||
- Resetting via the UI (or calling `POST /api/admin/settings/public-site/reset`) restores the bundled template and clears custom CSS.
|
||||
- The landing page response is cached in-memory. Override the default 60s cache window by setting `PUBLIC_SITE_CACHE_TTL_MS` (milliseconds) in your environment if you need faster cache busting.
|
||||
- When the toggle is off PicPeak continues to serve the SPA/login redirect at `/`, preserving legacy behaviour until you explicitly enable the feature.
|
||||
|
||||
### Backend Configuration (.env)
|
||||
Update `.env` with:
|
||||
- `JWT_SECRET` - Authentication secret (REQUIRED - generate a secure random value)
|
||||
- `DB_PASSWORD` - PostgreSQL password
|
||||
- `REDIS_PASSWORD` - Redis password
|
||||
- `SMTP_*` - Email configuration
|
||||
- **URL Configuration** (for backend CORS):
|
||||
- `FRONTEND_URL` - Frontend origin (use full URL with scheme, no trailing slash)
|
||||
- Example (Docker): `http://localhost:3000`
|
||||
- `ADMIN_URL` - Admin origin (same as `FRONTEND_URL` for Docker; full URL, no trailing slash)
|
||||
- Example (Docker): `http://localhost:3000`
|
||||
|
||||
Notes:
|
||||
- Do not include trailing `/` (e.g., use `http://host:3000`, not `http://host:3000/`).
|
||||
- Always include the scheme (`http://` or `https://`).
|
||||
- The backend compares origins strictly for CORS; malformed values will cause login requests to fail with 500.
|
||||
|
||||
#### Authentication Security
|
||||
- Configure login attempt thresholds from **Admin → Settings → Security**. Defaults are 5 failed attempts per IP within 15 minutes, resulting in a 30 minute lockout.
|
||||
|
||||
#### External Database Example
|
||||
To use an external PostgreSQL instead of the bundled container, set the following in `.env` and ensure the `postgres` service is disabled or removed:
|
||||
|
||||
```env
|
||||
DB_HOST=db.example.com
|
||||
DB_PORT=5432
|
||||
DB_USER=picpeak
|
||||
DB_PASSWORD=change_me
|
||||
DB_NAME=picpeak_prod
|
||||
```
|
||||
|
||||
Compose uses these values via `env_file: .env`. The backend service also defaults `DB_HOST=${DB_HOST:-postgres}` so if you don’t set `DB_HOST` it will use the bundled `postgres` container.
|
||||
|
||||
### Frontend Configuration (frontend/.env)
|
||||
Create `frontend/.env` from `frontend/.env.example`:
|
||||
```bash
|
||||
cp frontend/.env.example frontend/.env
|
||||
```
|
||||
|
||||
Update `frontend/.env` with:
|
||||
- `VITE_API_URL` - Backend API URL
|
||||
- Docker (pre-built images) and production behind reverse proxy: `/api` (recommended; avoids CORS and matches the frontend Nginx proxy in the image)
|
||||
- Local dev (Vite): `http://localhost:3001` or `/api` if proxying through a dev proxy
|
||||
|
||||
Note: When using pre-built frontend images, runtime container env does not change the already-built JS. Prefer the default `/api` and let the frontend Nginx proxy forward to the backend.
|
||||
|
||||
⚠️ **IMPORTANT PORT CONFIGURATION**:
|
||||
- The frontend runs on port **3000** in Docker (exposed via nginx)
|
||||
- The backend API runs on port **3001**
|
||||
- The frontend `.env` file MUST point to the correct backend port (3001)
|
||||
- Default `.env.example` is configured for Docker deployment
|
||||
|
||||
### Email Configuration Examples
|
||||
|
||||
#### Gmail
|
||||
```env
|
||||
SMTP_HOST=smtp.gmail.com
|
||||
SMTP_PORT=587
|
||||
SMTP_SECURE=false
|
||||
SMTP_USER=your-email@gmail.com
|
||||
SMTP_PASS=your-app-specific-password
|
||||
```
|
||||
|
||||
#### SendGrid
|
||||
```env
|
||||
SMTP_HOST=smtp.sendgrid.net
|
||||
SMTP_PORT=587
|
||||
SMTP_SECURE=false
|
||||
SMTP_USER=apikey
|
||||
SMTP_PASS=your-sendgrid-api-key
|
||||
```
|
||||
|
||||
## 📦 Deployment
|
||||
|
||||
### Using Pre-built Images (Fastest)
|
||||
|
||||
```bash
|
||||
# Pull latest images from GitHub Container Registry
|
||||
docker pull ghcr.io/the-luap/picpeak/backend:latest
|
||||
docker pull ghcr.io/the-luap/picpeak/frontend:latest
|
||||
|
||||
# Start services using production compose file
|
||||
docker compose -f docker-compose.production.yml up -d
|
||||
|
||||
# View running containers
|
||||
docker compose ps
|
||||
```
|
||||
|
||||
### Building from Source (For Customization)
|
||||
|
||||
```bash
|
||||
# Build images locally
|
||||
docker compose build
|
||||
|
||||
# Or build with no cache for clean build
|
||||
docker compose build --no-cache
|
||||
|
||||
# Start all services
|
||||
docker compose up -d
|
||||
|
||||
# View running containers
|
||||
docker compose ps
|
||||
```
|
||||
|
||||
### Access Points
|
||||
|
||||
By default, services are exposed on:
|
||||
- Frontend (UI + Admin): http://localhost:3000 (admin at `/admin`)
|
||||
- Backend/API: http://localhost:3001 (API only; no UI routes)
|
||||
- PostgreSQL: localhost:5432 (if needed)
|
||||
- Redis: localhost:6379 (if needed)
|
||||
|
||||
### Initial Admin Setup
|
||||
|
||||
When deploying for the first time, an admin account is automatically created with a secure, randomly generated password. This password is displayed in the Docker logs during initialization and **must be changed** on first login.
|
||||
|
||||
#### Finding the Auto-Generated Admin Password
|
||||
|
||||
The admin password is automatically generated during the first startup and displayed in the backend container logs. Here's how to find it:
|
||||
|
||||
**Option 1: Search Docker logs for admin password** (recommended)
|
||||
```bash
|
||||
# Find the auto-generated admin password in logs
|
||||
docker compose logs backend | grep "Admin password"
|
||||
```
|
||||
|
||||
You should see output like:
|
||||
```
|
||||
✅ Admin password generated: BraveTiger6231!
|
||||
```
|
||||
|
||||
**Option 2: View the complete initialization logs**
|
||||
```bash
|
||||
# View the complete admin setup logs
|
||||
docker compose logs backend | grep -A 10 "Admin user created"
|
||||
```
|
||||
|
||||
**Option 3: Check the saved credentials file**
|
||||
```bash
|
||||
# The password is also saved in the backend container
|
||||
docker exec picpeak-backend cat data/ADMIN_CREDENTIALS.txt
|
||||
```
|
||||
|
||||
**Option 4: Use the helper script**
|
||||
```bash
|
||||
# Show current admin username and email (password is hidden)
|
||||
docker exec picpeak-backend node scripts/show-admin-credentials.js
|
||||
|
||||
# Reset the admin password to a new random password (displays new password in console)
|
||||
docker exec picpeak-backend node scripts/show-admin-credentials.js --reset
|
||||
```
|
||||
|
||||
> **Note:** When using `--reset`, the new password will be displayed in the console output. Save it immediately - it will not be shown again!
|
||||
|
||||
#### Important Security Notes
|
||||
|
||||
- **Login requires the email address**, not username
|
||||
- When resetting password, the new password is displayed once in the console - save it immediately
|
||||
- **Password change is MANDATORY** on first login - the system will force you to change it
|
||||
- If you lose the password before first login, use the `--reset` option to generate a new one
|
||||
- New password requirements: minimum 12 characters, mixed case, numbers, and special characters
|
||||
|
||||
## 🔐 First Login
|
||||
|
||||
After deployment, you must complete the first login process which includes mandatory password change for security.
|
||||
|
||||
### Step 1: Locate Your Admin Password
|
||||
|
||||
1. **Find the auto-generated password** from the credentials file:
|
||||
```bash
|
||||
# Docker deployment
|
||||
docker compose exec backend cat /app/data/ADMIN_CREDENTIALS.txt
|
||||
|
||||
# Or directly from the host (if you have access)
|
||||
cat data/ADMIN_CREDENTIALS.txt
|
||||
```
|
||||
|
||||
2. **Note the admin email** (default: `admin@example.com` unless customized)
|
||||
|
||||
### Step 2: Access Admin Panel
|
||||
|
||||
1. Navigate to your frontend domain and open the admin section:
|
||||
- `http://your-domain.com/admin` (behind reverse proxy)
|
||||
- `http://localhost:3000/admin` (Docker local)
|
||||
|
||||
The backend at `:3001` serves API only and does not serve the admin UI.
|
||||
2. Login using:
|
||||
- **Email**: `admin@example.com` (or your custom admin email)
|
||||
- **Password**: The auto-generated password from the logs
|
||||
|
||||
### Step 3: Mandatory Password Change
|
||||
|
||||
Upon first login, the system will **automatically redirect** you to change your password:
|
||||
|
||||
1. **You cannot skip this step** - it's enforced for security
|
||||
2. Enter the current auto-generated password
|
||||
3. Create a new secure password meeting these requirements:
|
||||
- Minimum 12 characters
|
||||
- At least one uppercase letter
|
||||
- At least one lowercase letter
|
||||
- At least one number
|
||||
- At least one special character (!@#$%^&*)
|
||||
|
||||
### Security Best Practices for New Password
|
||||
|
||||
- **Use a unique password** not used elsewhere
|
||||
- **Consider a password manager** for generation and storage
|
||||
- **Include mixed characters**: `MySecureP@ssw0rd2024!`
|
||||
- **Avoid personal information** (names, dates, etc.)
|
||||
- **Save securely** - you cannot recover this password easily
|
||||
|
||||
### If You Lose Access
|
||||
|
||||
If you lose your admin credentials after the first login, you'll need to manually reset the password in the database or create a new admin user through the database.
|
||||
|
||||
**Note**: The credentials file (`ADMIN_CREDENTIALS.txt`) is only created during initial deployment and contains the first admin password. After changing the password, this file becomes outdated but is kept for reference. If you need to regenerate the password and file during a reinstall, re-run the installer with the `--force-admin-password-reset` flag:
|
||||
|
||||
```bash
|
||||
# Native reinstall example
|
||||
sudo ./picpeak-setup.sh --native --force-admin-password-reset
|
||||
|
||||
# Docker reinstall example
|
||||
sudo ./picpeak-setup.sh --docker --force-admin-password-reset
|
||||
```
|
||||
|
||||
The flag calls `scripts/reset-admin-password.js` in non-interactive mode, writes a fresh random password into `data/ADMIN_CREDENTIALS.txt`, and prints the new credentials at the end of the installer run.
|
||||
|
||||
#### Configuring Admin Email
|
||||
|
||||
By default, the admin email is `admin@example.com`. To use a different email address, set it in your `.env` file before first deployment:
|
||||
|
||||
```env
|
||||
# .env
|
||||
ADMIN_EMAIL=your-email@yourdomain.com
|
||||
```
|
||||
|
||||
**Note**: This only works on first deployment. To change the admin email after deployment, you'll need to update it in the database or create a new admin user through the admin panel.
|
||||
|
||||
## 🔄 Release Channels
|
||||
|
||||
PicPeak offers two release channels for different needs:
|
||||
|
||||
### Stable Channel (Recommended)
|
||||
- Production-ready releases
|
||||
- Thoroughly tested before release
|
||||
- Docker tags: `stable`, `latest`, or specific version like `v2.3.0`
|
||||
|
||||
### Beta Channel
|
||||
- Early access to new features
|
||||
- May contain bugs or incomplete functionality
|
||||
- Docker tags: `beta` or specific version like `v2.3.0-beta.1`
|
||||
|
||||
### Configuring Your Channel
|
||||
|
||||
Set the `PICPEAK_CHANNEL` environment variable in your `.env` file:
|
||||
|
||||
```bash
|
||||
# For stable releases (default)
|
||||
PICPEAK_CHANNEL=stable
|
||||
|
||||
# For beta releases
|
||||
PICPEAK_CHANNEL=beta
|
||||
|
||||
# For a specific version
|
||||
PICPEAK_CHANNEL=v2.3.0
|
||||
```
|
||||
|
||||
The `docker-compose.production.yml` uses this variable for both backend and frontend images:
|
||||
```yaml
|
||||
image: ghcr.io/the-luap/picpeak/backend:${PICPEAK_CHANNEL:-stable}
|
||||
```
|
||||
|
||||
### Switching Channels
|
||||
|
||||
To switch between channels:
|
||||
|
||||
```bash
|
||||
# Edit your .env file
|
||||
nano .env
|
||||
# Change PICPEAK_CHANNEL=stable to PICPEAK_CHANNEL=beta (or vice versa)
|
||||
|
||||
# Pull the new images and restart
|
||||
docker compose -f docker-compose.production.yml pull
|
||||
docker compose -f docker-compose.production.yml up -d
|
||||
```
|
||||
|
||||
### Update Notifications
|
||||
|
||||
The admin dashboard automatically notifies you when updates are available for your channel. This feature:
|
||||
- Checks GitHub releases hourly (cached to avoid rate limits)
|
||||
- Shows updates relevant to your current channel (stable or beta)
|
||||
- Can be disabled by setting `UPDATE_CHECK_ENABLED=false` in your `.env`
|
||||
|
||||
## 🔒 Reverse Proxy Setup
|
||||
|
||||
For production deployments, you should use a reverse proxy for SSL/HTTPS. The application exposes ports directly, allowing you to use any reverse proxy solution.
|
||||
|
||||
### Routing Schema
|
||||
|
||||
PicPeak consists of two services that need to be routed correctly:
|
||||
|
||||
| Path | Service | Port | Description |
|
||||
|------|---------|------|-------------|
|
||||
| `/api/*` | Backend | 3001 | All API endpoints |
|
||||
| `/photos/*` | Backend | 3001 | Protected photo files |
|
||||
| `/thumbnails/*` | Backend | 3001 | Protected thumbnail files |
|
||||
| `/uploads/*` | Backend | 3001 | Upload files |
|
||||
| `/*` (everything else) | Frontend | 3000 | React SPA (including `/admin/*`, `/gallery/*`) |
|
||||
|
||||
> **Important:** The `/admin/*` routes are served by the frontend (React SPA), NOT the backend. The backend only handles `/api/admin/*` requests.
|
||||
|
||||
### Option 1: Nginx
|
||||
|
||||
Install nginx and create `/etc/nginx/sites-available/picpeak`:
|
||||
|
||||
```nginx
|
||||
server {
|
||||
listen 80;
|
||||
server_name your-domain.com;
|
||||
return 301 https://$server_name$request_uri;
|
||||
}
|
||||
|
||||
server {
|
||||
listen 443 ssl http2;
|
||||
server_name your-domain.com;
|
||||
|
||||
ssl_certificate /etc/letsencrypt/live/your-domain.com/fullchain.pem;
|
||||
ssl_certificate_key /etc/letsencrypt/live/your-domain.com/privkey.pem;
|
||||
|
||||
# Backend: API endpoints
|
||||
location /api/ {
|
||||
proxy_pass http://localhost:3001;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
|
||||
# Backend: Protected media files
|
||||
location ~ ^/(photos|thumbnails|uploads)/ {
|
||||
proxy_pass http://localhost:3001;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
|
||||
# Frontend: Everything else (React SPA)
|
||||
location / {
|
||||
proxy_pass http://localhost:3000;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Enable the site:
|
||||
```bash
|
||||
sudo ln -s /etc/nginx/sites-available/picpeak /etc/nginx/sites-enabled/
|
||||
sudo nginx -t
|
||||
sudo systemctl reload nginx
|
||||
```
|
||||
|
||||
### Option 2: Traefik
|
||||
|
||||
Add labels to `docker-compose.override.yml`:
|
||||
|
||||
```yaml
|
||||
version: '3.8'
|
||||
|
||||
services:
|
||||
frontend:
|
||||
labels:
|
||||
- "traefik.enable=true"
|
||||
- "traefik.http.routers.picpeak.rule=Host(`your-domain.com`)"
|
||||
- "traefik.http.routers.picpeak.entrypoints=websecure"
|
||||
- "traefik.http.routers.picpeak.tls.certresolver=letsencrypt"
|
||||
- "traefik.http.services.picpeak.loadbalancer.server.port=80"
|
||||
|
||||
backend:
|
||||
labels:
|
||||
- "traefik.enable=true"
|
||||
# API endpoints
|
||||
- "traefik.http.routers.picpeak-api.rule=Host(`your-domain.com`) && PathPrefix(`/api`)"
|
||||
- "traefik.http.routers.picpeak-api.entrypoints=websecure"
|
||||
- "traefik.http.routers.picpeak-api.tls.certresolver=letsencrypt"
|
||||
- "traefik.http.services.picpeak-api.loadbalancer.server.port=3001"
|
||||
# Protected media files
|
||||
- "traefik.http.routers.picpeak-media.rule=Host(`your-domain.com`) && (PathPrefix(`/photos`) || PathPrefix(`/thumbnails`) || PathPrefix(`/uploads`))"
|
||||
- "traefik.http.routers.picpeak-media.entrypoints=websecure"
|
||||
- "traefik.http.routers.picpeak-media.tls.certresolver=letsencrypt"
|
||||
- "traefik.http.services.picpeak-media.loadbalancer.server.port=3001"
|
||||
```
|
||||
|
||||
### Option 3: Caddy
|
||||
|
||||
Create a `Caddyfile`:
|
||||
|
||||
```caddyfile
|
||||
your-domain.com {
|
||||
# Backend: API endpoints
|
||||
handle /api/* {
|
||||
reverse_proxy localhost:3001
|
||||
}
|
||||
|
||||
# Backend: Protected media files
|
||||
handle /photos/* {
|
||||
reverse_proxy localhost:3001
|
||||
}
|
||||
|
||||
handle /thumbnails/* {
|
||||
reverse_proxy localhost:3001
|
||||
}
|
||||
|
||||
handle /uploads/* {
|
||||
reverse_proxy localhost:3001
|
||||
}
|
||||
|
||||
# Frontend: Everything else (React SPA including /admin/*, /gallery/*)
|
||||
handle {
|
||||
reverse_proxy localhost:3000
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### SSL Certificates
|
||||
|
||||
For any reverse proxy, you can use Let's Encrypt:
|
||||
|
||||
```bash
|
||||
# With Certbot
|
||||
sudo certbot certonly --webroot -w /var/www/certbot -d your-domain.com
|
||||
|
||||
# Or use your reverse proxy's built-in ACME support
|
||||
```
|
||||
|
||||
## 🔧 Maintenance
|
||||
|
||||
### Viewing Logs
|
||||
|
||||
```bash
|
||||
# All services
|
||||
docker compose logs -f
|
||||
|
||||
# Specific service
|
||||
docker compose logs -f backend
|
||||
docker compose logs -f frontend
|
||||
```
|
||||
|
||||
### Backup
|
||||
|
||||
#### Manual Backup
|
||||
```bash
|
||||
# Database backup
|
||||
docker exec picpeak-postgres pg_dump -U picpeak picpeak_prod > backup/db_$(date +%Y%m%d_%H%M%S).sql
|
||||
|
||||
# Files backup
|
||||
tar -czf backup/photos_$(date +%Y%m%d_%H%M%S).tar.gz events/
|
||||
```
|
||||
|
||||
#### Automated Backup
|
||||
The application includes a built-in backup service. Configure it in the admin panel:
|
||||
1. Login to admin panel
|
||||
2. Go to Settings → Backup
|
||||
3. Configure destination and schedule
|
||||
4. Enable backup service
|
||||
|
||||
### Updates
|
||||
|
||||
#### Method 1: Using Pre-built Images (Recommended)
|
||||
|
||||
```bash
|
||||
# Pull latest changes (for configuration updates)
|
||||
git pull
|
||||
|
||||
# Pull latest images from GitHub Container Registry
|
||||
docker compose -f docker-compose.production.yml pull
|
||||
|
||||
# Restart with new images
|
||||
docker compose -f docker-compose.production.yml down
|
||||
docker compose -f docker-compose.production.yml up -d
|
||||
|
||||
# Verify services are healthy
|
||||
docker compose -f docker-compose.production.yml ps
|
||||
```
|
||||
|
||||
#### Method 2: Building from Source
|
||||
|
||||
```bash
|
||||
# Pull latest changes
|
||||
git pull
|
||||
|
||||
# Rebuild and restart
|
||||
docker compose down
|
||||
docker compose build --no-cache
|
||||
docker compose up -d
|
||||
|
||||
# Verify services are healthy
|
||||
docker compose ps
|
||||
```
|
||||
|
||||
#### Specific Version or Channel Updates
|
||||
|
||||
To use a specific version or switch channels, update your `.env` file:
|
||||
|
||||
```bash
|
||||
# Edit .env to change the channel or pin to a specific version
|
||||
nano .env
|
||||
|
||||
# Options for PICPEAK_CHANNEL:
|
||||
# - stable (recommended, production-ready)
|
||||
# - beta (early access to new features)
|
||||
# - v2.3.0 (pin to specific stable version)
|
||||
# - v2.3.0-beta.1 (pin to specific beta version)
|
||||
|
||||
# Then pull and restart
|
||||
docker compose -f docker-compose.production.yml pull
|
||||
docker compose -f docker-compose.production.yml up -d
|
||||
```
|
||||
|
||||
The admin dashboard will notify you when updates are available for your configured channel.
|
||||
|
||||
### Database Migrations
|
||||
|
||||
Migrations run automatically on startup, but you can run them manually:
|
||||
|
||||
```bash
|
||||
docker exec picpeak-backend npm run migrate
|
||||
```
|
||||
|
||||
## 🚨 Troubleshooting
|
||||
|
||||
### Common Issues
|
||||
|
||||
#### 502 Bad Gateway / Login Failures
|
||||
**This is the most common deployment issue!** Usually caused by misconfigured URLs or network problems:
|
||||
|
||||
1. **CORS Configuration Errors**:
|
||||
```bash
|
||||
# WRONG - Missing port will cause CORS errors
|
||||
FRONTEND_URL=http://10.0.252.12
|
||||
|
||||
# CORRECT - Include the port you're accessing from
|
||||
FRONTEND_URL=http://10.0.252.12:3000
|
||||
```
|
||||
|
||||
The backend validates Origin headers against `FRONTEND_URL` for CORS. If they don't match exactly, you'll get 500 errors on login.
|
||||
|
||||
2. **After Container Restarts**:
|
||||
- Nginx may have cached old container IPs
|
||||
- Solution: `docker restart picpeak-frontend`
|
||||
- Always wait 30-60 seconds for health checks
|
||||
|
||||
3. **Backend Not Starting After Migrations**:
|
||||
- The logs may only show migrations completed
|
||||
- Check if server is actually running: `docker exec picpeak-backend ps aux | grep node`
|
||||
- Should see `node server.js` process
|
||||
|
||||
4. **Login After Fresh Install**:
|
||||
- Check backend logs for auto-generated admin password: `docker compose logs backend | grep "Admin password"`
|
||||
- Email: `admin@example.com` (or your custom admin email from .env)
|
||||
- Password: Auto-generated and shown in logs (e.g., `BraveTiger6231!`)
|
||||
- Remember: Password MUST be changed on first login
|
||||
|
||||
5. **Complete Fix Sequence**:
|
||||
```bash
|
||||
# 1. Fix your .env file URLs
|
||||
# 2. Full restart
|
||||
docker-compose down
|
||||
docker-compose up -d
|
||||
|
||||
# 3. Wait for healthy status
|
||||
sleep 60
|
||||
docker ps # All should show (healthy)
|
||||
|
||||
# 4. Test backend directly
|
||||
curl http://localhost:3001/health
|
||||
|
||||
# 5. Test through frontend
|
||||
curl http://localhost:3000/api/public/settings
|
||||
```
|
||||
|
||||
#### Port Already in Use
|
||||
```bash
|
||||
# Check what's using the port
|
||||
sudo lsof -i :3000
|
||||
sudo lsof -i :3001
|
||||
|
||||
# Change ports in .env
|
||||
FRONTEND_PORT=3002
|
||||
BACKEND_PORT=3003
|
||||
```
|
||||
|
||||
#### Docker Compose Variable Substitution Errors
|
||||
If you see warnings like:
|
||||
```
|
||||
WARN[0000] The "fgbf" variable is not set. Defaulting to a blank string.
|
||||
```
|
||||
|
||||
This means your password contains `$` which Docker Compose interprets as a variable. Solutions:
|
||||
1. **Best**: Generate passwords without `$`: `openssl rand -base64 32 | tr -d '$'`
|
||||
2. **Alternative**: Escape `$` as `$$` in your .env file
|
||||
3. **Example**: `DB_PASSWORD=Pass@#$$fgbf` instead of `DB_PASSWORD=Pass@#$fgbf`
|
||||
|
||||
#### Permission Errors
|
||||
```bash
|
||||
# Fix ownership
|
||||
sudo chown -R 1000:1000 events data logs backup storage
|
||||
chmod -R 755 events data logs backup storage
|
||||
```
|
||||
|
||||
#### Database Connection Issues
|
||||
```bash
|
||||
# Check if database is running
|
||||
docker compose ps
|
||||
docker compose logs postgres
|
||||
|
||||
# Test connection
|
||||
docker exec picpeak-postgres pg_isready
|
||||
```
|
||||
|
||||
#### Email Not Sending
|
||||
- Verify SMTP settings in .env
|
||||
- Check email queue: `docker exec picpeak-backend psql -U picpeak -d picpeak_prod -c "SELECT * FROM email_queue ORDER BY created_at DESC LIMIT 10;"`
|
||||
- For Gmail, use app-specific password
|
||||
- Check logs: `docker compose logs backend | grep email`
|
||||
|
||||
### Health Checks
|
||||
|
||||
```bash
|
||||
# Backend health
|
||||
curl http://localhost:3001/api/health
|
||||
|
||||
# Frontend health
|
||||
curl http://localhost:3000
|
||||
|
||||
# Database health
|
||||
docker exec picpeak-postgres pg_isready
|
||||
```
|
||||
|
||||
### Useful Commands
|
||||
|
||||
```bash
|
||||
# Enter backend container
|
||||
docker exec -it picpeak-backend sh
|
||||
|
||||
# Enter database
|
||||
docker exec -it picpeak-postgres psql -U picpeak picpeak_prod
|
||||
|
||||
# Reset admin password
|
||||
docker exec picpeak-backend node scripts/show-admin-credentials.js --reset
|
||||
|
||||
# Check disk usage
|
||||
df -h
|
||||
du -sh events/ storage/ backup/
|
||||
|
||||
# View running processes
|
||||
docker compose top
|
||||
```
|
||||
|
||||
## Security Recommendations
|
||||
|
||||
1. **Use HTTPS**: Always use a reverse proxy with SSL in production
|
||||
2. **Firewall**: Only expose necessary ports (80, 443)
|
||||
3. **Secure passwords**: Use strong, unique passwords for all services
|
||||
4. **Regular updates**: Keep Docker images and system packages updated
|
||||
5. **Backup strategy**: Set up automated backups and test restoration
|
||||
6. **Monitor logs**: Regularly check logs for suspicious activity
|
||||
7. **Rate limiting**: The app includes built-in rate limiting, configure as needed
|
||||
|
||||
## Support
|
||||
|
||||
For issues and questions:
|
||||
- Check logs first: `docker compose logs`
|
||||
- Review documentation in the repository
|
||||
- Check existing issues on GitHub
|
||||
- Create a new issue with:
|
||||
- Error messages
|
||||
- Log output
|
||||
- Environment details (without secrets)
|
||||
- Steps to reproduce
|
||||
@@ -1,378 +0,0 @@
|
||||
# Production Deployment Guide
|
||||
|
||||
This comprehensive guide addresses all production deployment scenarios and common issues.
|
||||
|
||||
## Pre-Deployment Checklist
|
||||
|
||||
### 1. Environment Variables
|
||||
Create a `.env` file with ALL required variables:
|
||||
|
||||
```bash
|
||||
# CRITICAL - Must change these!
|
||||
JWT_SECRET=<generate-with-openssl-rand-base64-32>
|
||||
DB_PASSWORD=<strong-password>
|
||||
|
||||
# Application URLs (your actual domain)
|
||||
ADMIN_URL=https://yourdomain.com
|
||||
FRONTEND_URL=https://yourdomain.com
|
||||
BACKEND_URL=https://yourdomain.com
|
||||
|
||||
# Database (PostgreSQL)
|
||||
DATABASE_CLIENT=pg
|
||||
DB_HOST=postgres # or external host
|
||||
DB_PORT=5432
|
||||
DB_USER=picpeak
|
||||
DB_NAME=picpeak
|
||||
|
||||
# Email Configuration (required for notifications)
|
||||
SMTP_HOST=smtp.gmail.com
|
||||
SMTP_PORT=587
|
||||
SMTP_SECURE=false
|
||||
SMTP_USER=your-email@gmail.com
|
||||
SMTP_PASS=your-app-password # Use app-specific password
|
||||
EMAIL_FROM=PicPeak <noreply@yourdomain.com>
|
||||
|
||||
# Port Configuration
|
||||
PORT=3001
|
||||
|
||||
# Performance Tuning
|
||||
DB_POOL_MIN=5
|
||||
DB_POOL_MAX=25
|
||||
NODE_ENV=production
|
||||
LOG_LEVEL=info
|
||||
|
||||
# Optional: Umami Analytics (configured via Admin UI)
|
||||
# UMAMI_URL=https://analytics.yourdomain.com
|
||||
# UMAMI_WEBSITE_ID=your-website-id
|
||||
```
|
||||
|
||||
### 2. Generate Secrets
|
||||
|
||||
```bash
|
||||
# Generate JWT Secret (REQUIRED)
|
||||
openssl rand -base64 32
|
||||
|
||||
# Generate Database Password
|
||||
openssl rand -base64 24
|
||||
```
|
||||
|
||||
## Frontend Configuration
|
||||
|
||||
For production deployment behind a reverse proxy:
|
||||
|
||||
### Frontend Environment
|
||||
```bash
|
||||
# frontend/.env.production
|
||||
VITE_API_URL=/api # Uses relative path for reverse proxy
|
||||
|
||||
# Optional: Umami fallback (primary config via Admin UI)
|
||||
# VITE_UMAMI_URL=https://analytics.yourdomain.com
|
||||
# VITE_UMAMI_WEBSITE_ID=your-website-id
|
||||
```
|
||||
|
||||
This ensures all API calls use the same domain/protocol as the frontend.
|
||||
|
||||
### Nginx Proxy Configuration
|
||||
|
||||
The frontend nginx configuration already includes proper proxy settings for:
|
||||
- `/api` → Backend API
|
||||
- `/photos` → Protected photo access
|
||||
- `/thumbnails` → Thumbnail images
|
||||
- `/uploads` → Public uploads (logos, favicons)
|
||||
|
||||
All static assets are served through the nginx proxy, inheriting authentication headers.
|
||||
|
||||
## Deployment Steps
|
||||
|
||||
### 1. Initial Setup
|
||||
|
||||
```bash
|
||||
# Clone repository
|
||||
git clone https://github.com/the-luap/wedding-photo-sharing.git
|
||||
cd wedding-photo-sharing
|
||||
|
||||
# Create required directories
|
||||
mkdir -p storage/events/active storage/events/archived storage/thumbnails storage/uploads
|
||||
mkdir -p data logs
|
||||
mkdir -p certbot/conf certbot/www
|
||||
|
||||
# Set permissions (important!)
|
||||
chmod -R 755 storage data logs
|
||||
```
|
||||
|
||||
### 2. Fix Docker Volume Permissions
|
||||
|
||||
Create `docker-compose.override.yml` for local volume configuration:
|
||||
|
||||
```yaml
|
||||
version: '3.8'
|
||||
|
||||
services:
|
||||
backend:
|
||||
volumes:
|
||||
- ./storage:/app/storage:delegated
|
||||
- ./data:/app/data:delegated
|
||||
- ./logs:/app/logs:delegated
|
||||
user: "1001:1001" # nodejs user
|
||||
|
||||
db:
|
||||
volumes:
|
||||
- ./postgres-data:/var/lib/postgresql/data
|
||||
```
|
||||
|
||||
### 3. Build and Deploy
|
||||
|
||||
```bash
|
||||
# Build images
|
||||
docker-compose -f docker-compose.prod.yml build
|
||||
|
||||
# Start services
|
||||
docker-compose -f docker-compose.prod.yml up -d
|
||||
|
||||
# Check logs
|
||||
docker-compose -f docker-compose.prod.yml logs -f backend
|
||||
```
|
||||
|
||||
### 4. Initial Admin Setup
|
||||
|
||||
The admin user is automatically created during database migration:
|
||||
|
||||
```bash
|
||||
# Run migrations (this creates admin user)
|
||||
docker-compose -f docker-compose.prod.yml exec backend npm run migrate
|
||||
|
||||
# Admin credentials will be displayed in console and saved to ADMIN_CREDENTIALS.txt
|
||||
# Example output:
|
||||
# ========================================
|
||||
# ✅ Admin user created successfully!
|
||||
# ========================================
|
||||
# Username: admin
|
||||
# Password: SwiftEagle3847!
|
||||
#
|
||||
# ⚠️ IMPORTANT: Change password on first login
|
||||
# ========================================
|
||||
|
||||
# Retrieve credentials if needed
|
||||
docker-compose -f docker-compose.prod.yml exec backend cat ADMIN_CREDENTIALS.txt
|
||||
```
|
||||
|
||||
**Important**: You MUST change the auto-generated password on first login.
|
||||
|
||||
### 5. Configure Email (if using database config)
|
||||
|
||||
1. Login to admin panel: https://yourdomain.com/admin
|
||||
2. Go to Settings > Email Configuration
|
||||
3. Enter SMTP details
|
||||
4. Test email sending
|
||||
|
||||
## Common Issues and Solutions
|
||||
|
||||
### Issue 1: Migration Failures
|
||||
|
||||
**Error**: "relation already exists"
|
||||
|
||||
**Solution**: The safe migration runner handles this automatically. If issues persist:
|
||||
|
||||
```bash
|
||||
# Reset migrations tracking
|
||||
docker-compose -f docker-compose.prod.yml exec db psql -U picpeak -d picpeak
|
||||
|
||||
# In PostgreSQL:
|
||||
DROP TABLE IF EXISTS migrations;
|
||||
\q
|
||||
|
||||
# Re-run migrations
|
||||
docker-compose -f docker-compose.prod.yml exec backend npm run migrate:safe
|
||||
```
|
||||
|
||||
### Issue 2: Permission Denied Errors
|
||||
|
||||
**Error**: "EACCES: permission denied"
|
||||
|
||||
**Solution**: Fix container permissions:
|
||||
|
||||
```bash
|
||||
# Stop containers
|
||||
docker-compose -f docker-compose.prod.yml down
|
||||
|
||||
# Fix permissions on host
|
||||
sudo chown -R 1001:1001 storage data logs
|
||||
|
||||
# Restart
|
||||
docker-compose -f docker-compose.prod.yml up -d
|
||||
```
|
||||
|
||||
### Issue 3: Database Connection Failed
|
||||
|
||||
**Error**: "no pg_hba.conf entry"
|
||||
|
||||
**Solution**: Already fixed in docker-compose.prod.yml with:
|
||||
- SSL disabled for internal Docker network
|
||||
- Proper authentication method (scram-sha-256)
|
||||
|
||||
### Issue 4: Frontend Can't Connect to Backend
|
||||
|
||||
**Error**: CORS errors or connection refused
|
||||
|
||||
**Solution**: Ensure environment variables match:
|
||||
- Backend: `FRONTEND_URL` must match your frontend URL
|
||||
- Frontend: `VITE_API_URL` must be set during build
|
||||
|
||||
### Issue 5: Email Not Sending
|
||||
|
||||
**Solution**: Check email configuration:
|
||||
|
||||
```bash
|
||||
# Check backend logs
|
||||
docker-compose -f docker-compose.prod.yml logs backend | grep email
|
||||
|
||||
# Verify SMTP settings
|
||||
# Gmail users: Use app password, not regular password
|
||||
# Enable "Less secure app access" or use OAuth2
|
||||
```
|
||||
|
||||
## SSL/HTTPS Setup
|
||||
|
||||
### Option 1: Using Traefik (Recommended)
|
||||
|
||||
Add these labels to your docker-compose override:
|
||||
|
||||
```yaml
|
||||
services:
|
||||
frontend:
|
||||
labels:
|
||||
- "traefik.enable=true"
|
||||
- "traefik.http.routers.picpeak.rule=Host(`yourdomain.com`)"
|
||||
- "traefik.http.routers.picpeak.entrypoints=websecure"
|
||||
- "traefik.http.routers.picpeak.tls.certresolver=letsencrypt"
|
||||
- "traefik.http.services.picpeak.loadbalancer.server.port=80"
|
||||
```
|
||||
|
||||
### Option 2: Using Certbot
|
||||
|
||||
1. Update `nginx/sites-enabled/default` with your domain
|
||||
2. Run certbot:
|
||||
|
||||
```bash
|
||||
# Initial certificate
|
||||
docker-compose -f docker-compose.prod.yml run --rm certbot certonly \
|
||||
--webroot --webroot-path=/var/www/certbot \
|
||||
-d yourdomain.com -d www.yourdomain.com
|
||||
|
||||
# Auto-renewal is handled by the certbot container
|
||||
```
|
||||
|
||||
## Monitoring
|
||||
|
||||
### Health Checks
|
||||
|
||||
```bash
|
||||
# Backend health
|
||||
curl http://localhost/api/health
|
||||
|
||||
# Database connection
|
||||
docker-compose -f docker-compose.prod.yml exec backend \
|
||||
psql -U picpeak -d picpeak -c "SELECT 1"
|
||||
```
|
||||
|
||||
### Logs
|
||||
|
||||
```bash
|
||||
# All services
|
||||
docker-compose -f docker-compose.prod.yml logs -f
|
||||
|
||||
# Specific service
|
||||
docker-compose -f docker-compose.prod.yml logs -f backend
|
||||
```
|
||||
|
||||
## Backup and Restore
|
||||
|
||||
### Backup
|
||||
|
||||
```bash
|
||||
#!/bin/bash
|
||||
# backup.sh
|
||||
DATE=$(date +%Y%m%d_%H%M%S)
|
||||
BACKUP_DIR="./backups/$DATE"
|
||||
|
||||
mkdir -p $BACKUP_DIR
|
||||
|
||||
# Database
|
||||
docker-compose -f docker-compose.prod.yml exec -T db \
|
||||
pg_dump -U picpeak picpeak > $BACKUP_DIR/database.sql
|
||||
|
||||
# Files
|
||||
tar -czf $BACKUP_DIR/storage.tar.gz storage/
|
||||
|
||||
echo "Backup completed: $BACKUP_DIR"
|
||||
```
|
||||
|
||||
### Restore
|
||||
|
||||
```bash
|
||||
# Database
|
||||
docker-compose -f docker-compose.prod.yml exec -T db \
|
||||
psql -U picpeak picpeak < ./backups/20240713_120000/database.sql
|
||||
|
||||
# Files
|
||||
tar -xzf ./backups/20240713_120000/storage.tar.gz
|
||||
```
|
||||
|
||||
## Production Best Practices
|
||||
|
||||
1. **Always use named volumes** in production for better data persistence
|
||||
2. **Set up monitoring** with Prometheus/Grafana
|
||||
3. **Enable backups** with automated scripts
|
||||
4. **Use a reverse proxy** (Nginx) for SSL termination
|
||||
5. **Implement rate limiting** at the Nginx level
|
||||
6. **Regular updates** - Keep Docker images updated
|
||||
7. **Log rotation** - Configure log rotation for application logs
|
||||
|
||||
## Troubleshooting Commands
|
||||
|
||||
```bash
|
||||
# Check running containers
|
||||
docker-compose -f docker-compose.prod.yml ps
|
||||
|
||||
# Restart a service
|
||||
docker-compose -f docker-compose.prod.yml restart backend
|
||||
|
||||
# View real-time logs
|
||||
docker-compose -f docker-compose.prod.yml logs -f --tail=100
|
||||
|
||||
# Execute commands in container
|
||||
docker-compose -f docker-compose.prod.yml exec backend sh
|
||||
|
||||
# Database shell
|
||||
docker-compose -f docker-compose.prod.yml exec db psql -U picpeak
|
||||
|
||||
# Clean restart
|
||||
docker-compose -f docker-compose.prod.yml down
|
||||
docker-compose -f docker-compose.prod.yml up -d
|
||||
```
|
||||
|
||||
## Security Checklist
|
||||
|
||||
- [ ] Strong JWT_SECRET (min 32 chars)
|
||||
- [ ] Strong database password
|
||||
- [ ] Admin password changed from auto-generated one
|
||||
- [ ] SSL/HTTPS enabled
|
||||
- [ ] Firewall configured (only 80/443 open)
|
||||
- [ ] Regular security updates
|
||||
- [ ] Backup encryption
|
||||
- [ ] Access logs monitored
|
||||
- [ ] Rate limiting enabled (built-in)
|
||||
- [ ] File upload restrictions configured
|
||||
- [ ] Password complexity requirements configured (Admin > Settings)
|
||||
- [ ] Session timeout configured (default 60 min)
|
||||
- [ ] Umami analytics configured (if using)
|
||||
- [ ] SMTP credentials secured with app-specific password
|
||||
|
||||
## Support
|
||||
|
||||
For issues not covered here:
|
||||
1. Check application logs
|
||||
2. Review error messages carefully
|
||||
3. Ensure all environment variables are set
|
||||
4. Verify file permissions
|
||||
5. Check Docker daemon logs
|
||||
@@ -7,12 +7,27 @@
|
||||
[](https://www.docker.com/)
|
||||
[](https://nodejs.org/)
|
||||
[](https://reactjs.org/)
|
||||
|
||||
[Homepage](https://www.picpeak.app) · [Live Demo](https://demo.picpeak.app) · [Documentation](DEPLOYMENT_GUIDE.md)
|
||||
</div>
|
||||
|
||||
**PicPeak** is a powerful, self-hosted open-source alternative to commercial photo-sharing platforms like PicDrop.com and Scrapbook.de. Designed specifically for photographers and event organizers, PicPeak makes it simple to share beautiful, time-limited photo galleries with clients while maintaining full control over your data and branding.
|
||||
|
||||

|
||||
|
||||
## 🎮 Live Demo
|
||||
|
||||
Try PicPeak without installing anything:
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Demo URL** | [demo.picpeak.app](https://demo.picpeak.app) |
|
||||
| **Admin Panel** | [demo.picpeak.app/admin](https://demo.picpeak.app/admin) |
|
||||
| **Email** | `demo@picpeak.app` |
|
||||
| **Password** | `Demo2026!` |
|
||||
|
||||
> The demo resets periodically. Uploaded content may be removed without notice.
|
||||
|
||||
## 🌟 Why Choose PicPeak?
|
||||
|
||||
Unlike expensive SaaS solutions, PicPeak gives you:
|
||||
@@ -28,11 +43,13 @@ Unlike expensive SaaS solutions, PicPeak gives you:
|
||||
|
||||
### For Photographers
|
||||
- 📁 **Drag & Drop Upload** - Simply drop photos into folders
|
||||
- 🔗 **External Media (Reference Mode)** - Browse and import from a read‑only external folder library without copying originals
|
||||
- ⏰ **Auto-Expiring Galleries** - Set expiration dates (default: 30 days)
|
||||
- 🔐 **Password Protection** - Secure client galleries
|
||||
- 📧 **Automated Emails** - Creation confirmations and expiration warnings
|
||||
- 📊 **Analytics Dashboard** - Track views, downloads, and engagement
|
||||
- 🎨 **Custom Themes** - Match your brand perfectly
|
||||
- 🌐 **Public Landing Page** - Publish a curated marketing page when guests visit your root URL
|
||||
|
||||
### For Clients
|
||||
- 🖼️ **Beautiful Galleries** - Clean, modern interface
|
||||
@@ -40,10 +57,12 @@ Unlike expensive SaaS solutions, PicPeak gives you:
|
||||
- ⬇️ **Bulk Downloads** - Download all photos with one click
|
||||
- 🔍 **Smart Search** - Find photos quickly
|
||||
- 📤 **Guest Uploads** - Optional client photo uploads
|
||||
- 🛡️ **Download Protection** - Advanced image protection with watermarking and right-click prevention
|
||||
|
||||
### Technical Excellence
|
||||
- 🐳 **Docker Ready** - Deploy in minutes
|
||||
- 🔄 **Auto-Processing** - Automatic thumbnail generation
|
||||
- 🗂️ **Reference Library Support** - Point PicPeak at `EXTERNAL_MEDIA_ROOT` to reference existing originals, index quickly, and generate thumbnails on demand
|
||||
- 💾 **Smart Storage** - Automatic archiving of expired galleries
|
||||
- 🛡️ **Security First** - JWT auth, rate limiting, CORS protection
|
||||
- 📈 **Scalable** - From small studios to large agencies
|
||||
@@ -64,19 +83,86 @@ cp .env.example .env
|
||||
nano .env
|
||||
|
||||
# Start with Docker Compose
|
||||
docker-compose up -d
|
||||
docker compose up -d
|
||||
|
||||
# Access at http://localhost:3005
|
||||
# Access at http://localhost:3000
|
||||
```
|
||||
|
||||
Note on Docker file permissions (PUID/PGID)
|
||||
- When using bind mounts (e.g., `./storage`, `./data`, `./logs`, `./events`), ensure the container user can write to these host folders. The backend runs as a non‑root user by default.
|
||||
- Set `PUID` and `PGID` in your `.env` to match your host user’s UID/GID (run `id -u` and `id -g` on the host). Compose maps the container user to these values.
|
||||
- Example in `.env`:
|
||||
- `PUID=1000`
|
||||
- `PGID=1000`
|
||||
- Without this, creating events, uploads, thumbnails, or logs can fail with "Permission denied".
|
||||
|
||||
## 🔄 Release Channels
|
||||
|
||||
PicPeak offers two release channels for different needs:
|
||||
|
||||
### Stable Channel (Recommended)
|
||||
- Production-ready releases
|
||||
- Thoroughly tested before release
|
||||
- Docker tags: `stable`, `latest`, or specific version like `v2.3.0`
|
||||
|
||||
### Beta Channel
|
||||
- Early access to new features
|
||||
- May contain bugs or incomplete functionality
|
||||
- Docker tags: `beta` or specific version like `v2.3.0-beta.1`
|
||||
|
||||
### Switching Channels
|
||||
|
||||
Set the `PICPEAK_CHANNEL` environment variable in your `.env` file:
|
||||
|
||||
```bash
|
||||
# For stable releases (default)
|
||||
PICPEAK_CHANNEL=stable
|
||||
|
||||
# For beta releases
|
||||
PICPEAK_CHANNEL=beta
|
||||
|
||||
# For a specific version
|
||||
PICPEAK_CHANNEL=v2.3.0
|
||||
```
|
||||
|
||||
Then update your containers:
|
||||
|
||||
```bash
|
||||
docker compose -f docker-compose.production.yml pull
|
||||
docker compose -f docker-compose.production.yml up -d
|
||||
```
|
||||
|
||||
### Update Notifications
|
||||
|
||||
The admin dashboard automatically notifies you when updates are available for your channel. To disable update checks, set:
|
||||
|
||||
```bash
|
||||
UPDATE_CHECK_ENABLED=false
|
||||
```
|
||||
|
||||
## 📖 Documentation
|
||||
|
||||
- 📘 [**Deployment Guide**](DEPLOYMENT.md) - Detailed installation instructions
|
||||
- 📘 [**Deployment Guide**](DEPLOYMENT_GUIDE.md) - Detailed installation instructions
|
||||
- Includes the new [External Media Library](DEPLOYMENT_GUIDE.md#external-media-library) reference mode
|
||||
- 📚 [**Admin API (OpenAPI)**](docs/picpeak-admin-api.openapi.yaml) - Machine-readable documentation for event automation endpoints
|
||||
- 🛠️ [**Admin API Quickstart**](docs/admin-api-quickstart.md) - Step-by-step authentication and testing guide for the documented endpoints
|
||||
- 🤝 [**Contributing**](CONTRIBUTING.md) - How to contribute
|
||||
- 📜 [**License**](LICENSE) - MIT License
|
||||
- 🔒 [**Security**](SECURITY.md) - Security policies
|
||||
- 📋 [**Code of Conduct**](CODE_OF_CONDUCT.md) - Community guidelines
|
||||
|
||||
## 🌐 Public Landing Page
|
||||
|
||||
Spotlight your studio with a customizable marketing page at `/`:
|
||||
|
||||
- Head to **Admin → CMS Pages** to enable the public landing page toggle.
|
||||
- Edit the provided HTML template (rich sections, hero, testimonials) and optional CSS overrides.
|
||||
- The preview renders in a sandboxed iframe so you can iterate safely before publishing.
|
||||
- PicPeak sanitizes stored HTML and CSS server-side—scripts, iframes, and unsafe attributes are stripped automatically.
|
||||
- Use **Reset to default** anytime to restore the bundled template.
|
||||
- The backend caches the rendered landing page for 60 seconds by default; override with `PUBLIC_SITE_CACHE_TTL_MS` if you need a different TTL.
|
||||
- When the landing page is disabled PicPeak continues to serve the admin SPA/login exactly as before.
|
||||
|
||||
## 🎯 Use Cases
|
||||
|
||||
Perfect for:
|
||||
@@ -108,6 +194,31 @@ Perfect for:
|
||||
- **Docker**: v20.10.0+
|
||||
- **Docker Compose**: v2.0.0+
|
||||
|
||||
### Video Support Requirements
|
||||
When enabling video uploads, consider these additional resources:
|
||||
|
||||
| Resource | Recommendation | Notes |
|
||||
|----------|----------------|-------|
|
||||
| **RAM** | 4GB+ recommended | FFmpeg processing requires more memory |
|
||||
| **Storage** | Plan for 10-100x more | Videos are significantly larger than images |
|
||||
| **CPU** | Additional cores help | Video thumbnail extraction is CPU-intensive |
|
||||
| **Bandwidth** | Higher throughput | Video streaming requires more bandwidth |
|
||||
|
||||
**Technical Notes:**
|
||||
- FFmpeg is bundled via npm (`@ffmpeg-installer/ffmpeg`) - no system installation required
|
||||
- Maximum upload size: **10GB per video file**
|
||||
- Chunked upload support for files >100MB (resumable uploads)
|
||||
- Supported formats: MP4, WebM, MOV, AVI
|
||||
- Video thumbnails are automatically generated from the first few seconds
|
||||
|
||||
**For Nginx/Reverse Proxy:**
|
||||
If using Nginx, increase the client max body size:
|
||||
```nginx
|
||||
client_max_body_size 10G;
|
||||
proxy_read_timeout 3600;
|
||||
proxy_send_timeout 3600;
|
||||
```
|
||||
|
||||
## 🤝 Contributing
|
||||
|
||||
We love contributions! PicPeak is built by photographers, for photographers. Whether you're fixing bugs, adding features, or improving documentation, your help is welcome.
|
||||
@@ -138,7 +249,7 @@ PicPeak takes security seriously:
|
||||
- 📝 Activity logging
|
||||
- 🔒 Secure file access
|
||||
|
||||
Found a security issue? Please email security@example.com
|
||||
Found a security issue? Please open a [security issue](https://github.com/the-luap/picpeak/issues/new?labels=security) on GitHub
|
||||
|
||||
## 📸 Screenshots
|
||||
|
||||
@@ -177,13 +288,27 @@ Organize and manage your photo galleries with intuitive event management tools.
|
||||
|
||||
We're constantly improving PicPeak and welcome contributions from our community! If you have ideas for new features or want to help implement existing ones, please open an issue or submit a pull request. Your contributions help make PicPeak better for everyone.
|
||||
|
||||
### 🚧 Beta Features (Use at your own risk)
|
||||
|
||||
These features are currently in beta testing and may have limited functionality or stability:
|
||||
|
||||
| Feature | Description | Status |
|
||||
|---------|-------------|--------|
|
||||
| **Simple Deployment Script** | One-click deployment script for quick server setup with automated configuration and dependency installation | 🧪 Beta |
|
||||
|
||||
### 📋 Future Enhancements
|
||||
|
||||
| Feature | Description | Priority | Status |
|
||||
|---------|-------------|----------|---------|
|
||||
| **Backup & Restore** | Comprehensive backup system with S3/MinIO support, automated scheduling, and safe restore functionality | High | ✅ Implemented |
|
||||
| **Gallery Templates** | Additional gallery layouts and themes (masonry, slideshow, story-style) for different event types | Medium | 🔄 Open |
|
||||
| **External Media Library (Reference Mode)** | Use an external folder library as a read‑only source with import and on‑demand thumbnail generation | High | ✅ Implemented |
|
||||
| **Download Protection** | Advanced image protection system with canvas rendering, invisible watermarking, right-click prevention, and DevTools detection to protect photos from unauthorized downloads | High | ✅ Implemented |
|
||||
| **Gallery Templates** | Multiple gallery layouts (grid, masonry, carousel, timeline, hero, mosaic) with custom CSS styling support. Includes starter templates like Apple Liquid Glass for complete visual customization | Medium | ✅ Implemented |
|
||||
| **Face Recognition** | AI-powered face detection to help guests find their photos and create automatic person-based albums | Low | 🔄 Open |
|
||||
| **Gallery Feedback** | Allow guests to like, rate, and comment on photos with admin notifications and moderation | Medium | 🔄 Open |
|
||||
| **Video Support** | Upload and display videos alongside photos in galleries with streaming support | Low | 🔄 Open |
|
||||
| **Gallery Feedback** | Allow guests to like, rate, and comment on photos with admin notifications and moderation | Medium | ✅ Implemented |
|
||||
| **Video Support** | Upload and display videos alongside photos in galleries with streaming support | Low | ✅ Implemented |
|
||||
| **Multiple Administrators** | Support for multiple admin accounts with role-based permissions and activity tracking | Low | ✅ Implemented |
|
||||
| **Filtering & Export Options** | Filter photos by likes, ratings, comments, or favorites. Search by filename. Sort by date, name, size, or rating. Export filtered selections as ZIP or generate Capture One/Lightroom-compatible file lists for professional workflows | Medium | ✅ Implemented |
|
||||
|
||||
**Status Legend:** ✅ Implemented | 🚧 In Progress | 🔄 Open | 📋 Planned
|
||||
|
||||
@@ -191,6 +316,16 @@ We're constantly improving PicPeak and welcome contributions from our community!
|
||||
|
||||
PicPeak is inspired by the best features of commercial platforms while remaining completely open source. Special thanks to all contributors who make this project possible.
|
||||
|
||||
### 🤖 AI-Assisted Development
|
||||
|
||||
This project was generated with the assistance of AI technology, but has been:
|
||||
- ✅ **Fully tested end-to-end** by human developers
|
||||
- 🔒 **Security audited** with comprehensive security checks
|
||||
- 👨💻 **Human-reviewed** for code quality and best practices
|
||||
- 🧪 **Production-tested** in real-world scenarios
|
||||
|
||||
We believe in transparent development practices and the responsible use of AI as a tool to accelerate development while maintaining high standards of quality and security.
|
||||
|
||||
## 📄 License
|
||||
|
||||
PicPeak is released under the [MIT License](LICENSE). Use it freely for personal or commercial projects.
|
||||
@@ -198,7 +333,7 @@ PicPeak is released under the [MIT License](LICENSE). Use it freely for personal
|
||||
## 🚀 Ready to Get Started?
|
||||
|
||||
1. ⭐ **Star this repository** to show your support
|
||||
2. 📖 Read the [Deployment Guide](DEPLOYMENT.md)
|
||||
2. 📖 Read the [Deployment Guide](DEPLOYMENT_GUIDE.md)
|
||||
3. 🐛 Report issues or request features
|
||||
4. 🤝 Join our community and contribute!
|
||||
|
||||
@@ -207,7 +342,9 @@ PicPeak is released under the [MIT License](LICENSE). Use it freely for personal
|
||||
<p align="center">
|
||||
Made with ❤️ by photographers, for photographers
|
||||
<br>
|
||||
<a href="https://www.picpeak.app">Homepage</a> •
|
||||
<a href="https://demo.picpeak.app">Live Demo</a> •
|
||||
<a href="https://github.com/the-luap/picpeak">GitHub</a> •
|
||||
<a href="DEPLOYMENT.md">Documentation</a> •
|
||||
<a href="DEPLOYMENT_GUIDE.md">Documentation</a> •
|
||||
<a href="https://github.com/the-luap/picpeak/issues">Support</a>
|
||||
</p>
|
||||
</p>
|
||||
|
||||
+12
-9
@@ -6,8 +6,8 @@ We release patches for security vulnerabilities. Currently supported versions:
|
||||
|
||||
| Version | Supported |
|
||||
| ------- | ------------------ |
|
||||
| 1.x.x | :white_check_mark: |
|
||||
| < 1.0 | :x: |
|
||||
| 2.x.x | :white_check_mark: |
|
||||
| < 2.0 | :x: |
|
||||
|
||||
## Reporting a Vulnerability
|
||||
|
||||
@@ -15,11 +15,14 @@ We take the security of PicPeak seriously. If you have discovered a security vul
|
||||
|
||||
### 1. **Do NOT create a public GitHub issue**
|
||||
|
||||
### 2. Email us at security@example.com with:
|
||||
- Description of the vulnerability
|
||||
- Steps to reproduce
|
||||
- Potential impact
|
||||
- Suggested fix (if any)
|
||||
### 2. Report the vulnerability privately by:
|
||||
- **Preferred:** Use [GitHub Private Vulnerability Reporting](https://github.com/the-luap/picpeak/security/advisories/new)
|
||||
- **Alternative:** Email us at **info@picpeak.app** with the details
|
||||
- Include:
|
||||
- Description of the vulnerability
|
||||
- Steps to reproduce
|
||||
- Potential impact
|
||||
- Suggested fix (if any)
|
||||
|
||||
### 3. You can expect:
|
||||
- Acknowledgment within 48 hours
|
||||
@@ -79,7 +82,7 @@ We believe in responsible disclosure. Once a vulnerability is fixed:
|
||||
|
||||
## Contact
|
||||
|
||||
- Security issues: security@example.com
|
||||
- General support: https://github.com/the-luap/picpeak/issues
|
||||
- Security issues: Email **info@picpeak.app** or use [GitHub Private Vulnerability Reporting](https://github.com/the-luap/picpeak/security/advisories/new)
|
||||
- General support: [GitHub Issues](https://github.com/the-luap/picpeak/issues)
|
||||
|
||||
Thank you for helping keep PicPeak and its users safe!
|
||||
+553
@@ -0,0 +1,553 @@
|
||||
# 🚀 PicPeak Simple Setup Guide
|
||||
|
||||
This guide provides easy installation instructions for PicPeak on Linux servers with both Docker and non-Docker options.
|
||||
|
||||
## 📋 Quick Start
|
||||
|
||||
### One-Line Installation
|
||||
|
||||
```bash
|
||||
# Download and run the unified setup script
|
||||
curl -fsSL https://raw.githubusercontent.com/the-luap/picpeak/main/scripts/picpeak-setup.sh -o picpeak-setup.sh && \
|
||||
chmod +x picpeak-setup.sh && \
|
||||
sudo ./picpeak-setup.sh
|
||||
```
|
||||
|
||||
The script will automatically detect your environment and recommend the best installation method.
|
||||
|
||||
## 🎯 Installation Methods
|
||||
|
||||
### Method 1: Docker Installation (Recommended)
|
||||
Best for: Most users, easy updates, isolated environment
|
||||
|
||||
```bash
|
||||
sudo ./picpeak-setup.sh --docker
|
||||
```
|
||||
|
||||
**Pros:**
|
||||
- ✅ Easier installation and updates
|
||||
- ✅ Better isolation from system
|
||||
- ✅ Consistent environment across platforms
|
||||
- ✅ Built-in PostgreSQL and Redis
|
||||
|
||||
**Cons:**
|
||||
- ❌ Requires more resources (~4GB RAM recommended)
|
||||
- ❌ Additional Docker overhead
|
||||
|
||||
### Method 2: Native Installation
|
||||
Best for: Resource-constrained systems, Raspberry Pi, direct control
|
||||
|
||||
```bash
|
||||
sudo ./picpeak-setup.sh --native
|
||||
```
|
||||
|
||||
**Pros:**
|
||||
- ✅ Lower resource usage (~1GB RAM minimum)
|
||||
- ✅ Direct system control
|
||||
- ✅ No Docker overhead
|
||||
- ✅ Better for ARM devices
|
||||
|
||||
**Cons:**
|
||||
- ❌ More complex setup
|
||||
- ❌ System dependencies required
|
||||
- ❌ Manual update process
|
||||
|
||||
## 📋 System Requirements
|
||||
|
||||
### Minimum Requirements
|
||||
- **OS**: Ubuntu 20.04+, Debian 11+, Fedora 38+, RHEL/CentOS 8+, Raspberry Pi OS
|
||||
- **RAM**:
|
||||
- Docker: 2GB minimum (4GB recommended)
|
||||
- Native: 1GB minimum (2GB recommended)
|
||||
- **Storage**: 2GB for application + space for photos
|
||||
- **Network**: Port 3001 (or 80/443 with proxy)
|
||||
|
||||
### Supported Platforms
|
||||
- ✅ Ubuntu 20.04, 22.04, 24.04
|
||||
- ✅ Debian 11, 12
|
||||
- ✅ Raspberry Pi OS (32-bit and 64-bit)
|
||||
- ✅ Fedora 38, 39, 40
|
||||
- ✅ RHEL/CentOS/Rocky/AlmaLinux 8, 9
|
||||
|
||||
## 🛠️ Installation Options
|
||||
|
||||
### Interactive Mode (Default)
|
||||
```bash
|
||||
sudo ./picpeak-setup.sh
|
||||
```
|
||||
|
||||
The script will prompt you to choose:
|
||||
1. Installation method (Docker or Native)
|
||||
2. Admin email and password
|
||||
3. Domain configuration (optional)
|
||||
4. Email server settings (optional)
|
||||
5. SSL/HTTPS setup (optional)
|
||||
|
||||
### Unattended Installation
|
||||
|
||||
#### Docker with full configuration:
|
||||
```bash
|
||||
sudo ./picpeak-setup.sh --docker --unattended \
|
||||
--domain photos.example.com \
|
||||
--email admin@example.com \
|
||||
--admin-password SecurePass123 \
|
||||
--smtp-host smtp.gmail.com \
|
||||
--smtp-port 587 \
|
||||
--smtp-user your-email@gmail.com \
|
||||
--smtp-pass your-app-password \
|
||||
--enable-ssl
|
||||
```
|
||||
|
||||
#### Native with minimal configuration:
|
||||
```bash
|
||||
sudo ./picpeak-setup.sh --native --unattended \
|
||||
--email admin@example.com \
|
||||
--admin-password SecurePass123
|
||||
```
|
||||
|
||||
### Command Line Options
|
||||
|
||||
| Option | Description | Example |
|
||||
|--------|-------------|---------|
|
||||
| `--docker` | Use Docker installation | `--docker` |
|
||||
| `--native` | Use native installation | `--native` |
|
||||
| `--unattended` | Run without prompts | `--unattended` |
|
||||
| `--domain` | Domain for HTTPS setup | `--domain photos.example.com` |
|
||||
| `--email` | Admin email address | `--email admin@example.com` |
|
||||
| `--admin-password` | Set admin password | `--admin-password MySecurePass` |
|
||||
| `--smtp-host` | SMTP server hostname | `--smtp-host smtp.gmail.com` |
|
||||
| `--smtp-port` | SMTP server port | `--smtp-port 587` |
|
||||
| `--smtp-user` | SMTP username | `--smtp-user user@gmail.com` |
|
||||
| `--smtp-pass` | SMTP password | `--smtp-pass app-password` |
|
||||
| `--enable-ssl` | Enable HTTPS with Let's Encrypt | `--enable-ssl` |
|
||||
| `--port` | Custom port (native only) | `--port 8080` |
|
||||
| `--update` | Update existing installation | `--update` |
|
||||
| `--uninstall` | Remove installation | `--uninstall` |
|
||||
| `--help` | Show help message | `--help` |
|
||||
|
||||
## 🏗️ What Gets Installed
|
||||
|
||||
### Docker Installation
|
||||
```
|
||||
~/picpeak/ # Or custom directory
|
||||
├── docker-compose.yml # Service definitions
|
||||
├── .env # Configuration
|
||||
├── storage/
|
||||
│ └── events/ # Photo storage
|
||||
│ ├── active/ # Current galleries
|
||||
│ └── archived/ # Expired galleries
|
||||
├── logs/ # Application logs
|
||||
└── backup/ # Backup directory
|
||||
```
|
||||
|
||||
**Services:**
|
||||
- PicPeak Backend (Node.js application)
|
||||
- PostgreSQL Database
|
||||
- Redis Cache
|
||||
- Nginx Reverse Proxy (optional)
|
||||
- Background Workers
|
||||
|
||||
### Native Installation
|
||||
```
|
||||
/opt/picpeak/ # Installation directory
|
||||
├── backend/ # Application code
|
||||
├── events/ # Photo storage
|
||||
│ ├── active/ # Current galleries
|
||||
│ └── archived/ # Expired galleries
|
||||
├── logs/ # Application logs
|
||||
└── config/ # Configuration files
|
||||
```
|
||||
|
||||
**Services (systemd):**
|
||||
- `picpeak-backend` - Main application
|
||||
- `picpeak-workers` - Background workers
|
||||
- `caddy` - Web server (optional)
|
||||
|
||||
## 🌐 Access Methods
|
||||
|
||||
### Direct Access (Simplest)
|
||||
- Docker: `http://your-server:3000` (frontend and admin at `/admin`)
|
||||
- Backend/API: `http://your-server:3001` (API only; no UI routes)
|
||||
|
||||
For native installs, serve the built frontend (e.g., with nginx or Caddy) and access the admin at `/admin` on the frontend domain.
|
||||
|
||||
### With Domain & HTTPS
|
||||
If configured during setup:
|
||||
- `https://your-domain.com` - Gallery frontend
|
||||
- `https://your-domain.com/admin` - Admin panel
|
||||
|
||||
### Behind Existing Proxy
|
||||
Add to your Nginx/Apache configuration (split frontend vs backend):
|
||||
```nginx
|
||||
# Frontend (UI + /admin/*)
|
||||
location / {
|
||||
proxy_pass http://localhost:3000;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Upgrade $http_upgrade;
|
||||
proxy_set_header Connection 'upgrade';
|
||||
proxy_set_header Host $host;
|
||||
proxy_cache_bypass $http_upgrade;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
|
||||
# Backend API and protected resources
|
||||
location /api {
|
||||
proxy_pass http://localhost:3001;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Upgrade $http_upgrade;
|
||||
proxy_set_header Connection 'upgrade';
|
||||
proxy_set_header Host $host;
|
||||
proxy_cache_bypass $http_upgrade;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
client_max_body_size 100M;
|
||||
}
|
||||
location ~ ^/(photos|thumbnails|uploads) {
|
||||
proxy_pass http://localhost:3001;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
```
|
||||
|
||||
## 📁 Managing Galleries
|
||||
|
||||
### Creating a Gallery
|
||||
|
||||
#### Via Admin Panel
|
||||
1. Login to admin panel at `/admin`
|
||||
2. Click "Create New Event"
|
||||
3. Configure settings (name, date, password, customer email)
|
||||
4. Upload photos via drag & drop in the Photos tab
|
||||
5. Publish the gallery when ready
|
||||
|
||||
#### Adding Photos via File System
|
||||
|
||||
> **Important:** You must first create the event in the admin panel. The file watcher only detects new photos for events that already exist in the database. You cannot create a gallery by copying files alone.
|
||||
|
||||
Once an event exists, you can add photos by copying them into the event's folder. PicPeak's built-in file watcher will automatically detect the new files, create database records, and generate thumbnails.
|
||||
|
||||
```bash
|
||||
# Docker installation — copy photos into an existing event's folder
|
||||
cp /path/to/photos/*.jpg ~/picpeak/storage/events/active/<event-slug>/
|
||||
|
||||
# Native installation
|
||||
sudo cp /path/to/photos/*.jpg /opt/picpeak/events/active/<event-slug>/
|
||||
sudo chown -R picpeak:picpeak /opt/picpeak/events/active/<event-slug>
|
||||
```
|
||||
|
||||
The event slug is visible in the admin panel URL or share link (e.g. `wedding-smith-2024`). Supported formats: `.jpg`, `.jpeg`, `.png`, `.webp`. The file watcher has a 2-second stability delay before processing new files.
|
||||
|
||||
### Gallery Structure
|
||||
```
|
||||
<event-slug>/
|
||||
├── collages/ # Group photos (optional subfolder)
|
||||
├── individual/ # Individual photos (optional subfolder)
|
||||
└── photo.jpg # Photos at root level also work
|
||||
```
|
||||
|
||||
## 🔧 Service Management
|
||||
|
||||
### Docker Installation
|
||||
|
||||
```bash
|
||||
cd ~/picpeak
|
||||
|
||||
# Check status
|
||||
docker compose ps
|
||||
|
||||
# View logs
|
||||
docker compose logs -f
|
||||
|
||||
# Stop services
|
||||
docker compose down
|
||||
|
||||
# Start services
|
||||
docker compose up -d
|
||||
|
||||
# Restart services
|
||||
docker compose restart
|
||||
|
||||
# Update PicPeak
|
||||
docker compose pull
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
### Native Installation
|
||||
|
||||
```bash
|
||||
# Check status
|
||||
sudo systemctl status picpeak-backend
|
||||
sudo systemctl status picpeak-workers
|
||||
|
||||
# View logs
|
||||
sudo journalctl -u picpeak-backend -f
|
||||
sudo journalctl -u picpeak-workers -f
|
||||
|
||||
# Start services
|
||||
sudo systemctl start picpeak-backend picpeak-workers
|
||||
|
||||
# Stop services
|
||||
sudo systemctl stop picpeak-backend picpeak-workers
|
||||
|
||||
# Restart services
|
||||
sudo systemctl restart picpeak-backend picpeak-workers
|
||||
|
||||
# Update PicPeak
|
||||
# (reruns migrations to pick up schema fixes for native installs)
|
||||
sudo ./picpeak-setup.sh --update
|
||||
```
|
||||
|
||||
## ⚙️ Configuration
|
||||
|
||||
### Docker Configuration
|
||||
Edit `~/picpeak/.env`:
|
||||
```bash
|
||||
nano ~/picpeak/.env
|
||||
docker compose restart
|
||||
```
|
||||
|
||||
### Native Configuration
|
||||
Edit `/opt/picpeak/app/backend/.env`:
|
||||
```bash
|
||||
sudo nano /opt/picpeak/app/backend/.env
|
||||
sudo systemctl restart picpeak-backend
|
||||
```
|
||||
|
||||
### Key Settings
|
||||
|
||||
| Setting | Description | Default |
|
||||
|---------|-------------|---------|
|
||||
| `JWT_SECRET` | Token signing secret | Auto-generated |
|
||||
| `ADMIN_EMAIL` | Admin email | admin@example.com |
|
||||
| `ADMIN_PASSWORD` | Admin password | Auto-generated |
|
||||
| `PHOTOS_DIR` | Photo storage path | Varies by method |
|
||||
| `SMTP_ENABLED` | Email notifications | false |
|
||||
| `DEFAULT_EXPIRY_DAYS` | Gallery expiration | 30 |
|
||||
|
||||
## 📧 Email Configuration
|
||||
|
||||
### Gmail Setup
|
||||
1. Enable 2-Factor Authentication
|
||||
2. Generate App Password
|
||||
3. Configure:
|
||||
```env
|
||||
SMTP_ENABLED=true
|
||||
SMTP_HOST=smtp.gmail.com
|
||||
SMTP_PORT=587
|
||||
SMTP_SECURE=false
|
||||
SMTP_USER=your-email@gmail.com
|
||||
SMTP_PASS=your-app-password
|
||||
SMTP_FROM=noreply@yourdomain.com
|
||||
```
|
||||
|
||||
### SendGrid Setup
|
||||
1. Sign up at sendgrid.com (100 emails/day free)
|
||||
2. Create API key
|
||||
3. Configure:
|
||||
```env
|
||||
SMTP_ENABLED=true
|
||||
SMTP_HOST=smtp.sendgrid.net
|
||||
SMTP_PORT=587
|
||||
SMTP_USER=apikey
|
||||
SMTP_PASS=your-sendgrid-api-key
|
||||
SMTP_FROM=verified-sender@yourdomain.com
|
||||
```
|
||||
|
||||
## 🔄 Maintenance
|
||||
|
||||
### Backups
|
||||
|
||||
#### Docker:
|
||||
```bash
|
||||
# Backup script included
|
||||
cd ~/picpeak
|
||||
./backup.sh
|
||||
|
||||
# Manual backup
|
||||
docker exec picpeak-postgres pg_dump -U picpeak picpeak > backup.sql
|
||||
tar -czf photos-backup.tar.gz storage/events/
|
||||
```
|
||||
|
||||
#### Native:
|
||||
```bash
|
||||
# Database backup
|
||||
sudo cp /opt/picpeak/app/backend/data/photo_sharing.db /backup/database-$(date +%Y%m%d).sqlite
|
||||
|
||||
# Photos backup
|
||||
sudo tar -czf /backup/photos-$(date +%Y%m%d).tar.gz /opt/picpeak/events/
|
||||
```
|
||||
|
||||
### Updates
|
||||
|
||||
```bash
|
||||
# Docker
|
||||
cd ~/picpeak
|
||||
docker compose pull
|
||||
docker compose up -d
|
||||
|
||||
# Native
|
||||
sudo ./picpeak-setup.sh --update
|
||||
```
|
||||
|
||||
### Uninstall
|
||||
|
||||
```bash
|
||||
# Will prompt for confirmation and data removal options
|
||||
sudo ./picpeak-setup.sh --uninstall
|
||||
```
|
||||
|
||||
## 🐛 Troubleshooting
|
||||
|
||||
### Common Issues
|
||||
|
||||
#### Service Won't Start
|
||||
```bash
|
||||
# Docker
|
||||
docker compose logs backend
|
||||
docker compose down && docker compose up -d
|
||||
|
||||
# Native
|
||||
sudo journalctl -u picpeak-backend -n 50
|
||||
sudo systemctl restart picpeak-backend
|
||||
```
|
||||
|
||||
#### Can't Access Admin Panel
|
||||
1. Check firewall:
|
||||
```bash
|
||||
# Ubuntu/Debian
|
||||
sudo ufw allow 3001
|
||||
|
||||
# RHEL/CentOS
|
||||
sudo firewall-cmd --add-port=3001/tcp --permanent
|
||||
sudo firewall-cmd --reload
|
||||
```
|
||||
|
||||
2. Verify service:
|
||||
```bash
|
||||
# Docker
|
||||
curl http://localhost:3001/api/health
|
||||
|
||||
# Native
|
||||
sudo systemctl is-active picpeak-backend
|
||||
```
|
||||
|
||||
#### Photos Not Showing
|
||||
```bash
|
||||
# Check permissions (Native)
|
||||
sudo chown -R picpeak:picpeak /opt/picpeak/events/
|
||||
sudo chmod -R 755 /opt/picpeak/events/
|
||||
|
||||
# Check permissions (Docker)
|
||||
ls -la ~/picpeak/storage/events/
|
||||
```
|
||||
|
||||
#### Reset Admin Password
|
||||
|
||||
```bash
|
||||
# Docker
|
||||
docker exec picpeak-backend node scripts/reset-admin-password.js
|
||||
|
||||
# Native
|
||||
cd /opt/picpeak/app/backend
|
||||
sudo -u picpeak node scripts/reset-admin-password.js
|
||||
```
|
||||
|
||||
> **Note:** The new password will be displayed in the console output and saved to `ADMIN_PASSWORD_RESET.txt`. Save it immediately!
|
||||
|
||||
### Getting Help
|
||||
|
||||
1. **Check logs:**
|
||||
- Docker: `docker compose logs -f`
|
||||
- Native: `sudo journalctl -u picpeak-backend -f`
|
||||
- Installation: `/tmp/picpeak-setup-*.log`
|
||||
|
||||
2. **Documentation:**
|
||||
- [Full Documentation](https://github.com/the-luap/picpeak)
|
||||
- [Deployment Guide](./DEPLOYMENT_GUIDE.md)
|
||||
|
||||
3. **Support:**
|
||||
- [GitHub Issues](https://github.com/the-luap/picpeak/issues)
|
||||
- Include: Error messages, system info (`uname -a`), installation method
|
||||
|
||||
## 🔒 Security Best Practices
|
||||
|
||||
### Essential Security
|
||||
1. **Change default admin password immediately**
|
||||
2. **Use HTTPS for production** (Let's Encrypt included)
|
||||
3. **Configure firewall** (only open necessary ports)
|
||||
4. **Regular updates** (system and PicPeak)
|
||||
5. **Automated backups** (configure in admin panel)
|
||||
|
||||
### Advanced Security
|
||||
- Use VPN for admin panel access
|
||||
- Configure fail2ban for brute force protection
|
||||
- Enable audit logging
|
||||
- Regular security scans
|
||||
- Implement IP whitelisting
|
||||
|
||||
## 📊 Performance Optimization
|
||||
|
||||
### Docker Optimization
|
||||
```yaml
|
||||
# Adjust in docker-compose.yml
|
||||
services:
|
||||
backend:
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
cpus: '2'
|
||||
memory: 2G
|
||||
```
|
||||
|
||||
### Native Optimization
|
||||
```bash
|
||||
# Increase Node.js memory
|
||||
echo "NODE_OPTIONS=--max-old-space-size=2048" >> /opt/picpeak/app/backend/.env
|
||||
sudo systemctl restart picpeak-backend
|
||||
```
|
||||
|
||||
## 🎯 Quick Setup Examples
|
||||
|
||||
### Home/Office Network
|
||||
```bash
|
||||
# Simple local setup without domain
|
||||
sudo ./picpeak-setup.sh --native --email admin@local.com
|
||||
```
|
||||
|
||||
### Public Website with HTTPS
|
||||
```bash
|
||||
# Full production setup
|
||||
sudo ./picpeak-setup.sh --docker \
|
||||
--domain photos.company.com \
|
||||
--email admin@company.com \
|
||||
--enable-ssl
|
||||
```
|
||||
|
||||
### Raspberry Pi Setup
|
||||
```bash
|
||||
# Optimized for ARM devices
|
||||
sudo ./picpeak-setup.sh --native \
|
||||
--port 8080 \
|
||||
--email pi@local.com
|
||||
```
|
||||
|
||||
## ✅ Post-Installation Checklist
|
||||
|
||||
- [ ] Admin password changed
|
||||
- [ ] Email configuration tested
|
||||
- [ ] First test gallery created
|
||||
- [ ] Backup schedule configured
|
||||
- [ ] Firewall rules applied
|
||||
- [ ] SSL certificate working (if applicable)
|
||||
- [ ] Monitoring setup
|
||||
- [ ] Documentation bookmarked
|
||||
|
||||
---
|
||||
|
||||
**PicPeak Setup v1.0** | [Documentation](https://github.com/the-luap/picpeak) | [Support](https://github.com/the-luap/picpeak/issues)
|
||||
@@ -9,9 +9,43 @@ PORT=3001
|
||||
# Generate with: openssl rand -base64 32
|
||||
JWT_SECRET=your-very-secure-jwt-secret-at-least-32-characters-long-example123456
|
||||
|
||||
# Auth cookie Secure flag
|
||||
# unset - default: follows NODE_ENV (production=true, dev=false)
|
||||
# true - always set Secure (HTTPS-only cookies; breaks plain-HTTP access)
|
||||
# false - never set Secure (allows HTTP; cookies not protected on HTTPS)
|
||||
# auto - decide per request: Secure on HTTPS, not on HTTP
|
||||
#
|
||||
# Use COOKIE_SECURE=auto if your deployment is reachable over both HTTPS
|
||||
# (via a reverse proxy like Nginx Proxy Manager, Traefik, Caddy) AND plain
|
||||
# HTTP (e.g. LAN access at http://192.168.x.x:3001). The backend reads
|
||||
# req.secure from Express, which respects the X-Forwarded-Proto header
|
||||
# when the proxy is in the trust list.
|
||||
#
|
||||
# Requirements for auto mode:
|
||||
# 1. Your reverse proxy MUST send X-Forwarded-Proto: https on HTTPS
|
||||
# requests. Standard configs for NPM/Traefik/Caddy do this by default.
|
||||
# 2. The proxy must be on a trusted IP range. By default PicPeak trusts
|
||||
# loopback and private networks (127.0.0.1, 10.x, 172.16-31.x,
|
||||
# 192.168.x, link-local). Proxies outside those ranges need custom
|
||||
# trust proxy configuration.
|
||||
# COOKIE_SECURE=auto
|
||||
|
||||
# Cookie SameSite attribute (Lax | Strict | None). Default: Lax
|
||||
# COOKIE_SAMESITE=Lax
|
||||
|
||||
# Cookie Domain — set this if serving auth cookies across subdomains.
|
||||
# Leave unset for same-origin setups.
|
||||
# COOKIE_DOMAIN=.example.com
|
||||
|
||||
# URLs (adjust for your domain)
|
||||
ADMIN_URL=https://photos.example.com
|
||||
FRONTEND_URL=https://photos.example.com
|
||||
BACKEND_URL=https://photos.example.com # Or https://api.photos.example.com if separate
|
||||
|
||||
# API URL for email assets (logos, images in emails)
|
||||
# This must be the publicly accessible URL where recipients can load images
|
||||
# If not set, defaults to http://localhost:3001 which will break images in production emails
|
||||
API_URL=https://photos.example.com/api
|
||||
|
||||
# Database Configuration
|
||||
DATABASE_CLIENT=pg
|
||||
@@ -38,6 +72,7 @@ SMTP_PASS=your-sendgrid-api-key
|
||||
EMAIL_FROM=noreply@example.com
|
||||
|
||||
# Storage Paths
|
||||
# IMPORTANT: STORAGE_PATH must be set to avoid file path resolution issues
|
||||
# Docker deployment:
|
||||
STORAGE_PATH=/app/storage
|
||||
EVENTS_PATH=/app/storage/events
|
||||
|
||||
+22
-7
@@ -1,24 +1,39 @@
|
||||
FROM node:18-alpine AS builder
|
||||
FROM node:22-alpine AS builder
|
||||
|
||||
# Add build argument for cache busting
|
||||
# Add build arguments
|
||||
ARG CACHEBUST=1
|
||||
ARG BUILD_DATE
|
||||
ARG VCS_REF
|
||||
ARG VERSION
|
||||
|
||||
# Add labels for GitHub Container Registry
|
||||
LABEL org.opencontainers.image.source="https://github.com/the-luap/picpeak"
|
||||
LABEL org.opencontainers.image.description="PicPeak Backend Service"
|
||||
LABEL org.opencontainers.image.licenses="MIT"
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
# Copy package files
|
||||
COPY package*.json ./
|
||||
|
||||
# Install dependencies
|
||||
RUN npm ci --only=production
|
||||
# Install dependencies (--omit=dev replaces deprecated --only=production)
|
||||
RUN npm ci --omit=dev
|
||||
|
||||
# Copy application files
|
||||
COPY . .
|
||||
|
||||
# Production stage
|
||||
FROM node:18-alpine
|
||||
FROM node:22-alpine
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
# Upgrade all packages to fix security vulnerabilities (OpenSSL, libexpat, BusyBox CVEs)
|
||||
RUN apk upgrade --no-cache
|
||||
|
||||
# Upgrade npm to fix tar, minimatch, brace-expansion CVEs in npm's own deps
|
||||
# Pin to 10.x to stay compatible with Node 22 Alpine (npm 11.x has dependency issues)
|
||||
RUN npm install -g npm@10
|
||||
|
||||
# Install dumb-init for proper signal handling and postgresql-client for database checks
|
||||
RUN apk add --no-cache dumb-init postgresql-client
|
||||
|
||||
@@ -29,8 +44,8 @@ RUN addgroup -g 1001 -S nodejs && adduser -S nodejs -u 1001
|
||||
COPY --from=builder --chown=nodejs:nodejs /app/node_modules ./node_modules
|
||||
COPY --chown=nodejs:nodejs . .
|
||||
|
||||
# Make wait script executable
|
||||
RUN chmod +x wait-for-db.sh
|
||||
# Ensure all source files are readable and wait script is executable
|
||||
RUN chmod -R a+r /app && chmod +x wait-for-db.sh
|
||||
|
||||
# Create necessary directories
|
||||
RUN mkdir -p storage/events/active storage/events/archived storage/thumbnails data logs && \
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
FROM node:18-alpine
|
||||
FROM node:20-alpine
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
# Upgrade all packages to fix security vulnerabilities (BusyBox CVEs)
|
||||
RUN apk upgrade --no-cache
|
||||
|
||||
# Install dumb-init for proper signal handling
|
||||
RUN apk add --no-cache dumb-init
|
||||
|
||||
|
||||
@@ -0,0 +1,184 @@
|
||||
const fs = require('fs');
|
||||
const fsPromises = fs.promises;
|
||||
const os = require('os');
|
||||
const path = require('path');
|
||||
const express = require('express');
|
||||
const request = require('supertest');
|
||||
|
||||
describe('Admin settings logo upload flow', () => {
|
||||
let tmpDir;
|
||||
let router;
|
||||
let app;
|
||||
let settingsStore;
|
||||
|
||||
const resetModules = () => {
|
||||
jest.resetModules();
|
||||
jest.clearAllMocks();
|
||||
};
|
||||
|
||||
beforeEach(async () => {
|
||||
resetModules();
|
||||
|
||||
tmpDir = await fsPromises.mkdtemp(path.join(os.tmpdir(), 'picpeak-logo-'));
|
||||
process.env.STORAGE_PATH = tmpDir;
|
||||
|
||||
settingsStore = new Map();
|
||||
|
||||
const buildQuery = (table) => {
|
||||
const filters = [];
|
||||
const applyFilters = (rows) => {
|
||||
if (filters.length === 0) {
|
||||
return rows;
|
||||
}
|
||||
return rows.filter((row) =>
|
||||
filters.every(({ column, value }) => row[column] === value)
|
||||
);
|
||||
};
|
||||
|
||||
const makeRow = (row) => ({ ...row });
|
||||
|
||||
return {
|
||||
where(column, value) {
|
||||
filters.push({ column, value });
|
||||
return this;
|
||||
},
|
||||
first() {
|
||||
if (table === 'app_settings') {
|
||||
const rows = applyFilters(Array.from(settingsStore.values()).map(makeRow));
|
||||
return Promise.resolve(rows[0]);
|
||||
}
|
||||
return Promise.resolve(undefined);
|
||||
},
|
||||
select() {
|
||||
return Promise.resolve([]);
|
||||
},
|
||||
sum() {
|
||||
return Promise.resolve({ total: 0 });
|
||||
},
|
||||
join() {
|
||||
return this;
|
||||
},
|
||||
groupBy() {
|
||||
return this;
|
||||
},
|
||||
orderBy() {
|
||||
return this;
|
||||
},
|
||||
limit() {
|
||||
return this;
|
||||
},
|
||||
insert(payload) {
|
||||
const rows = Array.isArray(payload) ? payload : [payload];
|
||||
const upsert = (row, overrides = {}) => {
|
||||
if (table === 'app_settings') {
|
||||
const key = row.setting_key;
|
||||
const existing = settingsStore.get(key) || {};
|
||||
settingsStore.set(key, { ...existing, ...row, ...overrides });
|
||||
}
|
||||
return Promise.resolve();
|
||||
};
|
||||
|
||||
return {
|
||||
onConflict() {
|
||||
return {
|
||||
merge(overrides) {
|
||||
return Promise.all(rows.map((row) => upsert(row, overrides))).then(() => undefined);
|
||||
}
|
||||
};
|
||||
}
|
||||
};
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
const dbMock = jest.fn((table) => buildQuery(table));
|
||||
dbMock.raw = jest.fn();
|
||||
dbMock.transaction = async (handler) => handler({
|
||||
commit: async () => {},
|
||||
rollback: async () => {}
|
||||
});
|
||||
|
||||
jest.doMock('../src/database/db', () => ({
|
||||
db: dbMock,
|
||||
logActivity: jest.fn()
|
||||
}));
|
||||
|
||||
jest.doMock('../src/middleware/auth', () => ({
|
||||
adminAuth: (req, res, next) => {
|
||||
req.admin = { id: 1, username: 'tester' };
|
||||
next();
|
||||
}
|
||||
}));
|
||||
|
||||
jest.doMock('../src/services/publicSiteService', () => ({
|
||||
clearPublicSiteCache: jest.fn(),
|
||||
getDefaultPublicSitePayload: jest.fn(),
|
||||
getRawPublicSiteSettings: jest.fn().mockResolvedValue({})
|
||||
}));
|
||||
|
||||
jest.doMock('../src/services/rateLimitService', () => ({
|
||||
clearSettingsCache: jest.fn()
|
||||
}));
|
||||
|
||||
jest.doMock('../src/middleware/maintenance', () => ({
|
||||
maintenanceMiddleware: (req, res, next) => next(),
|
||||
clearMaintenanceCache: jest.fn()
|
||||
}));
|
||||
|
||||
router = require('../src/routes/adminSettings');
|
||||
|
||||
app = express();
|
||||
app.use(express.json());
|
||||
app.use('/api/admin/settings', router);
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
resetModules();
|
||||
if (tmpDir) {
|
||||
await fsPromises.rm(tmpDir, { recursive: true, force: true });
|
||||
tmpDir = null;
|
||||
}
|
||||
delete process.env.STORAGE_PATH;
|
||||
});
|
||||
|
||||
it('stores logo uploads under STORAGE_PATH and deletes on branding reset', async () => {
|
||||
const fileBuffer = Buffer.from('fake image data');
|
||||
|
||||
const uploadResponse = await request(app)
|
||||
.post('/api/admin/settings/logo')
|
||||
.attach('logo', fileBuffer, 'logo.png');
|
||||
|
||||
expect(uploadResponse.status).toBe(200);
|
||||
expect(uploadResponse.body).toHaveProperty('logoUrl');
|
||||
const logoUrl = uploadResponse.body.logoUrl;
|
||||
expect(logoUrl.startsWith('/uploads/logos/')).toBe(true);
|
||||
|
||||
const storedPath = path.join(tmpDir, logoUrl.replace('/uploads/', 'uploads/'));
|
||||
await expect(fsPromises.access(storedPath)).resolves.toBeUndefined();
|
||||
|
||||
await request(app)
|
||||
.put('/api/admin/settings/branding')
|
||||
.send({
|
||||
company_name: 'Test Co',
|
||||
company_tagline: 'Tagline',
|
||||
support_email: 'test@example.com',
|
||||
footer_text: 'Footer',
|
||||
watermark_enabled: false,
|
||||
watermark_position: 'bottom-right',
|
||||
watermark_opacity: 0.5,
|
||||
watermark_size: 'medium',
|
||||
favicon_url: null,
|
||||
logo_url: '',
|
||||
watermark_logo_url: null,
|
||||
logo_size: 'medium',
|
||||
logo_max_height: 120,
|
||||
logo_position: 'left',
|
||||
logo_display_header: true,
|
||||
logo_display_hero: false,
|
||||
logo_display_mode: 'default'
|
||||
})
|
||||
.expect(200);
|
||||
|
||||
await expect(fsPromises.access(storedPath)).rejects.toThrow();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,207 @@
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const os = require('os');
|
||||
const express = require('express');
|
||||
const request = require('supertest');
|
||||
|
||||
describe('Admin photos in reference mode', () => {
|
||||
let tmpDir;
|
||||
let storagePath;
|
||||
let db;
|
||||
let app;
|
||||
let categoryId;
|
||||
|
||||
const resetModules = () => {
|
||||
jest.resetModules();
|
||||
jest.clearAllMocks();
|
||||
};
|
||||
|
||||
beforeAll(async () => {
|
||||
tmpDir = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'picpeak-admin-photos-'));
|
||||
storagePath = path.join(tmpDir, 'storage');
|
||||
await fs.promises.mkdir(storagePath, { recursive: true });
|
||||
|
||||
process.env.NODE_ENV = 'test';
|
||||
process.env.TEST_DATABASE_PATH = path.join(tmpDir, 'data', 'photo_sharing_test.db');
|
||||
await fs.promises.mkdir(path.dirname(process.env.TEST_DATABASE_PATH), { recursive: true });
|
||||
try {
|
||||
await fs.promises.unlink(process.env.TEST_DATABASE_PATH);
|
||||
} catch (_) {
|
||||
/* ignore */
|
||||
}
|
||||
process.env.STORAGE_PATH = storagePath;
|
||||
|
||||
resetModules();
|
||||
|
||||
jest.doMock('../../src/middleware/auth', () => ({
|
||||
adminAuth: (req, _res, next) => {
|
||||
req.admin = { id: 1, username: 'tester' };
|
||||
next();
|
||||
}
|
||||
}));
|
||||
|
||||
jest.doMock('../../src/services/imageProcessor', () => ({
|
||||
generateThumbnail: jest.fn().mockResolvedValue('thumbnails/mock-thumb.jpg'),
|
||||
ensureThumbnail: jest.fn()
|
||||
}));
|
||||
|
||||
jest.doMock('../../src/middleware/uploadValidation', () => ({
|
||||
validateUploadedFiles: (_req, _res, next) => next()
|
||||
}));
|
||||
|
||||
jest.doMock('../../src/utils/fileSecurityUtils', () => {
|
||||
const actual = jest.requireActual('../../src/utils/fileSecurityUtils');
|
||||
return {
|
||||
...actual,
|
||||
validateFileType: () => true,
|
||||
createFileUploadValidator: () => (_req, _res, next) => next()
|
||||
};
|
||||
});
|
||||
|
||||
jest.doMock('../../src/utils/logger', () => ({
|
||||
debug: jest.fn(),
|
||||
info: jest.fn(),
|
||||
warn: jest.fn(),
|
||||
error: jest.fn()
|
||||
}));
|
||||
|
||||
const dbModule = require('../../src/database/db');
|
||||
db = dbModule.db;
|
||||
|
||||
await db.schema.dropTableIfExists('photo_feedback');
|
||||
await db.schema.dropTableIfExists('photos');
|
||||
await db.schema.dropTableIfExists('photo_categories');
|
||||
await db.schema.dropTableIfExists('events');
|
||||
|
||||
await db.schema.createTable('events', (table) => {
|
||||
table.increments('id').primary();
|
||||
table.string('slug').notNullable();
|
||||
table.string('event_name').notNullable();
|
||||
table.string('source_mode').notNullable();
|
||||
table.string('external_path');
|
||||
});
|
||||
|
||||
await db.schema.createTable('photo_categories', (table) => {
|
||||
table.increments('id').primary();
|
||||
table.string('name').notNullable();
|
||||
table.string('slug').notNullable();
|
||||
table.boolean('is_global').defaultTo(true);
|
||||
table.integer('event_id');
|
||||
});
|
||||
|
||||
await db.schema.createTable('photos', (table) => {
|
||||
table.increments('id').primary();
|
||||
table.integer('event_id').notNullable();
|
||||
table.string('filename').notNullable();
|
||||
table.string('path').notNullable();
|
||||
table.string('thumbnail_path');
|
||||
table.string('type').notNullable();
|
||||
table.integer('size_bytes');
|
||||
table.integer('category_id');
|
||||
table.string('source_origin');
|
||||
table.string('external_relpath');
|
||||
table.datetime('uploaded_at').defaultTo(db.fn.now());
|
||||
table.float('average_rating').defaultTo(0);
|
||||
table.integer('like_count').defaultTo(0);
|
||||
table.integer('favorite_count').defaultTo(0);
|
||||
});
|
||||
|
||||
await db.schema.createTable('photo_feedback', (table) => {
|
||||
table.increments('id');
|
||||
table.integer('photo_id');
|
||||
table.string('feedback_type');
|
||||
table.boolean('is_approved');
|
||||
table.boolean('is_hidden');
|
||||
});
|
||||
|
||||
await db('events').insert({
|
||||
id: 1,
|
||||
slug: 'test-event',
|
||||
event_name: 'Test Event',
|
||||
source_mode: 'reference',
|
||||
external_path: 'external/library'
|
||||
});
|
||||
|
||||
const insertedCategory = await db('photo_categories').insert({
|
||||
name: 'Highlights',
|
||||
slug: 'highlights',
|
||||
is_global: true
|
||||
});
|
||||
categoryId = Array.isArray(insertedCategory) ? insertedCategory[0] : insertedCategory;
|
||||
|
||||
const router = require('../../src/routes/adminPhotos');
|
||||
app = express();
|
||||
app.use(express.json());
|
||||
app.use('/api/admin/events', router);
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
if (db) {
|
||||
await db.destroy();
|
||||
}
|
||||
resetModules();
|
||||
delete process.env.TEST_DATABASE_PATH;
|
||||
delete process.env.STORAGE_PATH;
|
||||
if (tmpDir) {
|
||||
await fs.promises.rm(tmpDir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it('stores managed uploads with category information and managed origin', async () => {
|
||||
const uploadResponse = await request(app)
|
||||
.post(`/api/admin/events/1/upload`)
|
||||
.field('category_id', String(categoryId))
|
||||
.attach('photos', Buffer.from('fake image data'), 'photo.jpg');
|
||||
|
||||
expect(uploadResponse.status).toBe(200);
|
||||
expect(uploadResponse.body).toHaveProperty('photos');
|
||||
expect(Array.isArray(uploadResponse.body.photos)).toBe(true);
|
||||
|
||||
const photo = await db('photos').first();
|
||||
expect(photo).toBeTruthy();
|
||||
expect(photo.category_id).toBe(categoryId);
|
||||
expect(photo.source_origin).toBe('managed');
|
||||
expect(photo.external_relpath).toBeNull();
|
||||
});
|
||||
|
||||
it('returns numeric category metadata when listing photos', async () => {
|
||||
await db('photos').insert({
|
||||
event_id: 1,
|
||||
filename: 'external.jpg',
|
||||
path: 'test-event/external.jpg',
|
||||
thumbnail_path: null,
|
||||
type: 'individual',
|
||||
size_bytes: 123,
|
||||
source_origin: 'external',
|
||||
external_relpath: 'individual/external.jpg'
|
||||
});
|
||||
|
||||
const response = await request(app)
|
||||
.get(`/api/admin/events/1/photos`)
|
||||
.expect(200);
|
||||
|
||||
expect(Array.isArray(response.body.photos)).toBe(true);
|
||||
const managedPhoto = response.body.photos.find((p) => p.category_id === categoryId);
|
||||
expect(managedPhoto).toBeTruthy();
|
||||
expect(managedPhoto.category_name).toBe('Highlights');
|
||||
|
||||
const filtered = await request(app)
|
||||
.get(`/api/admin/events/1/photos`)
|
||||
.query({ category_id: String(categoryId) })
|
||||
.expect(200);
|
||||
|
||||
expect(filtered.body.photos.every((p) => p.category_id === categoryId)).toBe(true);
|
||||
});
|
||||
|
||||
it('normalizes category updates', async () => {
|
||||
const photo = await db('photos').first();
|
||||
|
||||
await request(app)
|
||||
.patch(`/api/admin/events/1/photos/${photo.id}`)
|
||||
.send({ category_id: '0' })
|
||||
.expect(200);
|
||||
|
||||
const updated = await db('photos').where({ id: photo.id }).first();
|
||||
expect(updated.category_id).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,4 @@
|
||||
const { describe, it, expect, jest, beforeAll, afterAll, beforeEach, afterEach } = require('@jest/globals');
|
||||
const { describe, it, expect, beforeAll, afterAll, beforeEach, afterEach } = require('@jest/globals');
|
||||
const { S3Client, CreateBucketCommand, DeleteBucketCommand, ListObjectsV2Command, DeleteObjectsCommand } = require('@aws-sdk/client-s3');
|
||||
const path = require('path');
|
||||
const fs = require('fs').promises;
|
||||
@@ -503,4 +503,4 @@ describe('S3 Backup Integration Tests', () => {
|
||||
console.error('Failed to cleanup S3 objects:', error);
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
const { describe, it, expect, jest, beforeEach, afterEach } = require('@jest/globals');
|
||||
const { describe, it, expect, beforeEach, afterEach } = require('@jest/globals');
|
||||
const mockFs = require('mock-fs');
|
||||
const path = require('path');
|
||||
const crypto = require('crypto');
|
||||
@@ -748,4 +748,4 @@ describe('Enhanced Backup Service Tests', () => {
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
const path = require('path');
|
||||
const mockPath = path;
|
||||
|
||||
jest.mock('../../src/services/externalMediaService', () => ({
|
||||
resolveExternalPath: jest.fn((event, relPath) => mockPath.join('/mock/external', event.external_path || '', relPath || '')),
|
||||
}));
|
||||
|
||||
const { resolveExternalPath } = require('../../src/services/externalMediaService');
|
||||
const { resolvePhotoFilePath } = require('../../src/services/photoResolver');
|
||||
|
||||
describe('resolvePhotoFilePath', () => {
|
||||
const backendRoot = path.resolve(__dirname, '../../');
|
||||
const originalStoragePath = process.env.STORAGE_PATH;
|
||||
|
||||
beforeEach(() => {
|
||||
process.env.STORAGE_PATH = path.join(backendRoot, 'storage');
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
jest.clearAllMocks();
|
||||
});
|
||||
|
||||
afterAll(() => {
|
||||
if (typeof originalStoragePath === 'string') {
|
||||
process.env.STORAGE_PATH = originalStoragePath;
|
||||
} else {
|
||||
delete process.env.STORAGE_PATH;
|
||||
}
|
||||
});
|
||||
|
||||
it('returns absolute path for managed photos with legacy slug paths', () => {
|
||||
const event = { slug: 'wedding-party', source_mode: 'managed' };
|
||||
const photo = { path: 'wedding-party/hero.jpg' };
|
||||
|
||||
const result = resolvePhotoFilePath(event, photo);
|
||||
|
||||
expect(result).toBe(path.join(backendRoot, 'storage', 'events/active', 'wedding-party', 'hero.jpg'));
|
||||
});
|
||||
|
||||
it('normalizes prefixed managed paths without duplicating segments', () => {
|
||||
const event = { slug: 'wedding-party', source_mode: 'managed' };
|
||||
const photo = { path: 'events/active/wedding-party/hero.jpg' };
|
||||
|
||||
const result = resolvePhotoFilePath(event, photo);
|
||||
|
||||
expect(result).toBe(path.join(backendRoot, 'storage', 'events/active', 'wedding-party', 'hero.jpg'));
|
||||
});
|
||||
|
||||
it('delegates external photos to external media resolver', () => {
|
||||
const event = { slug: 'fashion-show', source_mode: 'reference', external_path: 'picsum-demo' };
|
||||
const photo = { source_origin: 'external', external_relpath: 'individual/look-01.jpg' };
|
||||
|
||||
const result = resolvePhotoFilePath(event, photo);
|
||||
|
||||
expect(resolveExternalPath).toHaveBeenCalledWith(event, 'individual/look-01.jpg');
|
||||
expect(result).toBe(path.join('/mock/external', 'picsum-demo', 'individual', 'look-01.jpg'));
|
||||
});
|
||||
|
||||
it('deduplicates folder names when event external path already ends with segment', () => {
|
||||
const event = { slug: 'fashion-show', source_mode: 'reference', external_path: 'picsum-demo/individual' };
|
||||
const photo = { source_origin: 'external', external_relpath: 'individual/look-02.jpg' };
|
||||
|
||||
const result = resolvePhotoFilePath(event, photo);
|
||||
|
||||
expect(resolveExternalPath).toHaveBeenCalledWith(event, 'look-02.jpg');
|
||||
expect(result).toBe(path.join('/mock/external', 'picsum-demo/individual', 'look-02.jpg'));
|
||||
});
|
||||
|
||||
it('falls back to managed storage when external metadata is missing', () => {
|
||||
const event = { slug: 'fashion-show', source_mode: 'reference', external_path: 'picsum-demo' };
|
||||
const photo = { path: 'fashion-show/new-upload.jpg' };
|
||||
|
||||
const result = resolvePhotoFilePath(event, photo);
|
||||
|
||||
expect(resolveExternalPath).not.toHaveBeenCalled();
|
||||
expect(result).toBe(path.join(backendRoot, 'storage', 'events/active', 'fashion-show', 'new-upload.jpg'));
|
||||
});
|
||||
|
||||
it('throws when external photo is missing relative path data', () => {
|
||||
const event = { slug: 'fashion-show', source_mode: 'reference', external_path: 'picsum-demo' };
|
||||
const photo = { source_origin: 'external' };
|
||||
|
||||
expect(() => resolvePhotoFilePath(event, photo)).toThrow('Missing external_relpath for external photo');
|
||||
});
|
||||
});
|
||||
Binary file not shown.
@@ -1831,8 +1831,8 @@
|
||||
}
|
||||
},
|
||||
"nodemailer": {
|
||||
"version": "6.10.1",
|
||||
"resolved": "https://registry.npmjs.org/nodemailer/-/nodemailer-6.10.1.tgz",
|
||||
"version": "7.0.7",
|
||||
"resolved": "https://registry.npmjs.org/nodemailer/-/nodemailer-7.0.7.tgz",
|
||||
"overridden": false
|
||||
},
|
||||
"nodemon": {
|
||||
@@ -2086,8 +2086,8 @@
|
||||
"version": "4.0.1"
|
||||
},
|
||||
"tar-fs": {
|
||||
"version": "2.1.3",
|
||||
"resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-2.1.3.tgz",
|
||||
"version": "2.1.4",
|
||||
"resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-2.1.4.tgz",
|
||||
"overridden": false
|
||||
},
|
||||
"tunnel-agent": {
|
||||
|
||||
@@ -1,4 +1,10 @@
|
||||
beforeAll(() => {
|
||||
process.env.NODE_ENV = 'test';
|
||||
process.env.JWT_SECRET = 'test-secret';
|
||||
if (!process.env.SKIP_S3_TESTS) {
|
||||
process.env.SKIP_S3_TESTS = 'true';
|
||||
}
|
||||
if (!process.env.STORAGE_PATH) {
|
||||
process.env.STORAGE_PATH = '/storage';
|
||||
}
|
||||
});
|
||||
|
||||
+102
-25
@@ -3,6 +3,54 @@ require('dotenv').config();
|
||||
const path = require('path');
|
||||
|
||||
// Database configuration for different environments
|
||||
const resolveSqliteFilename = (filenameEnv) => {
|
||||
const fallback = path.join(__dirname, './data/photo_sharing.db');
|
||||
|
||||
if (!filenameEnv) {
|
||||
return fallback;
|
||||
}
|
||||
|
||||
const trimmed = String(filenameEnv).trim();
|
||||
if (!trimmed) {
|
||||
return fallback;
|
||||
}
|
||||
|
||||
let resolved;
|
||||
if (path.isAbsolute(trimmed)) {
|
||||
resolved = trimmed;
|
||||
} else if (trimmed.startsWith('./') || trimmed.startsWith('../')) {
|
||||
resolved = path.resolve(__dirname, trimmed);
|
||||
} else {
|
||||
resolved = path.join(__dirname, trimmed);
|
||||
}
|
||||
|
||||
const normalized = path.normalize(resolved);
|
||||
const baseSuffix = path.relative(path.parse(__dirname).root, path.normalize(__dirname));
|
||||
const duplicatePattern = `${path.sep}${baseSuffix}${path.sep}${baseSuffix}`;
|
||||
|
||||
if (normalized.includes(duplicatePattern)) {
|
||||
return normalized.replace(duplicatePattern, `${path.sep}${baseSuffix}`);
|
||||
}
|
||||
|
||||
return normalized;
|
||||
};
|
||||
|
||||
const sqliteConnection = (filenameEnv) => ({
|
||||
filename: resolveSqliteFilename(filenameEnv)
|
||||
});
|
||||
|
||||
const baseSqliteConfig = {
|
||||
client: 'sqlite3',
|
||||
connection: sqliteConnection(),
|
||||
useNullAsDefault: true,
|
||||
migrations: {
|
||||
directory: './migrations'
|
||||
},
|
||||
seeds: {
|
||||
directory: './seeds'
|
||||
}
|
||||
};
|
||||
|
||||
const config = {
|
||||
development: {
|
||||
client: process.env.DATABASE_CLIENT || 'sqlite3',
|
||||
@@ -13,7 +61,7 @@ const config = {
|
||||
password: process.env.DB_PASSWORD || 'postgres',
|
||||
database: process.env.DB_NAME || 'photo_sharing'
|
||||
} : {
|
||||
filename: path.join(__dirname, process.env.DATABASE_PATH || './data/photo_sharing.db')
|
||||
filename: resolveSqliteFilename(process.env.DATABASE_PATH || './data/photo_sharing.db')
|
||||
},
|
||||
useNullAsDefault: process.env.DATABASE_CLIENT !== 'pg',
|
||||
migrations: {
|
||||
@@ -24,36 +72,65 @@ const config = {
|
||||
}
|
||||
},
|
||||
|
||||
test: (() => {
|
||||
const client = process.env.DATABASE_CLIENT || 'sqlite3';
|
||||
const isPostgres = client === 'pg';
|
||||
|
||||
return {
|
||||
...baseSqliteConfig,
|
||||
client,
|
||||
useNullAsDefault: !isPostgres,
|
||||
connection: isPostgres
|
||||
? {
|
||||
host: process.env.DB_HOST || 'localhost',
|
||||
port: process.env.DB_PORT || 5432,
|
||||
user: process.env.DB_USER || 'postgres',
|
||||
password: process.env.DB_PASSWORD || 'postgres',
|
||||
database: process.env.DB_NAME || 'photo_sharing_test'
|
||||
}
|
||||
: sqliteConnection(process.env.TEST_DATABASE_PATH || './data/photo_sharing_test.db')
|
||||
};
|
||||
})(),
|
||||
|
||||
production: {
|
||||
client: process.env.DATABASE_CLIENT || 'pg',
|
||||
connection: {
|
||||
host: process.env.DB_HOST || 'db',
|
||||
port: process.env.DB_PORT || 5432,
|
||||
user: process.env.DB_USER || 'picpeak',
|
||||
password: process.env.DB_PASSWORD,
|
||||
database: process.env.DB_NAME || 'picpeak',
|
||||
ssl: process.env.DB_SSL === 'true' ? { rejectUnauthorized: false } : false,
|
||||
// Connection stability settings
|
||||
connectionTimeoutMillis: 30000,
|
||||
idleTimeoutMillis: 30000,
|
||||
keepAlive: true,
|
||||
keepAliveInitialDelayMillis: 0
|
||||
},
|
||||
pool: {
|
||||
min: 5,
|
||||
max: 25,
|
||||
acquireTimeoutMillis: 60000,
|
||||
createTimeoutMillis: 60000,
|
||||
idleTimeoutMillis: 30000,
|
||||
reapIntervalMillis: 1000,
|
||||
createRetryIntervalMillis: 200,
|
||||
propagateCreateError: false
|
||||
},
|
||||
// Support both Postgres and SQLite in production based on DATABASE_CLIENT
|
||||
connection: (process.env.DATABASE_CLIENT || 'pg') === 'pg'
|
||||
? {
|
||||
host: process.env.DB_HOST || 'db',
|
||||
port: process.env.DB_PORT || 5432,
|
||||
user: process.env.DB_USER || 'picpeak',
|
||||
password: process.env.DB_PASSWORD,
|
||||
database: process.env.DB_NAME || 'picpeak',
|
||||
ssl: process.env.DB_SSL === 'true' ? { rejectUnauthorized: false } : false,
|
||||
// Connection stability settings
|
||||
connectionTimeoutMillis: 30000,
|
||||
idleTimeoutMillis: 30000,
|
||||
keepAlive: true,
|
||||
keepAliveInitialDelayMillis: 0
|
||||
}
|
||||
: {
|
||||
filename: resolveSqliteFilename(process.env.DATABASE_PATH || './data/photo_sharing.db')
|
||||
},
|
||||
useNullAsDefault: (process.env.DATABASE_CLIENT || 'pg') !== 'pg',
|
||||
pool: (process.env.DATABASE_CLIENT || 'pg') === 'pg'
|
||||
? {
|
||||
min: 5,
|
||||
max: 25,
|
||||
acquireTimeoutMillis: 60000,
|
||||
createTimeoutMillis: 60000,
|
||||
idleTimeoutMillis: 30000,
|
||||
reapIntervalMillis: 1000,
|
||||
createRetryIntervalMillis: 200,
|
||||
propagateCreateError: false
|
||||
}
|
||||
: undefined,
|
||||
migrations: {
|
||||
directory: './migrations'
|
||||
},
|
||||
acquireConnectionTimeout: 60000
|
||||
}
|
||||
};
|
||||
const env = process.env.NODE_ENV || 'development';
|
||||
|
||||
module.exports = config[process.env.NODE_ENV || 'development'];
|
||||
module.exports = config[env] || config.development;
|
||||
|
||||
@@ -1,101 +0,0 @@
|
||||
const { db } = require('../src/database/db');
|
||||
|
||||
async function up() {
|
||||
console.log('Adding photo categories and CMS tables...');
|
||||
|
||||
// Create photo_categories table
|
||||
await db.schema.createTable('photo_categories', (table) => {
|
||||
table.increments('id').primary();
|
||||
table.string('name', 100).notNullable();
|
||||
table.string('slug', 100).notNullable();
|
||||
table.boolean('is_global').defaultTo(true);
|
||||
table.integer('event_id').references('id').inTable('events').onDelete('CASCADE');
|
||||
table.timestamp('created_at').defaultTo(db.fn.now());
|
||||
|
||||
// Unique constraint for slug within event scope
|
||||
table.unique(['slug', 'event_id']);
|
||||
});
|
||||
|
||||
// Create cms_pages table
|
||||
await db.schema.createTable('cms_pages', (table) => {
|
||||
table.increments('id').primary();
|
||||
table.string('slug', 100).unique().notNullable();
|
||||
table.text('title_en');
|
||||
table.text('title_de');
|
||||
table.text('content_en');
|
||||
table.text('content_de');
|
||||
table.timestamp('updated_at').defaultTo(db.fn.now());
|
||||
});
|
||||
|
||||
// Add category_id to photos table
|
||||
await db.schema.alterTable('photos', (table) => {
|
||||
table.integer('category_id').references('id').inTable('photo_categories');
|
||||
});
|
||||
|
||||
// Add language preference to admin_users
|
||||
await db.schema.alterTable('admin_users', (table) => {
|
||||
table.string('language', 2).defaultTo('en');
|
||||
});
|
||||
|
||||
// Add language preference to app_settings for global default
|
||||
await db('app_settings').insert({
|
||||
setting_key: 'default_language',
|
||||
setting_value: 'en',
|
||||
setting_type: 'general',
|
||||
updated_at: new Date()
|
||||
});
|
||||
|
||||
// Insert default global categories
|
||||
const defaultCategories = [
|
||||
{ name: 'Ceremony', slug: 'ceremony', is_global: true },
|
||||
{ name: 'Reception', slug: 'reception', is_global: true },
|
||||
{ name: 'Portraits', slug: 'portraits', is_global: true },
|
||||
{ name: 'Group Photos', slug: 'group-photos', is_global: true },
|
||||
{ name: 'Details', slug: 'details', is_global: true },
|
||||
{ name: 'Party', slug: 'party', is_global: true }
|
||||
];
|
||||
|
||||
await db('photo_categories').insert(defaultCategories);
|
||||
|
||||
// Insert default legal pages
|
||||
await db('cms_pages').insert([
|
||||
{
|
||||
slug: 'impressum',
|
||||
title_en: 'Legal Notice',
|
||||
title_de: 'Impressum',
|
||||
content_en: '<h2>Legal Notice</h2><p>Please edit this content in the admin panel.</p>',
|
||||
content_de: '<h2>Impressum</h2><p>Bitte bearbeiten Sie diesen Inhalt im Admin-Panel.</p>',
|
||||
updated_at: new Date()
|
||||
},
|
||||
{
|
||||
slug: 'datenschutz',
|
||||
title_en: 'Privacy Policy',
|
||||
title_de: 'Datenschutzerklärung',
|
||||
content_en: '<h2>Privacy Policy</h2><p>Please edit this content in the admin panel.</p>',
|
||||
content_de: '<h2>Datenschutzerklärung</h2><p>Bitte bearbeiten Sie diesen Inhalt im Admin-Panel.</p>',
|
||||
updated_at: new Date()
|
||||
}
|
||||
]);
|
||||
|
||||
console.log('Photo categories and CMS tables created successfully');
|
||||
}
|
||||
|
||||
async function down() {
|
||||
// Remove language from app_settings
|
||||
await db('app_settings').where('setting_key', 'default_language').delete();
|
||||
|
||||
// Drop columns
|
||||
await db.schema.alterTable('admin_users', (table) => {
|
||||
table.dropColumn('language');
|
||||
});
|
||||
|
||||
await db.schema.alterTable('photos', (table) => {
|
||||
table.dropColumn('category_id');
|
||||
});
|
||||
|
||||
// Drop tables
|
||||
await db.schema.dropTableIfExists('cms_pages');
|
||||
await db.schema.dropTableIfExists('photo_categories');
|
||||
}
|
||||
|
||||
module.exports = { up, down };
|
||||
@@ -1,28 +0,0 @@
|
||||
exports.up = async function(knex) {
|
||||
// Add photo_counter column to photo_categories table
|
||||
await knex.schema.alterTable('photo_categories', function(table) {
|
||||
table.integer('photo_counter').defaultTo(0).notNullable();
|
||||
});
|
||||
|
||||
// Initialize counters based on existing photos
|
||||
const categories = await knex('photo_categories').select('id');
|
||||
|
||||
for (const category of categories) {
|
||||
const photoCount = await knex('photos')
|
||||
.where('category_id', category.id)
|
||||
.count('id as count')
|
||||
.first();
|
||||
|
||||
if (photoCount && photoCount.count > 0) {
|
||||
await knex('photo_categories')
|
||||
.where('id', category.id)
|
||||
.update({ photo_counter: photoCount.count });
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
exports.down = async function(knex) {
|
||||
await knex.schema.alterTable('photo_categories', function(table) {
|
||||
table.dropColumn('photo_counter');
|
||||
});
|
||||
};
|
||||
@@ -1,35 +0,0 @@
|
||||
exports.up = async function(knex) {
|
||||
// Add language-specific columns to email_templates
|
||||
await knex.schema.alterTable('email_templates', function(table) {
|
||||
// Add English versions (rename existing columns for consistency)
|
||||
table.renameColumn('subject', 'subject_en');
|
||||
table.renameColumn('body_html', 'body_html_en');
|
||||
table.renameColumn('body_text', 'body_text_en');
|
||||
|
||||
// Add German versions
|
||||
table.string('subject_de');
|
||||
table.text('body_html_de');
|
||||
table.text('body_text_de');
|
||||
});
|
||||
|
||||
// Copy existing values to German columns as defaults
|
||||
await knex('email_templates').update({
|
||||
subject_de: knex.raw('subject_en'),
|
||||
body_html_de: knex.raw('body_html_en'),
|
||||
body_text_de: knex.raw('body_text_en')
|
||||
});
|
||||
};
|
||||
|
||||
exports.down = async function(knex) {
|
||||
await knex.schema.alterTable('email_templates', function(table) {
|
||||
// Remove German columns
|
||||
table.dropColumn('subject_de');
|
||||
table.dropColumn('body_html_de');
|
||||
table.dropColumn('body_text_de');
|
||||
|
||||
// Rename columns back
|
||||
table.renameColumn('subject_en', 'subject');
|
||||
table.renameColumn('body_html_en', 'body_html');
|
||||
table.renameColumn('body_text_en', 'body_text');
|
||||
});
|
||||
};
|
||||
@@ -1,23 +0,0 @@
|
||||
exports.up = async function(knex) {
|
||||
// Add user upload settings to events table
|
||||
await knex.schema.alterTable('events', function(table) {
|
||||
table.boolean('allow_user_uploads').defaultTo(false);
|
||||
table.integer('upload_category_id').references('id').inTable('photo_categories').onDelete('SET NULL');
|
||||
});
|
||||
|
||||
// Add uploaded_by field to photos table to track who uploaded
|
||||
await knex.schema.alterTable('photos', function(table) {
|
||||
table.string('uploaded_by').defaultTo('admin'); // 'admin' or guest identifier
|
||||
});
|
||||
};
|
||||
|
||||
exports.down = async function(knex) {
|
||||
await knex.schema.alterTable('events', function(table) {
|
||||
table.dropColumn('allow_user_uploads');
|
||||
table.dropColumn('upload_category_id');
|
||||
});
|
||||
|
||||
await knex.schema.alterTable('photos', function(table) {
|
||||
table.dropColumn('uploaded_by');
|
||||
});
|
||||
};
|
||||
@@ -1,19 +0,0 @@
|
||||
exports.up = function(knex) {
|
||||
return knex.schema.createTable('login_attempts', table => {
|
||||
table.increments('id').primary();
|
||||
table.string('identifier').notNullable(); // username or email
|
||||
table.string('ip_address', 45).notNullable(); // IPv4 or IPv6
|
||||
table.text('user_agent');
|
||||
table.timestamp('attempt_time').defaultTo(knex.fn.now());
|
||||
table.boolean('success').defaultTo(false);
|
||||
|
||||
// Indexes for performance
|
||||
table.index('identifier');
|
||||
table.index('attempt_time');
|
||||
table.index(['identifier', 'success', 'attempt_time']);
|
||||
});
|
||||
};
|
||||
|
||||
exports.down = function(knex) {
|
||||
return knex.schema.dropTableIfExists('login_attempts');
|
||||
};
|
||||
@@ -1,25 +0,0 @@
|
||||
exports.up = function(knex) {
|
||||
return knex.schema.table('admin_users', table => {
|
||||
// Add password change tracking
|
||||
table.timestamp('password_changed_at').nullable();
|
||||
|
||||
// Add last login IP for security monitoring
|
||||
table.string('last_login_ip', 45).nullable();
|
||||
|
||||
// Add account security flags
|
||||
table.boolean('two_factor_enabled').defaultTo(false);
|
||||
table.string('two_factor_secret').nullable();
|
||||
|
||||
// Add index for performance
|
||||
table.index('password_changed_at');
|
||||
});
|
||||
};
|
||||
|
||||
exports.down = function(knex) {
|
||||
return knex.schema.table('admin_users', table => {
|
||||
table.dropColumn('password_changed_at');
|
||||
table.dropColumn('last_login_ip');
|
||||
table.dropColumn('two_factor_enabled');
|
||||
table.dropColumn('two_factor_secret');
|
||||
});
|
||||
};
|
||||
@@ -1,34 +0,0 @@
|
||||
exports.up = function(knex) {
|
||||
return knex.schema
|
||||
// Table for individual token revocations
|
||||
.createTable('revoked_tokens', table => {
|
||||
table.increments('id').primary();
|
||||
table.string('token_id').notNullable().unique(); // JWT ID or generated ID
|
||||
table.integer('user_id').nullable(); // User who owned the token
|
||||
table.string('token_type', 20); // admin, gallery, etc.
|
||||
table.timestamp('revoked_at').defaultTo(knex.fn.now());
|
||||
table.timestamp('expires_at').notNullable(); // When token would have expired
|
||||
table.string('reason', 100); // password_change, logout, compromised, etc.
|
||||
table.text('metadata'); // Additional JSON data
|
||||
|
||||
// Indexes for performance
|
||||
table.index('token_id');
|
||||
table.index('user_id');
|
||||
table.index('expires_at'); // For cleanup
|
||||
})
|
||||
// Table for user-level revocations (revoke all tokens before a certain time)
|
||||
.createTable('user_token_revocations', table => {
|
||||
table.integer('user_id').primary();
|
||||
table.timestamp('revoked_at').notNullable();
|
||||
table.string('reason', 100);
|
||||
|
||||
// Index for quick lookups
|
||||
table.index('revoked_at');
|
||||
});
|
||||
};
|
||||
|
||||
exports.down = function(knex) {
|
||||
return knex.schema
|
||||
.dropTableIfExists('user_token_revocations')
|
||||
.dropTableIfExists('revoked_tokens');
|
||||
};
|
||||
@@ -1,129 +0,0 @@
|
||||
// No helpers needed for boolean values
|
||||
|
||||
exports.up = async function(knex) {
|
||||
console.log('Adding gallery feedback tables...');
|
||||
|
||||
// Create event_feedback_settings table
|
||||
await knex.schema.createTable('event_feedback_settings', (table) => {
|
||||
table.increments('id').primary();
|
||||
table.integer('event_id').references('id').inTable('events').onDelete('CASCADE');
|
||||
table.boolean('feedback_enabled').defaultTo(false);
|
||||
table.boolean('allow_ratings').defaultTo(true);
|
||||
table.boolean('allow_likes').defaultTo(true);
|
||||
table.boolean('allow_comments').defaultTo(false);
|
||||
table.boolean('allow_favorites').defaultTo(true);
|
||||
table.boolean('require_name_email').defaultTo(false);
|
||||
table.boolean('moderate_comments').defaultTo(true);
|
||||
table.boolean('show_feedback_to_guests').defaultTo(true);
|
||||
table.timestamp('created_at').defaultTo(knex.fn.now());
|
||||
table.timestamp('updated_at').defaultTo(knex.fn.now());
|
||||
table.unique(['event_id']);
|
||||
});
|
||||
|
||||
// Create photo_feedback table
|
||||
await knex.schema.createTable('photo_feedback', (table) => {
|
||||
table.increments('id').primary();
|
||||
table.integer('photo_id').references('id').inTable('photos').onDelete('CASCADE');
|
||||
table.integer('event_id').references('id').inTable('events').onDelete('CASCADE');
|
||||
table.string('feedback_type', 20).notNullable();
|
||||
table.integer('rating');
|
||||
table.text('comment_text');
|
||||
table.string('guest_name', 100);
|
||||
table.string('guest_email', 255);
|
||||
table.string('guest_identifier', 64);
|
||||
table.string('ip_address', 45);
|
||||
table.text('user_agent');
|
||||
table.boolean('is_approved').defaultTo(true);
|
||||
table.boolean('is_hidden').defaultTo(false);
|
||||
table.timestamp('created_at').defaultTo(knex.fn.now());
|
||||
table.timestamp('updated_at').defaultTo(knex.fn.now());
|
||||
|
||||
// Add indexes
|
||||
table.index(['photo_id']);
|
||||
table.index(['event_id']);
|
||||
table.index(['feedback_type']);
|
||||
table.index(['guest_identifier']);
|
||||
|
||||
// Add check constraint for rating (PostgreSQL)
|
||||
if (knex.client.config.client === 'pg') {
|
||||
table.check('?? >= 1 AND ?? <= 5', ['rating', 'rating']);
|
||||
}
|
||||
});
|
||||
|
||||
// Create feedback_rate_limits table
|
||||
await knex.schema.createTable('feedback_rate_limits', (table) => {
|
||||
table.increments('id').primary();
|
||||
table.string('identifier', 64).notNullable();
|
||||
table.integer('event_id').references('id').inTable('events').onDelete('CASCADE');
|
||||
table.string('action_type', 20).notNullable();
|
||||
table.integer('action_count').defaultTo(1);
|
||||
table.timestamp('window_start').defaultTo(knex.fn.now());
|
||||
|
||||
// Add indexes
|
||||
table.index(['identifier', 'event_id', 'action_type']);
|
||||
table.index(['window_start']);
|
||||
});
|
||||
|
||||
// Create feedback_word_filters table
|
||||
await knex.schema.createTable('feedback_word_filters', (table) => {
|
||||
table.increments('id').primary();
|
||||
table.string('word', 100).notNullable();
|
||||
table.string('severity', 20).defaultTo('moderate');
|
||||
table.boolean('is_active').defaultTo(true);
|
||||
table.timestamp('created_at').defaultTo(knex.fn.now());
|
||||
table.unique(['word']);
|
||||
});
|
||||
|
||||
// Add feedback summary columns to photos table
|
||||
await knex.schema.alterTable('photos', (table) => {
|
||||
table.integer('feedback_count').defaultTo(0);
|
||||
table.integer('like_count').defaultTo(0);
|
||||
table.decimal('average_rating', 3, 2).defaultTo(0);
|
||||
table.integer('favorite_count').defaultTo(0);
|
||||
});
|
||||
|
||||
// Add feedback notification settings to app_settings
|
||||
await knex('app_settings').insert([
|
||||
{
|
||||
setting_key: 'feedback_notification_email',
|
||||
setting_value: JSON.stringify(''),
|
||||
setting_type: 'feedback'
|
||||
},
|
||||
{
|
||||
setting_key: 'feedback_rate_limits',
|
||||
setting_value: JSON.stringify({
|
||||
rating: { max: 100, window: 3600 }, // 100 ratings per hour
|
||||
comment: { max: 20, window: 3600 }, // 20 comments per hour
|
||||
like: { max: 200, window: 3600 } // 200 likes per hour
|
||||
}),
|
||||
setting_type: 'feedback'
|
||||
}
|
||||
]);
|
||||
|
||||
console.log('Gallery feedback tables created successfully');
|
||||
};
|
||||
|
||||
exports.down = async function(knex) {
|
||||
console.log('Removing gallery feedback tables...');
|
||||
|
||||
// Remove feedback settings from app_settings
|
||||
await knex('app_settings')
|
||||
.whereIn('setting_key', ['feedback_notification_email', 'feedback_rate_limits'])
|
||||
.delete();
|
||||
|
||||
// Remove feedback columns from photos table
|
||||
await knex.schema.alterTable('photos', (table) => {
|
||||
table.dropColumn('feedback_count');
|
||||
table.dropColumn('like_count');
|
||||
table.dropColumn('average_rating');
|
||||
table.dropColumn('favorite_count');
|
||||
});
|
||||
|
||||
// Drop tables in reverse order
|
||||
await knex.schema.dropTableIfExists('feedback_word_filters');
|
||||
await knex.schema.dropTableIfExists('feedback_rate_limits');
|
||||
await knex.schema.dropTableIfExists('photo_feedback');
|
||||
await knex.schema.dropTableIfExists('event_feedback_settings');
|
||||
|
||||
console.log('Gallery feedback tables removed');
|
||||
};
|
||||
@@ -0,0 +1,89 @@
|
||||
exports.up = async function(knex) {
|
||||
console.log('Running migration: 041_add_logo_customization_settings');
|
||||
|
||||
// Add default logo customization settings
|
||||
const logoSettings = [
|
||||
{
|
||||
setting_key: 'branding_logo_size',
|
||||
setting_value: JSON.stringify('medium'),
|
||||
setting_type: 'branding',
|
||||
description: 'Logo size: small, medium, large, xlarge, or custom',
|
||||
created_at: new Date(),
|
||||
updated_at: new Date()
|
||||
},
|
||||
{
|
||||
setting_key: 'branding_logo_max_height',
|
||||
setting_value: JSON.stringify(48),
|
||||
setting_type: 'branding',
|
||||
description: 'Maximum logo height in pixels (used when size is custom)',
|
||||
created_at: new Date(),
|
||||
updated_at: new Date()
|
||||
},
|
||||
{
|
||||
setting_key: 'branding_logo_position',
|
||||
setting_value: JSON.stringify('left'),
|
||||
setting_type: 'branding',
|
||||
description: 'Logo position in header: left, center, right',
|
||||
created_at: new Date(),
|
||||
updated_at: new Date()
|
||||
},
|
||||
{
|
||||
setting_key: 'branding_logo_display_header',
|
||||
setting_value: JSON.stringify(true),
|
||||
setting_type: 'branding',
|
||||
description: 'Show logo in gallery header',
|
||||
created_at: new Date(),
|
||||
updated_at: new Date()
|
||||
},
|
||||
{
|
||||
setting_key: 'branding_logo_display_hero',
|
||||
setting_value: JSON.stringify(true),
|
||||
setting_type: 'branding',
|
||||
description: 'Show logo in hero section (for non-grid layouts)',
|
||||
created_at: new Date(),
|
||||
updated_at: new Date()
|
||||
},
|
||||
{
|
||||
setting_key: 'branding_logo_display_mode',
|
||||
setting_value: JSON.stringify('logo_and_text'),
|
||||
setting_type: 'branding',
|
||||
description: 'Display mode: logo_only, text_only, logo_and_text',
|
||||
created_at: new Date(),
|
||||
updated_at: new Date()
|
||||
}
|
||||
];
|
||||
|
||||
// Insert settings that don't already exist
|
||||
for (const setting of logoSettings) {
|
||||
const exists = await knex('app_settings')
|
||||
.where('setting_key', setting.setting_key)
|
||||
.first();
|
||||
|
||||
if (!exists) {
|
||||
await knex('app_settings').insert(setting);
|
||||
console.log(`Added setting: ${setting.setting_key}`);
|
||||
} else {
|
||||
console.log(`Setting already exists: ${setting.setting_key}`);
|
||||
}
|
||||
}
|
||||
|
||||
console.log('Migration 041_add_logo_customization_settings completed');
|
||||
};
|
||||
|
||||
exports.down = async function(knex) {
|
||||
console.log('Rolling back migration: 041_add_logo_customization_settings');
|
||||
|
||||
// Remove the logo customization settings
|
||||
await knex('app_settings')
|
||||
.whereIn('setting_key', [
|
||||
'branding_logo_size',
|
||||
'branding_logo_max_height',
|
||||
'branding_logo_position',
|
||||
'branding_logo_display_header',
|
||||
'branding_logo_display_hero',
|
||||
'branding_logo_display_mode'
|
||||
])
|
||||
.del();
|
||||
|
||||
console.log('Rollback of 041_add_logo_customization_settings completed');
|
||||
};
|
||||
@@ -0,0 +1,47 @@
|
||||
# Database Migrations
|
||||
|
||||
This directory contains database migrations for the PicPeak photo sharing platform.
|
||||
|
||||
## Directory Structure
|
||||
|
||||
### `/core`
|
||||
Essential migrations that are always run for new deployments. These include:
|
||||
- `init.js` - Initial database schema creation
|
||||
- Backup service tables (029-035)
|
||||
- Gallery feedback tables (033)
|
||||
- Pre-generated watermarks (061)
|
||||
|
||||
### `/legacy`
|
||||
Migrations needed only when upgrading from older versions. New deployments can skip these as the core schema already includes all necessary tables and columns.
|
||||
|
||||
## For New Deployments
|
||||
|
||||
If you're deploying this application for the first time:
|
||||
1. The `initializeDatabase()` function in `src/database/db.js` will create all necessary tables
|
||||
2. Only migrations in the `/core` directory will be run
|
||||
3. This ensures a clean, optimized database schema
|
||||
|
||||
## For Existing Deployments
|
||||
|
||||
If you're upgrading from an older version:
|
||||
1. All migrations (both core and legacy) will be run in sequence
|
||||
2. The migration system tracks which migrations have been applied
|
||||
3. Only new migrations will be executed
|
||||
|
||||
## Running Migrations
|
||||
|
||||
```bash
|
||||
# Development
|
||||
npm run migrate
|
||||
|
||||
# Production
|
||||
npm run migrate:prod
|
||||
```
|
||||
|
||||
## Note on Duplicate Migration Numbers
|
||||
|
||||
The legacy directory contains renamed duplicates:
|
||||
- `014_add_host_name_to_events_duplicate.js` (was duplicate of 014)
|
||||
- `027_add_rate_limit_settings_duplicate.js` (was duplicate of 027)
|
||||
|
||||
These have been renamed to avoid conflicts while preserving the migration history.
|
||||
@@ -1,33 +1,39 @@
|
||||
const bcrypt = require('bcrypt');
|
||||
const { db, initializeDatabase } = require('../src/database/db');
|
||||
const { generateReadablePassword } = require('../src/utils/passwordGenerator');
|
||||
const { initializeDatabase } = require('../../src/database/db');
|
||||
const { generateReadablePassword } = require('../../src/utils/passwordGenerator');
|
||||
const fs = require('fs').promises;
|
||||
const path = require('path');
|
||||
|
||||
async function runMigrations() {
|
||||
console.log('Running database migrations...');
|
||||
exports.up = async function(knex) {
|
||||
console.log('Initializing database schema...');
|
||||
|
||||
try {
|
||||
// Initialize tables
|
||||
await initializeDatabase();
|
||||
|
||||
// Create default admin user if none exists
|
||||
const adminExists = await db('admin_users').first();
|
||||
const adminExists = await knex('admin_users').first();
|
||||
if (!adminExists) {
|
||||
// Generate a secure random password
|
||||
const generatedPassword = generateReadablePassword();
|
||||
// Use ADMIN_PASSWORD from environment if set, otherwise generate a random one
|
||||
const generatedPassword = process.env.ADMIN_PASSWORD || generateReadablePassword();
|
||||
const passwordHash = await bcrypt.hash(generatedPassword, 12); // Increased rounds for better security
|
||||
|
||||
await db('admin_users').insert({
|
||||
username: 'admin',
|
||||
email: 'admin@example.com',
|
||||
// Get admin credentials from environment or use defaults
|
||||
const adminUsername = process.env.ADMIN_USERNAME || 'admin';
|
||||
const adminEmail = process.env.ADMIN_EMAIL || 'admin@example.com';
|
||||
|
||||
await knex('admin_users').insert({
|
||||
username: adminUsername,
|
||||
email: adminEmail,
|
||||
password_hash: passwordHash,
|
||||
must_change_password: true, // Flag for forcing password change
|
||||
must_change_password: true,
|
||||
created_at: new Date()
|
||||
});
|
||||
|
||||
// Save the generated password to a file for the user to retrieve
|
||||
const setupInfoPath = path.join(__dirname, '..', '..', 'ADMIN_CREDENTIALS.txt');
|
||||
// Try to save credentials to file, but don't fail if we can't
|
||||
const dataDir = path.join(__dirname, '..', '..', 'data');
|
||||
const setupInfoPath = path.join(dataDir, 'ADMIN_CREDENTIALS.txt');
|
||||
|
||||
const setupInfo = `
|
||||
========================================
|
||||
PicPeak Admin Credentials
|
||||
@@ -35,39 +41,49 @@ PicPeak Admin Credentials
|
||||
|
||||
Your admin account has been created with these credentials:
|
||||
|
||||
Username: admin
|
||||
Email: ${adminEmail}
|
||||
Password: ${generatedPassword}
|
||||
|
||||
IMPORTANT SECURITY NOTES:
|
||||
1. You MUST change this password on first login
|
||||
1. Please change this password after first login
|
||||
2. This file will be created only once
|
||||
3. Store these credentials securely
|
||||
4. Delete this file after noting the password
|
||||
|
||||
Login URL: ${process.env.ADMIN_URL || 'http://localhost:3001'}/admin
|
||||
|
||||
Login with the email address shown above
|
||||
|
||||
Generated on: ${new Date().toISOString()}
|
||||
========================================
|
||||
`;
|
||||
|
||||
await fs.writeFile(setupInfoPath, setupInfo, 'utf8');
|
||||
try {
|
||||
// Try to create directory and write file
|
||||
await fs.mkdir(dataDir, { recursive: true });
|
||||
await fs.writeFile(setupInfoPath, setupInfo, 'utf8');
|
||||
console.log(`📁 Credentials also saved to: data/ADMIN_CREDENTIALS.txt`);
|
||||
} catch (error) {
|
||||
// If we can't write the file, that's okay - credentials are shown in console
|
||||
console.log('⚠️ Could not save credentials to file (permission denied)');
|
||||
console.log(' Please copy the credentials shown above');
|
||||
}
|
||||
|
||||
console.log('\n========================================');
|
||||
console.log('✅ Admin user created successfully!');
|
||||
console.log('========================================');
|
||||
console.log('Username: admin');
|
||||
console.log(`Email: ${adminEmail}`);
|
||||
console.log(`Password: ${generatedPassword}`);
|
||||
console.log('\n⚠️ IMPORTANT:');
|
||||
console.log('1. Save these credentials securely');
|
||||
console.log('2. You will be required to change the password on first login');
|
||||
console.log('3. Credentials are also saved in: ADMIN_CREDENTIALS.txt');
|
||||
console.log('2. Please change the password after first login');
|
||||
console.log('========================================\n');
|
||||
}
|
||||
|
||||
// Create default email templates if none exist
|
||||
const templateExists = await db('email_templates').first();
|
||||
const templateExists = await knex('email_templates').first();
|
||||
if (!templateExists) {
|
||||
await db('email_templates').insert([
|
||||
await knex('email_templates').insert([
|
||||
{
|
||||
template_key: 'gallery_created',
|
||||
subject: 'Your Photo Gallery is Ready!',
|
||||
@@ -101,9 +117,9 @@ Generated on: ${new Date().toISOString()}
|
||||
}
|
||||
|
||||
// Create default email config if none exists
|
||||
const emailConfig = await db('email_configs').first();
|
||||
const emailConfig = await knex('email_configs').first();
|
||||
if (!emailConfig) {
|
||||
await db('email_configs').insert({
|
||||
await knex('email_configs').insert({
|
||||
smtp_host: process.env.SMTP_HOST || 'mailhog',
|
||||
smtp_port: process.env.SMTP_PORT || 1025,
|
||||
smtp_secure: process.env.SMTP_SECURE === 'true',
|
||||
@@ -116,11 +132,13 @@ Generated on: ${new Date().toISOString()}
|
||||
}
|
||||
|
||||
console.log('Migrations completed successfully');
|
||||
process.exit(0);
|
||||
} catch (error) {
|
||||
console.error('Migration failed:', error);
|
||||
process.exit(1);
|
||||
console.error('Initial setup failed:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
runMigrations();
|
||||
exports.down = async function(knex) {
|
||||
// This migration cannot be rolled back as it creates the initial schema
|
||||
console.log('Initial setup cannot be rolled back');
|
||||
};
|
||||
+7
-30
@@ -1,4 +1,4 @@
|
||||
const { db } = require('../src/database/db');
|
||||
const { db } = require('../../src/database/db');
|
||||
|
||||
async function up() {
|
||||
console.log('Adding backup service tables and settings...');
|
||||
@@ -156,9 +156,8 @@ async function up() {
|
||||
const backupEmailTemplates = [
|
||||
{
|
||||
template_key: 'backup_failed',
|
||||
subject_en: 'Backup Failed - Immediate Attention Required',
|
||||
subject_de: 'Backup fehlgeschlagen - Sofortige Aufmerksamkeit erforderlich',
|
||||
body_html_en: `<h2>Backup Failed</h2>
|
||||
subject: 'Backup Failed - Immediate Attention Required',
|
||||
body_html: `<h2>Backup Failed</h2>
|
||||
<p>The scheduled backup has failed and requires immediate attention.</p>
|
||||
<p><strong>Error Details:</strong></p>
|
||||
<ul>
|
||||
@@ -167,24 +166,13 @@ async function up() {
|
||||
<li>Error: {{error_message}}</li>
|
||||
</ul>
|
||||
<p>Please check the system logs for more details and resolve the issue as soon as possible.</p>`,
|
||||
body_html_de: `<h2>Backup fehlgeschlagen</h2>
|
||||
<p>Das geplante Backup ist fehlgeschlagen und erfordert sofortige Aufmerksamkeit.</p>
|
||||
<p><strong>Fehlerdetails:</strong></p>
|
||||
<ul>
|
||||
<li>Startzeit: {{start_time}}</li>
|
||||
<li>Backup-Typ: {{backup_type}}</li>
|
||||
<li>Fehler: {{error_message}}</li>
|
||||
</ul>
|
||||
<p>Bitte überprüfen Sie die Systemprotokolle für weitere Details und beheben Sie das Problem so schnell wie möglich.</p>`,
|
||||
body_text_en: 'Backup Failed\n\nThe scheduled backup has failed and requires immediate attention.\n\nStart Time: {{start_time}}\nBackup Type: {{backup_type}}\nError: {{error_message}}\n\nPlease check the system logs for more details.',
|
||||
body_text_de: 'Backup fehlgeschlagen\n\nDas geplante Backup ist fehlgeschlagen und erfordert sofortige Aufmerksamkeit.\n\nStartzeit: {{start_time}}\nBackup-Typ: {{backup_type}}\nFehler: {{error_message}}\n\nBitte überprüfen Sie die Systemprotokolle für weitere Details.',
|
||||
body_text: 'Backup Failed\n\nThe scheduled backup has failed and requires immediate attention.\n\nStart Time: {{start_time}}\nBackup Type: {{backup_type}}\nError: {{error_message}}\n\nPlease check the system logs for more details.',
|
||||
variables: JSON.stringify(['start_time', 'backup_type', 'error_message'])
|
||||
},
|
||||
{
|
||||
template_key: 'backup_completed',
|
||||
subject_en: 'Backup Completed Successfully',
|
||||
subject_de: 'Backup erfolgreich abgeschlossen',
|
||||
body_html_en: `<h2>Backup Completed</h2>
|
||||
subject: 'Backup Completed Successfully',
|
||||
body_html: `<h2>Backup Completed</h2>
|
||||
<p>The scheduled backup has been completed successfully.</p>
|
||||
<p><strong>Backup Summary:</strong></p>
|
||||
<ul>
|
||||
@@ -194,18 +182,7 @@ async function up() {
|
||||
<li>Total Size: {{total_size}}</li>
|
||||
<li>Backup Type: {{backup_type}}</li>
|
||||
</ul>`,
|
||||
body_html_de: `<h2>Backup abgeschlossen</h2>
|
||||
<p>Das geplante Backup wurde erfolgreich abgeschlossen.</p>
|
||||
<p><strong>Backup-Zusammenfassung:</strong></p>
|
||||
<ul>
|
||||
<li>Startzeit: {{start_time}}</li>
|
||||
<li>Dauer: {{duration}}</li>
|
||||
<li>Gesicherte Dateien: {{files_count}}</li>
|
||||
<li>Gesamtgröße: {{total_size}}</li>
|
||||
<li>Backup-Typ: {{backup_type}}</li>
|
||||
</ul>`,
|
||||
body_text_en: 'Backup Completed\n\nThe scheduled backup has been completed successfully.\n\nStart Time: {{start_time}}\nDuration: {{duration}}\nFiles Backed Up: {{files_count}}\nTotal Size: {{total_size}}\nBackup Type: {{backup_type}}',
|
||||
body_text_de: 'Backup abgeschlossen\n\nDas geplante Backup wurde erfolgreich abgeschlossen.\n\nStartzeit: {{start_time}}\nDauer: {{duration}}\nGesicherte Dateien: {{files_count}}\nGesamtgröße: {{total_size}}\nBackup-Typ: {{backup_type}}',
|
||||
body_text: 'Backup Completed\n\nThe scheduled backup has been completed successfully.\n\nStart Time: {{start_time}}\nDuration: {{duration}}\nFiles Backed Up: {{files_count}}\nTotal Size: {{total_size}}\nBackup Type: {{backup_type}}',
|
||||
variables: JSON.stringify(['start_time', 'duration', 'files_count', 'total_size', 'backup_type'])
|
||||
}
|
||||
];
|
||||
+7
-30
@@ -1,4 +1,4 @@
|
||||
const { db } = require('../src/database/db');
|
||||
const { db } = require('../../src/database/db');
|
||||
|
||||
async function up() {
|
||||
console.log('Adding database backup tables and settings...');
|
||||
@@ -96,9 +96,8 @@ async function up() {
|
||||
const databaseBackupEmailTemplates = [
|
||||
{
|
||||
template_key: 'database_backup_failed',
|
||||
subject_en: 'Database Backup Failed - Critical Alert',
|
||||
subject_de: 'Datenbank-Backup fehlgeschlagen - Kritische Warnung',
|
||||
body_html_en: `<h2>Database Backup Failed</h2>
|
||||
subject: 'Database Backup Failed - Critical Alert',
|
||||
body_html: `<h2>Database Backup Failed</h2>
|
||||
<p>The scheduled database backup has failed and requires immediate attention.</p>
|
||||
<p><strong>Error Details:</strong></p>
|
||||
<ul>
|
||||
@@ -107,24 +106,13 @@ async function up() {
|
||||
<li>Error: {{error_message}}</li>
|
||||
</ul>
|
||||
<p>This is a critical issue that could affect disaster recovery. Please investigate immediately.</p>`,
|
||||
body_html_de: `<h2>Datenbank-Backup fehlgeschlagen</h2>
|
||||
<p>Das geplante Datenbank-Backup ist fehlgeschlagen und erfordert sofortige Aufmerksamkeit.</p>
|
||||
<p><strong>Fehlerdetails:</strong></p>
|
||||
<ul>
|
||||
<li>Backup-Typ: {{backup_type}}</li>
|
||||
<li>Zeitstempel: {{timestamp}}</li>
|
||||
<li>Fehler: {{error_message}}</li>
|
||||
</ul>
|
||||
<p>Dies ist ein kritisches Problem, das die Disaster-Recovery beeinträchtigen könnte. Bitte untersuchen Sie es sofort.</p>`,
|
||||
body_text_en: 'Database Backup Failed\n\nThe scheduled database backup has failed.\n\nBackup Type: {{backup_type}}\nTimestamp: {{timestamp}}\nError: {{error_message}}\n\nThis is critical - please investigate immediately.',
|
||||
body_text_de: 'Datenbank-Backup fehlgeschlagen\n\nDas geplante Datenbank-Backup ist fehlgeschlagen.\n\nBackup-Typ: {{backup_type}}\nZeitstempel: {{timestamp}}\nFehler: {{error_message}}\n\nDies ist kritisch - bitte sofort untersuchen.',
|
||||
body_text: 'Database Backup Failed\n\nThe scheduled database backup has failed.\n\nBackup Type: {{backup_type}}\nTimestamp: {{timestamp}}\nError: {{error_message}}\n\nThis is critical - please investigate immediately.',
|
||||
variables: JSON.stringify(['backup_type', 'timestamp', 'error_message'])
|
||||
},
|
||||
{
|
||||
template_key: 'database_backup_completed',
|
||||
subject_en: 'Database Backup Completed Successfully',
|
||||
subject_de: 'Datenbank-Backup erfolgreich abgeschlossen',
|
||||
body_html_en: `<h2>Database Backup Completed</h2>
|
||||
subject: 'Database Backup Completed Successfully',
|
||||
body_html: `<h2>Database Backup Completed</h2>
|
||||
<p>The scheduled database backup has been completed successfully.</p>
|
||||
<p><strong>Backup Summary:</strong></p>
|
||||
<ul>
|
||||
@@ -134,18 +122,7 @@ async function up() {
|
||||
<li>Compression Ratio: {{compression_ratio}}</li>
|
||||
<li>File Path: {{file_path}}</li>
|
||||
</ul>`,
|
||||
body_html_de: `<h2>Datenbank-Backup abgeschlossen</h2>
|
||||
<p>Das geplante Datenbank-Backup wurde erfolgreich abgeschlossen.</p>
|
||||
<p><strong>Backup-Zusammenfassung:</strong></p>
|
||||
<ul>
|
||||
<li>Backup-Typ: {{backup_type}}</li>
|
||||
<li>Dauer: {{duration}}</li>
|
||||
<li>Dateigröße: {{file_size}}</li>
|
||||
<li>Komprimierungsverhältnis: {{compression_ratio}}</li>
|
||||
<li>Dateipfad: {{file_path}}</li>
|
||||
</ul>`,
|
||||
body_text_en: 'Database Backup Completed\n\nThe scheduled database backup has been completed successfully.\n\nBackup Type: {{backup_type}}\nDuration: {{duration}}\nFile Size: {{file_size}}\nCompression Ratio: {{compression_ratio}}\nFile Path: {{file_path}}',
|
||||
body_text_de: 'Datenbank-Backup abgeschlossen\n\nDas geplante Datenbank-Backup wurde erfolgreich abgeschlossen.\n\nBackup-Typ: {{backup_type}}\nDauer: {{duration}}\nDateigröße: {{file_size}}\nKomprimierungsverhältnis: {{compression_ratio}}\nDateipfad: {{file_path}}',
|
||||
body_text: 'Database Backup Completed\n\nThe scheduled database backup has been completed successfully.\n\nBackup Type: {{backup_type}}\nDuration: {{duration}}\nFile Size: {{file_size}}\nCompression Ratio: {{compression_ratio}}\nFile Path: {{file_path}}',
|
||||
variables: JSON.stringify(['backup_type', 'duration', 'file_size', 'compression_ratio', 'file_path'])
|
||||
}
|
||||
];
|
||||
+2
-2
@@ -1,5 +1,5 @@
|
||||
const { db } = require('../src/database/db');
|
||||
const logger = require('../src/utils/logger');
|
||||
const { db } = require('../../src/database/db');
|
||||
const logger = require('../../src/utils/logger');
|
||||
|
||||
async function up() {
|
||||
console.log('Adding backup manifest columns...');
|
||||
+42
-67
@@ -5,7 +5,9 @@
|
||||
*/
|
||||
exports.up = async function(knex) {
|
||||
// Create restore_runs table
|
||||
await knex.schema.createTable('restore_runs', table => {
|
||||
const hasRestoreRunsTable = await knex.schema.hasTable('restore_runs');
|
||||
if (!hasRestoreRunsTable) {
|
||||
await knex.schema.createTable('restore_runs', table => {
|
||||
table.increments('id').primary();
|
||||
|
||||
// Timing
|
||||
@@ -44,10 +46,13 @@ exports.up = async function(knex) {
|
||||
|
||||
table.index(['status', 'started_at']);
|
||||
table.index(['restore_type', 'started_at']);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// Create restore_file_operations table for tracking individual file operations
|
||||
await knex.schema.createTable('restore_file_operations', table => {
|
||||
const hasRestoreFileOperationsTable = await knex.schema.hasTable('restore_file_operations');
|
||||
if (!hasRestoreFileOperationsTable) {
|
||||
await knex.schema.createTable('restore_file_operations', table => {
|
||||
table.increments('id').primary();
|
||||
|
||||
table.integer('restore_run_id').notNullable()
|
||||
@@ -67,10 +72,13 @@ exports.up = async function(knex) {
|
||||
|
||||
table.index(['restore_run_id', 'status']);
|
||||
table.index(['file_path']);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// Create restore_validation_results table
|
||||
await knex.schema.createTable('restore_validation_results', table => {
|
||||
const hasRestoreValidationResultsTable = await knex.schema.hasTable('restore_validation_results');
|
||||
if (!hasRestoreValidationResultsTable) {
|
||||
await knex.schema.createTable('restore_validation_results', table => {
|
||||
table.increments('id').primary();
|
||||
|
||||
table.integer('restore_run_id').notNullable()
|
||||
@@ -86,10 +94,11 @@ exports.up = async function(knex) {
|
||||
table.timestamp('validated_at').notNullable().defaultTo(knex.fn.now());
|
||||
|
||||
table.index(['restore_run_id', 'validation_type']);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// Add restore-related settings to app_settings
|
||||
await knex('app_settings').insert([
|
||||
const restoreSettings = [
|
||||
{
|
||||
setting_key: 'restore_allow_force',
|
||||
setting_value: JSON.stringify(false),
|
||||
@@ -120,15 +129,24 @@ exports.up = async function(knex) {
|
||||
setting_value: '30',
|
||||
setting_type: 'restore'
|
||||
}
|
||||
]);
|
||||
];
|
||||
|
||||
for (const setting of restoreSettings) {
|
||||
const exists = await knex('app_settings')
|
||||
.where('setting_key', setting.setting_key)
|
||||
.first();
|
||||
|
||||
if (!exists) {
|
||||
await knex('app_settings').insert(setting);
|
||||
}
|
||||
}
|
||||
|
||||
// Add new email templates for restore notifications
|
||||
const emailTemplates = [
|
||||
{
|
||||
template_key: 'restore_completed',
|
||||
subject_en: '✅ Restore Completed Successfully',
|
||||
subject_de: '✅ Wiederherstellung erfolgreich abgeschlossen',
|
||||
body_html_en: `<h2>Restore Operation Completed</h2>
|
||||
subject: '✅ Restore Completed Successfully',
|
||||
body_html: `<h2>Restore Operation Completed</h2>
|
||||
<p>A restore operation has completed successfully.</p>
|
||||
|
||||
<h3>Details:</h3>
|
||||
@@ -141,20 +159,7 @@ exports.up = async function(knex) {
|
||||
</ul>
|
||||
|
||||
<p>Please verify that all systems are functioning correctly after the restore.</p>`,
|
||||
body_html_de: `<h2>Wiederherstellungsvorgang abgeschlossen</h2>
|
||||
<p>Ein Wiederherstellungsvorgang wurde erfolgreich abgeschlossen.</p>
|
||||
|
||||
<h3>Details:</h3>
|
||||
<ul>
|
||||
<li><strong>Wiederherstellungstyp:</strong> {{restore_type}}</li>
|
||||
<li><strong>Dauer:</strong> {{duration}}</li>
|
||||
<li><strong>Wiederhergestellte Dateien:</strong> {{files_restored}}</li>
|
||||
<li><strong>Backup-ID:</strong> {{backup_id}}</li>
|
||||
<li><strong>Zeitstempel:</strong> {{timestamp}}</li>
|
||||
</ul>
|
||||
|
||||
<p>Bitte überprüfen Sie, ob alle Systeme nach der Wiederherstellung ordnungsgemäß funktionieren.</p>`,
|
||||
body_text_en: `Restore Operation Completed
|
||||
body_text: `Restore Operation Completed
|
||||
|
||||
A restore operation has completed successfully.
|
||||
|
||||
@@ -166,25 +171,12 @@ Details:
|
||||
- Timestamp: {{timestamp}}
|
||||
|
||||
Please verify that all systems are functioning correctly after the restore.`,
|
||||
body_text_de: `Wiederherstellungsvorgang abgeschlossen
|
||||
|
||||
Ein Wiederherstellungsvorgang wurde erfolgreich abgeschlossen.
|
||||
|
||||
Details:
|
||||
- Wiederherstellungstyp: {{restore_type}}
|
||||
- Dauer: {{duration}}
|
||||
- Wiederhergestellte Dateien: {{files_restored}}
|
||||
- Backup-ID: {{backup_id}}
|
||||
- Zeitstempel: {{timestamp}}
|
||||
|
||||
Bitte überprüfen Sie, ob alle Systeme nach der Wiederherstellung ordnungsgemäß funktionieren.`,
|
||||
variables: JSON.stringify(['restore_type', 'duration', 'files_restored', 'backup_id', 'timestamp'])
|
||||
},
|
||||
{
|
||||
template_key: 'restore_failed',
|
||||
subject_en: '❌ Restore Operation Failed',
|
||||
subject_de: '❌ Wiederherstellungsvorgang fehlgeschlagen',
|
||||
body_html_en: `<h2>Restore Operation Failed</h2>
|
||||
subject: '❌ Restore Operation Failed',
|
||||
body_html: `<h2>Restore Operation Failed</h2>
|
||||
<p>A restore operation has failed and requires attention.</p>
|
||||
|
||||
<h3>Details:</h3>
|
||||
@@ -197,20 +189,7 @@ Bitte überprüfen Sie, ob alle Systeme nach der Wiederherstellung ordnungsgemä
|
||||
<p>Please check the system logs for more details and take appropriate action.</p>
|
||||
|
||||
<p><strong>Important:</strong> If a pre-restore backup was created, it may be used for recovery.</p>`,
|
||||
body_html_de: `<h2>Wiederherstellungsvorgang fehlgeschlagen</h2>
|
||||
<p>Ein Wiederherstellungsvorgang ist fehlgeschlagen und erfordert Ihre Aufmerksamkeit.</p>
|
||||
|
||||
<h3>Details:</h3>
|
||||
<ul>
|
||||
<li><strong>Wiederherstellungstyp:</strong> {{restore_type}}</li>
|
||||
<li><strong>Fehler:</strong> {{error_message}}</li>
|
||||
<li><strong>Zeitstempel:</strong> {{timestamp}}</li>
|
||||
</ul>
|
||||
|
||||
<p>Bitte überprüfen Sie die Systemprotokolle für weitere Details und ergreifen Sie entsprechende Maßnahmen.</p>
|
||||
|
||||
<p><strong>Wichtig:</strong> Falls ein Backup vor der Wiederherstellung erstellt wurde, kann es zur Wiederherstellung verwendet werden.</p>`,
|
||||
body_text_en: `Restore Operation Failed
|
||||
body_text: `Restore Operation Failed
|
||||
|
||||
A restore operation has failed and requires attention.
|
||||
|
||||
@@ -222,23 +201,19 @@ Details:
|
||||
Please check the system logs for more details and take appropriate action.
|
||||
|
||||
Important: If a pre-restore backup was created, it may be used for recovery.`,
|
||||
body_text_de: `Wiederherstellungsvorgang fehlgeschlagen
|
||||
|
||||
Ein Wiederherstellungsvorgang ist fehlgeschlagen und erfordert Ihre Aufmerksamkeit.
|
||||
|
||||
Details:
|
||||
- Wiederherstellungstyp: {{restore_type}}
|
||||
- Fehler: {{error_message}}
|
||||
- Zeitstempel: {{timestamp}}
|
||||
|
||||
Bitte überprüfen Sie die Systemprotokolle für weitere Details und ergreifen Sie entsprechende Maßnahmen.
|
||||
|
||||
Wichtig: Falls ein Backup vor der Wiederherstellung erstellt wurde, kann es zur Wiederherstellung verwendet werden.`,
|
||||
variables: JSON.stringify(['restore_type', 'error_message', 'timestamp'])
|
||||
}
|
||||
];
|
||||
|
||||
await knex('email_templates').insert(emailTemplates);
|
||||
for (const template of emailTemplates) {
|
||||
const exists = await knex('email_templates')
|
||||
.where('template_key', template.template_key)
|
||||
.first();
|
||||
|
||||
if (!exists) {
|
||||
await knex('email_templates').insert(template);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
exports.down = async function(knex) {
|
||||
@@ -0,0 +1,152 @@
|
||||
// No helpers needed for boolean values
|
||||
|
||||
exports.up = async function(knex) {
|
||||
console.log('Adding gallery feedback tables...');
|
||||
|
||||
// Check if tables and columns already exist
|
||||
const hasEventFeedbackSettingsTable = await knex.schema.hasTable('event_feedback_settings');
|
||||
const hasPhotoFeedbackTable = await knex.schema.hasTable('photo_feedback');
|
||||
const hasFeedbackRateLimitsTable = await knex.schema.hasTable('feedback_rate_limits');
|
||||
const hasFeedbackWordFiltersTable = await knex.schema.hasTable('feedback_word_filters');
|
||||
const hasFeedbackCountColumn = await knex.schema.hasColumn('photos', 'feedback_count');
|
||||
|
||||
// Create event_feedback_settings table
|
||||
if (!hasEventFeedbackSettingsTable) {
|
||||
await knex.schema.createTable('event_feedback_settings', (table) => {
|
||||
table.increments('id').primary();
|
||||
table.integer('event_id').references('id').inTable('events').onDelete('CASCADE');
|
||||
table.boolean('feedback_enabled').defaultTo(false);
|
||||
table.boolean('allow_ratings').defaultTo(true);
|
||||
table.boolean('allow_likes').defaultTo(true);
|
||||
table.boolean('allow_comments').defaultTo(false);
|
||||
table.boolean('allow_favorites').defaultTo(true);
|
||||
table.boolean('require_name_email').defaultTo(false);
|
||||
table.boolean('moderate_comments').defaultTo(true);
|
||||
table.boolean('show_feedback_to_guests').defaultTo(true);
|
||||
table.timestamp('created_at').defaultTo(knex.fn.now());
|
||||
table.timestamp('updated_at').defaultTo(knex.fn.now());
|
||||
table.unique(['event_id']);
|
||||
});
|
||||
}
|
||||
|
||||
// Create photo_feedback table
|
||||
if (!hasPhotoFeedbackTable) {
|
||||
await knex.schema.createTable('photo_feedback', (table) => {
|
||||
table.increments('id').primary();
|
||||
table.integer('photo_id').references('id').inTable('photos').onDelete('CASCADE');
|
||||
table.integer('event_id').references('id').inTable('events').onDelete('CASCADE');
|
||||
table.string('feedback_type', 20).notNullable();
|
||||
table.integer('rating');
|
||||
table.text('comment_text');
|
||||
table.string('guest_name', 100);
|
||||
table.string('guest_email', 255);
|
||||
table.string('guest_identifier', 64);
|
||||
table.string('ip_address', 45);
|
||||
table.text('user_agent');
|
||||
table.boolean('is_approved').defaultTo(true);
|
||||
table.boolean('is_hidden').defaultTo(false);
|
||||
table.timestamp('created_at').defaultTo(knex.fn.now());
|
||||
table.timestamp('updated_at').defaultTo(knex.fn.now());
|
||||
|
||||
// Add indexes
|
||||
table.index(['photo_id']);
|
||||
table.index(['event_id']);
|
||||
table.index(['feedback_type']);
|
||||
table.index(['guest_identifier']);
|
||||
|
||||
// Add check constraint for rating (PostgreSQL)
|
||||
if (knex.client.config.client === 'pg') {
|
||||
table.check('?? >= 1 AND ?? <= 5', ['rating', 'rating']);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Create feedback_rate_limits table
|
||||
if (!hasFeedbackRateLimitsTable) {
|
||||
await knex.schema.createTable('feedback_rate_limits', (table) => {
|
||||
table.increments('id').primary();
|
||||
table.string('identifier', 64).notNullable();
|
||||
table.integer('event_id').references('id').inTable('events').onDelete('CASCADE');
|
||||
table.string('action_type', 20).notNullable();
|
||||
table.integer('action_count').defaultTo(1);
|
||||
table.timestamp('window_start').defaultTo(knex.fn.now());
|
||||
|
||||
// Add indexes
|
||||
table.index(['identifier', 'event_id', 'action_type']);
|
||||
table.index(['window_start']);
|
||||
});
|
||||
}
|
||||
|
||||
// Create feedback_word_filters table
|
||||
if (!hasFeedbackWordFiltersTable) {
|
||||
await knex.schema.createTable('feedback_word_filters', (table) => {
|
||||
table.increments('id').primary();
|
||||
table.string('word', 100).notNullable();
|
||||
table.string('severity', 20).defaultTo('moderate');
|
||||
table.boolean('is_active').defaultTo(true);
|
||||
table.timestamp('created_at').defaultTo(knex.fn.now());
|
||||
table.unique(['word']);
|
||||
});
|
||||
}
|
||||
|
||||
// Add feedback summary columns to photos table
|
||||
if (!hasFeedbackCountColumn) {
|
||||
await knex.schema.alterTable('photos', (table) => {
|
||||
table.integer('feedback_count').defaultTo(0);
|
||||
table.integer('like_count').defaultTo(0);
|
||||
table.decimal('average_rating', 3, 2).defaultTo(0);
|
||||
table.integer('favorite_count').defaultTo(0);
|
||||
});
|
||||
}
|
||||
|
||||
// Add feedback notification settings to app_settings
|
||||
const hasFeedbackNotificationEmail = await knex('app_settings')
|
||||
.where('setting_key', 'feedback_notification_email')
|
||||
.first();
|
||||
|
||||
if (!hasFeedbackNotificationEmail) {
|
||||
await knex('app_settings').insert([
|
||||
{
|
||||
setting_key: 'feedback_notification_email',
|
||||
setting_value: JSON.stringify(''),
|
||||
setting_type: 'feedback'
|
||||
},
|
||||
{
|
||||
setting_key: 'feedback_rate_limits',
|
||||
setting_value: JSON.stringify({
|
||||
rating: { max: 100, window: 3600 }, // 100 ratings per hour
|
||||
comment: { max: 20, window: 3600 }, // 20 comments per hour
|
||||
like: { max: 200, window: 3600 } // 200 likes per hour
|
||||
}),
|
||||
setting_type: 'feedback'
|
||||
}
|
||||
]);
|
||||
}
|
||||
|
||||
console.log('Gallery feedback tables created successfully');
|
||||
};
|
||||
|
||||
exports.down = async function(knex) {
|
||||
console.log('Removing gallery feedback tables...');
|
||||
|
||||
// Remove feedback settings from app_settings
|
||||
await knex('app_settings')
|
||||
.whereIn('setting_key', ['feedback_notification_email', 'feedback_rate_limits'])
|
||||
.delete();
|
||||
|
||||
// Remove feedback columns from photos table
|
||||
await knex.schema.alterTable('photos', (table) => {
|
||||
table.dropColumn('feedback_count');
|
||||
table.dropColumn('like_count');
|
||||
table.dropColumn('average_rating');
|
||||
table.dropColumn('favorite_count');
|
||||
});
|
||||
|
||||
// Drop tables in reverse order
|
||||
await knex.schema.dropTableIfExists('feedback_word_filters');
|
||||
await knex.schema.dropTableIfExists('feedback_rate_limits');
|
||||
await knex.schema.dropTableIfExists('photo_feedback');
|
||||
await knex.schema.dropTableIfExists('event_feedback_settings');
|
||||
|
||||
console.log('Gallery feedback tables removed');
|
||||
};
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
const { db } = require('../src/database/db');
|
||||
const { db } = require('../../src/database/db');
|
||||
|
||||
async function up() {
|
||||
console.log('Adding version tracking to backup tables...');
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
const { db } = require('../src/database/db');
|
||||
const { db } = require('../../src/database/db');
|
||||
|
||||
async function up() {
|
||||
console.log('Enhancing backup system...');
|
||||
@@ -0,0 +1,87 @@
|
||||
// Fix missing columns identified in GitHub issues
|
||||
|
||||
exports.up = async function(knex) {
|
||||
console.log('Adding missing columns to database tables...');
|
||||
|
||||
// Add must_change_password column to admin_users table
|
||||
const hasMustChangePassword = await knex.schema.hasColumn('admin_users', 'must_change_password');
|
||||
if (!hasMustChangePassword) {
|
||||
console.log('Adding must_change_password column to admin_users table...');
|
||||
await knex.schema.table('admin_users', (table) => {
|
||||
table.boolean('must_change_password').defaultTo(false);
|
||||
});
|
||||
}
|
||||
|
||||
// Add password_changed_at column to admin_users table
|
||||
const hasPasswordChangedAt = await knex.schema.hasColumn('admin_users', 'password_changed_at');
|
||||
if (!hasPasswordChangedAt) {
|
||||
console.log('Adding password_changed_at column to admin_users table...');
|
||||
await knex.schema.table('admin_users', (table) => {
|
||||
table.datetime('password_changed_at');
|
||||
});
|
||||
}
|
||||
|
||||
// Add require_moderation column to event_feedback_settings table
|
||||
const hasEventFeedbackSettings = await knex.schema.hasTable('event_feedback_settings');
|
||||
if (hasEventFeedbackSettings) {
|
||||
const hasRequireModeration = await knex.schema.hasColumn('event_feedback_settings', 'require_moderation');
|
||||
if (!hasRequireModeration) {
|
||||
console.log('Adding require_moderation column to event_feedback_settings table...');
|
||||
await knex.schema.table('event_feedback_settings', (table) => {
|
||||
table.boolean('require_moderation').defaultTo(true);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Add host_name column to events table if missing
|
||||
const hasHostName = await knex.schema.hasColumn('events', 'host_name');
|
||||
if (!hasHostName) {
|
||||
console.log('Adding host_name column to events table...');
|
||||
await knex.schema.table('events', (table) => {
|
||||
table.string('host_name');
|
||||
});
|
||||
}
|
||||
|
||||
console.log('Missing columns have been added successfully');
|
||||
};
|
||||
|
||||
exports.down = async function(knex) {
|
||||
console.log('Removing added columns...');
|
||||
|
||||
// Remove must_change_password column from admin_users table
|
||||
const hasMustChangePassword = await knex.schema.hasColumn('admin_users', 'must_change_password');
|
||||
if (hasMustChangePassword) {
|
||||
await knex.schema.table('admin_users', (table) => {
|
||||
table.dropColumn('must_change_password');
|
||||
});
|
||||
}
|
||||
|
||||
// Remove password_changed_at column from admin_users table
|
||||
const hasPasswordChangedAt = await knex.schema.hasColumn('admin_users', 'password_changed_at');
|
||||
if (hasPasswordChangedAt) {
|
||||
await knex.schema.table('admin_users', (table) => {
|
||||
table.dropColumn('password_changed_at');
|
||||
});
|
||||
}
|
||||
|
||||
// Remove require_moderation column from event_feedback_settings table
|
||||
const hasEventFeedbackSettings = await knex.schema.hasTable('event_feedback_settings');
|
||||
if (hasEventFeedbackSettings) {
|
||||
const hasRequireModeration = await knex.schema.hasColumn('event_feedback_settings', 'require_moderation');
|
||||
if (hasRequireModeration) {
|
||||
await knex.schema.table('event_feedback_settings', (table) => {
|
||||
table.dropColumn('require_moderation');
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Remove host_name column from events table
|
||||
const hasHostName = await knex.schema.hasColumn('events', 'host_name');
|
||||
if (hasHostName) {
|
||||
await knex.schema.table('events', (table) => {
|
||||
table.dropColumn('host_name');
|
||||
});
|
||||
}
|
||||
|
||||
console.log('Columns removed');
|
||||
};
|
||||
@@ -0,0 +1,69 @@
|
||||
// Add download control features to events table
|
||||
|
||||
exports.up = async function(knex) {
|
||||
console.log('Adding download control columns to events table...');
|
||||
|
||||
// Add download control columns to events table
|
||||
const hasAllowDownloads = await knex.schema.hasColumn('events', 'allow_downloads');
|
||||
if (!hasAllowDownloads) {
|
||||
await knex.schema.table('events', (table) => {
|
||||
table.boolean('allow_downloads').defaultTo(true);
|
||||
table.boolean('disable_right_click').defaultTo(false);
|
||||
table.boolean('watermark_downloads').defaultTo(false);
|
||||
table.text('watermark_text');
|
||||
});
|
||||
}
|
||||
|
||||
// Add download control settings to app_settings
|
||||
const downloadSettingExists = await knex('app_settings')
|
||||
.where('setting_key', 'default_allow_downloads')
|
||||
.first();
|
||||
|
||||
if (!downloadSettingExists) {
|
||||
await knex('app_settings').insert([
|
||||
{
|
||||
setting_key: 'default_allow_downloads',
|
||||
setting_value: JSON.stringify(true),
|
||||
setting_type: 'gallery'
|
||||
},
|
||||
{
|
||||
setting_key: 'default_disable_right_click',
|
||||
setting_value: JSON.stringify(false),
|
||||
setting_type: 'gallery'
|
||||
},
|
||||
{
|
||||
setting_key: 'default_watermark_downloads',
|
||||
setting_value: JSON.stringify(false),
|
||||
setting_type: 'gallery'
|
||||
}
|
||||
]);
|
||||
}
|
||||
|
||||
console.log('Download control features added successfully');
|
||||
};
|
||||
|
||||
exports.down = async function(knex) {
|
||||
console.log('Removing download control columns...');
|
||||
|
||||
// Remove app settings
|
||||
await knex('app_settings')
|
||||
.whereIn('setting_key', [
|
||||
'default_allow_downloads',
|
||||
'default_disable_right_click',
|
||||
'default_watermark_downloads'
|
||||
])
|
||||
.delete();
|
||||
|
||||
// Remove columns from events table
|
||||
const hasAllowDownloads = await knex.schema.hasColumn('events', 'allow_downloads');
|
||||
if (hasAllowDownloads) {
|
||||
await knex.schema.table('events', (table) => {
|
||||
table.dropColumn('allow_downloads');
|
||||
table.dropColumn('disable_right_click');
|
||||
table.dropColumn('watermark_downloads');
|
||||
table.dropColumn('watermark_text');
|
||||
});
|
||||
}
|
||||
|
||||
console.log('Download control columns removed');
|
||||
};
|
||||
@@ -0,0 +1,128 @@
|
||||
// Add enhanced image protection features
|
||||
|
||||
exports.up = async function(knex) {
|
||||
console.log('Adding enhanced image protection features...');
|
||||
|
||||
// Add protection columns to events table
|
||||
const hasProtectionLevel = await knex.schema.hasColumn('events', 'protection_level');
|
||||
if (!hasProtectionLevel) {
|
||||
await knex.schema.table('events', (table) => {
|
||||
table.enum('protection_level', ['basic', 'standard', 'enhanced', 'maximum']).defaultTo('standard');
|
||||
table.integer('image_quality').defaultTo(85);
|
||||
table.boolean('add_fingerprint').defaultTo(true);
|
||||
table.boolean('enable_devtools_protection').defaultTo(true);
|
||||
table.boolean('use_canvas_rendering').defaultTo(false);
|
||||
table.integer('fragmentation_level').defaultTo(3);
|
||||
table.boolean('overlay_protection').defaultTo(true);
|
||||
});
|
||||
}
|
||||
|
||||
// Create image access logs table
|
||||
const hasImageAccessLogs = await knex.schema.hasTable('image_access_logs');
|
||||
if (!hasImageAccessLogs) {
|
||||
await knex.schema.createTable('image_access_logs', (table) => {
|
||||
table.increments('id').primary();
|
||||
table.integer('photo_id').unsigned().notNullable();
|
||||
table.integer('event_id').unsigned().notNullable();
|
||||
table.string('client_ip', 45).notNullable();
|
||||
table.text('user_agent');
|
||||
table.string('access_type', 20).defaultTo('view'); // view, download, suspicious
|
||||
table.string('client_fingerprint', 32).notNullable();
|
||||
table.timestamp('accessed_at').defaultTo(knex.fn.now());
|
||||
table.json('metadata'); // Additional security metadata
|
||||
|
||||
table.foreign('photo_id').references('id').inTable('photos').onDelete('CASCADE');
|
||||
table.foreign('event_id').references('id').inTable('events').onDelete('CASCADE');
|
||||
|
||||
table.index(['photo_id', 'accessed_at']);
|
||||
table.index(['client_fingerprint', 'accessed_at']);
|
||||
table.index(['client_ip', 'accessed_at']);
|
||||
});
|
||||
}
|
||||
|
||||
// Add protection settings to app_settings
|
||||
const protectionSettingExists = await knex('app_settings')
|
||||
.where('setting_key', 'default_protection_level')
|
||||
.first();
|
||||
|
||||
if (!protectionSettingExists) {
|
||||
await knex('app_settings').insert([
|
||||
{
|
||||
setting_key: 'default_protection_level',
|
||||
setting_value: JSON.stringify('standard'),
|
||||
setting_type: 'security'
|
||||
},
|
||||
{
|
||||
setting_key: 'default_image_quality',
|
||||
setting_value: JSON.stringify(85),
|
||||
setting_type: 'security'
|
||||
},
|
||||
{
|
||||
setting_key: 'enable_devtools_protection',
|
||||
setting_value: JSON.stringify(true),
|
||||
setting_type: 'security'
|
||||
},
|
||||
{
|
||||
setting_key: 'max_image_requests_per_minute',
|
||||
setting_value: JSON.stringify(30),
|
||||
setting_type: 'security'
|
||||
},
|
||||
{
|
||||
setting_key: 'suspicious_activity_threshold',
|
||||
setting_value: JSON.stringify(10),
|
||||
setting_type: 'security'
|
||||
},
|
||||
{
|
||||
setting_key: 'enable_canvas_rendering',
|
||||
setting_value: JSON.stringify(false),
|
||||
setting_type: 'security'
|
||||
},
|
||||
{
|
||||
setting_key: 'default_fragmentation_level',
|
||||
setting_value: JSON.stringify(3),
|
||||
setting_type: 'security'
|
||||
}
|
||||
]);
|
||||
}
|
||||
|
||||
console.log('Enhanced image protection features added successfully');
|
||||
};
|
||||
|
||||
exports.down = async function(knex) {
|
||||
console.log('Removing enhanced image protection features...');
|
||||
|
||||
// Remove app settings
|
||||
await knex('app_settings')
|
||||
.whereIn('setting_key', [
|
||||
'default_protection_level',
|
||||
'default_image_quality',
|
||||
'enable_devtools_protection',
|
||||
'max_image_requests_per_minute',
|
||||
'suspicious_activity_threshold',
|
||||
'enable_canvas_rendering',
|
||||
'default_fragmentation_level'
|
||||
])
|
||||
.delete();
|
||||
|
||||
// Drop image access logs table
|
||||
const hasImageAccessLogs = await knex.schema.hasTable('image_access_logs');
|
||||
if (hasImageAccessLogs) {
|
||||
await knex.schema.dropTable('image_access_logs');
|
||||
}
|
||||
|
||||
// Remove protection columns from events table
|
||||
const hasProtectionLevel = await knex.schema.hasColumn('events', 'protection_level');
|
||||
if (hasProtectionLevel) {
|
||||
await knex.schema.table('events', (table) => {
|
||||
table.dropColumn('protection_level');
|
||||
table.dropColumn('image_quality');
|
||||
table.dropColumn('add_fingerprint');
|
||||
table.dropColumn('enable_devtools_protection');
|
||||
table.dropColumn('use_canvas_rendering');
|
||||
table.dropColumn('fragmentation_level');
|
||||
table.dropColumn('overlay_protection');
|
||||
});
|
||||
}
|
||||
|
||||
console.log('Enhanced image protection features removed');
|
||||
};
|
||||
@@ -0,0 +1,117 @@
|
||||
// Add security logging and monitoring tables
|
||||
|
||||
exports.up = async function(knex) {
|
||||
console.log('Adding security logging and monitoring tables...');
|
||||
|
||||
// Create security logs table for general security events
|
||||
const hasSecurityLogs = await knex.schema.hasTable('security_logs');
|
||||
if (!hasSecurityLogs) {
|
||||
await knex.schema.createTable('security_logs', (table) => {
|
||||
table.increments('id').primary();
|
||||
table.string('event_type', 50).notNullable(); // rate_limit_exceeded, suspicious_activity, etc.
|
||||
table.string('client_ip', 45).notNullable();
|
||||
table.string('client_fingerprint', 32);
|
||||
table.text('user_agent');
|
||||
table.string('request_path');
|
||||
table.string('request_method', 10);
|
||||
table.json('details'); // Additional event details
|
||||
table.timestamp('timestamp').defaultTo(knex.fn.now());
|
||||
|
||||
// Indexes for performance
|
||||
table.index(['event_type', 'timestamp']);
|
||||
table.index(['client_ip', 'timestamp']);
|
||||
table.index(['client_fingerprint', 'timestamp']);
|
||||
});
|
||||
}
|
||||
|
||||
// Add security monitoring settings to app_settings
|
||||
const securitySettings = [
|
||||
{
|
||||
setting_key: 'security_monitoring_enabled',
|
||||
setting_value: JSON.stringify(true),
|
||||
setting_type: 'security'
|
||||
},
|
||||
{
|
||||
setting_key: 'max_image_requests_per_5_minutes',
|
||||
setting_value: JSON.stringify(100),
|
||||
setting_type: 'security'
|
||||
},
|
||||
{
|
||||
setting_key: 'max_image_requests_per_hour',
|
||||
setting_value: JSON.stringify(500),
|
||||
setting_type: 'security'
|
||||
},
|
||||
{
|
||||
setting_key: 'block_suspicious_ips',
|
||||
setting_value: JSON.stringify(true),
|
||||
setting_type: 'security'
|
||||
},
|
||||
{
|
||||
setting_key: 'log_security_events_to_db',
|
||||
setting_value: JSON.stringify(true),
|
||||
setting_type: 'security'
|
||||
},
|
||||
{
|
||||
setting_key: 'auto_block_threshold',
|
||||
setting_value: JSON.stringify(5),
|
||||
setting_type: 'security'
|
||||
}
|
||||
];
|
||||
|
||||
for (const setting of securitySettings) {
|
||||
const exists = await knex('app_settings')
|
||||
.where('setting_key', setting.setting_key)
|
||||
.first();
|
||||
|
||||
if (!exists) {
|
||||
await knex('app_settings').insert(setting);
|
||||
}
|
||||
}
|
||||
|
||||
// Add mime_type column to photos table if it doesn't exist
|
||||
const hasMimeType = await knex.schema.hasColumn('photos', 'mime_type');
|
||||
if (!hasMimeType) {
|
||||
await knex.schema.table('photos', (table) => {
|
||||
table.string('mime_type', 100);
|
||||
});
|
||||
|
||||
// Update existing photos with default mime type
|
||||
await knex('photos')
|
||||
.whereNull('mime_type')
|
||||
.update({ mime_type: 'image/jpeg' });
|
||||
}
|
||||
|
||||
console.log('Security logging and monitoring tables added successfully');
|
||||
};
|
||||
|
||||
exports.down = async function(knex) {
|
||||
console.log('Removing security logging and monitoring tables...');
|
||||
|
||||
// Remove security settings
|
||||
await knex('app_settings')
|
||||
.whereIn('setting_key', [
|
||||
'security_monitoring_enabled',
|
||||
'max_image_requests_per_5_minutes',
|
||||
'max_image_requests_per_hour',
|
||||
'block_suspicious_ips',
|
||||
'log_security_events_to_db',
|
||||
'auto_block_threshold'
|
||||
])
|
||||
.delete();
|
||||
|
||||
// Drop security logs table
|
||||
const hasSecurityLogs = await knex.schema.hasTable('security_logs');
|
||||
if (hasSecurityLogs) {
|
||||
await knex.schema.dropTable('security_logs');
|
||||
}
|
||||
|
||||
// Remove mime_type column from photos table
|
||||
const hasMimeType = await knex.schema.hasColumn('photos', 'mime_type');
|
||||
if (hasMimeType) {
|
||||
await knex.schema.table('photos', (table) => {
|
||||
table.dropColumn('mime_type');
|
||||
});
|
||||
}
|
||||
|
||||
console.log('Security logging and monitoring tables removed');
|
||||
};
|
||||
@@ -0,0 +1,33 @@
|
||||
exports.up = async function(knex) {
|
||||
// Add thumbnail settings to app_settings table
|
||||
const thumbnailSettings = [
|
||||
{ setting_key: 'thumbnail_width', setting_value: 300, setting_type: 'number' },
|
||||
{ setting_key: 'thumbnail_height', setting_value: 300, setting_type: 'number' },
|
||||
{ setting_key: 'thumbnail_fit', setting_value: JSON.stringify('cover'), setting_type: 'string' },
|
||||
{ setting_key: 'thumbnail_quality', setting_value: 85, setting_type: 'number' },
|
||||
{ setting_key: 'thumbnail_format', setting_value: JSON.stringify('jpeg'), setting_type: 'string' }
|
||||
];
|
||||
|
||||
for (const setting of thumbnailSettings) {
|
||||
const exists = await knex('app_settings').where('setting_key', setting.setting_key).first();
|
||||
if (!exists) {
|
||||
await knex('app_settings').insert({
|
||||
...setting,
|
||||
updated_at: knex.fn.now()
|
||||
});
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
exports.down = async function(knex) {
|
||||
// Remove thumbnail settings
|
||||
await knex('app_settings')
|
||||
.whereIn('setting_key', [
|
||||
'thumbnail_width',
|
||||
'thumbnail_height',
|
||||
'thumbnail_fit',
|
||||
'thumbnail_quality',
|
||||
'thumbnail_format'
|
||||
])
|
||||
.del();
|
||||
};
|
||||
@@ -0,0 +1,54 @@
|
||||
/**
|
||||
* Migration 041: Add external media reference support
|
||||
* - events.source_mode: 'managed' | 'reference'
|
||||
* - events.external_path: relative path under external media root
|
||||
* - photos.source_origin: 'managed' | 'external'
|
||||
* - photos.external_relpath: relative path within event.external_path
|
||||
*/
|
||||
|
||||
const { addColumnIfNotExists } = require('../helpers');
|
||||
|
||||
exports.up = async function(knex) {
|
||||
console.log('Running migration: 041_add_external_media');
|
||||
|
||||
// events.source_mode (default 'managed')
|
||||
await addColumnIfNotExists(knex, 'events', 'source_mode', (table) => {
|
||||
table.string('source_mode').notNullable().defaultTo('managed');
|
||||
});
|
||||
|
||||
// events.external_path (nullable)
|
||||
await addColumnIfNotExists(knex, 'events', 'external_path', (table) => {
|
||||
table.text('external_path');
|
||||
});
|
||||
|
||||
// photos.source_origin (default 'managed')
|
||||
await addColumnIfNotExists(knex, 'photos', 'source_origin', (table) => {
|
||||
table.string('source_origin').notNullable().defaultTo('managed');
|
||||
});
|
||||
|
||||
// photos.external_relpath (nullable)
|
||||
await addColumnIfNotExists(knex, 'photos', 'external_relpath', (table) => {
|
||||
table.text('external_relpath');
|
||||
});
|
||||
|
||||
// Helpful index for queries
|
||||
try {
|
||||
if (knex.client.config.client === 'pg') {
|
||||
await knex.raw("CREATE INDEX IF NOT EXISTS photos_event_source_idx ON photos (event_id, source_origin)");
|
||||
} else {
|
||||
await knex.schema.alterTable('photos', (table) => {
|
||||
table.index(['event_id', 'source_origin'], 'photos_event_source_idx');
|
||||
});
|
||||
}
|
||||
} catch (e) {
|
||||
console.log('Index creation skipped or failed (may already exist):', e.message);
|
||||
}
|
||||
|
||||
console.log('Migration 041_add_external_media completed');
|
||||
};
|
||||
|
||||
exports.down = async function(knex) {
|
||||
console.log('Rollback: 041_add_external_media');
|
||||
// Keep columns (safe rollback not removing data). Intentionally no-op.
|
||||
};
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
const logger = require('../../src/utils/logger');
|
||||
|
||||
async function ensureColumn(knex, tableName, columnName, alterFn) {
|
||||
const exists = await knex.schema.hasColumn(tableName, columnName);
|
||||
if (!exists) {
|
||||
logger.info(`Adding column ${tableName}.${columnName}`);
|
||||
await knex.schema.table(tableName, alterFn);
|
||||
}
|
||||
}
|
||||
|
||||
exports.up = async function(knex) {
|
||||
await ensureColumn(knex, 'events', 'host_name', (table) => {
|
||||
table.string('host_name');
|
||||
});
|
||||
|
||||
await ensureColumn(knex, 'events', 'allow_user_uploads', (table) => {
|
||||
table.boolean('allow_user_uploads').defaultTo(false);
|
||||
});
|
||||
|
||||
await ensureColumn(knex, 'events', 'upload_category_id', (table) => {
|
||||
table.integer('upload_category_id');
|
||||
});
|
||||
|
||||
await ensureColumn(knex, 'events', 'allow_downloads', (table) => {
|
||||
table.boolean('allow_downloads').defaultTo(true);
|
||||
});
|
||||
|
||||
await ensureColumn(knex, 'events', 'disable_right_click', (table) => {
|
||||
table.boolean('disable_right_click').defaultTo(false);
|
||||
});
|
||||
|
||||
await ensureColumn(knex, 'events', 'watermark_downloads', (table) => {
|
||||
table.boolean('watermark_downloads').defaultTo(false);
|
||||
});
|
||||
|
||||
await ensureColumn(knex, 'events', 'watermark_text', (table) => {
|
||||
table.text('watermark_text');
|
||||
});
|
||||
|
||||
await ensureColumn(knex, 'events', 'hero_photo_id', (table) => {
|
||||
table.integer('hero_photo_id').references('id').inTable('photos').onDelete('SET NULL');
|
||||
});
|
||||
|
||||
await ensureColumn(knex, 'photos', 'uploaded_by', (table) => {
|
||||
table.string('uploaded_by').defaultTo('admin');
|
||||
});
|
||||
};
|
||||
|
||||
exports.down = async function() {
|
||||
// Non destructive migration; no rollback
|
||||
};
|
||||
@@ -0,0 +1,46 @@
|
||||
const {
|
||||
DEFAULT_PUBLIC_SITE_HTML,
|
||||
} = require('../../src/constants/publicSiteDefaults');
|
||||
|
||||
exports.up = async function(knex) {
|
||||
const defaults = [
|
||||
{
|
||||
setting_key: 'general_public_site_enabled',
|
||||
setting_value: JSON.stringify(false),
|
||||
setting_type: 'general'
|
||||
},
|
||||
{
|
||||
setting_key: 'general_public_site_html',
|
||||
setting_value: JSON.stringify(DEFAULT_PUBLIC_SITE_HTML.trim()),
|
||||
setting_type: 'general'
|
||||
},
|
||||
{
|
||||
setting_key: 'general_public_site_custom_css',
|
||||
setting_value: JSON.stringify(''),
|
||||
setting_type: 'general'
|
||||
}
|
||||
];
|
||||
|
||||
for (const setting of defaults) {
|
||||
const exists = await knex('app_settings')
|
||||
.where('setting_key', setting.setting_key)
|
||||
.first();
|
||||
|
||||
if (!exists) {
|
||||
await knex('app_settings').insert({
|
||||
...setting,
|
||||
updated_at: knex.fn.now()
|
||||
});
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
exports.down = async function(knex) {
|
||||
await knex('app_settings')
|
||||
.whereIn('setting_key', [
|
||||
'general_public_site_enabled',
|
||||
'general_public_site_html',
|
||||
'general_public_site_custom_css'
|
||||
])
|
||||
.del();
|
||||
};
|
||||
@@ -0,0 +1,18 @@
|
||||
exports.up = async function (knex) {
|
||||
const hasColumn = await knex.schema.hasColumn('events', 'require_password');
|
||||
if (!hasColumn) {
|
||||
await knex.schema.table('events', (table) => {
|
||||
table.boolean('require_password').notNullable().defaultTo(true);
|
||||
});
|
||||
await knex('events').update({ require_password: true });
|
||||
}
|
||||
};
|
||||
|
||||
exports.down = async function (knex) {
|
||||
const hasColumn = await knex.schema.hasColumn('events', 'require_password');
|
||||
if (hasColumn) {
|
||||
await knex.schema.table('events', (table) => {
|
||||
table.dropColumn('require_password');
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,48 @@
|
||||
const { DEFAULT_MAX_FILES_PER_UPLOAD, MAX_ALLOWED_FILES_PER_UPLOAD } = require('../../src/services/uploadSettings');
|
||||
|
||||
exports.up = async function up(knex) {
|
||||
const settingKey = 'general_max_files_per_upload';
|
||||
|
||||
const existing = await knex('app_settings')
|
||||
.where({ setting_key: settingKey })
|
||||
.first();
|
||||
|
||||
if (existing) {
|
||||
// Normalize existing value into allowed bounds
|
||||
let parsedValue;
|
||||
try {
|
||||
parsedValue = existing.setting_value != null ? JSON.parse(existing.setting_value) : null;
|
||||
} catch {
|
||||
parsedValue = existing.setting_value;
|
||||
}
|
||||
|
||||
const numeric = Number(parsedValue);
|
||||
let normalized = DEFAULT_MAX_FILES_PER_UPLOAD;
|
||||
if (Number.isFinite(numeric) && numeric >= 1) {
|
||||
normalized = Math.min(MAX_ALLOWED_FILES_PER_UPLOAD, Math.floor(numeric));
|
||||
}
|
||||
|
||||
if (normalized !== numeric) {
|
||||
await knex('app_settings')
|
||||
.where({ setting_key: settingKey })
|
||||
.update({
|
||||
setting_value: JSON.stringify(normalized),
|
||||
updated_at: new Date()
|
||||
});
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
await knex('app_settings').insert({
|
||||
setting_key: settingKey,
|
||||
setting_value: JSON.stringify(DEFAULT_MAX_FILES_PER_UPLOAD),
|
||||
setting_type: 'general',
|
||||
updated_at: new Date()
|
||||
});
|
||||
};
|
||||
|
||||
exports.down = async function down(knex) {
|
||||
await knex('app_settings')
|
||||
.where({ setting_key: 'general_max_files_per_upload' })
|
||||
.del();
|
||||
};
|
||||
@@ -0,0 +1,44 @@
|
||||
const { addColumnIfNotExists } = require('../helpers');
|
||||
|
||||
exports.up = async function up(knex) {
|
||||
await addColumnIfNotExists(knex, 'events', 'customer_name', (table) => {
|
||||
table.string('customer_name');
|
||||
});
|
||||
|
||||
await addColumnIfNotExists(knex, 'events', 'customer_email', (table) => {
|
||||
table.string('customer_email');
|
||||
});
|
||||
|
||||
// Backfill new columns from legacy host_* fields
|
||||
const client = knex?.client?.config?.client;
|
||||
|
||||
if (client === 'pg') {
|
||||
await knex.raw(`
|
||||
UPDATE events
|
||||
SET customer_name = COALESCE(customer_name, host_name),
|
||||
customer_email = COALESCE(customer_email, host_email)
|
||||
`);
|
||||
} else {
|
||||
// SQLite fallback
|
||||
await knex('events').update({
|
||||
customer_name: knex.raw('COALESCE(customer_name, host_name)'),
|
||||
customer_email: knex.raw('COALESCE(customer_email, host_email)')
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
exports.down = async function down(knex) {
|
||||
const hasCustomerName = await knex.schema.hasColumn('events', 'customer_name');
|
||||
if (hasCustomerName) {
|
||||
await knex.schema.alterTable('events', (table) => {
|
||||
table.dropColumn('customer_name');
|
||||
});
|
||||
}
|
||||
|
||||
const hasCustomerEmail = await knex.schema.hasColumn('events', 'customer_email');
|
||||
if (hasCustomerEmail) {
|
||||
await knex.schema.alterTable('events', (table) => {
|
||||
table.dropColumn('customer_email');
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,18 @@
|
||||
const { addColumnIfNotExists } = require('../helpers');
|
||||
|
||||
exports.up = async function up(knex) {
|
||||
// Add tls_reject_unauthorized column to email_configs table
|
||||
// Default is true (validate certificates), false means ignore SSL/TLS certificate errors
|
||||
await addColumnIfNotExists(knex, 'email_configs', 'tls_reject_unauthorized', (table) => {
|
||||
table.boolean('tls_reject_unauthorized').defaultTo(true);
|
||||
});
|
||||
};
|
||||
|
||||
exports.down = async function down(knex) {
|
||||
const hasColumn = await knex.schema.hasColumn('email_configs', 'tls_reject_unauthorized');
|
||||
if (hasColumn) {
|
||||
await knex.schema.alterTable('email_configs', (table) => {
|
||||
table.dropColumn('tls_reject_unauthorized');
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,109 @@
|
||||
const { addColumnIfNotExists } = require('../helpers');
|
||||
|
||||
/**
|
||||
* Migration: Add video support to photos table
|
||||
* - Adds columns for video metadata (media_type, duration, codecs, dimensions)
|
||||
* - Updates existing photos to have media_type 'image'
|
||||
*/
|
||||
|
||||
exports.up = async function(knex) {
|
||||
console.log('Running migration: 042_add_video_support');
|
||||
|
||||
// Add media_type column (image or video)
|
||||
await addColumnIfNotExists(knex, 'photos', 'media_type', (table) => {
|
||||
table.string('media_type').defaultTo('image');
|
||||
});
|
||||
|
||||
// Add mime_type column if not exists
|
||||
await addColumnIfNotExists(knex, 'photos', 'mime_type', (table) => {
|
||||
table.string('mime_type');
|
||||
});
|
||||
|
||||
// Add duration column (for videos, in seconds)
|
||||
await addColumnIfNotExists(knex, 'photos', 'duration', (table) => {
|
||||
table.integer('duration');
|
||||
});
|
||||
|
||||
// Add video codec information
|
||||
await addColumnIfNotExists(knex, 'photos', 'video_codec', (table) => {
|
||||
table.string('video_codec');
|
||||
});
|
||||
|
||||
// Add audio codec information
|
||||
await addColumnIfNotExists(knex, 'photos', 'audio_codec', (table) => {
|
||||
table.string('audio_codec');
|
||||
});
|
||||
|
||||
// Add width dimension
|
||||
await addColumnIfNotExists(knex, 'photos', 'width', (table) => {
|
||||
table.integer('width');
|
||||
});
|
||||
|
||||
// Add height dimension
|
||||
await addColumnIfNotExists(knex, 'photos', 'height', (table) => {
|
||||
table.integer('height');
|
||||
});
|
||||
|
||||
// Update existing photos to have media_type 'image' if not set
|
||||
const hasMediaType = await knex.schema.hasColumn('photos', 'media_type');
|
||||
if (hasMediaType) {
|
||||
await knex('photos')
|
||||
.whereNull('media_type')
|
||||
.orWhere('media_type', '')
|
||||
.update({ media_type: 'image' });
|
||||
console.log('Updated existing photos to have media_type "image"');
|
||||
}
|
||||
|
||||
console.log('Migration 042_add_video_support completed');
|
||||
};
|
||||
|
||||
exports.down = async function(knex) {
|
||||
console.log('Rolling back migration: 042_add_video_support');
|
||||
|
||||
// Remove video support columns
|
||||
const hasMediaType = await knex.schema.hasColumn('photos', 'media_type');
|
||||
if (hasMediaType) {
|
||||
await knex.schema.alterTable('photos', (table) => {
|
||||
table.dropColumn('media_type');
|
||||
});
|
||||
}
|
||||
|
||||
const hasDuration = await knex.schema.hasColumn('photos', 'duration');
|
||||
if (hasDuration) {
|
||||
await knex.schema.alterTable('photos', (table) => {
|
||||
table.dropColumn('duration');
|
||||
});
|
||||
}
|
||||
|
||||
const hasVideoCodec = await knex.schema.hasColumn('photos', 'video_codec');
|
||||
if (hasVideoCodec) {
|
||||
await knex.schema.alterTable('photos', (table) => {
|
||||
table.dropColumn('video_codec');
|
||||
});
|
||||
}
|
||||
|
||||
const hasAudioCodec = await knex.schema.hasColumn('photos', 'audio_codec');
|
||||
if (hasAudioCodec) {
|
||||
await knex.schema.alterTable('photos', (table) => {
|
||||
table.dropColumn('audio_codec');
|
||||
});
|
||||
}
|
||||
|
||||
const hasWidth = await knex.schema.hasColumn('photos', 'width');
|
||||
if (hasWidth) {
|
||||
await knex.schema.alterTable('photos', (table) => {
|
||||
table.dropColumn('width');
|
||||
});
|
||||
}
|
||||
|
||||
const hasHeight = await knex.schema.hasColumn('photos', 'height');
|
||||
if (hasHeight) {
|
||||
await knex.schema.alterTable('photos', (table) => {
|
||||
table.dropColumn('height');
|
||||
});
|
||||
}
|
||||
|
||||
// Note: We don't drop mime_type as it may be used by images as well
|
||||
|
||||
console.log('Rollback of 042_add_video_support completed');
|
||||
};
|
||||
@@ -0,0 +1,21 @@
|
||||
/**
|
||||
* Migration: Add slug_redirects table for event rename feature
|
||||
* This table stores old slugs that should redirect to new slugs
|
||||
*/
|
||||
|
||||
exports.up = function(knex) {
|
||||
return knex.schema.createTable('slug_redirects', (table) => {
|
||||
table.increments('id').primary();
|
||||
table.string('old_slug', 255).notNullable().unique();
|
||||
table.string('new_slug', 255).notNullable();
|
||||
table.integer('event_id').references('id').inTable('events').onDelete('CASCADE');
|
||||
table.timestamp('created_at').defaultTo(knex.fn.now());
|
||||
|
||||
// Index for fast lookup
|
||||
table.index('old_slug');
|
||||
});
|
||||
};
|
||||
|
||||
exports.down = function(knex) {
|
||||
return knex.schema.dropTableIfExists('slug_redirects');
|
||||
};
|
||||
@@ -0,0 +1,33 @@
|
||||
/**
|
||||
* Migration: Add optional event fields settings
|
||||
* These settings control whether customer name, customer email, and admin email
|
||||
* are required when creating new events.
|
||||
*/
|
||||
|
||||
exports.up = async function(knex) {
|
||||
const settings = [
|
||||
{ setting_key: 'event_require_customer_name', setting_value: JSON.stringify(true), setting_type: 'boolean' },
|
||||
{ setting_key: 'event_require_customer_email', setting_value: JSON.stringify(true), setting_type: 'boolean' },
|
||||
{ setting_key: 'event_require_admin_email', setting_value: JSON.stringify(true), setting_type: 'boolean' }
|
||||
];
|
||||
|
||||
for (const setting of settings) {
|
||||
const exists = await knex('app_settings').where('setting_key', setting.setting_key).first();
|
||||
if (!exists) {
|
||||
await knex('app_settings').insert({
|
||||
...setting,
|
||||
updated_at: knex.fn.now()
|
||||
});
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
exports.down = function(knex) {
|
||||
return knex('app_settings')
|
||||
.whereIn('setting_key', [
|
||||
'event_require_customer_name',
|
||||
'event_require_customer_email',
|
||||
'event_require_admin_email'
|
||||
])
|
||||
.del();
|
||||
};
|
||||
@@ -0,0 +1,100 @@
|
||||
/**
|
||||
* Migration: Add indexes for photo filtering performance
|
||||
* These indexes optimize queries that filter by feedback metrics
|
||||
*/
|
||||
|
||||
exports.up = async function(knex) {
|
||||
// Add comment_count column if it doesn't exist
|
||||
const hasCommentCount = await knex.schema.hasColumn('photos', 'comment_count');
|
||||
if (!hasCommentCount) {
|
||||
await knex.schema.alterTable('photos', (table) => {
|
||||
table.integer('comment_count').defaultTo(0);
|
||||
});
|
||||
}
|
||||
|
||||
// Add indexes for common filter queries
|
||||
// Note: PostgreSQL supports partial indexes, SQLite does not
|
||||
const client = knex.client.config.client;
|
||||
|
||||
if (client === 'pg' || client === 'postgresql') {
|
||||
// Partial indexes for PostgreSQL
|
||||
await knex.raw(`
|
||||
CREATE INDEX IF NOT EXISTS idx_photos_rating_filter
|
||||
ON photos(event_id, average_rating)
|
||||
WHERE average_rating > 0
|
||||
`);
|
||||
|
||||
await knex.raw(`
|
||||
CREATE INDEX IF NOT EXISTS idx_photos_likes_filter
|
||||
ON photos(event_id, like_count)
|
||||
WHERE like_count > 0
|
||||
`);
|
||||
|
||||
await knex.raw(`
|
||||
CREATE INDEX IF NOT EXISTS idx_photos_favorites_filter
|
||||
ON photos(event_id, favorite_count)
|
||||
WHERE favorite_count > 0
|
||||
`);
|
||||
|
||||
await knex.raw(`
|
||||
CREATE INDEX IF NOT EXISTS idx_photos_comments_filter
|
||||
ON photos(event_id, comment_count)
|
||||
WHERE comment_count > 0
|
||||
`);
|
||||
} else {
|
||||
// Regular indexes for SQLite
|
||||
await knex.raw(`
|
||||
CREATE INDEX IF NOT EXISTS idx_photos_rating_filter
|
||||
ON photos(event_id, average_rating)
|
||||
`);
|
||||
|
||||
await knex.raw(`
|
||||
CREATE INDEX IF NOT EXISTS idx_photos_likes_filter
|
||||
ON photos(event_id, like_count)
|
||||
`);
|
||||
|
||||
await knex.raw(`
|
||||
CREATE INDEX IF NOT EXISTS idx_photos_favorites_filter
|
||||
ON photos(event_id, favorite_count)
|
||||
`);
|
||||
|
||||
await knex.raw(`
|
||||
CREATE INDEX IF NOT EXISTS idx_photos_comments_filter
|
||||
ON photos(event_id, comment_count)
|
||||
`);
|
||||
}
|
||||
|
||||
// Create export_jobs table for tracking large exports
|
||||
const hasExportJobs = await knex.schema.hasTable('export_jobs');
|
||||
if (!hasExportJobs) {
|
||||
await knex.schema.createTable('export_jobs', (table) => {
|
||||
table.increments('id').primary();
|
||||
table.string('job_id', 50).unique().notNullable();
|
||||
table.integer('event_id').references('id').inTable('events').onDelete('CASCADE');
|
||||
table.integer('admin_user_id').references('id').inTable('admin_users').onDelete('SET NULL');
|
||||
table.string('format', 20).notNullable();
|
||||
table.string('status', 20).defaultTo('pending');
|
||||
table.integer('progress').defaultTo(0);
|
||||
table.integer('total_photos');
|
||||
table.json('options');
|
||||
table.string('file_path', 500);
|
||||
table.bigInteger('file_size');
|
||||
table.text('error_message');
|
||||
table.timestamp('created_at').defaultTo(knex.fn.now());
|
||||
table.timestamp('completed_at');
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
exports.down = async function(knex) {
|
||||
// Drop indexes
|
||||
await knex.raw('DROP INDEX IF EXISTS idx_photos_rating_filter');
|
||||
await knex.raw('DROP INDEX IF EXISTS idx_photos_likes_filter');
|
||||
await knex.raw('DROP INDEX IF EXISTS idx_photos_favorites_filter');
|
||||
await knex.raw('DROP INDEX IF EXISTS idx_photos_comments_filter');
|
||||
|
||||
// Drop export_jobs table
|
||||
await knex.schema.dropTableIfExists('export_jobs');
|
||||
|
||||
// Note: We don't remove comment_count column as it might have data
|
||||
};
|
||||
@@ -0,0 +1,192 @@
|
||||
/**
|
||||
* Migration: Add CSS Templates feature
|
||||
* Creates css_templates table and adds css_template_id to events table
|
||||
*/
|
||||
|
||||
// Default CSS template content
|
||||
const DEFAULT_CSS_TEMPLATE = `/*
|
||||
* PicPeak Custom CSS Template: Elegant Dark
|
||||
*
|
||||
* Available CSS Custom Properties:
|
||||
* --gallery-bg: Background color
|
||||
* --gallery-text: Primary text color
|
||||
* --gallery-accent: Accent/highlight color
|
||||
* --gallery-border: Border color
|
||||
* --gallery-shadow: Box shadow value
|
||||
* --gallery-radius: Border radius value
|
||||
* --gallery-spacing: Base spacing unit
|
||||
*/
|
||||
|
||||
/* ===== Base Theme Variables ===== */
|
||||
.gallery-page {
|
||||
--gallery-bg: #1a1a2e;
|
||||
--gallery-bg-secondary: #16213e;
|
||||
--gallery-text: #eaeaea;
|
||||
--gallery-text-muted: #8b8b9a;
|
||||
--gallery-accent: #e94560;
|
||||
--gallery-accent-hover: #ff6b6b;
|
||||
--gallery-border: #2d2d44;
|
||||
--gallery-shadow: 0 4px 20px rgba(0, 0, 0, 0.3);
|
||||
--gallery-radius: 12px;
|
||||
--gallery-spacing: 16px;
|
||||
}
|
||||
|
||||
/* ===== Page Background ===== */
|
||||
.gallery-page {
|
||||
background: linear-gradient(135deg, var(--gallery-bg) 0%, var(--gallery-bg-secondary) 100%);
|
||||
min-height: 100vh;
|
||||
color: var(--gallery-text);
|
||||
}
|
||||
|
||||
/* ===== Gallery Header ===== */
|
||||
.gallery-header {
|
||||
background: rgba(22, 33, 62, 0.8);
|
||||
backdrop-filter: blur(10px);
|
||||
border-bottom: 1px solid var(--gallery-border);
|
||||
padding: calc(var(--gallery-spacing) * 2);
|
||||
}
|
||||
|
||||
.gallery-title {
|
||||
color: var(--gallery-text);
|
||||
font-size: 2rem;
|
||||
font-weight: 700;
|
||||
letter-spacing: -0.02em;
|
||||
}
|
||||
|
||||
/* ===== Photo Grid ===== */
|
||||
.photo-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
|
||||
gap: var(--gallery-spacing);
|
||||
padding: calc(var(--gallery-spacing) * 2);
|
||||
}
|
||||
|
||||
/* ===== Photo Cards ===== */
|
||||
.photo-card {
|
||||
background: var(--gallery-bg-secondary);
|
||||
border-radius: var(--gallery-radius);
|
||||
overflow: hidden;
|
||||
transition: transform 0.3s ease, box-shadow 0.3s ease;
|
||||
border: 1px solid var(--gallery-border);
|
||||
}
|
||||
|
||||
.photo-card:hover {
|
||||
transform: translateY(-4px);
|
||||
box-shadow: var(--gallery-shadow);
|
||||
}
|
||||
|
||||
.photo-card img {
|
||||
width: 100%;
|
||||
height: 200px;
|
||||
object-fit: cover;
|
||||
transition: transform 0.3s ease;
|
||||
}
|
||||
|
||||
.photo-card:hover img {
|
||||
transform: scale(1.05);
|
||||
}
|
||||
|
||||
/* ===== Buttons ===== */
|
||||
.gallery-btn {
|
||||
background: var(--gallery-accent);
|
||||
color: white;
|
||||
border: none;
|
||||
border-radius: calc(var(--gallery-radius) / 2);
|
||||
padding: calc(var(--gallery-spacing) / 2) var(--gallery-spacing);
|
||||
font-weight: 600;
|
||||
cursor: pointer;
|
||||
transition: background 0.2s ease, transform 0.2s ease;
|
||||
}
|
||||
|
||||
.gallery-btn:hover {
|
||||
background: var(--gallery-accent-hover);
|
||||
transform: translateY(-2px);
|
||||
}
|
||||
|
||||
/* ===== Lightbox ===== */
|
||||
.lightbox-overlay {
|
||||
background: rgba(10, 10, 20, 0.95);
|
||||
backdrop-filter: blur(20px);
|
||||
}
|
||||
|
||||
/* ===== Responsive Adjustments ===== */
|
||||
@media (max-width: 768px) {
|
||||
.gallery-page {
|
||||
--gallery-spacing: 12px;
|
||||
}
|
||||
|
||||
.photo-grid {
|
||||
grid-template-columns: repeat(auto-fill, minmax(160px, 1fr));
|
||||
}
|
||||
|
||||
.gallery-title {
|
||||
font-size: 1.5rem;
|
||||
}
|
||||
}`;
|
||||
|
||||
exports.up = async function(knex) {
|
||||
// Create css_templates table
|
||||
const hasTable = await knex.schema.hasTable('css_templates');
|
||||
if (!hasTable) {
|
||||
await knex.schema.createTable('css_templates', (table) => {
|
||||
table.increments('id').primary();
|
||||
table.integer('slot_number').notNullable();
|
||||
table.string('name', 50).notNullable().defaultTo('Untitled');
|
||||
table.text('css_content').notNullable().defaultTo('');
|
||||
table.boolean('is_enabled').notNullable().defaultTo(false);
|
||||
table.boolean('is_default').notNullable().defaultTo(false);
|
||||
table.timestamp('created_at').defaultTo(knex.fn.now());
|
||||
table.timestamp('updated_at').defaultTo(knex.fn.now());
|
||||
table.unique('slot_number');
|
||||
});
|
||||
|
||||
// Insert default templates
|
||||
await knex('css_templates').insert([
|
||||
{
|
||||
slot_number: 1,
|
||||
name: 'Elegant Dark',
|
||||
css_content: DEFAULT_CSS_TEMPLATE,
|
||||
is_enabled: true,
|
||||
is_default: true
|
||||
},
|
||||
{
|
||||
slot_number: 2,
|
||||
name: 'Untitled',
|
||||
css_content: '',
|
||||
is_enabled: false,
|
||||
is_default: false
|
||||
},
|
||||
{
|
||||
slot_number: 3,
|
||||
name: 'Untitled',
|
||||
css_content: '',
|
||||
is_enabled: false,
|
||||
is_default: false
|
||||
}
|
||||
]);
|
||||
}
|
||||
|
||||
// Add css_template_id to events table
|
||||
const hasColumn = await knex.schema.hasColumn('events', 'css_template_id');
|
||||
if (!hasColumn) {
|
||||
await knex.schema.alterTable('events', (table) => {
|
||||
table.integer('css_template_id').references('id').inTable('css_templates').onDelete('SET NULL');
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
exports.down = async function(knex) {
|
||||
// Remove css_template_id from events table
|
||||
const hasColumn = await knex.schema.hasColumn('events', 'css_template_id');
|
||||
if (hasColumn) {
|
||||
await knex.schema.alterTable('events', (table) => {
|
||||
table.dropColumn('css_template_id');
|
||||
});
|
||||
}
|
||||
|
||||
// Drop css_templates table
|
||||
await knex.schema.dropTableIfExists('css_templates');
|
||||
};
|
||||
|
||||
// Export default template for use in reset functionality
|
||||
module.exports.DEFAULT_CSS_TEMPLATE = DEFAULT_CSS_TEMPLATE;
|
||||
@@ -0,0 +1,731 @@
|
||||
/**
|
||||
* Migration: Add Liquid Glass CSS Templates
|
||||
* Updates template slots 2 and 3 with Apple-inspired Liquid Glass designs
|
||||
*
|
||||
* These are starter example templates for new installations.
|
||||
* Users can edit or replace them as needed.
|
||||
*/
|
||||
|
||||
const APPLE_LIQUID_GLASS = `/*
|
||||
* PicPeak Custom CSS Template: Apple Liquid Glass
|
||||
* Authentic iOS 26 / macOS Tahoe Liquid Glass Design
|
||||
*/
|
||||
|
||||
/* ===== Apple System Fonts ===== */
|
||||
.gallery-page,
|
||||
.gallery-page *,
|
||||
.gallery-sidebar,
|
||||
.gallery-sidebar * {
|
||||
font-family: -apple-system, BlinkMacSystemFont, "SF Pro Display", "SF Pro Text",
|
||||
"Helvetica Neue", Arial, sans-serif;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
-moz-osx-font-smoothing: grayscale;
|
||||
}
|
||||
|
||||
/* ===== CSS Variables ===== */
|
||||
:root {
|
||||
--glass-blur: 20px;
|
||||
--glass-blur-heavy: 40px;
|
||||
--glass-saturation: 180%;
|
||||
--glass-bg: rgba(255, 255, 255, 0.08);
|
||||
--glass-bg-medium: rgba(255, 255, 255, 0.18);
|
||||
--glass-bg-solid: rgba(255, 255, 255, 0.25);
|
||||
--glass-border: rgba(255, 255, 255, 0.2);
|
||||
--glass-border-light: rgba(255, 255, 255, 0.4);
|
||||
--glass-shadow: 0 8px 32px rgba(31, 38, 135, 0.15);
|
||||
--glass-inset: inset 0 1px 1px rgba(255, 255, 255, 0.4),
|
||||
inset 0 -1px 1px rgba(0, 0, 0, 0.05);
|
||||
--gallery-gradient: linear-gradient(135deg, #667eea 0%, #764ba2 50%, #f093fb 100%);
|
||||
--gallery-text: #1a1a2e;
|
||||
--gallery-text-light: #ffffff;
|
||||
--gallery-accent: #667eea;
|
||||
--gallery-radius: 20px;
|
||||
--gallery-radius-sm: 12px;
|
||||
}
|
||||
|
||||
/* ===== Page Background ===== */
|
||||
.gallery-page {
|
||||
background: var(--gallery-gradient) !important;
|
||||
background-attachment: fixed !important;
|
||||
min-height: 100vh;
|
||||
}
|
||||
|
||||
.gallery-page::before {
|
||||
content: '';
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
background:
|
||||
radial-gradient(ellipse 600px 400px at 15% 85%, rgba(255, 255, 255, 0.2) 0%, transparent 50%),
|
||||
radial-gradient(ellipse 500px 350px at 85% 15%, rgba(255, 255, 255, 0.15) 0%, transparent 45%);
|
||||
pointer-events: none;
|
||||
z-index: 0;
|
||||
}
|
||||
|
||||
/* ===== TOP BAR / HEADER - Liquid Glass ===== */
|
||||
.gallery-page .gallery-header,
|
||||
.gallery-page header {
|
||||
background: var(--glass-bg-medium) !important;
|
||||
backdrop-filter: blur(var(--glass-blur-heavy)) saturate(var(--glass-saturation)) !important;
|
||||
-webkit-backdrop-filter: blur(var(--glass-blur-heavy)) saturate(var(--glass-saturation)) !important;
|
||||
border-bottom: 1px solid var(--glass-border) !important;
|
||||
box-shadow: var(--glass-shadow), var(--glass-inset) !important;
|
||||
}
|
||||
|
||||
.gallery-page .gallery-header > div {
|
||||
background: transparent !important;
|
||||
border: none !important;
|
||||
}
|
||||
|
||||
/* ===== SIDEBAR - Liquid Glass ===== */
|
||||
.gallery-sidebar {
|
||||
background: var(--glass-bg-medium) !important;
|
||||
backdrop-filter: blur(var(--glass-blur-heavy)) saturate(var(--glass-saturation)) !important;
|
||||
-webkit-backdrop-filter: blur(var(--glass-blur-heavy)) saturate(var(--glass-saturation)) !important;
|
||||
border-right: 1px solid var(--glass-border) !important;
|
||||
box-shadow: 4px 0 32px rgba(31, 38, 135, 0.1), var(--glass-inset) !important;
|
||||
}
|
||||
|
||||
.gallery-sidebar h2,
|
||||
.gallery-sidebar h3 {
|
||||
color: var(--gallery-text) !important;
|
||||
font-weight: 600 !important;
|
||||
}
|
||||
|
||||
/* ===== HERO LAYOUT - Transform to Glass Title Box ===== */
|
||||
/* Target the hero wrapper */
|
||||
.gallery-page .relative.-mt-6 {
|
||||
margin-top: 0 !important;
|
||||
}
|
||||
|
||||
/* Target the hero section (first child with h-[60vh]) */
|
||||
.gallery-page .relative.-mt-6 > .relative:first-child {
|
||||
height: auto !important;
|
||||
min-height: auto !important;
|
||||
margin: 0 !important;
|
||||
padding: 2rem !important;
|
||||
display: flex !important;
|
||||
justify-content: center !important;
|
||||
align-items: center !important;
|
||||
background: transparent !important;
|
||||
}
|
||||
|
||||
/* Hide the hero background image */
|
||||
.gallery-page .relative.-mt-6 > .relative:first-child > img,
|
||||
.gallery-page .relative.-mt-6 > .relative:first-child > canvas {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
/* Hide the dark overlay */
|
||||
.gallery-page .relative.-mt-6 > .relative:first-child > .absolute.inset-0.bg-black {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
/* Style the content area as glass title box */
|
||||
.gallery-page .relative.-mt-6 > .relative:first-child > .absolute.inset-0.flex {
|
||||
position: relative !important;
|
||||
inset: auto !important;
|
||||
background: var(--glass-bg-medium) !important;
|
||||
backdrop-filter: blur(var(--glass-blur)) saturate(var(--glass-saturation)) !important;
|
||||
-webkit-backdrop-filter: blur(var(--glass-blur)) saturate(var(--glass-saturation)) !important;
|
||||
border: 1px solid var(--glass-border-light) !important;
|
||||
border-radius: var(--gallery-radius) !important;
|
||||
padding: 2rem 3rem !important;
|
||||
box-shadow: var(--glass-shadow), var(--glass-inset) !important;
|
||||
max-width: 600px !important;
|
||||
width: auto !important;
|
||||
}
|
||||
|
||||
/* Hide logo in glass title box */
|
||||
.gallery-page .relative.-mt-6 > .relative:first-child .mb-6 {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
/* Style title text */
|
||||
.gallery-page .relative.-mt-6 > .relative:first-child h1 {
|
||||
color: var(--gallery-text) !important;
|
||||
text-shadow: none !important;
|
||||
font-weight: 700 !important;
|
||||
font-size: 2.25rem !important;
|
||||
margin-bottom: 0.75rem !important;
|
||||
}
|
||||
|
||||
/* Style date text */
|
||||
.gallery-page .relative.-mt-6 > .relative:first-child .text-white\\/90 {
|
||||
color: var(--gallery-text) !important;
|
||||
opacity: 0.8;
|
||||
}
|
||||
|
||||
/* Hide scroll down button */
|
||||
.gallery-page .relative.-mt-6 > .relative:first-child > .absolute.bottom-8,
|
||||
.gallery-page .relative.-mt-6 > .relative:first-child > button.absolute {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
/* ===== PHOTO GRID ===== */
|
||||
.gallery-page .photo-grid {
|
||||
display: grid !important;
|
||||
grid-template-columns: repeat(auto-fill, minmax(280px, 1fr)) !important;
|
||||
gap: 1.25rem !important;
|
||||
padding: 1rem !important;
|
||||
}
|
||||
|
||||
/* ===== PHOTO CARDS - Liquid Glass ===== */
|
||||
.gallery-page .photo-card {
|
||||
background: var(--glass-bg) !important;
|
||||
backdrop-filter: blur(var(--glass-blur)) saturate(var(--glass-saturation)) !important;
|
||||
-webkit-backdrop-filter: blur(var(--glass-blur)) saturate(var(--glass-saturation)) !important;
|
||||
border: 1px solid var(--glass-border) !important;
|
||||
border-radius: var(--gallery-radius) !important;
|
||||
overflow: hidden !important;
|
||||
transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1) !important;
|
||||
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1), var(--glass-inset) !important;
|
||||
}
|
||||
|
||||
.gallery-page .photo-card:hover {
|
||||
transform: translateY(-6px) scale(1.02) !important;
|
||||
box-shadow: 0 20px 40px rgba(102, 126, 234, 0.25),
|
||||
0 8px 16px rgba(0, 0, 0, 0.1),
|
||||
var(--glass-inset) !important;
|
||||
border-color: var(--glass-border-light) !important;
|
||||
}
|
||||
|
||||
.gallery-page .photo-card img {
|
||||
transition: transform 0.4s ease !important;
|
||||
}
|
||||
|
||||
.gallery-page .photo-card:hover img {
|
||||
transform: scale(1.05) !important;
|
||||
}
|
||||
|
||||
/* ===== BUTTONS - Glass Pill Style ===== */
|
||||
.gallery-page button,
|
||||
.gallery-page [role="button"],
|
||||
.gallery-sidebar button {
|
||||
background: var(--glass-bg) !important;
|
||||
backdrop-filter: blur(12px) saturate(150%) !important;
|
||||
-webkit-backdrop-filter: blur(12px) saturate(150%) !important;
|
||||
border: 1px solid var(--glass-border) !important;
|
||||
border-radius: 9999px !important;
|
||||
color: var(--gallery-text) !important;
|
||||
font-weight: 500 !important;
|
||||
transition: all 0.3s ease !important;
|
||||
}
|
||||
|
||||
.gallery-page button:hover,
|
||||
.gallery-page [role="button"]:hover,
|
||||
.gallery-sidebar button:hover {
|
||||
background: var(--glass-bg-medium) !important;
|
||||
transform: translateY(-1px);
|
||||
box-shadow: 0 4px 16px rgba(102, 126, 234, 0.2) !important;
|
||||
}
|
||||
|
||||
.gallery-page button[class*="bg-primary"],
|
||||
.gallery-page .gallery-btn-download {
|
||||
background: linear-gradient(135deg, var(--gallery-accent) 0%, #764ba2 100%) !important;
|
||||
color: white !important;
|
||||
border: none !important;
|
||||
}
|
||||
|
||||
/* ===== INPUT FIELDS ===== */
|
||||
.gallery-page input,
|
||||
.gallery-page select,
|
||||
.gallery-sidebar input,
|
||||
.gallery-sidebar select {
|
||||
background: rgba(255, 255, 255, 0.25) !important;
|
||||
backdrop-filter: blur(8px) !important;
|
||||
-webkit-backdrop-filter: blur(8px) !important;
|
||||
border: 1px solid var(--glass-border) !important;
|
||||
border-radius: var(--gallery-radius-sm) !important;
|
||||
color: var(--gallery-text) !important;
|
||||
}
|
||||
|
||||
/* Input placeholder text - make it visible */
|
||||
.gallery-page input::placeholder,
|
||||
.gallery-sidebar input::placeholder {
|
||||
color: rgba(26, 26, 46, 0.6) !important;
|
||||
opacity: 1 !important;
|
||||
}
|
||||
|
||||
/* Input focus state */
|
||||
.gallery-page input:focus,
|
||||
.gallery-sidebar input:focus {
|
||||
background: rgba(255, 255, 255, 0.35) !important;
|
||||
border-color: var(--glass-border-light) !important;
|
||||
outline: none !important;
|
||||
box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.2) !important;
|
||||
}
|
||||
|
||||
/* ===== FOOTER ===== */
|
||||
.gallery-page .gallery-footer,
|
||||
.gallery-page footer {
|
||||
background: var(--glass-bg) !important;
|
||||
backdrop-filter: blur(var(--glass-blur)) saturate(var(--glass-saturation)) !important;
|
||||
-webkit-backdrop-filter: blur(var(--glass-blur)) saturate(var(--glass-saturation)) !important;
|
||||
border-top: 1px solid var(--glass-border) !important;
|
||||
}
|
||||
|
||||
/* ===== LIGHTBOX ===== */
|
||||
.gallery-page [class*="fixed"][class*="inset-0"][class*="z-50"] {
|
||||
background: rgba(0, 0, 0, 0.7) !important;
|
||||
backdrop-filter: blur(30px) !important;
|
||||
-webkit-backdrop-filter: blur(30px) !important;
|
||||
}
|
||||
|
||||
/* ===== SCROLLBAR ===== */
|
||||
.gallery-page ::-webkit-scrollbar,
|
||||
.gallery-sidebar ::-webkit-scrollbar {
|
||||
width: 8px;
|
||||
}
|
||||
|
||||
.gallery-page ::-webkit-scrollbar-track,
|
||||
.gallery-sidebar ::-webkit-scrollbar-track {
|
||||
background: rgba(255, 255, 255, 0.1);
|
||||
}
|
||||
|
||||
.gallery-page ::-webkit-scrollbar-thumb,
|
||||
.gallery-sidebar ::-webkit-scrollbar-thumb {
|
||||
background: rgba(255, 255, 255, 0.3);
|
||||
border-radius: 4px;
|
||||
}
|
||||
|
||||
/* ===== RESPONSIVE ===== */
|
||||
@media (max-width: 768px) {
|
||||
:root {
|
||||
--gallery-radius: 16px;
|
||||
--glass-blur: 16px;
|
||||
}
|
||||
|
||||
.gallery-page .relative.-mt-6 > .relative:first-child > .absolute.inset-0.flex {
|
||||
padding: 1.5rem 2rem !important;
|
||||
max-width: 90% !important;
|
||||
}
|
||||
|
||||
.gallery-page .relative.-mt-6 > .relative:first-child h1 {
|
||||
font-size: 1.5rem !important;
|
||||
}
|
||||
|
||||
.gallery-page .photo-grid {
|
||||
grid-template-columns: repeat(2, 1fr) !important;
|
||||
gap: 0.75rem !important;
|
||||
}
|
||||
}
|
||||
|
||||
/* ===== ACCESSIBILITY ===== */
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.gallery-page .photo-card,
|
||||
.gallery-page button {
|
||||
transition: none !important;
|
||||
}
|
||||
|
||||
.gallery-page .photo-card:hover {
|
||||
transform: none !important;
|
||||
}
|
||||
}
|
||||
|
||||
@media (prefers-reduced-transparency: reduce) {
|
||||
.gallery-page .photo-card,
|
||||
.gallery-page button,
|
||||
.gallery-sidebar {
|
||||
backdrop-filter: none !important;
|
||||
-webkit-backdrop-filter: none !important;
|
||||
background: rgba(255, 255, 255, 0.95) !important;
|
||||
}
|
||||
}`;
|
||||
|
||||
const LIQUID_GLASS_DARK = `/*
|
||||
* PicPeak Custom CSS Template: Liquid Glass Dark
|
||||
* Inspired by Apple's iOS 26 Liquid Glass Design Language
|
||||
*
|
||||
* Features:
|
||||
* - Deep translucent dark surfaces
|
||||
* - Neon accent highlights
|
||||
* - Dramatic glass reflections
|
||||
* - Subtle animated gradients
|
||||
*/
|
||||
|
||||
/* ===== Base Theme Variables ===== */
|
||||
.gallery-page {
|
||||
--glass-bg: rgba(15, 15, 35, 0.7);
|
||||
--glass-bg-elevated: rgba(25, 25, 55, 0.85);
|
||||
--glass-border: rgba(255, 255, 255, 0.1);
|
||||
--glass-border-highlight: rgba(255, 255, 255, 0.2);
|
||||
--glass-shadow: 0 8px 32px rgba(0, 0, 0, 0.4);
|
||||
--glass-blur: 24px;
|
||||
--glass-saturation: 150%;
|
||||
|
||||
--gallery-bg: #0a0a1a;
|
||||
--gallery-text: #f0f0f5;
|
||||
--gallery-text-muted: rgba(240, 240, 245, 0.6);
|
||||
--gallery-accent: #00d4ff;
|
||||
--gallery-accent-secondary: #ff00e5;
|
||||
--gallery-accent-hover: #00ffea;
|
||||
--gallery-radius: 20px;
|
||||
--gallery-spacing: 20px;
|
||||
|
||||
/* Neon glow variables */
|
||||
--neon-glow: 0 0 20px rgba(0, 212, 255, 0.5), 0 0 40px rgba(0, 212, 255, 0.2);
|
||||
--neon-glow-secondary: 0 0 20px rgba(255, 0, 229, 0.5), 0 0 40px rgba(255, 0, 229, 0.2);
|
||||
}
|
||||
|
||||
/* ===== Page Background ===== */
|
||||
.gallery-page {
|
||||
background: var(--gallery-bg);
|
||||
min-height: 100vh;
|
||||
position: relative;
|
||||
overflow-x: hidden;
|
||||
}
|
||||
|
||||
/* Animated mesh gradient background */
|
||||
.gallery-page::before {
|
||||
content: '';
|
||||
position: fixed;
|
||||
top: -50%;
|
||||
left: -50%;
|
||||
right: -50%;
|
||||
bottom: -50%;
|
||||
background:
|
||||
radial-gradient(circle at 30% 20%, rgba(0, 212, 255, 0.15) 0%, transparent 40%),
|
||||
radial-gradient(circle at 70% 80%, rgba(255, 0, 229, 0.1) 0%, transparent 40%),
|
||||
radial-gradient(circle at 50% 50%, rgba(100, 100, 255, 0.05) 0%, transparent 60%);
|
||||
animation: gradientShift 20s ease-in-out infinite;
|
||||
pointer-events: none;
|
||||
z-index: 0;
|
||||
}
|
||||
|
||||
@keyframes gradientShift {
|
||||
0%, 100% { transform: translate(0, 0) rotate(0deg); }
|
||||
25% { transform: translate(2%, 2%) rotate(1deg); }
|
||||
50% { transform: translate(-1%, 3%) rotate(-1deg); }
|
||||
75% { transform: translate(3%, -2%) rotate(2deg); }
|
||||
}
|
||||
|
||||
/* ===== Gallery Header ===== */
|
||||
.gallery-header {
|
||||
background: var(--glass-bg-elevated);
|
||||
backdrop-filter: blur(30px) saturate(var(--glass-saturation));
|
||||
-webkit-backdrop-filter: blur(30px) saturate(var(--glass-saturation));
|
||||
border-bottom: 1px solid var(--glass-border-highlight);
|
||||
padding: calc(var(--gallery-spacing) * 1.5);
|
||||
position: sticky;
|
||||
top: 0;
|
||||
z-index: 100;
|
||||
box-shadow:
|
||||
0 4px 24px rgba(0, 0, 0, 0.3),
|
||||
inset 0 1px 0 rgba(255, 255, 255, 0.1);
|
||||
}
|
||||
|
||||
.gallery-title {
|
||||
color: var(--gallery-text);
|
||||
font-weight: 700;
|
||||
font-size: 1.75rem;
|
||||
letter-spacing: -0.02em;
|
||||
background: linear-gradient(135deg, var(--gallery-text) 0%, var(--gallery-accent) 100%);
|
||||
-webkit-background-clip: text;
|
||||
-webkit-text-fill-color: transparent;
|
||||
background-clip: text;
|
||||
}
|
||||
|
||||
/* ===== Photo Grid ===== */
|
||||
.photo-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
|
||||
gap: var(--gallery-spacing);
|
||||
padding: calc(var(--gallery-spacing) * 2);
|
||||
position: relative;
|
||||
z-index: 1;
|
||||
}
|
||||
|
||||
/* ===== Photo Cards - Dark Glass Style ===== */
|
||||
.photo-card {
|
||||
position: relative;
|
||||
background: var(--glass-bg);
|
||||
backdrop-filter: blur(var(--glass-blur)) saturate(var(--glass-saturation));
|
||||
-webkit-backdrop-filter: blur(var(--glass-blur)) saturate(var(--glass-saturation));
|
||||
border: 1px solid var(--glass-border);
|
||||
border-radius: var(--gallery-radius);
|
||||
overflow: hidden;
|
||||
transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
|
||||
box-shadow:
|
||||
0 4px 24px rgba(0, 0, 0, 0.3),
|
||||
inset 0 1px 0 rgba(255, 255, 255, 0.05);
|
||||
}
|
||||
|
||||
/* Top highlight reflection */
|
||||
.photo-card::before {
|
||||
content: '';
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
height: 1px;
|
||||
background: linear-gradient(
|
||||
90deg,
|
||||
transparent 0%,
|
||||
rgba(255, 255, 255, 0.3) 50%,
|
||||
transparent 100%
|
||||
);
|
||||
z-index: 2;
|
||||
}
|
||||
|
||||
/* Inner glow effect */
|
||||
.photo-card::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
border-radius: var(--gallery-radius);
|
||||
padding: 1px;
|
||||
background: linear-gradient(
|
||||
135deg,
|
||||
rgba(0, 212, 255, 0) 0%,
|
||||
rgba(0, 212, 255, 0) 40%,
|
||||
rgba(0, 212, 255, 0.1) 100%
|
||||
);
|
||||
-webkit-mask: linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0);
|
||||
-webkit-mask-composite: xor;
|
||||
mask-composite: exclude;
|
||||
pointer-events: none;
|
||||
opacity: 0;
|
||||
transition: opacity 0.4s ease;
|
||||
}
|
||||
|
||||
.photo-card:hover {
|
||||
transform: translateY(-8px) scale(1.02);
|
||||
border-color: var(--glass-border-highlight);
|
||||
box-shadow:
|
||||
0 24px 48px rgba(0, 0, 0, 0.4),
|
||||
0 0 0 1px rgba(0, 212, 255, 0.2),
|
||||
var(--neon-glow);
|
||||
}
|
||||
|
||||
.photo-card:hover::after {
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
.photo-card img {
|
||||
width: 100%;
|
||||
height: 240px;
|
||||
object-fit: cover;
|
||||
transition: transform 0.4s ease, filter 0.4s ease;
|
||||
filter: brightness(0.9);
|
||||
}
|
||||
|
||||
.photo-card:hover img {
|
||||
transform: scale(1.05);
|
||||
filter: brightness(1);
|
||||
}
|
||||
|
||||
.photo-card-info {
|
||||
padding: var(--gallery-spacing);
|
||||
background: linear-gradient(
|
||||
180deg,
|
||||
rgba(0, 0, 0, 0.2) 0%,
|
||||
rgba(0, 0, 0, 0.4) 100%
|
||||
);
|
||||
color: var(--gallery-text);
|
||||
}
|
||||
|
||||
.photo-card-info p {
|
||||
color: var(--gallery-text-muted);
|
||||
font-size: 0.875rem;
|
||||
}
|
||||
|
||||
/* ===== Buttons - Neon Glass Style ===== */
|
||||
.gallery-btn {
|
||||
background: var(--glass-bg);
|
||||
backdrop-filter: blur(10px);
|
||||
-webkit-backdrop-filter: blur(10px);
|
||||
border: 1px solid var(--glass-border);
|
||||
border-radius: calc(var(--gallery-radius) / 2);
|
||||
padding: 12px 24px;
|
||||
color: var(--gallery-text);
|
||||
font-weight: 600;
|
||||
cursor: pointer;
|
||||
transition: all 0.3s ease;
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.gallery-btn:hover {
|
||||
border-color: var(--gallery-accent);
|
||||
box-shadow: var(--neon-glow);
|
||||
color: var(--gallery-accent);
|
||||
}
|
||||
|
||||
.gallery-btn-primary {
|
||||
background: linear-gradient(135deg, var(--gallery-accent) 0%, var(--gallery-accent-secondary) 100%);
|
||||
color: white;
|
||||
border: none;
|
||||
box-shadow: var(--neon-glow);
|
||||
}
|
||||
|
||||
.gallery-btn-primary:hover {
|
||||
box-shadow:
|
||||
0 0 30px rgba(0, 212, 255, 0.6),
|
||||
0 0 60px rgba(0, 212, 255, 0.3),
|
||||
0 0 90px rgba(255, 0, 229, 0.2);
|
||||
transform: translateY(-2px);
|
||||
}
|
||||
|
||||
/* ===== Lightbox - Dark Glass ===== */
|
||||
.lightbox-overlay {
|
||||
background: rgba(5, 5, 15, 0.9);
|
||||
backdrop-filter: blur(40px);
|
||||
-webkit-backdrop-filter: blur(40px);
|
||||
}
|
||||
|
||||
.lightbox-content {
|
||||
background: var(--glass-bg-elevated);
|
||||
backdrop-filter: blur(24px);
|
||||
-webkit-backdrop-filter: blur(24px);
|
||||
border: 1px solid var(--glass-border-highlight);
|
||||
border-radius: var(--gallery-radius);
|
||||
box-shadow:
|
||||
0 24px 80px rgba(0, 0, 0, 0.5),
|
||||
var(--neon-glow);
|
||||
}
|
||||
|
||||
/* ===== Category Pills ===== */
|
||||
.category-pill {
|
||||
background: var(--glass-bg);
|
||||
backdrop-filter: blur(10px);
|
||||
-webkit-backdrop-filter: blur(10px);
|
||||
border: 1px solid var(--glass-border);
|
||||
border-radius: 9999px;
|
||||
padding: 8px 20px;
|
||||
font-size: 0.875rem;
|
||||
font-weight: 500;
|
||||
color: var(--gallery-text-muted);
|
||||
transition: all 0.3s ease;
|
||||
}
|
||||
|
||||
.category-pill:hover {
|
||||
border-color: var(--gallery-accent);
|
||||
color: var(--gallery-accent);
|
||||
box-shadow: var(--neon-glow);
|
||||
}
|
||||
|
||||
.category-pill.active {
|
||||
background: linear-gradient(135deg, var(--gallery-accent) 0%, var(--gallery-accent-secondary) 100%);
|
||||
color: white;
|
||||
border-color: transparent;
|
||||
box-shadow: var(--neon-glow);
|
||||
}
|
||||
|
||||
/* ===== Scrollbar Styling ===== */
|
||||
.gallery-page ::-webkit-scrollbar {
|
||||
width: 8px;
|
||||
height: 8px;
|
||||
}
|
||||
|
||||
.gallery-page ::-webkit-scrollbar-track {
|
||||
background: var(--glass-bg);
|
||||
border-radius: 4px;
|
||||
}
|
||||
|
||||
.gallery-page ::-webkit-scrollbar-thumb {
|
||||
background: linear-gradient(180deg, var(--gallery-accent) 0%, var(--gallery-accent-secondary) 100%);
|
||||
border-radius: 4px;
|
||||
}
|
||||
|
||||
/* ===== Responsive ===== */
|
||||
@media (max-width: 768px) {
|
||||
.gallery-page {
|
||||
--gallery-radius: 16px;
|
||||
--gallery-spacing: 12px;
|
||||
--glass-blur: 16px;
|
||||
}
|
||||
|
||||
.photo-grid {
|
||||
grid-template-columns: repeat(auto-fill, minmax(160px, 1fr));
|
||||
}
|
||||
|
||||
.photo-card img {
|
||||
height: 180px;
|
||||
}
|
||||
|
||||
/* Reduce animation complexity on mobile */
|
||||
.gallery-page::before {
|
||||
animation: none;
|
||||
}
|
||||
}
|
||||
|
||||
/* ===== Accessibility: Reduce Motion ===== */
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.gallery-page::before {
|
||||
animation: none;
|
||||
}
|
||||
|
||||
.photo-card,
|
||||
.gallery-btn {
|
||||
transition: none;
|
||||
}
|
||||
|
||||
.photo-card:hover {
|
||||
transform: none;
|
||||
}
|
||||
}
|
||||
|
||||
/* ===== Accessibility: Reduce Transparency ===== */
|
||||
@media (prefers-reduced-transparency: reduce) {
|
||||
.photo-card,
|
||||
.gallery-btn,
|
||||
.gallery-header {
|
||||
backdrop-filter: none;
|
||||
-webkit-backdrop-filter: none;
|
||||
}
|
||||
|
||||
.gallery-page {
|
||||
--glass-bg: rgba(20, 20, 40, 0.98);
|
||||
--glass-bg-elevated: rgba(30, 30, 60, 0.98);
|
||||
}
|
||||
}`;
|
||||
|
||||
exports.up = async function(knex) {
|
||||
// Update template slot 2 with Apple Liquid Glass (Light)
|
||||
await knex('css_templates')
|
||||
.where({ slot_number: 2 })
|
||||
.update({
|
||||
name: 'Apple Liquid Glass',
|
||||
css_content: APPLE_LIQUID_GLASS,
|
||||
is_enabled: true,
|
||||
is_default: false,
|
||||
updated_at: knex.fn.now()
|
||||
});
|
||||
|
||||
// Update template slot 3 with Liquid Glass Dark
|
||||
await knex('css_templates')
|
||||
.where({ slot_number: 3 })
|
||||
.update({
|
||||
name: 'Liquid Glass Dark',
|
||||
css_content: LIQUID_GLASS_DARK,
|
||||
is_enabled: true,
|
||||
is_default: false,
|
||||
updated_at: knex.fn.now()
|
||||
});
|
||||
};
|
||||
|
||||
exports.down = async function(knex) {
|
||||
// Revert to empty templates
|
||||
await knex('css_templates')
|
||||
.where({ slot_number: 2 })
|
||||
.update({
|
||||
name: 'Untitled',
|
||||
css_content: '',
|
||||
is_enabled: false,
|
||||
is_default: false,
|
||||
updated_at: knex.fn.now()
|
||||
});
|
||||
|
||||
await knex('css_templates')
|
||||
.where({ slot_number: 3 })
|
||||
.update({
|
||||
name: 'Untitled',
|
||||
css_content: '',
|
||||
is_enabled: false,
|
||||
is_default: false,
|
||||
updated_at: knex.fn.now()
|
||||
});
|
||||
};
|
||||
|
||||
// Export templates for use elsewhere
|
||||
module.exports.APPLE_LIQUID_GLASS = APPLE_LIQUID_GLASS;
|
||||
module.exports.LIQUID_GLASS_DARK = LIQUID_GLASS_DARK;
|
||||
@@ -0,0 +1,91 @@
|
||||
/**
|
||||
* Migration: Add Roles Table
|
||||
* Creates the roles table for RBAC multi-administrator support.
|
||||
*
|
||||
* Default roles:
|
||||
* - super_admin (priority 100): Full system access including user management
|
||||
* - admin (priority 80): Full event and photo management
|
||||
* - editor (priority 50): Can edit events and photos but not create or delete
|
||||
* - viewer (priority 20): Read-only access to dashboard and events
|
||||
*/
|
||||
|
||||
exports.up = async function(knex) {
|
||||
console.log('Creating roles table...');
|
||||
|
||||
// Check if table already exists
|
||||
const hasRolesTable = await knex.schema.hasTable('roles');
|
||||
|
||||
if (!hasRolesTable) {
|
||||
await knex.schema.createTable('roles', (table) => {
|
||||
table.increments('id').primary();
|
||||
table.string('name', 50).unique().notNullable(); // 'super_admin', 'admin', 'editor', 'viewer'
|
||||
table.string('display_name', 100).notNullable(); // 'Super Admin', 'Admin', etc.
|
||||
table.text('description');
|
||||
table.boolean('is_system').defaultTo(false); // System roles cannot be deleted
|
||||
table.integer('priority').defaultTo(0); // Higher = more privileged (for hierarchy)
|
||||
table.timestamp('created_at').defaultTo(knex.fn.now());
|
||||
table.timestamp('updated_at').defaultTo(knex.fn.now());
|
||||
|
||||
// Index for name lookups
|
||||
table.index(['name']);
|
||||
// Index for priority-based ordering
|
||||
table.index(['priority']);
|
||||
});
|
||||
|
||||
console.log('Roles table created');
|
||||
}
|
||||
|
||||
// Insert default system roles
|
||||
const existingRoles = await knex('roles').select('name');
|
||||
const existingRoleNames = existingRoles.map(r => r.name);
|
||||
|
||||
const defaultRoles = [
|
||||
{
|
||||
name: 'super_admin',
|
||||
display_name: 'Super Admin',
|
||||
description: 'Full system access including user management',
|
||||
is_system: true,
|
||||
priority: 100
|
||||
},
|
||||
{
|
||||
name: 'admin',
|
||||
display_name: 'Admin',
|
||||
description: 'Full event and photo management',
|
||||
is_system: true,
|
||||
priority: 80
|
||||
},
|
||||
{
|
||||
name: 'editor',
|
||||
display_name: 'Editor',
|
||||
description: 'Can edit events and photos but not create or delete',
|
||||
is_system: true,
|
||||
priority: 50
|
||||
},
|
||||
{
|
||||
name: 'viewer',
|
||||
display_name: 'Viewer',
|
||||
description: 'Read-only access to dashboard and events',
|
||||
is_system: true,
|
||||
priority: 20
|
||||
}
|
||||
];
|
||||
|
||||
const rolesToInsert = defaultRoles.filter(role => !existingRoleNames.includes(role.name));
|
||||
|
||||
if (rolesToInsert.length > 0) {
|
||||
await knex('roles').insert(rolesToInsert);
|
||||
console.log(`Inserted ${rolesToInsert.length} default roles`);
|
||||
}
|
||||
|
||||
console.log('Roles table migration completed successfully');
|
||||
};
|
||||
|
||||
exports.down = async function(knex) {
|
||||
console.log('Removing roles table...');
|
||||
|
||||
// Note: This will fail if there are foreign key references
|
||||
// The role_permissions and admin_users tables must be rolled back first
|
||||
await knex.schema.dropTableIfExists('roles');
|
||||
|
||||
console.log('Roles table removed');
|
||||
};
|
||||
@@ -0,0 +1,122 @@
|
||||
/**
|
||||
* Migration: Add Permissions Table
|
||||
* Creates the permissions table for granular access control.
|
||||
*
|
||||
* Permission categories:
|
||||
* - events: View, create, edit, delete, archive events
|
||||
* - photos: View, upload, edit, delete, download photos
|
||||
* - archives: View, restore, download, delete archives
|
||||
* - analytics: View analytics and statistics
|
||||
* - email: View, edit, send emails
|
||||
* - branding: View and edit branding settings
|
||||
* - cms: View and edit CMS pages
|
||||
* - settings: View and edit application settings
|
||||
* - backup: View, create, restore, delete backups
|
||||
* - users: View, create, edit, delete admin users (Super Admin only)
|
||||
* - activity: View and export activity logs
|
||||
*/
|
||||
|
||||
exports.up = async function(knex) {
|
||||
console.log('Creating permissions table...');
|
||||
|
||||
// Check if table already exists
|
||||
const hasPermissionsTable = await knex.schema.hasTable('permissions');
|
||||
|
||||
if (!hasPermissionsTable) {
|
||||
await knex.schema.createTable('permissions', (table) => {
|
||||
table.increments('id').primary();
|
||||
table.string('name', 100).unique().notNullable(); // 'events.create', 'users.manage', etc.
|
||||
table.string('display_name', 150).notNullable();
|
||||
table.string('category', 50).notNullable(); // 'events', 'photos', 'users', 'settings'
|
||||
table.text('description');
|
||||
table.timestamp('created_at').defaultTo(knex.fn.now());
|
||||
|
||||
// Indexes for efficient lookups
|
||||
table.index(['name']);
|
||||
table.index(['category']);
|
||||
});
|
||||
|
||||
console.log('Permissions table created');
|
||||
}
|
||||
|
||||
// Check for existing permissions
|
||||
const existingPermissions = await knex('permissions').select('name');
|
||||
const existingPermissionNames = existingPermissions.map(p => p.name);
|
||||
|
||||
// Define all permissions
|
||||
const permissions = [
|
||||
// Events
|
||||
{ name: 'events.view', display_name: 'View Events', category: 'events', description: 'View event list and details' },
|
||||
{ name: 'events.create', display_name: 'Create Events', category: 'events', description: 'Create new events' },
|
||||
{ name: 'events.edit', display_name: 'Edit Events', category: 'events', description: 'Edit existing events' },
|
||||
{ name: 'events.delete', display_name: 'Delete Events', category: 'events', description: 'Delete events' },
|
||||
{ name: 'events.archive', display_name: 'Archive Events', category: 'events', description: 'Archive and restore events' },
|
||||
|
||||
// Photos
|
||||
{ name: 'photos.view', display_name: 'View Photos', category: 'photos', description: 'View photos in events' },
|
||||
{ name: 'photos.upload', display_name: 'Upload Photos', category: 'photos', description: 'Upload photos to events' },
|
||||
{ name: 'photos.edit', display_name: 'Edit Photos', category: 'photos', description: 'Edit photo metadata and categories' },
|
||||
{ name: 'photos.delete', display_name: 'Delete Photos', category: 'photos', description: 'Delete photos from events' },
|
||||
{ name: 'photos.download', display_name: 'Download Photos', category: 'photos', description: 'Download photos and bulk export' },
|
||||
|
||||
// Archives
|
||||
{ name: 'archives.view', display_name: 'View Archives', category: 'archives', description: 'View archived events' },
|
||||
{ name: 'archives.restore', display_name: 'Restore Archives', category: 'archives', description: 'Restore archived events' },
|
||||
{ name: 'archives.download', display_name: 'Download Archives', category: 'archives', description: 'Download archive files' },
|
||||
{ name: 'archives.delete', display_name: 'Delete Archives', category: 'archives', description: 'Permanently delete archives' },
|
||||
|
||||
// Analytics
|
||||
{ name: 'analytics.view', display_name: 'View Analytics', category: 'analytics', description: 'View analytics and statistics' },
|
||||
|
||||
// Email
|
||||
{ name: 'email.view', display_name: 'View Email Settings', category: 'email', description: 'View email configuration' },
|
||||
{ name: 'email.edit', display_name: 'Edit Email Settings', category: 'email', description: 'Configure email settings and templates' },
|
||||
{ name: 'email.send', display_name: 'Send Emails', category: 'email', description: 'Send and resend gallery emails' },
|
||||
|
||||
// Branding & CMS
|
||||
{ name: 'branding.view', display_name: 'View Branding', category: 'branding', description: 'View branding settings' },
|
||||
{ name: 'branding.edit', display_name: 'Edit Branding', category: 'branding', description: 'Edit branding and theme settings' },
|
||||
{ name: 'cms.view', display_name: 'View CMS Pages', category: 'cms', description: 'View CMS content pages' },
|
||||
{ name: 'cms.edit', display_name: 'Edit CMS Pages', category: 'cms', description: 'Edit CMS content pages' },
|
||||
|
||||
// Settings
|
||||
{ name: 'settings.view', display_name: 'View Settings', category: 'settings', description: 'View application settings' },
|
||||
{ name: 'settings.edit', display_name: 'Edit Settings', category: 'settings', description: 'Modify application settings' },
|
||||
|
||||
// Backup
|
||||
{ name: 'backup.view', display_name: 'View Backups', category: 'backup', description: 'View backup status and history' },
|
||||
{ name: 'backup.create', display_name: 'Create Backups', category: 'backup', description: 'Create new backups' },
|
||||
{ name: 'backup.restore', display_name: 'Restore Backups', category: 'backup', description: 'Restore from backups' },
|
||||
{ name: 'backup.delete', display_name: 'Delete Backups', category: 'backup', description: 'Delete backup files' },
|
||||
|
||||
// User Management (Super Admin only)
|
||||
{ name: 'users.view', display_name: 'View Users', category: 'users', description: 'View admin user list' },
|
||||
{ name: 'users.create', display_name: 'Create Users', category: 'users', description: 'Invite new admin users' },
|
||||
{ name: 'users.edit', display_name: 'Edit Users', category: 'users', description: 'Edit admin user details and roles' },
|
||||
{ name: 'users.delete', display_name: 'Delete Users', category: 'users', description: 'Deactivate or delete admin users' },
|
||||
|
||||
// Activity Logs
|
||||
{ name: 'activity.view', display_name: 'View Activity Logs', category: 'activity', description: 'View system activity logs' },
|
||||
{ name: 'activity.export', display_name: 'Export Activity Logs', category: 'activity', description: 'Export activity logs' }
|
||||
];
|
||||
|
||||
// Filter out already existing permissions
|
||||
const permissionsToInsert = permissions.filter(p => !existingPermissionNames.includes(p.name));
|
||||
|
||||
if (permissionsToInsert.length > 0) {
|
||||
await knex('permissions').insert(permissionsToInsert);
|
||||
console.log(`Inserted ${permissionsToInsert.length} permissions`);
|
||||
}
|
||||
|
||||
console.log('Permissions table migration completed successfully');
|
||||
};
|
||||
|
||||
exports.down = async function(knex) {
|
||||
console.log('Removing permissions table...');
|
||||
|
||||
// Note: This will fail if there are foreign key references
|
||||
// The role_permissions table must be rolled back first
|
||||
await knex.schema.dropTableIfExists('permissions');
|
||||
|
||||
console.log('Permissions table removed');
|
||||
};
|
||||
@@ -0,0 +1,134 @@
|
||||
/**
|
||||
* Migration: Add Role Permissions Junction Table
|
||||
* Creates the junction table mapping permissions to roles.
|
||||
*
|
||||
* Role permission mappings:
|
||||
* - super_admin: All permissions
|
||||
* - admin: Events, Photos, Archives, Analytics, Email, Branding, CMS, Settings (view), Backup (view/create), Activity (view)
|
||||
* - editor: View/Create/Edit own events and photos, Analytics (view), Activity (view)
|
||||
* - viewer: View-only access to events, photos, archives, analytics, branding, cms
|
||||
*/
|
||||
|
||||
exports.up = async function(knex) {
|
||||
console.log('Creating role_permissions junction table...');
|
||||
|
||||
// Check if table already exists
|
||||
const hasRolePermissionsTable = await knex.schema.hasTable('role_permissions');
|
||||
|
||||
if (!hasRolePermissionsTable) {
|
||||
await knex.schema.createTable('role_permissions', (table) => {
|
||||
table.integer('role_id').unsigned().references('id').inTable('roles').onDelete('CASCADE');
|
||||
table.integer('permission_id').unsigned().references('id').inTable('permissions').onDelete('CASCADE');
|
||||
table.primary(['role_id', 'permission_id']);
|
||||
|
||||
// Indexes for efficient lookups
|
||||
table.index(['role_id']);
|
||||
table.index(['permission_id']);
|
||||
});
|
||||
|
||||
console.log('Role permissions junction table created');
|
||||
}
|
||||
|
||||
// Get role and permission IDs
|
||||
const roles = await knex('roles').select('id', 'name');
|
||||
const permissions = await knex('permissions').select('id', 'name');
|
||||
|
||||
if (roles.length === 0 || permissions.length === 0) {
|
||||
console.log('No roles or permissions found, skipping permission mappings');
|
||||
return;
|
||||
}
|
||||
|
||||
const roleMap = Object.fromEntries(roles.map(r => [r.name, r.id]));
|
||||
const permMap = Object.fromEntries(permissions.map(p => [p.name, p.id]));
|
||||
|
||||
// Define role-permission mappings
|
||||
const rolePermissions = {
|
||||
super_admin: permissions.map(p => p.name), // All permissions
|
||||
admin: [
|
||||
// Events - full access
|
||||
'events.view', 'events.create', 'events.edit', 'events.delete', 'events.archive',
|
||||
// Photos - full access
|
||||
'photos.view', 'photos.upload', 'photos.edit', 'photos.delete', 'photos.download',
|
||||
// Archives - full access
|
||||
'archives.view', 'archives.restore', 'archives.download', 'archives.delete',
|
||||
// Analytics - view only
|
||||
'analytics.view',
|
||||
// Email - full access
|
||||
'email.view', 'email.edit', 'email.send',
|
||||
// Branding - full access
|
||||
'branding.view', 'branding.edit',
|
||||
// CMS - full access
|
||||
'cms.view', 'cms.edit',
|
||||
// Settings - view only
|
||||
'settings.view',
|
||||
// Backup - view and create only
|
||||
'backup.view', 'backup.create',
|
||||
// Activity - view only
|
||||
'activity.view'
|
||||
],
|
||||
editor: [
|
||||
// Events - view, create, and edit (can only see their own events)
|
||||
'events.view', 'events.create', 'events.edit',
|
||||
// Photos - view, upload, edit (no delete)
|
||||
'photos.view', 'photos.upload', 'photos.edit',
|
||||
// Analytics - view only
|
||||
'analytics.view',
|
||||
// Activity - view only
|
||||
'activity.view'
|
||||
],
|
||||
viewer: [
|
||||
// Events - view only
|
||||
'events.view',
|
||||
// Photos - view only
|
||||
'photos.view',
|
||||
// Archives - view only
|
||||
'archives.view',
|
||||
// Analytics - view only
|
||||
'analytics.view',
|
||||
// Branding - view only
|
||||
'branding.view',
|
||||
// CMS - view only
|
||||
'cms.view'
|
||||
]
|
||||
};
|
||||
|
||||
// Check for existing mappings to avoid duplicates
|
||||
const existingMappings = await knex('role_permissions').select('role_id', 'permission_id');
|
||||
const existingSet = new Set(existingMappings.map(m => `${m.role_id}-${m.permission_id}`));
|
||||
|
||||
// Build insert list
|
||||
const inserts = [];
|
||||
for (const [roleName, perms] of Object.entries(rolePermissions)) {
|
||||
for (const permName of perms) {
|
||||
if (roleMap[roleName] && permMap[permName]) {
|
||||
const key = `${roleMap[roleName]}-${permMap[permName]}`;
|
||||
if (!existingSet.has(key)) {
|
||||
inserts.push({
|
||||
role_id: roleMap[roleName],
|
||||
permission_id: permMap[permName]
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (inserts.length > 0) {
|
||||
// Insert in batches to avoid hitting database limits
|
||||
const batchSize = 50;
|
||||
for (let i = 0; i < inserts.length; i += batchSize) {
|
||||
const batch = inserts.slice(i, i + batchSize);
|
||||
await knex('role_permissions').insert(batch);
|
||||
}
|
||||
console.log(`Inserted ${inserts.length} role-permission mappings`);
|
||||
}
|
||||
|
||||
console.log('Role permissions junction table migration completed successfully');
|
||||
};
|
||||
|
||||
exports.down = async function(knex) {
|
||||
console.log('Removing role_permissions junction table...');
|
||||
|
||||
await knex.schema.dropTableIfExists('role_permissions');
|
||||
|
||||
console.log('Role permissions junction table removed');
|
||||
};
|
||||
@@ -0,0 +1,115 @@
|
||||
/**
|
||||
* Migration: Add Role to Admin Users
|
||||
* Adds RBAC-related columns to the admin_users table:
|
||||
* - role_id: Foreign key to roles table
|
||||
* - created_by: Foreign key to admin_users (who invited this user)
|
||||
* - invite_token: Token for invitation acceptance (64 chars = 256 bits)
|
||||
* - invite_expires_at: When the invitation token expires
|
||||
* - invite_accepted_at: When the user accepted the invitation
|
||||
*
|
||||
* Also migrates existing admin users to super_admin role.
|
||||
*/
|
||||
|
||||
exports.up = async function(knex) {
|
||||
console.log('Adding role columns to admin_users table...');
|
||||
|
||||
// Check if columns already exist
|
||||
const hasRoleId = await knex.schema.hasColumn('admin_users', 'role_id');
|
||||
const hasCreatedBy = await knex.schema.hasColumn('admin_users', 'created_by');
|
||||
const hasInviteToken = await knex.schema.hasColumn('admin_users', 'invite_token');
|
||||
const hasInviteExpiresAt = await knex.schema.hasColumn('admin_users', 'invite_expires_at');
|
||||
const hasInviteAcceptedAt = await knex.schema.hasColumn('admin_users', 'invite_accepted_at');
|
||||
|
||||
// Add new columns if they don't exist
|
||||
if (!hasRoleId || !hasCreatedBy || !hasInviteToken || !hasInviteExpiresAt || !hasInviteAcceptedAt) {
|
||||
await knex.schema.alterTable('admin_users', (table) => {
|
||||
if (!hasRoleId) {
|
||||
// Note: We add as nullable first, then set values, then alter to not null
|
||||
table.integer('role_id').unsigned().references('id').inTable('roles').onDelete('SET NULL');
|
||||
}
|
||||
if (!hasCreatedBy) {
|
||||
table.integer('created_by').unsigned().references('id').inTable('admin_users').onDelete('SET NULL');
|
||||
}
|
||||
if (!hasInviteToken) {
|
||||
// 64 characters = 32 bytes hex = 256 bits of entropy (cryptographically secure)
|
||||
table.string('invite_token', 64);
|
||||
}
|
||||
if (!hasInviteExpiresAt) {
|
||||
table.timestamp('invite_expires_at');
|
||||
}
|
||||
if (!hasInviteAcceptedAt) {
|
||||
table.timestamp('invite_accepted_at');
|
||||
}
|
||||
});
|
||||
|
||||
console.log('Role columns added to admin_users table');
|
||||
}
|
||||
|
||||
// Add index on invite_token for fast lookup
|
||||
const hasInviteTokenIndex = await knex.schema.hasColumn('admin_users', 'invite_token');
|
||||
if (hasInviteTokenIndex) {
|
||||
// Create index if it doesn't exist (safe for both PostgreSQL and SQLite)
|
||||
try {
|
||||
await knex.schema.alterTable('admin_users', (table) => {
|
||||
table.index(['invite_token']);
|
||||
});
|
||||
} catch (e) {
|
||||
// Index may already exist
|
||||
if (!e.message.includes('already exists')) {
|
||||
console.log('Note: invite_token index may already exist');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Get super_admin role ID
|
||||
const superAdminRole = await knex('roles').where('name', 'super_admin').first();
|
||||
|
||||
if (superAdminRole) {
|
||||
// Migrate existing admin users without a role to super_admin
|
||||
const usersWithoutRole = await knex('admin_users')
|
||||
.whereNull('role_id')
|
||||
.select('id');
|
||||
|
||||
if (usersWithoutRole.length > 0) {
|
||||
await knex('admin_users')
|
||||
.whereNull('role_id')
|
||||
.update({ role_id: superAdminRole.id });
|
||||
|
||||
console.log(`Migrated ${usersWithoutRole.length} existing admin user(s) to super_admin role`);
|
||||
}
|
||||
} else {
|
||||
console.log('Warning: super_admin role not found. Run migration 054 first.');
|
||||
}
|
||||
|
||||
console.log('Admin users role migration completed successfully');
|
||||
};
|
||||
|
||||
exports.down = async function(knex) {
|
||||
console.log('Removing role columns from admin_users table...');
|
||||
|
||||
const hasRoleId = await knex.schema.hasColumn('admin_users', 'role_id');
|
||||
const hasCreatedBy = await knex.schema.hasColumn('admin_users', 'created_by');
|
||||
const hasInviteToken = await knex.schema.hasColumn('admin_users', 'invite_token');
|
||||
const hasInviteExpiresAt = await knex.schema.hasColumn('admin_users', 'invite_expires_at');
|
||||
const hasInviteAcceptedAt = await knex.schema.hasColumn('admin_users', 'invite_accepted_at');
|
||||
|
||||
await knex.schema.alterTable('admin_users', (table) => {
|
||||
if (hasInviteAcceptedAt) {
|
||||
table.dropColumn('invite_accepted_at');
|
||||
}
|
||||
if (hasInviteExpiresAt) {
|
||||
table.dropColumn('invite_expires_at');
|
||||
}
|
||||
if (hasInviteToken) {
|
||||
table.dropColumn('invite_token');
|
||||
}
|
||||
if (hasCreatedBy) {
|
||||
table.dropColumn('created_by');
|
||||
}
|
||||
if (hasRoleId) {
|
||||
table.dropColumn('role_id');
|
||||
}
|
||||
});
|
||||
|
||||
console.log('Role columns removed from admin_users table');
|
||||
};
|
||||
@@ -0,0 +1,68 @@
|
||||
/**
|
||||
* Migration: Add Admin Invitations Table
|
||||
* Creates the admin_invitations table for managing pending admin user invitations.
|
||||
*
|
||||
* Security features:
|
||||
* - Token is 64 characters (32 bytes hex = 256 bits of entropy)
|
||||
* - Tokens are unique and indexed for fast lookup
|
||||
* - Invitations have expiration timestamps
|
||||
* - Tracks who invited whom and when accepted
|
||||
* - Foreign key constraints with appropriate CASCADE behavior
|
||||
*/
|
||||
|
||||
exports.up = async function(knex) {
|
||||
console.log('Creating admin_invitations table...');
|
||||
|
||||
// Check if table already exists
|
||||
const hasAdminInvitationsTable = await knex.schema.hasTable('admin_invitations');
|
||||
|
||||
if (!hasAdminInvitationsTable) {
|
||||
await knex.schema.createTable('admin_invitations', (table) => {
|
||||
table.increments('id').primary();
|
||||
|
||||
// Email of the invited user
|
||||
table.string('email', 255).notNullable();
|
||||
|
||||
// Invitation token - 64 characters = 32 bytes hex = 256 bits of entropy
|
||||
// Cryptographically secure for one-time use tokens
|
||||
table.string('token', 64).unique().notNullable();
|
||||
|
||||
// Role to assign when invitation is accepted
|
||||
table.integer('role_id').unsigned().references('id').inTable('roles').onDelete('CASCADE').notNullable();
|
||||
|
||||
// Who created this invitation
|
||||
table.integer('invited_by').unsigned().references('id').inTable('admin_users').onDelete('CASCADE').notNullable();
|
||||
|
||||
// When the invitation expires (typically 7 days from creation)
|
||||
table.timestamp('expires_at').notNullable();
|
||||
|
||||
// When the invitation was accepted (null if pending)
|
||||
table.timestamp('accepted_at');
|
||||
|
||||
// The admin_user ID created when invitation was accepted (for audit trail)
|
||||
table.integer('accepted_user_id').unsigned().references('id').inTable('admin_users').onDelete('SET NULL');
|
||||
|
||||
// When the invitation was created
|
||||
table.timestamp('created_at').defaultTo(knex.fn.now());
|
||||
|
||||
// Indexes for efficient lookups
|
||||
table.index(['token']); // Fast token validation
|
||||
table.index(['email']); // Check for existing invitations by email
|
||||
table.index(['expires_at']); // Cleanup expired invitations
|
||||
table.index(['invited_by']); // List invitations by inviter
|
||||
table.index(['accepted_at']); // Filter pending vs accepted
|
||||
});
|
||||
|
||||
console.log('Admin invitations table created');
|
||||
}
|
||||
|
||||
console.log('Admin invitations table migration completed successfully');
|
||||
};
|
||||
|
||||
exports.down = async function(knex) {
|
||||
console.log('Removing admin_invitations table...');
|
||||
|
||||
await knex.schema.dropTableIfExists('admin_invitations');
|
||||
|
||||
console.log('Admin invitations table removed');
|
||||
};
|
||||
@@ -0,0 +1,314 @@
|
||||
/**
|
||||
* Migration to add email templates for admin invitation and password reset
|
||||
* These templates support the RBAC (Role-Based Access Control) feature
|
||||
*/
|
||||
exports.up = async function(knex) {
|
||||
// First, ensure the email_templates table has multilingual columns
|
||||
// This is needed for fresh installations where legacy migrations don't run
|
||||
const columnInfo = await knex('email_templates').columnInfo();
|
||||
|
||||
if (!columnInfo.subject_en) {
|
||||
// Need to add multilingual columns
|
||||
console.log('Adding multilingual columns to email_templates table...');
|
||||
|
||||
// Check if we're using SQLite or PostgreSQL
|
||||
const client = knex.client.config.client;
|
||||
const isSqlite = client === 'sqlite3' || client === 'better-sqlite3';
|
||||
|
||||
if (isSqlite) {
|
||||
// SQLite doesn't support column rename directly in all versions
|
||||
// We need to recreate the table with new structure
|
||||
|
||||
// Get existing data
|
||||
const existingData = await knex('email_templates').select('*');
|
||||
|
||||
// Drop the old table
|
||||
await knex.schema.dropTable('email_templates');
|
||||
|
||||
// Create new table with multilingual columns
|
||||
await knex.schema.createTable('email_templates', (table) => {
|
||||
table.increments('id').primary();
|
||||
table.string('template_key').unique().notNullable();
|
||||
table.string('subject_en');
|
||||
table.string('subject_de');
|
||||
table.text('body_html_en');
|
||||
table.text('body_html_de');
|
||||
table.text('body_text_en');
|
||||
table.text('body_text_de');
|
||||
table.json('variables');
|
||||
table.datetime('updated_at').defaultTo(knex.fn.now());
|
||||
});
|
||||
|
||||
// Re-insert existing data with column mapping
|
||||
for (const row of existingData) {
|
||||
await knex('email_templates').insert({
|
||||
template_key: row.template_key,
|
||||
subject_en: row.subject,
|
||||
subject_de: row.subject, // Copy to German as default
|
||||
body_html_en: row.body_html,
|
||||
body_html_de: row.body_html,
|
||||
body_text_en: row.body_text,
|
||||
body_text_de: row.body_text,
|
||||
variables: row.variables,
|
||||
updated_at: row.updated_at
|
||||
});
|
||||
}
|
||||
|
||||
console.log('Migrated email_templates table to multilingual structure');
|
||||
} else {
|
||||
// PostgreSQL supports ALTER TABLE for column operations
|
||||
await knex.schema.alterTable('email_templates', (table) => {
|
||||
table.renameColumn('subject', 'subject_en');
|
||||
table.renameColumn('body_html', 'body_html_en');
|
||||
table.renameColumn('body_text', 'body_text_en');
|
||||
});
|
||||
|
||||
await knex.schema.alterTable('email_templates', (table) => {
|
||||
table.string('subject_de');
|
||||
table.text('body_html_de');
|
||||
table.text('body_text_de');
|
||||
});
|
||||
|
||||
// Copy English values to German as defaults
|
||||
await knex('email_templates').update({
|
||||
subject_de: knex.raw('subject_en'),
|
||||
body_html_de: knex.raw('body_html_en'),
|
||||
body_text_de: knex.raw('body_text_en')
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Check which templates already exist
|
||||
const existingTemplates = await knex('email_templates')
|
||||
.select('template_key')
|
||||
.whereIn('template_key', ['admin_invitation', 'admin_password_reset']);
|
||||
|
||||
const existingKeys = existingTemplates.map(t => t.template_key);
|
||||
|
||||
// Admin Invitation Email Template
|
||||
if (!existingKeys.includes('admin_invitation')) {
|
||||
await knex('email_templates').insert({
|
||||
template_key: 'admin_invitation',
|
||||
subject_en: 'You have been invited to join PicPeak as {{role_name}}',
|
||||
subject_de: 'Sie wurden eingeladen, PicPeak als {{role_name}} beizutreten',
|
||||
body_html_en: `
|
||||
<h2>Welcome to PicPeak!</h2>
|
||||
|
||||
<p>You have been invited to join the PicPeak photo sharing platform as a <strong>{{role_name}}</strong>.</p>
|
||||
|
||||
<div style="background-color: #f0f8ff; border-left: 4px solid #5C8762; padding: 20px; margin: 20px 0; border-radius: 4px;">
|
||||
<p style="margin: 0;"><strong>Your Role:</strong> {{role_name}}</p>
|
||||
<p style="margin: 10px 0 0 0;">This role grants you access to manage and administer the photo sharing platform.</p>
|
||||
</div>
|
||||
|
||||
<p>To accept this invitation and set up your account, click the button below:</p>
|
||||
|
||||
<div style="text-align: center; margin: 30px 0;">
|
||||
<a href="{{invite_link}}" style="display: inline-block; padding: 14px 35px; background-color: #5C8762; color: white; text-decoration: none; border-radius: 5px; font-weight: 600; font-size: 16px;">Accept Invitation</a>
|
||||
</div>
|
||||
|
||||
<div style="background-color: #fff3cd; border: 1px solid #ffeaa7; color: #856404; padding: 15px; border-radius: 4px; margin: 20px 0;">
|
||||
<p style="margin: 0;"><strong>Important:</strong> This invitation expires on <strong>{{expires_at}}</strong>. Please accept the invitation before this date.</p>
|
||||
</div>
|
||||
|
||||
<p>If you did not expect this invitation or believe it was sent in error, you can safely ignore this email.</p>
|
||||
|
||||
<p style="color: #666; font-size: 13px; margin-top: 30px;">
|
||||
If the button above does not work, copy and paste this link into your browser:<br>
|
||||
<a href="{{invite_link}}" style="color: #5C8762; word-break: break-all;">{{invite_link}}</a>
|
||||
</p>
|
||||
|
||||
<p>Best regards,<br>
|
||||
The PicPeak Team</p>`,
|
||||
body_text_en: `Welcome to PicPeak!
|
||||
|
||||
You have been invited to join the PicPeak photo sharing platform as a {{role_name}}.
|
||||
|
||||
Your Role: {{role_name}}
|
||||
This role grants you access to manage and administer the photo sharing platform.
|
||||
|
||||
To accept this invitation and set up your account, visit the following link:
|
||||
{{invite_link}}
|
||||
|
||||
IMPORTANT: This invitation expires on {{expires_at}}. Please accept the invitation before this date.
|
||||
|
||||
If you did not expect this invitation or believe it was sent in error, you can safely ignore this email.
|
||||
|
||||
Best regards,
|
||||
The PicPeak Team`,
|
||||
body_html_de: `
|
||||
<h2>Willkommen bei PicPeak!</h2>
|
||||
|
||||
<p>Sie wurden eingeladen, der PicPeak Foto-Sharing-Plattform als <strong>{{role_name}}</strong> beizutreten.</p>
|
||||
|
||||
<div style="background-color: #f0f8ff; border-left: 4px solid #5C8762; padding: 20px; margin: 20px 0; border-radius: 4px;">
|
||||
<p style="margin: 0;"><strong>Ihre Rolle:</strong> {{role_name}}</p>
|
||||
<p style="margin: 10px 0 0 0;">Diese Rolle gewahrt Ihnen Zugang zur Verwaltung und Administration der Foto-Sharing-Plattform.</p>
|
||||
</div>
|
||||
|
||||
<p>Um diese Einladung anzunehmen und Ihr Konto einzurichten, klicken Sie auf die Schaltflache unten:</p>
|
||||
|
||||
<div style="text-align: center; margin: 30px 0;">
|
||||
<a href="{{invite_link}}" style="display: inline-block; padding: 14px 35px; background-color: #5C8762; color: white; text-decoration: none; border-radius: 5px; font-weight: 600; font-size: 16px;">Einladung annehmen</a>
|
||||
</div>
|
||||
|
||||
<div style="background-color: #fff3cd; border: 1px solid #ffeaa7; color: #856404; padding: 15px; border-radius: 4px; margin: 20px 0;">
|
||||
<p style="margin: 0;"><strong>Wichtig:</strong> Diese Einladung lauft am <strong>{{expires_at}}</strong> ab. Bitte nehmen Sie die Einladung vor diesem Datum an.</p>
|
||||
</div>
|
||||
|
||||
<p>Wenn Sie diese Einladung nicht erwartet haben oder glauben, dass sie irrtumlicherweise gesendet wurde, konnen Sie diese E-Mail ignorieren.</p>
|
||||
|
||||
<p style="color: #666; font-size: 13px; margin-top: 30px;">
|
||||
Wenn die Schaltflache oben nicht funktioniert, kopieren Sie diesen Link in Ihren Browser:<br>
|
||||
<a href="{{invite_link}}" style="color: #5C8762; word-break: break-all;">{{invite_link}}</a>
|
||||
</p>
|
||||
|
||||
<p>Mit freundlichen Grussen,<br>
|
||||
Ihr PicPeak-Team</p>`,
|
||||
body_text_de: `Willkommen bei PicPeak!
|
||||
|
||||
Sie wurden eingeladen, der PicPeak Foto-Sharing-Plattform als {{role_name}} beizutreten.
|
||||
|
||||
Ihre Rolle: {{role_name}}
|
||||
Diese Rolle gewahrt Ihnen Zugang zur Verwaltung und Administration der Foto-Sharing-Plattform.
|
||||
|
||||
Um diese Einladung anzunehmen und Ihr Konto einzurichten, besuchen Sie den folgenden Link:
|
||||
{{invite_link}}
|
||||
|
||||
WICHTIG: Diese Einladung lauft am {{expires_at}} ab. Bitte nehmen Sie die Einladung vor diesem Datum an.
|
||||
|
||||
Wenn Sie diese Einladung nicht erwartet haben oder glauben, dass sie irrtumlicherweise gesendet wurde, konnen Sie diese E-Mail ignorieren.
|
||||
|
||||
Mit freundlichen Grussen,
|
||||
Ihr PicPeak-Team`,
|
||||
variables: JSON.stringify(['invite_link', 'role_name', 'expires_at'])
|
||||
});
|
||||
}
|
||||
|
||||
// Admin Password Reset Email Template
|
||||
if (!existingKeys.includes('admin_password_reset')) {
|
||||
await knex('email_templates').insert({
|
||||
template_key: 'admin_password_reset',
|
||||
subject_en: 'Your PicPeak administrator password has been reset',
|
||||
subject_de: 'Ihr PicPeak-Administratorpasswort wurde zuruckgesetzt',
|
||||
body_html_en: `
|
||||
<h2>Password Reset Notification</h2>
|
||||
|
||||
<p>Hello <strong>{{username}}</strong>,</p>
|
||||
|
||||
<p>Your administrator password for PicPeak has been reset by a system administrator.</p>
|
||||
|
||||
<div style="background-color: #f9f9f9; padding: 20px; border-radius: 8px; margin: 20px 0;">
|
||||
<h3 style="margin-top: 0;">Your New Login Credentials:</h3>
|
||||
<ul style="list-style: none; padding: 0;">
|
||||
<li style="margin-bottom: 10px;"><strong>Username:</strong> {{username}}</li>
|
||||
<li style="margin-bottom: 10px;"><strong>Temporary Password:</strong> <code style="background-color: #e9ecef; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 14px;">{{new_password}}</code></li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<div style="background-color: #fee; border: 1px solid #fcc; color: #c33; padding: 20px; border-radius: 8px; margin: 20px 0;">
|
||||
<p style="margin: 0; font-weight: bold; font-size: 16px;">Security Notice</p>
|
||||
<ul style="margin: 10px 0 0 0; padding-left: 20px;">
|
||||
<li>This is a temporary password. Please change it immediately after logging in.</li>
|
||||
<li>Never share your password with anyone.</li>
|
||||
<li>If you did not request this password reset, please contact your system administrator immediately.</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<p>To log in to the admin panel, click the button below:</p>
|
||||
|
||||
<div style="text-align: center; margin: 30px 0;">
|
||||
<a href="{{admin_login_url}}" style="display: inline-block; padding: 14px 35px; background-color: #5C8762; color: white; text-decoration: none; border-radius: 5px; font-weight: 600; font-size: 16px;">Log In Now</a>
|
||||
</div>
|
||||
|
||||
<p style="color: #666; font-size: 13px;">After logging in, navigate to your profile settings to change your password to something secure that only you know.</p>
|
||||
|
||||
<p>Best regards,<br>
|
||||
The PicPeak Team</p>`,
|
||||
body_text_en: `Password Reset Notification
|
||||
|
||||
Hello {{username}},
|
||||
|
||||
Your administrator password for PicPeak has been reset by a system administrator.
|
||||
|
||||
Your New Login Credentials:
|
||||
- Username: {{username}}
|
||||
- Temporary Password: {{new_password}}
|
||||
|
||||
SECURITY NOTICE:
|
||||
- This is a temporary password. Please change it immediately after logging in.
|
||||
- Never share your password with anyone.
|
||||
- If you did not request this password reset, please contact your system administrator immediately.
|
||||
|
||||
To log in to the admin panel, visit: {{admin_login_url}}
|
||||
|
||||
After logging in, navigate to your profile settings to change your password to something secure that only you know.
|
||||
|
||||
Best regards,
|
||||
The PicPeak Team`,
|
||||
body_html_de: `
|
||||
<h2>Benachrichtigung uber Passwortzurucksetzung</h2>
|
||||
|
||||
<p>Hallo <strong>{{username}}</strong>,</p>
|
||||
|
||||
<p>Ihr Administratorpasswort fur PicPeak wurde von einem Systemadministrator zuruckgesetzt.</p>
|
||||
|
||||
<div style="background-color: #f9f9f9; padding: 20px; border-radius: 8px; margin: 20px 0;">
|
||||
<h3 style="margin-top: 0;">Ihre neuen Anmeldedaten:</h3>
|
||||
<ul style="list-style: none; padding: 0;">
|
||||
<li style="margin-bottom: 10px;"><strong>Benutzername:</strong> {{username}}</li>
|
||||
<li style="margin-bottom: 10px;"><strong>Vorlaufiges Passwort:</strong> <code style="background-color: #e9ecef; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 14px;">{{new_password}}</code></li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<div style="background-color: #fee; border: 1px solid #fcc; color: #c33; padding: 20px; border-radius: 8px; margin: 20px 0;">
|
||||
<p style="margin: 0; font-weight: bold; font-size: 16px;">Sicherheitshinweis</p>
|
||||
<ul style="margin: 10px 0 0 0; padding-left: 20px;">
|
||||
<li>Dies ist ein vorlaufiges Passwort. Bitte andern Sie es sofort nach der Anmeldung.</li>
|
||||
<li>Teilen Sie Ihr Passwort niemals mit anderen.</li>
|
||||
<li>Wenn Sie diese Passwortzurucksetzung nicht angefordert haben, wenden Sie sich bitte umgehend an Ihren Systemadministrator.</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<p>Um sich im Admin-Panel anzumelden, klicken Sie auf die Schaltflache unten:</p>
|
||||
|
||||
<div style="text-align: center; margin: 30px 0;">
|
||||
<a href="{{admin_login_url}}" style="display: inline-block; padding: 14px 35px; background-color: #5C8762; color: white; text-decoration: none; border-radius: 5px; font-weight: 600; font-size: 16px;">Jetzt anmelden</a>
|
||||
</div>
|
||||
|
||||
<p style="color: #666; font-size: 13px;">Nach der Anmeldung navigieren Sie zu Ihren Profileinstellungen, um Ihr Passwort in ein sicheres Passwort zu andern, das nur Sie kennen.</p>
|
||||
|
||||
<p>Mit freundlichen Grussen,<br>
|
||||
Ihr PicPeak-Team</p>`,
|
||||
body_text_de: `Benachrichtigung uber Passwortzurucksetzung
|
||||
|
||||
Hallo {{username}},
|
||||
|
||||
Ihr Administratorpasswort fur PicPeak wurde von einem Systemadministrator zuruckgesetzt.
|
||||
|
||||
Ihre neuen Anmeldedaten:
|
||||
- Benutzername: {{username}}
|
||||
- Vorlaufiges Passwort: {{new_password}}
|
||||
|
||||
SICHERHEITSHINWEIS:
|
||||
- Dies ist ein vorlaufiges Passwort. Bitte andern Sie es sofort nach der Anmeldung.
|
||||
- Teilen Sie Ihr Passwort niemals mit anderen.
|
||||
- Wenn Sie diese Passwortzurucksetzung nicht angefordert haben, wenden Sie sich bitte umgehend an Ihren Systemadministrator.
|
||||
|
||||
Um sich im Admin-Panel anzumelden, besuchen Sie: {{admin_login_url}}
|
||||
|
||||
Nach der Anmeldung navigieren Sie zu Ihren Profileinstellungen, um Ihr Passwort in ein sicheres Passwort zu andern, das nur Sie kennen.
|
||||
|
||||
Mit freundlichen Grussen,
|
||||
Ihr PicPeak-Team`,
|
||||
variables: JSON.stringify(['username', 'new_password', 'admin_login_url'])
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
exports.down = async function(knex) {
|
||||
// Remove the admin email templates
|
||||
await knex('email_templates')
|
||||
.whereIn('template_key', ['admin_invitation', 'admin_password_reset'])
|
||||
.delete();
|
||||
};
|
||||
@@ -0,0 +1,23 @@
|
||||
/**
|
||||
* Migration: Add created_by column to events table
|
||||
* This allows filtering events by owner for role-based access control
|
||||
*/
|
||||
|
||||
exports.up = async function(knex) {
|
||||
// Add created_by column to events table
|
||||
await knex.schema.alterTable('events', (table) => {
|
||||
table.integer('created_by').unsigned().references('id').inTable('admin_users').onDelete('SET NULL');
|
||||
});
|
||||
|
||||
// Set existing events to be owned by the first admin (super_admin)
|
||||
const superAdmin = await knex('admin_users').where('role_id', 1).first();
|
||||
if (superAdmin) {
|
||||
await knex('events').update({ created_by: superAdmin.id });
|
||||
}
|
||||
};
|
||||
|
||||
exports.down = async function(knex) {
|
||||
await knex.schema.alterTable('events', (table) => {
|
||||
table.dropColumn('created_by');
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,107 @@
|
||||
/**
|
||||
* Migration: Add event_types table
|
||||
*
|
||||
* Creates a customizable event types system to replace hardcoded event types.
|
||||
* This allows users to:
|
||||
* - Rename existing event types (wedding, birthday, corporate, other)
|
||||
* - Create custom event types with custom slug prefixes
|
||||
* - Associate default theme presets with event types
|
||||
*
|
||||
* Backward compatible: Existing events keep their event_type strings.
|
||||
* New events can use either legacy strings or custom event type slug_prefix.
|
||||
*/
|
||||
|
||||
const { createTableIfNotExists, insertIfNotExists } = require('../helpers');
|
||||
|
||||
exports.up = async function(knex) {
|
||||
console.log('Creating event_types table...');
|
||||
|
||||
// Create event_types table
|
||||
const hasEventTypesTable = await knex.schema.hasTable('event_types');
|
||||
if (!hasEventTypesTable) {
|
||||
await knex.schema.createTable('event_types', (table) => {
|
||||
table.increments('id').primary();
|
||||
table.string('name', 100).notNullable(); // Display name: "Family Shoot"
|
||||
table.string('slug_prefix', 50).unique().notNullable(); // URL prefix: "family"
|
||||
table.string('emoji', 10); // Icon emoji: "👨👩👧"
|
||||
table.string('theme_preset', 50); // Default theme: "elegantWedding"
|
||||
table.text('theme_config'); // Custom theme JSON overrides (optional)
|
||||
table.integer('display_order').defaultTo(0); // Sorting in dropdowns
|
||||
table.boolean('is_system').defaultTo(false); // Protect default types
|
||||
table.boolean('is_active').defaultTo(true); // Allow hiding types
|
||||
table.timestamp('created_at').defaultTo(knex.fn.now());
|
||||
table.timestamp('updated_at').defaultTo(knex.fn.now());
|
||||
|
||||
// Indexes for performance
|
||||
table.index('slug_prefix');
|
||||
table.index('display_order');
|
||||
table.index('is_active');
|
||||
});
|
||||
console.log('event_types table created');
|
||||
} else {
|
||||
console.log('event_types table already exists, skipping creation');
|
||||
}
|
||||
|
||||
// Seed default event types (matching current hardcoded values)
|
||||
const existingTypes = await knex('event_types').select('slug_prefix');
|
||||
const existingSlugs = existingTypes.map(t => t.slug_prefix);
|
||||
|
||||
const defaultTypes = [
|
||||
{
|
||||
name: 'Wedding',
|
||||
slug_prefix: 'wedding',
|
||||
emoji: '💒',
|
||||
theme_preset: 'elegantWedding',
|
||||
display_order: 1,
|
||||
is_system: true,
|
||||
is_active: true
|
||||
},
|
||||
{
|
||||
name: 'Birthday',
|
||||
slug_prefix: 'birthday',
|
||||
emoji: '🎂',
|
||||
theme_preset: 'birthdayFun',
|
||||
display_order: 2,
|
||||
is_system: true,
|
||||
is_active: true
|
||||
},
|
||||
{
|
||||
name: 'Corporate',
|
||||
slug_prefix: 'corporate',
|
||||
emoji: '🏢',
|
||||
theme_preset: 'corporateTimeline',
|
||||
display_order: 3,
|
||||
is_system: true,
|
||||
is_active: true
|
||||
},
|
||||
{
|
||||
name: 'Other',
|
||||
slug_prefix: 'other',
|
||||
emoji: '📸',
|
||||
theme_preset: 'default',
|
||||
display_order: 4,
|
||||
is_system: true,
|
||||
is_active: true
|
||||
}
|
||||
];
|
||||
|
||||
const typesToInsert = defaultTypes.filter(type => !existingSlugs.includes(type.slug_prefix));
|
||||
|
||||
if (typesToInsert.length > 0) {
|
||||
await knex('event_types').insert(typesToInsert);
|
||||
console.log(`Inserted ${typesToInsert.length} default event types`);
|
||||
} else {
|
||||
console.log('Default event types already exist, skipping seed');
|
||||
}
|
||||
|
||||
console.log('Migration 061_add_event_types_table completed successfully');
|
||||
};
|
||||
|
||||
exports.down = async function(knex) {
|
||||
console.log('Rolling back event_types table...');
|
||||
|
||||
// Drop the table (data will be lost)
|
||||
await knex.schema.dropTableIfExists('event_types');
|
||||
|
||||
console.log('event_types table dropped');
|
||||
};
|
||||
@@ -0,0 +1,53 @@
|
||||
/**
|
||||
* Migration: Add optional event date and expiration settings
|
||||
* These settings control whether event_date and expiration are required
|
||||
* when creating new events, supporting non-event use cases like portraits.
|
||||
*/
|
||||
|
||||
exports.up = async function(knex) {
|
||||
// Add new settings for optional date and expiration
|
||||
const settings = [
|
||||
{ setting_key: 'event_require_event_date', setting_value: JSON.stringify(true), setting_type: 'boolean' },
|
||||
{ setting_key: 'event_require_expiration', setting_value: JSON.stringify(true), setting_type: 'boolean' }
|
||||
];
|
||||
|
||||
for (const setting of settings) {
|
||||
const exists = await knex('app_settings').where('setting_key', setting.setting_key).first();
|
||||
if (!exists) {
|
||||
await knex('app_settings').insert({
|
||||
...setting,
|
||||
updated_at: knex.fn.now()
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Make event_date and expires_at columns nullable
|
||||
// PostgreSQL supports ALTER COLUMN ... DROP NOT NULL
|
||||
// SQLite requires table recreation (handled differently)
|
||||
const client = knex.client.config.client;
|
||||
|
||||
if (client === 'pg' || client === 'postgresql') {
|
||||
// PostgreSQL: directly alter columns
|
||||
await knex.raw('ALTER TABLE events ALTER COLUMN event_date DROP NOT NULL');
|
||||
await knex.raw('ALTER TABLE events ALTER COLUMN expires_at DROP NOT NULL');
|
||||
} else if (client === 'sqlite3' || client === 'better-sqlite3') {
|
||||
// SQLite: columns are already effectively nullable in most cases
|
||||
// SQLite doesn't enforce NOT NULL as strictly, and altering requires table recreation
|
||||
// For safety, we'll skip the schema change for SQLite as it's complex
|
||||
// The application logic will handle null values appropriately
|
||||
console.log('SQLite detected - skipping schema alteration (columns will accept NULL values)');
|
||||
}
|
||||
};
|
||||
|
||||
exports.down = async function(knex) {
|
||||
// Remove the settings
|
||||
await knex('app_settings')
|
||||
.whereIn('setting_key', [
|
||||
'event_require_event_date',
|
||||
'event_require_expiration'
|
||||
])
|
||||
.del();
|
||||
|
||||
// Note: We don't restore NOT NULL constraints as that could fail
|
||||
// if there are existing NULL values in the database
|
||||
};
|
||||
@@ -0,0 +1,28 @@
|
||||
/**
|
||||
* Migration 061: Add pre-generated watermark path to photos table
|
||||
* - photos.watermark_path: path to pre-generated watermarked image
|
||||
* - photos.watermark_generated_at: timestamp of watermark generation
|
||||
*/
|
||||
|
||||
const { addColumnIfNotExists } = require('../helpers');
|
||||
|
||||
exports.up = async function(knex) {
|
||||
console.log('Running migration: 061_add_watermark_path');
|
||||
|
||||
// photos.watermark_path (nullable - path to pre-generated watermarked image)
|
||||
await addColumnIfNotExists(knex, 'photos', 'watermark_path', (table) => {
|
||||
table.string('watermark_path', 512);
|
||||
});
|
||||
|
||||
// photos.watermark_generated_at (nullable - when watermark was last generated)
|
||||
await addColumnIfNotExists(knex, 'photos', 'watermark_generated_at', (table) => {
|
||||
table.timestamp('watermark_generated_at');
|
||||
});
|
||||
|
||||
console.log('Migration 061_add_watermark_path completed');
|
||||
};
|
||||
|
||||
exports.down = async function(knex) {
|
||||
console.log('Rollback: 061_add_watermark_path');
|
||||
// Keep columns (safe rollback not removing data). Intentionally no-op.
|
||||
};
|
||||
@@ -0,0 +1,70 @@
|
||||
/**
|
||||
* Migration: Add hero logo customization settings to events table
|
||||
*
|
||||
* Allows per-event customization of the hero gallery logo:
|
||||
* - hero_logo_visible: Show/hide the logo overlay
|
||||
* - hero_logo_size: Logo size (small, medium, large, xlarge)
|
||||
* - hero_logo_position: Logo position (top, center, bottom)
|
||||
*
|
||||
* Addresses GitHub Issue #138: Add Option to customize the Hero gallery layout
|
||||
*/
|
||||
|
||||
exports.up = async function (knex) {
|
||||
console.log('Adding hero logo settings to events table...');
|
||||
|
||||
// Add hero_logo_visible column
|
||||
const hasVisibleColumn = await knex.schema.hasColumn('events', 'hero_logo_visible');
|
||||
if (!hasVisibleColumn) {
|
||||
await knex.schema.table('events', (table) => {
|
||||
table.boolean('hero_logo_visible').notNullable().defaultTo(true);
|
||||
});
|
||||
console.log('Added hero_logo_visible column');
|
||||
}
|
||||
|
||||
// Add hero_logo_size column
|
||||
const hasSizeColumn = await knex.schema.hasColumn('events', 'hero_logo_size');
|
||||
if (!hasSizeColumn) {
|
||||
await knex.schema.table('events', (table) => {
|
||||
table.string('hero_logo_size', 20).notNullable().defaultTo('medium');
|
||||
});
|
||||
console.log('Added hero_logo_size column');
|
||||
}
|
||||
|
||||
// Add hero_logo_position column
|
||||
const hasPositionColumn = await knex.schema.hasColumn('events', 'hero_logo_position');
|
||||
if (!hasPositionColumn) {
|
||||
await knex.schema.table('events', (table) => {
|
||||
table.string('hero_logo_position', 20).notNullable().defaultTo('top');
|
||||
});
|
||||
console.log('Added hero_logo_position column');
|
||||
}
|
||||
|
||||
console.log('Migration 062_add_hero_logo_settings completed successfully');
|
||||
};
|
||||
|
||||
exports.down = async function (knex) {
|
||||
console.log('Rolling back hero logo settings...');
|
||||
|
||||
const hasVisibleColumn = await knex.schema.hasColumn('events', 'hero_logo_visible');
|
||||
if (hasVisibleColumn) {
|
||||
await knex.schema.table('events', (table) => {
|
||||
table.dropColumn('hero_logo_visible');
|
||||
});
|
||||
}
|
||||
|
||||
const hasSizeColumn = await knex.schema.hasColumn('events', 'hero_logo_size');
|
||||
if (hasSizeColumn) {
|
||||
await knex.schema.table('events', (table) => {
|
||||
table.dropColumn('hero_logo_size');
|
||||
});
|
||||
}
|
||||
|
||||
const hasPositionColumn = await knex.schema.hasColumn('events', 'hero_logo_position');
|
||||
if (hasPositionColumn) {
|
||||
await knex.schema.table('events', (table) => {
|
||||
table.dropColumn('hero_logo_position');
|
||||
});
|
||||
}
|
||||
|
||||
console.log('Hero logo settings columns dropped');
|
||||
};
|
||||
@@ -0,0 +1,23 @@
|
||||
/**
|
||||
* Migration 062: Add original_filename to photos table
|
||||
* - photos.original_filename: preserves the original filename from upload
|
||||
* This enables Lightroom integration by exporting filtered filenames
|
||||
*/
|
||||
|
||||
const { addColumnIfNotExists } = require('../helpers');
|
||||
|
||||
exports.up = async function(knex) {
|
||||
console.log('Running migration: 062_add_original_filename');
|
||||
|
||||
// photos.original_filename (nullable - original filename before renaming)
|
||||
await addColumnIfNotExists(knex, 'photos', 'original_filename', (table) => {
|
||||
table.string('original_filename', 512);
|
||||
});
|
||||
|
||||
console.log('Migration 062_add_original_filename completed');
|
||||
};
|
||||
|
||||
exports.down = async function(knex) {
|
||||
console.log('Rollback: 062_add_original_filename');
|
||||
// Keep column (safe rollback not removing data). Intentionally no-op.
|
||||
};
|
||||
@@ -0,0 +1,53 @@
|
||||
/**
|
||||
* Migration: Add custom logo support to events table
|
||||
*
|
||||
* Allows per-event custom logo that overrides the global branding logo:
|
||||
* - hero_logo_url: Public path to the uploaded custom logo
|
||||
* - hero_logo_path: Full filesystem path to the custom logo
|
||||
*
|
||||
* Logo priority: Event custom logo > Global branding logo > Default PicPeak logo
|
||||
*
|
||||
* Addresses GitHub Issue #138: Per-event custom logo option
|
||||
*/
|
||||
|
||||
exports.up = async function (knex) {
|
||||
console.log('Adding custom logo columns to events table...');
|
||||
|
||||
const hasUrlColumn = await knex.schema.hasColumn('events', 'hero_logo_url');
|
||||
if (!hasUrlColumn) {
|
||||
await knex.schema.table('events', (table) => {
|
||||
table.string('hero_logo_url', 500).nullable().defaultTo(null);
|
||||
});
|
||||
console.log('Added hero_logo_url column');
|
||||
}
|
||||
|
||||
const hasPathColumn = await knex.schema.hasColumn('events', 'hero_logo_path');
|
||||
if (!hasPathColumn) {
|
||||
await knex.schema.table('events', (table) => {
|
||||
table.string('hero_logo_path', 500).nullable().defaultTo(null);
|
||||
});
|
||||
console.log('Added hero_logo_path column');
|
||||
}
|
||||
|
||||
console.log('Migration 063_add_event_custom_logo completed successfully');
|
||||
};
|
||||
|
||||
exports.down = async function (knex) {
|
||||
console.log('Rolling back custom logo columns...');
|
||||
|
||||
const hasUrlColumn = await knex.schema.hasColumn('events', 'hero_logo_url');
|
||||
if (hasUrlColumn) {
|
||||
await knex.schema.table('events', (table) => {
|
||||
table.dropColumn('hero_logo_url');
|
||||
});
|
||||
}
|
||||
|
||||
const hasPathColumn = await knex.schema.hasColumn('events', 'hero_logo_path');
|
||||
if (hasPathColumn) {
|
||||
await knex.schema.table('events', (table) => {
|
||||
table.dropColumn('hero_logo_path');
|
||||
});
|
||||
}
|
||||
|
||||
console.log('Custom logo columns dropped');
|
||||
};
|
||||
@@ -0,0 +1,105 @@
|
||||
/**
|
||||
* Migration: Backfill photo dimensions
|
||||
*
|
||||
* This migration extracts width/height from existing photos that don't have
|
||||
* these dimensions stored. This is needed for aspect-ratio-aware layouts
|
||||
* (masonry, mosaic, justified) to work properly.
|
||||
*/
|
||||
|
||||
const path = require('path');
|
||||
const fs = require('fs');
|
||||
|
||||
exports.up = async function(knex) {
|
||||
// Check if the width/height columns exist
|
||||
const hasWidth = await knex.schema.hasColumn('photos', 'width');
|
||||
const hasHeight = await knex.schema.hasColumn('photos', 'height');
|
||||
|
||||
if (!hasWidth || !hasHeight) {
|
||||
console.log('[Migration 064] Width/height columns not found, skipping backfill');
|
||||
return;
|
||||
}
|
||||
|
||||
// Get storage path
|
||||
const storagePath = process.env.STORAGE_PATH || path.join(__dirname, '../../../storage');
|
||||
|
||||
// Find photos without dimensions
|
||||
const photos = await knex('photos')
|
||||
.whereNull('width')
|
||||
.orWhereNull('height')
|
||||
.select('id', 'path', 'filename', 'media_type');
|
||||
|
||||
console.log(`[Migration 064] Found ${photos.length} photos without dimensions`);
|
||||
|
||||
if (photos.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Import sharp dynamically (only needed during migration)
|
||||
let sharp;
|
||||
try {
|
||||
sharp = require('sharp');
|
||||
} catch (err) {
|
||||
console.error('[Migration 064] Sharp not available, skipping backfill:', err.message);
|
||||
return;
|
||||
}
|
||||
|
||||
let updated = 0;
|
||||
let failed = 0;
|
||||
|
||||
for (const photo of photos) {
|
||||
try {
|
||||
// Skip videos - they need ffprobe for metadata
|
||||
if (photo.media_type === 'video') {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Construct the full file path
|
||||
let fullPath;
|
||||
if (photo.path) {
|
||||
// Path is relative to events/active directory
|
||||
fullPath = path.join(storagePath, 'events/active', photo.path);
|
||||
} else {
|
||||
console.warn(`[Migration 064] Photo ${photo.id} (${photo.filename}) has no path, skipping`);
|
||||
continue;
|
||||
}
|
||||
|
||||
// Check if file exists
|
||||
if (!fs.existsSync(fullPath)) {
|
||||
console.warn(`[Migration 064] Photo ${photo.id} file not found: ${fullPath}`);
|
||||
failed++;
|
||||
continue;
|
||||
}
|
||||
|
||||
// Extract dimensions using sharp
|
||||
const metadata = await sharp(fullPath).metadata();
|
||||
|
||||
if (metadata.width && metadata.height) {
|
||||
await knex('photos')
|
||||
.where('id', photo.id)
|
||||
.update({
|
||||
width: metadata.width,
|
||||
height: metadata.height
|
||||
});
|
||||
updated++;
|
||||
|
||||
if (updated % 50 === 0) {
|
||||
console.log(`[Migration 064] Updated ${updated} photos...`);
|
||||
}
|
||||
} else {
|
||||
console.warn(`[Migration 064] Could not extract dimensions for photo ${photo.id}`);
|
||||
failed++;
|
||||
}
|
||||
} catch (err) {
|
||||
console.error(`[Migration 064] Error processing photo ${photo.id}:`, err.message);
|
||||
failed++;
|
||||
}
|
||||
}
|
||||
|
||||
console.log(`[Migration 064] Completed: ${updated} updated, ${failed} failed`);
|
||||
};
|
||||
|
||||
exports.down = async function(knex) {
|
||||
// This migration only adds data, no rollback needed
|
||||
// We don't want to null out dimensions on rollback as they're still valid
|
||||
console.log('[Migration 064] Rollback: No action needed (data-only migration)');
|
||||
};
|
||||
@@ -0,0 +1,131 @@
|
||||
/**
|
||||
* Migration: Add header_style and hero_divider_style columns
|
||||
*
|
||||
* This migration decouples the hero header style from gallery layout,
|
||||
* allowing any combination of header style with any layout type.
|
||||
*/
|
||||
|
||||
exports.up = async function(knex) {
|
||||
console.log('[Migration 065] Adding header_style and hero_divider_style columns');
|
||||
|
||||
// Check if columns already exist
|
||||
const hasHeaderStyle = await knex.schema.hasColumn('events', 'header_style');
|
||||
const hasDividerStyle = await knex.schema.hasColumn('events', 'hero_divider_style');
|
||||
|
||||
if (!hasHeaderStyle) {
|
||||
await knex.schema.alterTable('events', (table) => {
|
||||
table.string('header_style', 20).defaultTo('standard');
|
||||
});
|
||||
console.log('[Migration 065] Added header_style column');
|
||||
}
|
||||
|
||||
if (!hasDividerStyle) {
|
||||
await knex.schema.alterTable('events', (table) => {
|
||||
table.string('hero_divider_style', 20).defaultTo('wave');
|
||||
});
|
||||
console.log('[Migration 065] Added hero_divider_style column');
|
||||
}
|
||||
|
||||
// Migrate existing events with hero layout in color_theme
|
||||
console.log('[Migration 065] Migrating existing hero layouts...');
|
||||
|
||||
const events = await knex('events')
|
||||
.whereNotNull('color_theme')
|
||||
.select('id', 'color_theme');
|
||||
|
||||
let migratedCount = 0;
|
||||
|
||||
for (const event of events) {
|
||||
try {
|
||||
// Skip if color_theme is not JSON
|
||||
if (!event.color_theme || !event.color_theme.startsWith('{')) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const theme = JSON.parse(event.color_theme);
|
||||
|
||||
// Check if this event uses hero layout
|
||||
if (theme.galleryLayout === 'hero') {
|
||||
// Migrate: set headerStyle to 'hero' and galleryLayout to 'grid'
|
||||
const updatedTheme = {
|
||||
...theme,
|
||||
headerStyle: 'hero',
|
||||
galleryLayout: 'grid',
|
||||
heroDividerStyle: theme.heroDividerStyle || 'wave'
|
||||
};
|
||||
|
||||
await knex('events')
|
||||
.where('id', event.id)
|
||||
.update({
|
||||
color_theme: JSON.stringify(updatedTheme),
|
||||
header_style: 'hero',
|
||||
hero_divider_style: theme.heroDividerStyle || 'wave'
|
||||
});
|
||||
|
||||
migratedCount++;
|
||||
}
|
||||
} catch (err) {
|
||||
// Invalid JSON in color_theme, skip
|
||||
console.warn(`[Migration 065] Could not parse color_theme for event ${event.id}: ${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
console.log(`[Migration 065] Migrated ${migratedCount} events from hero layout`);
|
||||
console.log('[Migration 065] Completed');
|
||||
};
|
||||
|
||||
exports.down = async function(knex) {
|
||||
console.log('[Migration 065] Removing header_style and hero_divider_style columns');
|
||||
|
||||
// First, migrate any hero header styles back to hero layout
|
||||
const events = await knex('events')
|
||||
.where('header_style', 'hero')
|
||||
.whereNotNull('color_theme')
|
||||
.select('id', 'color_theme');
|
||||
|
||||
for (const event of events) {
|
||||
try {
|
||||
if (!event.color_theme || !event.color_theme.startsWith('{')) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const theme = JSON.parse(event.color_theme);
|
||||
|
||||
// Revert: set galleryLayout back to 'hero'
|
||||
const revertedTheme = {
|
||||
...theme,
|
||||
galleryLayout: 'hero'
|
||||
};
|
||||
|
||||
// Remove the new properties
|
||||
delete revertedTheme.headerStyle;
|
||||
delete revertedTheme.heroDividerStyle;
|
||||
|
||||
await knex('events')
|
||||
.where('id', event.id)
|
||||
.update({
|
||||
color_theme: JSON.stringify(revertedTheme)
|
||||
});
|
||||
} catch (err) {
|
||||
console.warn(`[Migration 065] Could not revert color_theme for event ${event.id}: ${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
// Remove the columns
|
||||
const hasHeaderStyle = await knex.schema.hasColumn('events', 'header_style');
|
||||
const hasDividerStyle = await knex.schema.hasColumn('events', 'hero_divider_style');
|
||||
|
||||
if (hasHeaderStyle) {
|
||||
await knex.schema.alterTable('events', (table) => {
|
||||
table.dropColumn('header_style');
|
||||
});
|
||||
}
|
||||
|
||||
if (hasDividerStyle) {
|
||||
await knex.schema.alterTable('events', (table) => {
|
||||
table.dropColumn('hero_divider_style');
|
||||
});
|
||||
}
|
||||
|
||||
console.log('[Migration 065] Rollback completed');
|
||||
};
|
||||
@@ -0,0 +1,48 @@
|
||||
/**
|
||||
* Migration: Add hero image anchor position and category-specific hero images
|
||||
*
|
||||
* Issue #162: Add hero_image_anchor column to events table for controlling
|
||||
* how hero images are cropped (top/center/bottom)
|
||||
*
|
||||
* Issue #163: Add hero_photo_id column to photo_categories table for
|
||||
* category-specific hero images
|
||||
*/
|
||||
|
||||
exports.up = async function(knex) {
|
||||
// Add hero_image_anchor to events table (Issue #162)
|
||||
const hasHeroAnchor = await knex.schema.hasColumn('events', 'hero_image_anchor');
|
||||
if (!hasHeroAnchor) {
|
||||
await knex.schema.alterTable('events', function(table) {
|
||||
// Values: 'top', 'center', 'bottom' - defaults to 'center' for backward compatibility
|
||||
table.string('hero_image_anchor', 10).defaultTo('center');
|
||||
});
|
||||
console.log('Added hero_image_anchor column to events table');
|
||||
}
|
||||
|
||||
// Add hero_photo_id to photo_categories table (Issue #163)
|
||||
const hasCategoryHero = await knex.schema.hasColumn('photo_categories', 'hero_photo_id');
|
||||
if (!hasCategoryHero) {
|
||||
await knex.schema.alterTable('photo_categories', function(table) {
|
||||
table.integer('hero_photo_id').references('id').inTable('photos').onDelete('SET NULL');
|
||||
});
|
||||
console.log('Added hero_photo_id column to photo_categories table');
|
||||
}
|
||||
};
|
||||
|
||||
exports.down = async function(knex) {
|
||||
// Remove hero_image_anchor from events table
|
||||
const hasHeroAnchor = await knex.schema.hasColumn('events', 'hero_image_anchor');
|
||||
if (hasHeroAnchor) {
|
||||
await knex.schema.alterTable('events', function(table) {
|
||||
table.dropColumn('hero_image_anchor');
|
||||
});
|
||||
}
|
||||
|
||||
// Remove hero_photo_id from photo_categories table
|
||||
const hasCategoryHero = await knex.schema.hasColumn('photo_categories', 'hero_photo_id');
|
||||
if (hasCategoryHero) {
|
||||
await knex.schema.alterTable('photo_categories', function(table) {
|
||||
table.dropColumn('hero_photo_id');
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,32 @@
|
||||
/**
|
||||
* Migration: Expand hero_image_anchor column to support focal point percentages
|
||||
*
|
||||
* Changes string(10) to string(20) so values like "100% 100%" (9 chars) fit
|
||||
* with room to spare. Existing 'top', 'center', 'bottom' values are preserved.
|
||||
*/
|
||||
|
||||
exports.up = async function(knex) {
|
||||
const hasColumn = await knex.schema.hasColumn('events', 'hero_image_anchor');
|
||||
if (!hasColumn) {
|
||||
// Column doesn't exist yet – nothing to expand
|
||||
return;
|
||||
}
|
||||
|
||||
// SQLite doesn't truly support ALTER COLUMN, but Knex handles the
|
||||
// rebuild-table strategy internally when we call alterTable.
|
||||
await knex.schema.alterTable('events', function(table) {
|
||||
table.string('hero_image_anchor', 20).defaultTo('center').alter();
|
||||
});
|
||||
console.log('Expanded hero_image_anchor column to string(20)');
|
||||
};
|
||||
|
||||
exports.down = async function(knex) {
|
||||
const hasColumn = await knex.schema.hasColumn('events', 'hero_image_anchor');
|
||||
if (!hasColumn) {
|
||||
return;
|
||||
}
|
||||
|
||||
await knex.schema.alterTable('events', function(table) {
|
||||
table.string('hero_image_anchor', 10).defaultTo('center').alter();
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,54 @@
|
||||
const DEFAULT_AI_AGENTS = [
|
||||
'GPTBot',
|
||||
'ChatGPT-User',
|
||||
'Google-Extended',
|
||||
'Claude-Web',
|
||||
'Anthropic-AI',
|
||||
'CCBot',
|
||||
'Bytespider',
|
||||
'FacebookBot',
|
||||
'Omgilibot',
|
||||
'Diffbot',
|
||||
'PetalBot',
|
||||
'Amazonbot',
|
||||
'PerplexityBot',
|
||||
'YouBot',
|
||||
'Applebot-Extended'
|
||||
];
|
||||
|
||||
exports.up = async function(knex) {
|
||||
const defaults = [
|
||||
{ setting_key: 'seo_allow_indexing', setting_value: JSON.stringify(false), setting_type: 'seo' },
|
||||
{ setting_key: 'seo_block_ai_crawlers', setting_value: JSON.stringify(true), setting_type: 'seo' },
|
||||
{ setting_key: 'seo_block_social_bots', setting_value: JSON.stringify(false), setting_type: 'seo' },
|
||||
{ setting_key: 'seo_blocked_ai_agents', setting_value: JSON.stringify(DEFAULT_AI_AGENTS), setting_type: 'seo' },
|
||||
{ setting_key: 'seo_custom_rules', setting_value: JSON.stringify([]), setting_type: 'seo' },
|
||||
{ setting_key: 'seo_meta_noindex', setting_value: JSON.stringify(true), setting_type: 'seo' },
|
||||
{ setting_key: 'seo_meta_nofollow', setting_value: JSON.stringify(false), setting_type: 'seo' },
|
||||
{ setting_key: 'seo_meta_noai', setting_value: JSON.stringify(true), setting_type: 'seo' },
|
||||
{ setting_key: 'seo_sitemap_url', setting_value: JSON.stringify(''), setting_type: 'seo' }
|
||||
];
|
||||
|
||||
for (const setting of defaults) {
|
||||
const exists = await knex('app_settings').where('setting_key', setting.setting_key).first();
|
||||
if (!exists) {
|
||||
await knex('app_settings').insert({ ...setting, updated_at: knex.fn.now() });
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
exports.down = async function(knex) {
|
||||
await knex('app_settings')
|
||||
.whereIn('setting_key', [
|
||||
'seo_allow_indexing',
|
||||
'seo_block_ai_crawlers',
|
||||
'seo_block_social_bots',
|
||||
'seo_blocked_ai_agents',
|
||||
'seo_custom_rules',
|
||||
'seo_meta_noindex',
|
||||
'seo_meta_nofollow',
|
||||
'seo_meta_noai',
|
||||
'seo_sitemap_url'
|
||||
])
|
||||
.del();
|
||||
};
|
||||
@@ -0,0 +1,22 @@
|
||||
/**
|
||||
* Migration 069: Add hero image path to photos table
|
||||
* - photos.hero_path: path to hero-optimized image (1920x1080) for gallery headers
|
||||
*/
|
||||
|
||||
const { addColumnIfNotExists } = require('../helpers');
|
||||
|
||||
exports.up = async function(knex) {
|
||||
console.log('Running migration: 069_add_hero_path');
|
||||
|
||||
// photos.hero_path (nullable - path to hero-optimized image)
|
||||
await addColumnIfNotExists(knex, 'photos', 'hero_path', (table) => {
|
||||
table.string('hero_path', 512);
|
||||
});
|
||||
|
||||
console.log('Migration 069_add_hero_path completed');
|
||||
};
|
||||
|
||||
exports.down = async function(knex) {
|
||||
console.log('Rollback: 069_add_hero_path');
|
||||
// Keep columns (safe rollback not removing data). Intentionally no-op.
|
||||
};
|
||||
@@ -0,0 +1,161 @@
|
||||
/**
|
||||
* Migration 070: Add update notification settings and email template
|
||||
* - Settings for email notifications when new versions are available
|
||||
* - Email template for version update notifications
|
||||
*/
|
||||
|
||||
exports.up = async function(knex) {
|
||||
console.log('Running migration: 070_add_update_notification_settings');
|
||||
|
||||
// Add app_settings for update notifications
|
||||
const settings = [
|
||||
{
|
||||
setting_key: 'update_email_notifications_enabled',
|
||||
setting_value: JSON.stringify(false),
|
||||
setting_type: 'notifications'
|
||||
},
|
||||
{
|
||||
setting_key: 'update_email_recipients',
|
||||
setting_value: JSON.stringify(''), // Comma-separated emails, or empty for all admin emails
|
||||
setting_type: 'notifications'
|
||||
},
|
||||
{
|
||||
setting_key: 'last_notified_version',
|
||||
setting_value: JSON.stringify(''),
|
||||
setting_type: 'notifications'
|
||||
}
|
||||
];
|
||||
|
||||
for (const setting of settings) {
|
||||
const exists = await knex('app_settings').where('setting_key', setting.setting_key).first();
|
||||
if (!exists) {
|
||||
await knex('app_settings').insert({ ...setting, updated_at: knex.fn.now() });
|
||||
}
|
||||
}
|
||||
|
||||
// Check if email template already exists
|
||||
const existingTemplate = await knex('email_templates')
|
||||
.where('template_key', 'version_update_available')
|
||||
.first();
|
||||
|
||||
if (!existingTemplate) {
|
||||
await knex('email_templates').insert({
|
||||
template_key: 'version_update_available',
|
||||
subject_en: 'PicPeak Update Available: Version {{new_version}}',
|
||||
subject_de: 'PicPeak Update verfugbar: Version {{new_version}}',
|
||||
body_html_en: `
|
||||
<h2>A New Version of PicPeak is Available</h2>
|
||||
|
||||
<p>Great news! A new version of PicPeak is available for your installation.</p>
|
||||
|
||||
<div style="background-color: #f0f8ff; border-left: 4px solid #5C8762; padding: 20px; margin: 20px 0; border-radius: 4px;">
|
||||
<p style="margin: 0;"><strong>Current Version:</strong> {{current_version}}</p>
|
||||
<p style="margin: 10px 0 0 0;"><strong>New Version:</strong> {{new_version}}</p>
|
||||
<p style="margin: 10px 0 0 0;"><strong>Channel:</strong> {{channel}}</p>
|
||||
</div>
|
||||
|
||||
<h3>What's New?</h3>
|
||||
<p>Check the release notes to see what's included in this update:</p>
|
||||
|
||||
<div style="text-align: center; margin: 30px 0;">
|
||||
<a href="{{release_notes_url}}" style="display: inline-block; padding: 14px 35px; background-color: #5C8762; color: white; text-decoration: none; border-radius: 5px; font-weight: 600; font-size: 16px;">View Release Notes</a>
|
||||
</div>
|
||||
|
||||
<h3>How to Update</h3>
|
||||
<p>To update your installation, log in to the admin panel and click on the "Update Available" notification. You'll find environment-specific instructions there.</p>
|
||||
|
||||
<div style="background-color: #fff3cd; border: 1px solid #ffeaa7; color: #856404; padding: 15px; border-radius: 4px; margin: 20px 0;">
|
||||
<p style="margin: 0;"><strong>Reminder:</strong> Always backup your database before updating to ensure you can recover if anything goes wrong.</p>
|
||||
</div>
|
||||
|
||||
<p>Best regards,<br>
|
||||
Your PicPeak Installation</p>`,
|
||||
body_text_en: `A New Version of PicPeak is Available
|
||||
|
||||
Great news! A new version of PicPeak is available for your installation.
|
||||
|
||||
Current Version: {{current_version}}
|
||||
New Version: {{new_version}}
|
||||
Channel: {{channel}}
|
||||
|
||||
What's New?
|
||||
Check the release notes to see what's included in this update:
|
||||
{{release_notes_url}}
|
||||
|
||||
How to Update
|
||||
To update your installation, log in to the admin panel and click on the "Update Available" notification. You'll find environment-specific instructions there.
|
||||
|
||||
REMINDER: Always backup your database before updating to ensure you can recover if anything goes wrong.
|
||||
|
||||
Best regards,
|
||||
Your PicPeak Installation`,
|
||||
body_html_de: `
|
||||
<h2>Eine neue Version von PicPeak ist verfugbar</h2>
|
||||
|
||||
<p>Gute Neuigkeiten! Eine neue Version von PicPeak ist fur Ihre Installation verfugbar.</p>
|
||||
|
||||
<div style="background-color: #f0f8ff; border-left: 4px solid #5C8762; padding: 20px; margin: 20px 0; border-radius: 4px;">
|
||||
<p style="margin: 0;"><strong>Aktuelle Version:</strong> {{current_version}}</p>
|
||||
<p style="margin: 10px 0 0 0;"><strong>Neue Version:</strong> {{new_version}}</p>
|
||||
<p style="margin: 10px 0 0 0;"><strong>Kanal:</strong> {{channel}}</p>
|
||||
</div>
|
||||
|
||||
<h3>Was ist neu?</h3>
|
||||
<p>Schauen Sie sich die Versionshinweise an, um zu sehen, was in diesem Update enthalten ist:</p>
|
||||
|
||||
<div style="text-align: center; margin: 30px 0;">
|
||||
<a href="{{release_notes_url}}" style="display: inline-block; padding: 14px 35px; background-color: #5C8762; color: white; text-decoration: none; border-radius: 5px; font-weight: 600; font-size: 16px;">Versionshinweise anzeigen</a>
|
||||
</div>
|
||||
|
||||
<h3>So aktualisieren Sie</h3>
|
||||
<p>Um Ihre Installation zu aktualisieren, melden Sie sich im Admin-Panel an und klicken Sie auf die Benachrichtigung "Update verfugbar". Dort finden Sie umgebungsspezifische Anweisungen.</p>
|
||||
|
||||
<div style="background-color: #fff3cd; border: 1px solid #ffeaa7; color: #856404; padding: 15px; border-radius: 4px; margin: 20px 0;">
|
||||
<p style="margin: 0;"><strong>Erinnerung:</strong> Erstellen Sie immer ein Backup Ihrer Datenbank, bevor Sie aktualisieren, um sicherzustellen, dass Sie im Fehlerfall wiederherstellen konnen.</p>
|
||||
</div>
|
||||
|
||||
<p>Mit freundlichen Grussen,<br>
|
||||
Ihre PicPeak-Installation</p>`,
|
||||
body_text_de: `Eine neue Version von PicPeak ist verfugbar
|
||||
|
||||
Gute Neuigkeiten! Eine neue Version von PicPeak ist fur Ihre Installation verfugbar.
|
||||
|
||||
Aktuelle Version: {{current_version}}
|
||||
Neue Version: {{new_version}}
|
||||
Kanal: {{channel}}
|
||||
|
||||
Was ist neu?
|
||||
Schauen Sie sich die Versionshinweise an, um zu sehen, was in diesem Update enthalten ist:
|
||||
{{release_notes_url}}
|
||||
|
||||
So aktualisieren Sie
|
||||
Um Ihre Installation zu aktualisieren, melden Sie sich im Admin-Panel an und klicken Sie auf die Benachrichtigung "Update verfugbar". Dort finden Sie umgebungsspezifische Anweisungen.
|
||||
|
||||
ERINNERUNG: Erstellen Sie immer ein Backup Ihrer Datenbank, bevor Sie aktualisieren, um sicherzustellen, dass Sie im Fehlerfall wiederherstellen konnen.
|
||||
|
||||
Mit freundlichen Grussen,
|
||||
Ihre PicPeak-Installation`,
|
||||
variables: JSON.stringify(['current_version', 'new_version', 'channel', 'release_notes_url'])
|
||||
});
|
||||
}
|
||||
|
||||
console.log('Migration 070_add_update_notification_settings completed');
|
||||
};
|
||||
|
||||
exports.down = async function(knex) {
|
||||
console.log('Rollback: 070_add_update_notification_settings');
|
||||
|
||||
// Remove settings
|
||||
await knex('app_settings')
|
||||
.whereIn('setting_key', [
|
||||
'update_email_notifications_enabled',
|
||||
'update_email_recipients',
|
||||
'last_notified_version'
|
||||
])
|
||||
.del();
|
||||
|
||||
// Remove email template
|
||||
await knex('email_templates')
|
||||
.where('template_key', 'version_update_available')
|
||||
.del();
|
||||
};
|
||||
@@ -0,0 +1,42 @@
|
||||
/**
|
||||
* Migration 071: Add captured_at column to photos table
|
||||
* - Stores the original capture date from EXIF metadata
|
||||
* - Enables sorting photos by capture date instead of upload date
|
||||
*/
|
||||
|
||||
const { addColumnIfNotExists } = require('../helpers');
|
||||
|
||||
exports.up = async function(knex) {
|
||||
console.log('Running migration: 071_add_captured_at');
|
||||
|
||||
// Add captured_at column to photos table
|
||||
await addColumnIfNotExists(knex, 'photos', 'captured_at', (table) => {
|
||||
table.datetime('captured_at').nullable();
|
||||
});
|
||||
|
||||
// Add index for sorting performance
|
||||
const indexExists = await knex.schema.hasIndex
|
||||
? await knex.schema.hasIndex('photos', 'idx_photos_captured_at')
|
||||
: false;
|
||||
|
||||
if (!indexExists) {
|
||||
// Use raw query for index creation with IF NOT EXISTS
|
||||
const client = knex.client.config.client;
|
||||
if (client === 'pg') {
|
||||
await knex.raw('CREATE INDEX IF NOT EXISTS idx_photos_captured_at ON photos(captured_at)');
|
||||
} else if (client === 'sqlite3' || client === 'better-sqlite3') {
|
||||
// SQLite doesn't support IF NOT EXISTS for indexes, so we need to check first
|
||||
const existingIndexes = await knex.raw("SELECT name FROM sqlite_master WHERE type='index' AND name='idx_photos_captured_at'");
|
||||
if (existingIndexes.length === 0) {
|
||||
await knex.raw('CREATE INDEX idx_photos_captured_at ON photos(captured_at)');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
console.log('Migration 071_add_captured_at completed');
|
||||
};
|
||||
|
||||
exports.down = async function(knex) {
|
||||
console.log('Rollback: 071_add_captured_at');
|
||||
// Keep column for safe rollback (intentionally no-op)
|
||||
};
|
||||
@@ -0,0 +1,13 @@
|
||||
exports.up = async function(knex) {
|
||||
await knex.schema.alterTable('events', (table) => {
|
||||
table.string('host_email', 255).nullable().alter();
|
||||
table.string('admin_email', 255).nullable().alter();
|
||||
});
|
||||
};
|
||||
|
||||
exports.down = async function(knex) {
|
||||
await knex.schema.alterTable('events', (table) => {
|
||||
table.string('host_email', 255).notNullable().defaultTo('').alter();
|
||||
table.string('admin_email', 255).notNullable().defaultTo('').alter();
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,13 @@
|
||||
const { addColumnIfNotExists } = require('../helpers');
|
||||
|
||||
exports.up = async function(knex) {
|
||||
console.log('Running migration: 074_add_photo_cap');
|
||||
await addColumnIfNotExists(knex, 'events', 'photo_cap', (table) => {
|
||||
table.integer('photo_cap').nullable().defaultTo(null);
|
||||
});
|
||||
console.log('Migration 074_add_photo_cap completed');
|
||||
};
|
||||
|
||||
exports.down = async function(knex) {
|
||||
console.log('Rollback: 074_add_photo_cap');
|
||||
};
|
||||
@@ -0,0 +1,28 @@
|
||||
const { addColumnIfNotExists, createIndexIfNotExists } = require('../helpers');
|
||||
|
||||
exports.up = async function(knex) {
|
||||
// Add visibility column to photos table
|
||||
await addColumnIfNotExists(knex, 'photos', 'visibility', (table) => {
|
||||
table.string('visibility', 20).defaultTo('visible').notNullable();
|
||||
});
|
||||
|
||||
// Add client access columns to events table
|
||||
await addColumnIfNotExists(knex, 'events', 'client_access_enabled', (table) => {
|
||||
table.boolean('client_access_enabled').defaultTo(false);
|
||||
});
|
||||
|
||||
await addColumnIfNotExists(knex, 'events', 'client_password_hash', (table) => {
|
||||
table.string('client_password_hash', 255).nullable();
|
||||
});
|
||||
|
||||
await addColumnIfNotExists(knex, 'events', 'client_share_token', (table) => {
|
||||
table.string('client_share_token', 64).nullable().unique();
|
||||
});
|
||||
|
||||
// Index for filtering photos by visibility
|
||||
await createIndexIfNotExists(knex, 'photos', ['event_id', 'visibility'], 'idx_photos_event_visibility');
|
||||
};
|
||||
|
||||
exports.down = async function(knex) {
|
||||
// Safe rollback - intentionally no-op to avoid data loss
|
||||
};
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user