nexusbert commited on
Commit
9b2db15
·
1 Parent(s): 6fd909e

feat(migrations): add CreateStudents migration to define students table structure

Browse files
Dockerfile CHANGED
@@ -12,6 +12,7 @@ RUN npm ci
12
 
13
  # Copy TypeScript config
14
  COPY cruciqe-id-card-backend/tsconfig.json ./
 
15
 
16
  # Copy source files
17
  COPY cruciqe-id-card-backend/src ./src
@@ -73,6 +74,7 @@ ENV PUPPETEER_EXECUTABLE_PATH=/usr/bin/chromium
73
 
74
  # Set port to 7860 (required for HF Spaces)
75
  ENV PORT=7860
 
76
 
77
  # Run the application
78
  CMD ["node", "dist/index.js"]
 
12
 
13
  # Copy TypeScript config
14
  COPY cruciqe-id-card-backend/tsconfig.json ./
15
+ COPY cruciqe-id-card-backend/scripts ./scripts
16
 
17
  # Copy source files
18
  COPY cruciqe-id-card-backend/src ./src
 
74
 
75
  # Set port to 7860 (required for HF Spaces)
76
  ENV PORT=7860
77
+ ENV NODE_ENV=production
78
 
79
  # Run the application
80
  CMD ["node", "dist/index.js"]
cruciqe-id-card-backend/.env.example ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ NODE_ENV=production
2
+ PORT=7860
3
+ DB_PATH=/app/data/dev.db
4
+ ADMIN_EMAIL=
5
+ ADMIN_PASSWORD=
6
+ JWT_SECRET=
7
+ ALLOWED_ORIGINS=https://your-frontend.example
8
+ TELEGRAM_BOT_TOKEN=
9
+ TELEGRAM_CHAT_ID=
cruciqe-id-card-backend/package.json CHANGED
@@ -5,7 +5,7 @@
5
  "main": "index.js",
6
  "scripts": {
7
  "dev": "nodemon --watch src --exec \"node --import tsx src/index.ts\"",
8
- "build": "tsc",
9
  "start": "node dist/index.js"
10
  },
11
  "keywords": [],
 
5
  "main": "index.js",
6
  "scripts": {
7
  "dev": "nodemon --watch src --exec \"node --import tsx src/index.ts\"",
8
+ "build": "tsc && node scripts/copy-assets.js",
9
  "start": "node dist/index.js"
10
  },
11
  "keywords": [],
cruciqe-id-card-backend/scripts/copy-assets.js ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ import { cpSync, mkdirSync } from 'node:fs'
2
+
3
+ mkdirSync('dist/assets', { recursive: true })
4
+ cpSync('src/assets', 'dist/assets', { recursive: true })
cruciqe-id-card-backend/src/assets/aluta-mandate-logos.png ADDED
cruciqe-id-card-backend/src/controllers/AuthController.ts CHANGED
@@ -5,26 +5,11 @@ import { loginSchema } from '../schemas.js'
5
  export class AuthController {
6
  async login(req: Request, res: Response) {
7
  try {
8
- // Debug request body
9
- console.debug('Login request body:', {
10
- bodyExists: !!req.body,
11
- bodyType: typeof req.body,
12
- contentType: req.headers['content-type'],
13
- body: req.body
14
- })
15
-
16
- // Debug: log presence of auth-related env vars (do not print secrets)
17
- console.debug('Auth env presence:', {
18
- ADMIN_EMAIL: !!process.env.ADMIN_EMAIL,
19
- ADMIN_PASSWORD: !!process.env.ADMIN_PASSWORD,
20
- JWT_SECRET: !!process.env.JWT_SECRET,
21
- })
22
-
23
  const validatedData = loginSchema.parse(req.body)
24
 
25
  const adminEmail = process.env.ADMIN_EMAIL
26
  const adminPassword = process.env.ADMIN_PASSWORD
27
- const jwtSecret = process.env.JWT_SECRET || "jdshjfshdhfghdguhdfhudgsfhdjgfhdgsjfh "
28
 
29
  if (!jwtSecret) {
30
  return res.status(500).json({ error: 'Server auth not configured' })
 
5
  export class AuthController {
6
  async login(req: Request, res: Response) {
7
  try {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
  const validatedData = loginSchema.parse(req.body)
9
 
10
  const adminEmail = process.env.ADMIN_EMAIL
11
  const adminPassword = process.env.ADMIN_PASSWORD
12
+ const jwtSecret = process.env.JWT_SECRET
13
 
14
  if (!jwtSecret) {
15
  return res.status(500).json({ error: 'Server auth not configured' })
cruciqe-id-card-backend/src/controllers/StudentController.ts CHANGED
@@ -22,6 +22,17 @@ export class StudentController {
22
  }
23
  }
24
 
 
 
 
 
 
 
 
 
 
 
 
25
  async createStudent(req: Request, res: Response) {
26
  try {
27
 
 
22
  }
23
  }
24
 
25
+ async getStudentById(req: Request, res: Response) {
26
+ try {
27
+ const student = await this.studentRepository.findOne({ where: { id: req.params.id } })
28
+ if (!student) return res.status(404).json({ error: 'Student not found' })
29
+ return res.json(student)
30
+ } catch (error) {
31
+ console.error('Error fetching student:', error)
32
+ return res.status(500).json({ error: 'Failed to fetch student' })
33
+ }
34
+ }
35
+
36
  async createStudent(req: Request, res: Response) {
37
  try {
38
 
cruciqe-id-card-backend/src/database.ts CHANGED
@@ -1,11 +1,14 @@
1
  import { DataSource } from 'typeorm'
2
  import { Student } from './entities/Student.js'
 
3
 
4
  export const AppDataSource = new DataSource({
5
  type: 'sqlite',
6
  database: process.env.DB_PATH || 'dev.db',
7
  entities: [Student],
8
- synchronize: true, // Only for development
 
 
9
  logging: false,
10
  })
11
 
 
1
  import { DataSource } from 'typeorm'
2
  import { Student } from './entities/Student.js'
3
+ import { CreateStudents1760000000000 } from './migrations/1760000000000-CreateStudents.js'
4
 
5
  export const AppDataSource = new DataSource({
6
  type: 'sqlite',
7
  database: process.env.DB_PATH || 'dev.db',
8
  entities: [Student],
9
+ synchronize: false,
10
+ migrations: [CreateStudents1760000000000],
11
+ migrationsRun: true,
12
  logging: false,
13
  })
14
 
cruciqe-id-card-backend/src/index.ts CHANGED
@@ -2,7 +2,7 @@ import './config/env.js'
2
  import 'reflect-metadata'
3
  import express from 'express'
4
  import cors from 'cors'
5
- import jwt from 'jsonwebtoken'
6
  import swaggerUi from 'swagger-ui-express'
7
  import { swaggerSpec } from './config/swagger.js'
8
  import { AppDataSource } from './database.js'
@@ -12,19 +12,28 @@ import { AuthController } from './controllers/AuthController.js'
12
  import { TelegramService } from './services/TelegramService.js'
13
  import { PDFService } from './services/PDFService.js'
14
  import archiver from 'archiver'
15
- import { createWriteStream } from 'fs'
16
- import { join } from 'path'
17
- import { mkdirSync, rmSync } from 'fs'
18
- import { tmpdir } from 'os'
19
 
20
  // Debug: Show dotenv loading
21
  console.log('Current working directory:', process.cwd())
22
  console.log('NODE_ENV:', process.env.NODE_ENV)
23
 
 
 
 
 
 
 
 
24
  const app = express()
 
25
 
26
- app.use(cors({ origin: '*' }))
27
- app.use(express.json())
 
 
 
 
 
28
 
29
  /**
30
  * @swagger
@@ -147,13 +156,28 @@ app.get('/health', (_req, res) => {
147
  * error: "Server auth not configured"
148
  */
149
  app.post('/auth/login', (req, res) => {
150
- console.log('Login attempt received:', {
151
- contentType: req.headers['content-type'],
152
- hasBody: !!req.body
153
- })
154
  return authController.login(req, res)
155
  })
156
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
157
  // Initialize database
158
  console.log('Initializing database connection...')
159
  AppDataSource.initialize().then(() => {
@@ -271,7 +295,7 @@ AppDataSource.initialize().then(() => {
271
  const pdfBuffer = await pdfService.generateStudentIDCard(student)
272
 
273
  res.setHeader('Content-Type', 'application/pdf')
274
- res.setHeader('Content-Disposition', `attachment; filename="${student.firstName}_${student.lastName}_ID_Card.pdf"`)
275
  res.send(pdfBuffer)
276
  } catch (error) {
277
  console.error('PDF generation error:', error)
@@ -343,7 +367,7 @@ AppDataSource.initialize().then(() => {
343
  const pdfBuffer = await pdfService.generateStudentIDCard(student)
344
 
345
  res.setHeader('Content-Type', 'application/pdf')
346
- res.setHeader('Content-Disposition', `attachment; filename="${student.firstName}_${student.lastName}_ID_Card.pdf"`)
347
  res.send(pdfBuffer)
348
  } catch (error) {
349
  console.error('PDF generation error:', error)
@@ -402,7 +426,7 @@ AppDataSource.initialize().then(() => {
402
  */
403
  app.get('/download-department/:department', async (req, res) => {
404
  try {
405
- const department = decodeURIComponent(req.params.department)
406
  const students = await AppDataSource.getRepository(Student).find({
407
  where: { department }
408
  })
@@ -412,79 +436,38 @@ AppDataSource.initialize().then(() => {
412
  }
413
 
414
  const pdfService = new PDFService()
415
- const tempDir = join(tmpdir(), `department_${Date.now()}`)
416
- mkdirSync(tempDir, { recursive: true })
 
 
 
 
 
417
 
418
- // Generate PDFs for all students
419
  for (const student of students) {
420
  try {
421
  const pdfBuffer = await pdfService.generateStudentIDCard(student)
422
- const filename = `${student.firstName}_${student.lastName}_${student.registrationNumber}.pdf`
423
- const filepath = join(tempDir, filename)
424
-
425
- require('fs').writeFileSync(filepath, pdfBuffer)
426
  } catch (error) {
427
  console.error(`Failed to generate PDF for ${student.firstName} ${student.lastName}:`, error)
428
  }
429
  }
430
 
431
- // Create zip file
432
- const zipFilename = `${department.replace(/[^a-zA-Z0-9]/g, '_')}_ID_Cards.zip`
433
- const zipPath = join(tempDir, zipFilename)
434
-
435
- const output = createWriteStream(zipPath)
436
- const archive = archiver('zip', { zlib: { level: 9 } })
437
-
438
- archive.pipe(output)
439
-
440
- // Add all PDF files to zip
441
- const fs = require('fs')
442
- const files = fs.readdirSync(tempDir).filter((file: string) => file.endsWith('.pdf'))
443
-
444
- for (const file of files) {
445
- archive.file(join(tempDir, file), { name: file })
446
- }
447
-
448
  await archive.finalize()
449
 
450
- // Send zip file
451
- output.on('close', () => {
452
- res.setHeader('Content-Type', 'application/zip')
453
- res.setHeader('Content-Disposition', `attachment; filename="${zipFilename}"`)
454
- res.sendFile(zipPath, (err) => {
455
- // Clean up temp directory
456
- rmSync(tempDir, { recursive: true, force: true })
457
- if (err) {
458
- console.error('Error sending zip file:', err)
459
- }
460
- })
461
- })
462
-
463
  } catch (error) {
464
  console.error('Bulk download error:', error)
465
  res.status(500).json({ error: 'Failed to generate bulk download' })
466
  }
467
  })
468
 
469
- // Auth middleware
470
- app.use((req, res, next) => {
471
- if (req.path.startsWith('/students')) {
472
- const authHeader = req.headers.authorization
473
- if (!authHeader?.startsWith('Bearer ')) {
474
- return res.status(401).json({ error: 'Unauthorized' })
475
- }
476
- const token = authHeader.slice(7)
477
- const secret = process.env.JWT_SECRET
478
- if (!secret) return res.status(500).json({ error: 'Server auth not configured' })
479
- try {
480
- jwt.verify(token, secret)
481
- } catch {
482
- return res.status(401).json({ error: 'Invalid token' })
483
- }
484
- }
485
- next()
486
- })
487
-
488
  /**
489
  * @swagger
490
  * /:
@@ -508,19 +491,13 @@ AppDataSource.initialize().then(() => {
508
  * properties:
509
  * email:
510
  * type: string
511
- * example: idika1996@gmail.com omo work pls
512
  * role:
513
  * type: string
514
  * example: admin
515
  */
516
  app.get('/', (req, res) => {
517
- res.json({
518
- message: 'Login successful',
519
- user: {
520
- email: 'idika1996@gmail.com omo work pls',
521
- role: 'admin'
522
- }
523
- })
524
  })
525
 
526
  /**
@@ -648,6 +625,7 @@ AppDataSource.initialize().then(() => {
648
  * $ref: '#/components/schemas/Error'
649
  */
650
  app.get('/students', (req, res) => studentController.getAllStudents(req, res))
 
651
  app.post('/students', (req, res) => studentController.createStudent(req, res))
652
 
653
  /**
@@ -834,8 +812,6 @@ AppDataSource.initialize().then(() => {
834
  app.listen(PORT, () => {
835
  console.log(`\n✓ API listening on http://localhost:${PORT}`)
836
  console.log(`\n📚 API Documentation available at http://localhost:${PORT}/api-docs`)
837
- console.log('\nTest the server with:')
838
- console.log(`curl -X POST http://localhost:${PORT}/auth/login -H "Content-Type: application/json" -d "{\\"email\\":\\"admin@futo.edu.ng\\",\\"password\\":\\"secgen@\\"}"`)
839
  })
840
  }).catch((err) => {
841
  console.error('Failed to initialize data source', err)
 
2
  import 'reflect-metadata'
3
  import express from 'express'
4
  import cors from 'cors'
5
+ import jwt, { type JwtPayload } from 'jsonwebtoken'
6
  import swaggerUi from 'swagger-ui-express'
7
  import { swaggerSpec } from './config/swagger.js'
8
  import { AppDataSource } from './database.js'
 
12
  import { TelegramService } from './services/TelegramService.js'
13
  import { PDFService } from './services/PDFService.js'
14
  import archiver from 'archiver'
 
 
 
 
15
 
16
  // Debug: Show dotenv loading
17
  console.log('Current working directory:', process.cwd())
18
  console.log('NODE_ENV:', process.env.NODE_ENV)
19
 
20
+ if (!process.env.JWT_SECRET || process.env.JWT_SECRET.length < 32) {
21
+ throw new Error('JWT_SECRET must be configured and contain at least 32 characters')
22
+ }
23
+ if (!process.env.ADMIN_EMAIL || !process.env.ADMIN_PASSWORD) {
24
+ throw new Error('ADMIN_EMAIL and ADMIN_PASSWORD must be configured')
25
+ }
26
+
27
  const app = express()
28
+ const safeFilename = (name: string) => name.replace(/[^a-zA-Z0-9_-]/g, '_')
29
 
30
+ const allowedOrigins = (process.env.ALLOWED_ORIGINS || 'http://localhost:3000')
31
+ .split(',').map((origin) => origin.trim()).filter(Boolean)
32
+ app.use(cors({ origin: (origin, callback) => {
33
+ if (!origin || allowedOrigins.includes(origin)) return callback(null, true)
34
+ return callback(new Error('Origin is not allowed by CORS'))
35
+ } }))
36
+ app.use(express.json({ limit: '1mb' }))
37
 
38
  /**
39
  * @swagger
 
156
  * error: "Server auth not configured"
157
  */
158
  app.post('/auth/login', (req, res) => {
 
 
 
 
159
  return authController.login(req, res)
160
  })
161
 
162
+ // Everything after login is protected by default; only explicit operational
163
+ // endpoints and API documentation are public.
164
+ app.use((req, res, next) => {
165
+ if (req.path === '/health' || req.path === '/api-docs' || req.path.startsWith('/api-docs/')) return next()
166
+ const secret = process.env.JWT_SECRET
167
+ if (!secret) return res.status(500).json({ error: 'Server auth not configured' })
168
+ const authHeader = req.headers.authorization
169
+ if (!authHeader?.startsWith('Bearer ')) return res.status(401).json({ error: 'Unauthorized' })
170
+ try {
171
+ const claims = jwt.verify(authHeader.slice(7), secret, { algorithms: ['HS256'] }) as JwtPayload
172
+ if (claims.role !== 'admin' || typeof claims.email !== 'string') {
173
+ return res.status(401).json({ error: 'Invalid token' })
174
+ }
175
+ return next()
176
+ } catch {
177
+ return res.status(401).json({ error: 'Invalid token' })
178
+ }
179
+ })
180
+
181
  // Initialize database
182
  console.log('Initializing database connection...')
183
  AppDataSource.initialize().then(() => {
 
295
  const pdfBuffer = await pdfService.generateStudentIDCard(student)
296
 
297
  res.setHeader('Content-Type', 'application/pdf')
298
+ res.setHeader('Content-Disposition', `attachment; filename="${safeFilename(`${student.firstName}_${student.lastName}`)}_ID_Card.pdf"`)
299
  res.send(pdfBuffer)
300
  } catch (error) {
301
  console.error('PDF generation error:', error)
 
367
  const pdfBuffer = await pdfService.generateStudentIDCard(student)
368
 
369
  res.setHeader('Content-Type', 'application/pdf')
370
+ res.setHeader('Content-Disposition', `attachment; filename="${safeFilename(`${student.firstName}_${student.lastName}`)}_ID_Card.pdf"`)
371
  res.send(pdfBuffer)
372
  } catch (error) {
373
  console.error('PDF generation error:', error)
 
426
  */
427
  app.get('/download-department/:department', async (req, res) => {
428
  try {
429
+ const department = req.params.department
430
  const students = await AppDataSource.getRepository(Student).find({
431
  where: { department }
432
  })
 
436
  }
437
 
438
  const pdfService = new PDFService()
439
+ const zipFilename = `${department.replace(/[^a-zA-Z0-9]/g, '_')}_ID_Cards.zip`
440
+ const archive = archiver('zip', { zlib: { level: 6 } })
441
+ archive.on('error', (error) => {
442
+ console.error('ZIP archive error:', error)
443
+ if (!res.headersSent) res.status(500).json({ error: 'Failed to generate bulk download' })
444
+ else res.destroy(error)
445
+ })
446
 
447
+ let generatedCount = 0
448
  for (const student of students) {
449
  try {
450
  const pdfBuffer = await pdfService.generateStudentIDCard(student)
451
+ const filename = `${safeFilename(`${student.firstName}_${student.lastName}_${student.registrationNumber}`)}.pdf`
452
+ archive.append(pdfBuffer, { name: filename })
453
+ generatedCount += 1
 
454
  } catch (error) {
455
  console.error(`Failed to generate PDF for ${student.firstName} ${student.lastName}:`, error)
456
  }
457
  }
458
 
459
+ if (!generatedCount) return res.status(500).json({ error: 'Could not generate any student cards' })
460
+ res.setHeader('Content-Type', 'application/zip')
461
+ res.setHeader('Content-Disposition', `attachment; filename="${zipFilename}"`)
462
+ archive.pipe(res)
 
 
 
 
 
 
 
 
 
 
 
 
 
463
  await archive.finalize()
464
 
 
 
 
 
 
 
 
 
 
 
 
 
 
465
  } catch (error) {
466
  console.error('Bulk download error:', error)
467
  res.status(500).json({ error: 'Failed to generate bulk download' })
468
  }
469
  })
470
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
471
  /**
472
  * @swagger
473
  * /:
 
491
  * properties:
492
  * email:
493
  * type: string
494
+ * example: admin@example.edu
495
  * role:
496
  * type: string
497
  * example: admin
498
  */
499
  app.get('/', (req, res) => {
500
+ res.json({ message: 'Crucique API', ok: true })
 
 
 
 
 
 
501
  })
502
 
503
  /**
 
625
  * $ref: '#/components/schemas/Error'
626
  */
627
  app.get('/students', (req, res) => studentController.getAllStudents(req, res))
628
+ app.get('/students/:id', (req, res) => studentController.getStudentById(req, res))
629
  app.post('/students', (req, res) => studentController.createStudent(req, res))
630
 
631
  /**
 
812
  app.listen(PORT, () => {
813
  console.log(`\n✓ API listening on http://localhost:${PORT}`)
814
  console.log(`\n📚 API Documentation available at http://localhost:${PORT}/api-docs`)
 
 
815
  })
816
  }).catch((err) => {
817
  console.error('Failed to initialize data source', err)
cruciqe-id-card-backend/src/migrations/1760000000000-CreateStudents.ts ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import type { MigrationInterface, QueryRunner } from 'typeorm'
2
+ import { Table } from 'typeorm'
3
+
4
+ export class CreateStudents1760000000000 implements MigrationInterface {
5
+ name = 'CreateStudents1760000000000'
6
+
7
+ async up(queryRunner: QueryRunner): Promise<void> {
8
+ // Existing installs already have this table from synchronize; treat them as
9
+ // the baseline and record this migration without replacing their data.
10
+ if (await queryRunner.hasTable('students')) return
11
+
12
+ await queryRunner.createTable(new Table({
13
+ name: 'students',
14
+ columns: [
15
+ { name: 'id', type: 'varchar', isPrimary: true },
16
+ { name: 'firstName', type: 'varchar', isNullable: false },
17
+ { name: 'lastName', type: 'varchar', isNullable: false },
18
+ { name: 'registrationNumber', type: 'varchar', isUnique: true, isNullable: false },
19
+ { name: 'department', type: 'varchar', isNullable: false },
20
+ { name: 'faculty', type: 'varchar', isNullable: false },
21
+ { name: 'level', type: 'varchar', isNullable: false },
22
+ { name: 'photoUrl', type: 'text', isNullable: true },
23
+ { name: 'createdAt', type: 'datetime', default: 'CURRENT_TIMESTAMP' },
24
+ { name: 'updatedAt', type: 'datetime', default: 'CURRENT_TIMESTAMP' },
25
+ ],
26
+ }))
27
+ }
28
+
29
+ async down(queryRunner: QueryRunner): Promise<void> {
30
+ // This migration also baselines existing databases; dropping here could
31
+ // erase a table whose data predates migration tracking.
32
+ }
33
+ }
cruciqe-id-card-backend/src/schemas.ts CHANGED
@@ -1,23 +1,26 @@
1
  import { z } from 'zod'
2
 
3
  export const createStudentSchema = z.object({
4
- firstName: z.string().min(1, 'First name is required'),
5
- lastName: z.string().min(1, 'Last name is required'),
6
  registrationNumber: z.string().regex(/^\d{11}$/, 'Registration number must be exactly 11 digits'),
7
- department: z.string().min(1, 'Department is required'),
8
- faculty: z.string().min(1, 'Faculty is required'),
9
- level: z.string().min(1, 'Level is required'),
10
- photoUrl: z.string().url().optional(),
11
  })
12
 
13
  export const updateStudentSchema = z.object({
14
- firstName: z.string().min(1, 'First name is required').optional(),
15
- lastName: z.string().min(1, 'Last name is required').optional(),
16
  registrationNumber: z.string().regex(/^\d{11}$/, 'Registration number must be exactly 11 digits').optional(),
17
- department: z.string().min(1, 'Department is required').optional(),
18
- faculty: z.string().min(1, 'Faculty is required').optional(),
19
- level: z.string().min(1, 'Level is required').optional(),
20
- photoUrl: z.union([z.string().url(), z.null()]).optional(),
 
 
 
21
  })
22
 
23
  export const loginSchema = z.object({
 
1
  import { z } from 'zod'
2
 
3
  export const createStudentSchema = z.object({
4
+ firstName: z.string().trim().min(1, 'First name is required').max(100),
5
+ lastName: z.string().trim().min(1, 'Last name is required').max(100),
6
  registrationNumber: z.string().regex(/^\d{11}$/, 'Registration number must be exactly 11 digits'),
7
+ department: z.string().trim().min(1, 'Department is required').max(150),
8
+ faculty: z.string().trim().min(1, 'Faculty is required').max(150),
9
+ level: z.string().trim().min(1, 'Level is required').max(20),
10
+ photoUrl: z.string().url().refine((value) => value.startsWith('https://'), 'Photo URL must use HTTPS').optional(),
11
  })
12
 
13
  export const updateStudentSchema = z.object({
14
+ firstName: z.string().trim().min(1, 'First name is required').max(100).optional(),
15
+ lastName: z.string().trim().min(1, 'Last name is required').max(100).optional(),
16
  registrationNumber: z.string().regex(/^\d{11}$/, 'Registration number must be exactly 11 digits').optional(),
17
+ department: z.string().trim().min(1, 'Department is required').max(150).optional(),
18
+ faculty: z.string().trim().min(1, 'Faculty is required').max(150).optional(),
19
+ level: z.string().trim().min(1, 'Level is required').max(20).optional(),
20
+ photoUrl: z.union([
21
+ z.string().url().refine((value) => value.startsWith('https://'), 'Photo URL must use HTTPS'),
22
+ z.null(),
23
+ ]).optional(),
24
  })
25
 
26
  export const loginSchema = z.object({
cruciqe-id-card-backend/src/services/PDFService.ts CHANGED
@@ -1,7 +1,15 @@
1
  import puppeteer from 'puppeteer'
2
  import { jsPDF } from 'jspdf'
 
 
 
3
  import type { Student } from '../entities/Student.js'
4
 
 
 
 
 
 
5
  export class PDFService {
6
  async generateStudentIDCard(student: Student): Promise<Buffer> {
7
  const browser = await puppeteer.launch({
@@ -13,7 +21,7 @@ export class PDFService {
13
  const page = await browser.newPage()
14
 
15
  // Set viewport to match card dimensions
16
- await page.setViewport({ width: 227, height: 340 })
17
 
18
  // Generate front card
19
  const frontHtml = this.generateCardHTML(student)
@@ -22,7 +30,7 @@ export class PDFService {
22
  // Take screenshot of the front card
23
  const frontScreenshot = await page.screenshot({
24
  type: 'png',
25
- clip: { x: 0, y: 0, width: 227, height: 340 }
26
  })
27
 
28
  // Generate back card
@@ -32,14 +40,14 @@ export class PDFService {
32
  // Take screenshot of the back card
33
  const backScreenshot = await page.screenshot({
34
  type: 'png',
35
- clip: { x: 0, y: 0, width: 227, height: 340 }
36
  })
37
 
38
  // Create PDF
39
  const pdf = new jsPDF({
40
  orientation: 'portrait',
41
  unit: 'mm',
42
- format: [60, 90] // Card dimensions in mm (6cm x 9cm)
43
  })
44
 
45
  // Convert screenshots to base64
@@ -47,11 +55,11 @@ export class PDFService {
47
  const backImageData = `data:image/png;base64,${Buffer.from(backScreenshot).toString('base64')}`
48
 
49
  // Add front image to PDF
50
- pdf.addImage(frontImageData, 'PNG', 0, 0, 60, 90)
51
 
52
  // Add back page
53
  pdf.addPage()
54
- pdf.addImage(backImageData, 'PNG', 0, 0, 60, 90)
55
 
56
  return Buffer.from(pdf.output('arraybuffer'))
57
  } finally {
@@ -60,356 +68,62 @@ export class PDFService {
60
  }
61
 
62
  private generateCardHTML(student: Student): string {
63
- return `
64
- <!DOCTYPE html>
65
- <html>
66
- <head>
67
- <meta charset="utf-8">
68
- <title>Student ID Card</title>
69
- <style>
70
- * {
71
- margin: 0;
72
- padding: 0;
73
- box-sizing: border-box;
74
- }
75
- body {
76
- font-family: Arial, sans-serif;
77
- background: #f3f4f6;
78
- display: flex;
79
- justify-content: center;
80
- align-items: center;
81
- min-height: 100vh;
82
- padding: 32px;
83
- }
84
- .card {
85
- width: 227px;
86
- height: 340px;
87
- background: white;
88
- border-radius: 8px;
89
- box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25);
90
- overflow: hidden;
91
- position: relative;
92
- }
93
- .header {
94
- background: white;
95
- padding: 8px;
96
- padding-bottom: 4px;
97
- }
98
- .logo-section {
99
- display: flex;
100
- align-items: center;
101
- justify-content: center;
102
- gap: 8px;
103
- margin-bottom: 4px;
104
- }
105
- .logos {
106
- display: flex;
107
- gap: 8px;
108
- }
109
- .logo {
110
- width: 24px;
111
- height: 24px;
112
- border-radius: 50%;
113
- overflow: hidden;
114
- box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
115
- }
116
- .logo img {
117
- width: 100%;
118
- height: 100%;
119
- object-fit: cover;
120
- }
121
- .university-info {
122
- border-bottom: 1px solid black;
123
- padding-bottom: 4px;
124
- }
125
- .university-title {
126
- font-size: 10px;
127
- font-weight: 900;
128
- line-height: 1.2;
129
- margin-bottom: 0;
130
- text-align: center;
131
- }
132
- .university-subtitle {
133
- font-size: 8px;
134
- font-weight: 700;
135
- margin-top: 0;
136
- text-align: center;
137
- }
138
- .student-union {
139
- font-size: 8px;
140
- font-weight: 900;
141
- color: #2563eb;
142
- text-decoration: underline;
143
- margin-top: 0;
144
- text-align: center;
145
- }
146
- .main-body {
147
- position: relative;
148
- height: 305px;
149
- overflow: hidden;
150
- }
151
- .background-gradient {
152
- position: absolute;
153
- inset: 0;
154
- background: linear-gradient(to bottom, #2563eb, #1d4ed8, #1e3a8a);
155
- }
156
- .watermark {
157
- position: absolute;
158
- inset: 0;
159
- opacity: 0.1;
160
- z-index: 0;
161
- }
162
- .watermark-center {
163
- position: absolute;
164
- top: 50%;
165
- left: 50%;
166
- transform: translate(-50%, -50%);
167
- width: 128px;
168
- height: 128px;
169
- }
170
- .watermark img {
171
- width: 100%;
172
- height: 100%;
173
- object-fit: contain;
174
- }
175
- .identity-label {
176
- position: absolute;
177
- top: 8px;
178
- right: 8px;
179
- background: #1e3a8a;
180
- border-radius: 4px;
181
- padding: 8px;
182
- box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
183
- z-index: 10;
184
- }
185
- .identity-content {
186
- display: flex;
187
- align-items: center;
188
- }
189
- .identity-text {
190
- color: white;
191
- font-size: 8px;
192
- font-weight: 900;
193
- line-height: 1.2;
194
- }
195
- .identity-divider {
196
- width: 1px;
197
- height: 12px;
198
- background: white;
199
- margin: 0 4px;
200
- }
201
- .photo-section {
202
- position: absolute;
203
- top: 32px;
204
- left: 16px;
205
- z-index: 10;
206
- }
207
- .photo-container {
208
- position: relative;
209
- }
210
- .photo-circle {
211
- width: 70px;
212
- height: 70px;
213
- border-radius: 50%;
214
- border: 2px solid white;
215
- box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
216
- overflow: hidden;
217
- }
218
- .photo-circle img {
219
- width: 100%;
220
- height: 100%;
221
- object-fit: cover;
222
- }
223
- .photo-placeholder {
224
- width: 100%;
225
- height: 100%;
226
- background: rgba(255, 255, 255, 0.2);
227
- display: flex;
228
- align-items: center;
229
- justify-content: center;
230
- font-size: 18px;
231
- color: white;
232
- }
233
- .student-info {
234
- position: absolute;
235
- bottom: 32px;
236
- left: 16px;
237
- right: 16px;
238
- z-index: 10;
239
- }
240
- .info-label {
241
- display: inline-block;
242
- background: linear-gradient(to right, #f97316, #fb923c);
243
- padding: 2px 8px;
244
- border-radius: 3px;
245
- margin-bottom: 4px;
246
- }
247
- .label-text {
248
- color: white;
249
- font-weight: bold;
250
- font-size: 8px;
251
- letter-spacing: 0.05em;
252
- }
253
- .student-name {
254
- margin-bottom: 8px;
255
- }
256
- .name-line {
257
- color: white;
258
- font-size: 10px;
259
- font-weight: 900;
260
- line-height: 1.2;
261
- letter-spacing: 0.05em;
262
- }
263
- .reg-number {
264
- margin-bottom: 8px;
265
- }
266
- .reg-text {
267
- color: white;
268
- font-size: 9px;
269
- font-weight: 900;
270
- letter-spacing: 0.1em;
271
- }
272
- .dept-text {
273
- color: white;
274
- font-size: 9px;
275
- font-weight: 900;
276
- line-height: 1.2;
277
- letter-spacing: 0.05em;
278
- }
279
- .qr-section {
280
- position: absolute;
281
- bottom: 8px;
282
- right: 8px;
283
- z-index: 10;
284
- }
285
- .qr-container {
286
- background: white;
287
- padding: 4px;
288
- border-radius: 4px;
289
- box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
290
- }
291
- .qr-code {
292
- width: 30px;
293
- height: 30px;
294
- background: white;
295
- border-radius: 3px;
296
- overflow: hidden;
297
- }
298
- .qr-code img {
299
- width: 100%;
300
- height: 100%;
301
- object-fit: cover;
302
- }
303
- </style>
304
- </head>
305
- <body>
306
- <div class="card">
307
- <!-- Header Section -->
308
- <div class="header">
309
- <div class="logo-section">
310
- <div class="logos">
311
- <div class="logo">
312
- <img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==" alt="FUTO Logo" />
313
- </div>
314
- <div class="logo">
315
- <img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==" alt="AC Logo" />
316
- </div>
317
- <div class="logo">
318
- <img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==" alt="AS Logo" />
319
- </div>
320
- </div>
321
- </div>
322
-
323
- <div class="university-info">
324
- <h1 class="university-title">FEDERAL UNIVERSITY OF TECHNOLOGY</h1>
325
- <h1 class="university-title">OWERRI</h1>
326
- <p class="university-subtitle">P.M.B 1526 OWERRI, IMO STATE</p>
327
- <p class="student-union">STUDENT UNION GOVERNMENT</p>
328
- </div>
329
- </div>
330
 
331
- <!-- Main Card Body -->
332
- <div class="main-body">
333
- <!-- Background gradient -->
334
- <div class="background-gradient"></div>
335
-
336
- <!-- AC Logo Watermark -->
337
- <div class="watermark">
338
- <div class="watermark-center">
339
- <img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==" alt="AC Watermark" />
340
- </div>
341
- </div>
342
-
343
- <!-- Student Identity Card Label -->
344
- <div class="identity-label">
345
- <div class="identity-content">
346
- <h2 class="identity-text">STUDENT</h2>
347
- <div class="identity-divider"></div>
348
- <div>
349
- <h2 class="identity-text">IDENTITY</h2>
350
- <h2 class="identity-text">CARD</h2>
351
- </div>
352
- </div>
353
- </div>
354
-
355
- <!-- Photo Circle -->
356
- <div class="photo-section">
357
- <div class="photo-container">
358
- <div class="photo-circle">
359
- ${student.photoUrl ?
360
- `<img src="${student.photoUrl}" alt="${student.firstName} ${student.lastName}" />` :
361
- `<div class="photo-placeholder">👤</div>`
362
- }
363
- </div>
364
- </div>
365
- </div>
366
-
367
- <!-- Student Information -->
368
- <div class="student-info">
369
- <!-- Name Label -->
370
- <div class="info-label">
371
- <span class="label-text">NAME:</span>
372
- </div>
373
-
374
- <!-- Name -->
375
- <div class="student-name">
376
- <div class="name-line">${student.firstName.toUpperCase()} ${student.lastName.toUpperCase()}</div>
377
- </div>
378
-
379
- <!-- Registration Number Label -->
380
- <div class="info-label">
381
- <span class="label-text">REG NO:</span>
382
- </div>
383
-
384
- <!-- Registration Number -->
385
- <div class="reg-number">
386
- <div class="reg-text">${student.registrationNumber}</div>
387
- </div>
388
-
389
- <!-- Department Label -->
390
- <div class="info-label">
391
- <span class="label-text">DEPT:</span>
392
- </div>
393
-
394
- <!-- Department -->
395
- <div>
396
- <div class="dept-text">${student.department.toUpperCase()}</div>
397
- </div>
398
- </div>
399
-
400
- <!-- QR Code -->
401
- <div class="qr-section">
402
- <div class="qr-container">
403
- <div class="qr-code">
404
- <img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==" alt="QR Code" />
405
- </div>
406
- </div>
407
- </div>
408
- </div>
409
- </div>
410
- </body>
411
- </html>
412
- `
413
  }
414
 
415
  private generateBackCardHTML(): string {
@@ -427,16 +141,15 @@ export class PDFService {
427
  }
428
  body {
429
  font-family: Arial, sans-serif;
430
- background: #f3f4f6;
431
- display: flex;
432
- justify-content: center;
433
- align-items: center;
434
- min-height: 100vh;
435
- padding: 32px;
436
  }
437
  .card {
438
- width: 227px;
439
- height: 340px;
440
  background: white;
441
  border-radius: 8px;
442
  box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25);
 
1
  import puppeteer from 'puppeteer'
2
  import { jsPDF } from 'jspdf'
3
+ import { readFileSync } from 'fs'
4
+ import { dirname, join } from 'path'
5
+ import { fileURLToPath } from 'url'
6
  import type { Student } from '../entities/Student.js'
7
 
8
+ const htmlEscapes: Record<string, string> = {
9
+ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;',
10
+ }
11
+ const escapeHtml = (value: string) => value.replace(/[&<>"']/g, (char) => htmlEscapes[char])
12
+
13
  export class PDFService {
14
  async generateStudentIDCard(student: Student): Promise<Buffer> {
15
  const browser = await puppeteer.launch({
 
21
  const page = await browser.newPage()
22
 
23
  // Set viewport to match card dimensions
24
+ await page.setViewport({ width: 400, height: 640 })
25
 
26
  // Generate front card
27
  const frontHtml = this.generateCardHTML(student)
 
30
  // Take screenshot of the front card
31
  const frontScreenshot = await page.screenshot({
32
  type: 'png',
33
+ clip: { x: 0, y: 0, width: 400, height: 640 }
34
  })
35
 
36
  // Generate back card
 
40
  // Take screenshot of the back card
41
  const backScreenshot = await page.screenshot({
42
  type: 'png',
43
+ clip: { x: 0, y: 0, width: 400, height: 640 }
44
  })
45
 
46
  // Create PDF
47
  const pdf = new jsPDF({
48
  orientation: 'portrait',
49
  unit: 'mm',
50
+ format: [60, 96]
51
  })
52
 
53
  // Convert screenshots to base64
 
55
  const backImageData = `data:image/png;base64,${Buffer.from(backScreenshot).toString('base64')}`
56
 
57
  // Add front image to PDF
58
+ pdf.addImage(frontImageData, 'PNG', 0, 0, 60, 96)
59
 
60
  // Add back page
61
  pdf.addPage()
62
+ pdf.addImage(backImageData, 'PNG', 0, 0, 60, 96)
63
 
64
  return Buffer.from(pdf.output('arraybuffer'))
65
  } finally {
 
68
  }
69
 
70
  private generateCardHTML(student: Student): string {
71
+ const logoPath = join(dirname(fileURLToPath(import.meta.url)), '../assets/aluta-mandate-logos.png')
72
+ const logos = `data:image/png;base64,${readFileSync(logoPath).toString('base64')}`
73
+ const fullName = escapeHtml(`${student.firstName} ${student.lastName}`.trim().toUpperCase())
74
+ const photo = student.photoUrl
75
+ ? `<img class="photo" src="${escapeHtml(student.photoUrl)}" alt="${fullName}" />`
76
+ : '<div class="photo photo-placeholder"></div>'
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
77
 
78
+ return `<!doctype html>
79
+ <html><head><meta charset="utf-8"><style>
80
+ * { box-sizing: border-box; }
81
+ @page { size: 400px 640px; margin: 0; }
82
+ html, body { width: 400px; height: 640px; margin: 0; padding: 0; }
83
+ body { font-family: Arial, Helvetica, sans-serif; }
84
+ .card { position: relative; width: 400px; height: 640px; overflow: hidden; background: #fff; }
85
+ .shape { position: absolute; inset: 0; width: 100%; height: 100%; }
86
+ .heading { position: absolute; z-index: 1; top: 5%; left: 7%; width: 86%; color: #090909; text-align: center; font-size: 8px; font-weight: 800; line-height: 1.12; }
87
+ .heading img { display: block; width: 26%; height: auto; margin: 0 auto; }
88
+ .rule { height: 1.5px; margin: 0 0 5px; background: #111; }
89
+ .heading p { margin: 0; }
90
+ .short-rule { width: 67%; margin: 6px auto 0; }
91
+ .title { position: absolute; z-index: 1; top: 18.5%; left: 2%; width: 96%; margin: 0; color: #080808; text-align: center; font-size: 19px; font-weight: 900; letter-spacing: -0.045em; line-height: 1; }
92
+ .photo-frame { position: absolute; z-index: 2; top: 23.4%; left: 23.5%; width: 53%; height: 28.5%; overflow: hidden; border: 5px solid #fff; border-radius: 22px; background: #60300f; }
93
+ .photo { display: block; width: 100%; height: 100%; object-fit: cover; }
94
+ .details { position: absolute; z-index: 2; top: 54.5%; left: 13%; width: 68%; height: 43%; color: #fff; }
95
+ .field { position: absolute; left: 0; width: 100%; overflow: hidden; border-bottom: 1px solid rgba(255,255,255,.9); color: #fff; }
96
+ .label { display: table; margin-bottom: 6px; padding-bottom: 2px; border-bottom: 1px solid #fff; font-size: 10px; font-weight: 700; line-height: 1; }
97
+ .value { display: block; overflow-wrap: anywhere; font-size: 21px; font-weight: 900; line-height: .96; text-transform: uppercase; }
98
+ .name { top: 0; height: 36%; } .name .value { font-size: 26px; }
99
+ .registration { top: 39%; height: 12%; } .registration .value { font-size: 23px; }
100
+ .department { top: 53%; height: 20%; } .department .value { font-size: 20px; }
101
+ .faculty { top: 78%; height: 22%; border: 0; } .faculty .value { font-size: 16px; }
102
+ </style></head><body>
103
+ <main class="card">
104
+ <svg class="shape" viewBox="0 0 400 640" preserveAspectRatio="none" aria-hidden="true">
105
+ <defs><linearGradient id="aluta-brown" x1="0" y1="0" x2="0" y2="1"><stop offset="0%" stop-color="#371805" /><stop offset="100%" stop-color="#291000" /></linearGradient></defs>
106
+ <path d="M0 316 C164 316 251 329 316 303 C357 287 383 267 400 246 L400 640 L0 640 Z" fill="url(#aluta-brown)" />
107
+ <path d="M0 316 C164 316 251 329 316 303 C357 287 383 267 400 246" fill="none" stroke="#6d5745" stroke-width="2" />
108
+ </svg>
109
+ <header class="heading">
110
+ <img src="${logos}" alt="FUTO, Aluta Continuity, and Aluta Mandate logos" />
111
+ <div class="rule"></div>
112
+ <p>FEDERAL UNIVERSITY OF TECHNOLOGY, OWERRI</p>
113
+ <p>STUDENTS’ UNION GOVERNMENT (SUG)</p>
114
+ <p>ALUTA MANDATE EXECUTIVES</p>
115
+ <div class="rule short-rule"></div>
116
+ </header>
117
+ <h1 class="title">STUDENT IDENTITY CARD</h1>
118
+ <div class="photo-frame">${photo}</div>
119
+ <section class="details">
120
+ <div class="field name"><span class="label">STUDENT’S NAME:</span><strong class="value">${fullName}</strong></div>
121
+ <div class="field registration"><span class="label">STUDENT’S REG NO:</span><strong class="value">${escapeHtml(student.registrationNumber)}</strong></div>
122
+ <div class="field department"><span class="label">STUDENT’S DEPARTMENT:</span><strong class="value">${escapeHtml(student.department.toUpperCase())}</strong></div>
123
+ <div class="field faculty"><span class="label">STUDENT’S SCHOOL/FACULTY:</span><strong class="value">${escapeHtml(student.faculty.toUpperCase())}</strong></div>
124
+ </section>
125
+ </main>
126
+ </body></html>`
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
127
  }
128
 
129
  private generateBackCardHTML(): string {
 
141
  }
142
  body {
143
  font-family: Arial, sans-serif;
144
+ background: white;
145
+ width: 400px;
146
+ height: 640px;
147
+ margin: 0;
148
+ padding: 0;
 
149
  }
150
  .card {
151
+ width: 400px;
152
+ height: 640px;
153
  background: white;
154
  border-radius: 8px;
155
  box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25);
package-lock.json ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ {
2
+ "name": "crucique",
3
+ "lockfileVersion": 3,
4
+ "requires": true,
5
+ "packages": {}
6
+ }