From eea3a46801ea7e4168f3e24c0e600ce353ba981d Mon Sep 17 00:00:00 2001 From: AhmedFatthy1040 Date: Thu, 28 Nov 2024 20:23:07 +0200 Subject: [PATCH 1/8] chore(deps): add authentication and CORS dependencies chore(types): add TypeScript types for new dependencies --- api/package.json | 3 + package-lock.json | 151 ++++++++++++++++++++++++++++++++++++++++++++-- package.json | 6 +- 3 files changed, 154 insertions(+), 6 deletions(-) diff --git a/api/package.json b/api/package.json index 6e6a6b5..8f21432 100644 --- a/api/package.json +++ b/api/package.json @@ -18,6 +18,7 @@ "@types/multer": "^1.4.12", "@types/node": "^22.9.1", "bcrypt": "^5.1.1", + "cors": "^2.8.5", "dotenv": "^16.4.5", "express": "^4.21.1", "jsonwebtoken": "^9.0.2", @@ -28,6 +29,8 @@ "typescript": "^5.6.3" }, "devDependencies": { + "@types/bcrypt": "^5.0.2", + "@types/cors": "^2.8.17", "@types/jsonwebtoken": "^9.0.7", "@types/pg": "^8.11.10", "ts-node-dev": "^2.0.0" diff --git a/package-lock.json b/package-lock.json index fbda9d4..99a9e40 100644 --- a/package-lock.json +++ b/package-lock.json @@ -5,7 +5,11 @@ "packages": { "": { "dependencies": { - "@prisma/client": "^5.22.0" + "@prisma/client": "^5.22.0", + "@types/bcryptjs": "^2.4.6", + "@types/jsonwebtoken": "^9.0.7", + "bcryptjs": "^2.4.3", + "jsonwebtoken": "^9.0.2" }, "devDependencies": { "@commitlint/cli": "^19.6.0", @@ -365,6 +369,12 @@ "@prisma/debug": "5.22.0" } }, + "node_modules/@types/bcryptjs": { + "version": "2.4.6", + "resolved": "https://registry.npmjs.org/@types/bcryptjs/-/bcryptjs-2.4.6.tgz", + "integrity": "sha512-9xlo6R2qDs5uixm0bcIqCeMCE6HiQsIyel9KQySStiyqNl2tnj2mP3DX1Nf56MD6KMenNNlBBsy3LJ7gUEQPXQ==", + "license": "MIT" + }, "node_modules/@types/conventional-commits-parser": { "version": "5.0.0", "resolved": "https://registry.npmjs.org/@types/conventional-commits-parser/-/conventional-commits-parser-5.0.0.tgz", @@ -375,11 +385,19 @@ "@types/node": "*" } }, + "node_modules/@types/jsonwebtoken": { + "version": "9.0.7", + "resolved": "https://registry.npmjs.org/@types/jsonwebtoken/-/jsonwebtoken-9.0.7.tgz", + "integrity": "sha512-ugo316mmTYBl2g81zDFnZ7cfxlut3o+/EQdaP7J8QN2kY6lJ22hmQYCK5EHcJHbrW+dkCGSCPgbG8JtYj6qSrg==", + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, "node_modules/@types/node": { "version": "22.9.1", "resolved": "https://registry.npmjs.org/@types/node/-/node-22.9.1.tgz", "integrity": "sha512-p8Yy/8sw1caA8CdRIQBG5tiLHmxtQKObCijiAa9Ez+d4+PRffM4054xbju0msf+cvhJpnFEeNjxmVT/0ipktrg==", - "dev": true, "license": "MIT", "dependencies": { "undici-types": "~6.19.8" @@ -454,6 +472,18 @@ "dev": true, "license": "MIT" }, + "node_modules/bcryptjs": { + "version": "2.4.3", + "resolved": "https://registry.npmjs.org/bcryptjs/-/bcryptjs-2.4.3.tgz", + "integrity": "sha512-V/Hy/X9Vt7f3BbPJEi8BdVFMByHi+jNXrYkW3huaybV/kQ0KJg0Y6PkEMbn+zeT+i+SiKZ/HMqJGIIt4LZDqNQ==", + "license": "MIT" + }, + "node_modules/buffer-equal-constant-time": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/buffer-equal-constant-time/-/buffer-equal-constant-time-1.0.1.tgz", + "integrity": "sha512-zRpUiDwd/xk6ADqPMATG8vc9VPrkck7T07OIx0gnjmJAnHnTVXNQG3vfvWNuiZIkwu9KrKdA1iJKfsfTVxE6NA==", + "license": "BSD-3-Clause" + }, "node_modules/callsites": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/callsites/-/callsites-3.1.0.tgz", @@ -639,6 +669,15 @@ "node": ">=8" } }, + "node_modules/ecdsa-sig-formatter": { + "version": "1.0.11", + "resolved": "https://registry.npmjs.org/ecdsa-sig-formatter/-/ecdsa-sig-formatter-1.0.11.tgz", + "integrity": "sha512-nagl3RYrbNv6kQkeJIpt6NJZy8twLB/2vtz6yN9Z4vRKHN4/QZJIEbqohALSgwKdnksuY3k5Addp5lg8sVoVcQ==", + "license": "Apache-2.0", + "dependencies": { + "safe-buffer": "^5.0.1" + } + }, "node_modules/emoji-regex": { "version": "8.0.0", "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", @@ -942,6 +981,49 @@ "node": "*" } }, + "node_modules/jsonwebtoken": { + "version": "9.0.2", + "resolved": "https://registry.npmjs.org/jsonwebtoken/-/jsonwebtoken-9.0.2.tgz", + "integrity": "sha512-PRp66vJ865SSqOlgqS8hujT5U4AOgMfhrwYIuIhfKaoSCZcirrmASQr8CX7cUg+RMih+hgznrjp99o+W4pJLHQ==", + "license": "MIT", + "dependencies": { + "jws": "^3.2.2", + "lodash.includes": "^4.3.0", + "lodash.isboolean": "^3.0.3", + "lodash.isinteger": "^4.0.4", + "lodash.isnumber": "^3.0.3", + "lodash.isplainobject": "^4.0.6", + "lodash.isstring": "^4.0.1", + "lodash.once": "^4.0.0", + "ms": "^2.1.1", + "semver": "^7.5.4" + }, + "engines": { + "node": ">=12", + "npm": ">=6" + } + }, + "node_modules/jwa": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/jwa/-/jwa-1.4.1.tgz", + "integrity": "sha512-qiLX/xhEEFKUAJ6FiBMbes3w9ATzyk5W7Hvzpa/SLYdxNtng+gcurvrI7TbACjIXlsJyr05/S1oUhZrc63evQA==", + "license": "MIT", + "dependencies": { + "buffer-equal-constant-time": "1.0.1", + "ecdsa-sig-formatter": "1.0.11", + "safe-buffer": "^5.0.1" + } + }, + "node_modules/jws": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/jws/-/jws-3.2.2.tgz", + "integrity": "sha512-YHlZCB6lMTllWDtSPHz/ZXTsi8S00usEV6v1tjq8tOUZzw7DpSDWVXjXDre6ed1w/pd495ODpHZYSdkRTsa0HA==", + "license": "MIT", + "dependencies": { + "jwa": "^1.4.1", + "safe-buffer": "^5.0.1" + } + }, "node_modules/lines-and-columns": { "version": "1.2.4", "resolved": "https://registry.npmjs.org/lines-and-columns/-/lines-and-columns-1.2.4.tgz", @@ -972,11 +1054,40 @@ "dev": true, "license": "MIT" }, + "node_modules/lodash.includes": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/lodash.includes/-/lodash.includes-4.3.0.tgz", + "integrity": "sha512-W3Bx6mdkRTGtlJISOvVD/lbqjTlPPUDTMnlXZFnVwi9NKJ6tiAk6LVdlhZMm17VZisqhKcgzpO5Wz91PCt5b0w==", + "license": "MIT" + }, + "node_modules/lodash.isboolean": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/lodash.isboolean/-/lodash.isboolean-3.0.3.tgz", + "integrity": "sha512-Bz5mupy2SVbPHURB98VAcw+aHh4vRV5IPNhILUCsOzRmsTmSQ17jIuqopAentWoehktxGd9e/hbIXq980/1QJg==", + "license": "MIT" + }, + "node_modules/lodash.isinteger": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/lodash.isinteger/-/lodash.isinteger-4.0.4.tgz", + "integrity": "sha512-DBwtEWN2caHQ9/imiNeEA5ys1JoRtRfY3d7V9wkqtbycnAmTvRRmbHKDV4a0EYc678/dia0jrte4tjYwVBaZUA==", + "license": "MIT" + }, + "node_modules/lodash.isnumber": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/lodash.isnumber/-/lodash.isnumber-3.0.3.tgz", + "integrity": "sha512-QYqzpfwO3/CWf3XP+Z+tkQsfaLL/EnUlXWVkIk5FUPc4sBdTehEqZONuyRt2P67PXAk+NXmTBcc97zw9t1FQrw==", + "license": "MIT" + }, "node_modules/lodash.isplainobject": { "version": "4.0.6", "resolved": "https://registry.npmjs.org/lodash.isplainobject/-/lodash.isplainobject-4.0.6.tgz", "integrity": "sha512-oSXzaWypCMHkPC3NvBEaPHf0KsA5mvPrOPgQWDsbg8n7orZ290M0BmC/jgRZ4vcJ6DTAhjrsSYgdsW/F+MFOBA==", - "dev": true, + "license": "MIT" + }, + "node_modules/lodash.isstring": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/lodash.isstring/-/lodash.isstring-4.0.1.tgz", + "integrity": "sha512-0wJxfxH1wgO3GrbuP+dTTk7op+6L41QCXbGINEmD+ny/G/eCqGzxyCsh7159S+mgDDcoarnBw6PC1PS5+wUGgw==", "license": "MIT" }, "node_modules/lodash.kebabcase": { @@ -1000,6 +1111,12 @@ "dev": true, "license": "MIT" }, + "node_modules/lodash.once": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/lodash.once/-/lodash.once-4.1.1.tgz", + "integrity": "sha512-Sb487aTOCr9drQVL8pIxOzVhafOjZN9UU54hiN8PU3uAiSV7lx1yYNpbNmex2PK6dSJoNTSJUUswT651yww3Mg==", + "license": "MIT" + }, "node_modules/lodash.snakecase": { "version": "4.1.1", "resolved": "https://registry.npmjs.org/lodash.snakecase/-/lodash.snakecase-4.1.1.tgz", @@ -1051,6 +1168,12 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "license": "MIT" + }, "node_modules/obuf": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/obuf/-/obuf-1.1.2.tgz", @@ -1285,11 +1408,30 @@ "node": ">=8" } }, + "node_modules/safe-buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, "node_modules/semver": { "version": "7.6.3", "resolved": "https://registry.npmjs.org/semver/-/semver-7.6.3.tgz", "integrity": "sha512-oVekP1cKtI+CTDvHWYFUcMtsK/00wmAEfyqKfNdARm8u1wNVhSgaX7A8d4UuIlUI5e84iEwOhs7ZPYRmzU9U6A==", - "dev": true, "license": "ISC", "bin": { "semver": "bin/semver.js" @@ -1382,7 +1524,6 @@ "version": "6.19.8", "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.19.8.tgz", "integrity": "sha512-ve2KP6f/JnbPBFyobGHuerC9g1FYGn/F8n1LWTwNxCEzd6IfqTwUQcNXgEtmmQ6DlRrC1hrSrBnCZPokRrDHjw==", - "dev": true, "license": "MIT" }, "node_modules/unicorn-magic": { diff --git a/package.json b/package.json index a30a279..4bea433 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,10 @@ { "dependencies": { - "@prisma/client": "^5.22.0" + "@prisma/client": "^5.22.0", + "@types/bcryptjs": "^2.4.6", + "@types/jsonwebtoken": "^9.0.7", + "bcryptjs": "^2.4.3", + "jsonwebtoken": "^9.0.2" }, "devDependencies": { "@commitlint/cli": "^19.6.0", From 67fcf59447ade0b3beb5dcc6881d5aff04cd8780 Mon Sep 17 00:00:00 2001 From: AhmedFatthy1040 Date: Thu, 28 Nov 2024 20:26:55 +0200 Subject: [PATCH 2/8] feat(auth): implement password hashing and token validation --- api/src/services/authService.ts | 78 +++++++++++++++++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 api/src/services/authService.ts diff --git a/api/src/services/authService.ts b/api/src/services/authService.ts new file mode 100644 index 0000000..a1adff3 --- /dev/null +++ b/api/src/services/authService.ts @@ -0,0 +1,78 @@ +import bcrypt from 'bcrypt'; +import jwt from 'jsonwebtoken'; +import pool from '../config/db'; +import { User, UserResponse } from '../models/user'; + +export class AuthService { + private static readonly JWT_SECRET = process.env.JWT_SECRET || 'your-secret-key'; + private static readonly SALT_ROUNDS = 10; + + static async registerUser(username: string, email: string, password: string): Promise { + // Check if user already exists + const existingUser = await pool.query( + 'SELECT * FROM users WHERE email = $1 OR username = $2', + [email, username] + ); + + if (existingUser.rows.length > 0) { + throw new Error('User with this email or username already exists'); + } + + // Hash password + const hashedPassword = await bcrypt.hash(password, this.SALT_ROUNDS); + + // Insert new user + const query = ` + INSERT INTO users (username, email, password, created_at) + VALUES ($1, $2, $3, NOW()) + RETURNING id, username, email, created_at as "createdAt" + `; + + const result = await pool.query(query, [username, email, hashedPassword]); + return result.rows[0]; + } + + static async loginUser(email: string, password: string): Promise<{ user: UserResponse; token: string }> { + // Find user + const result = await pool.query( + 'SELECT * FROM users WHERE email = $1', + [email] + ); + + const user = result.rows[0]; + if (!user) { + throw new Error('User not found'); + } + + // Verify password + const isValidPassword = await bcrypt.compare(password, user.password); + if (!isValidPassword) { + throw new Error('Invalid password'); + } + + // Generate JWT token + const token = jwt.sign( + { userId: user.id, email: user.email }, + this.JWT_SECRET, + { expiresIn: '24h' } + ); + + // Return user data (excluding password) and token + const userResponse: UserResponse = { + id: user.id, + username: user.username, + email: user.email, + createdAt: user.created_at + }; + + return { user: userResponse, token }; + } + + static verifyToken(token: string): { userId: number; email: string } { + try { + return jwt.verify(token, this.JWT_SECRET) as { userId: number; email: string }; + } catch (error) { + throw new Error('Invalid token'); + } + } +} From 2a39f6ddbeccb9a38a825278ccbc5ac27035b298 Mon Sep 17 00:00:00 2001 From: AhmedFatthy1040 Date: Thu, 28 Nov 2024 20:27:12 +0200 Subject: [PATCH 3/8] feat(api): add protected route middleware --- api/src/routes/authRoutes.ts | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 api/src/routes/authRoutes.ts diff --git a/api/src/routes/authRoutes.ts b/api/src/routes/authRoutes.ts new file mode 100644 index 0000000..90bb667 --- /dev/null +++ b/api/src/routes/authRoutes.ts @@ -0,0 +1,15 @@ +import { Router, Request, Response } from 'express'; +import { AuthController } from '../controllers/authController'; + +const router = Router(); + +// Explicitly type the route handlers as RequestHandler +router.post('/register', async (req: Request, res: Response) => { + await AuthController.register(req, res); +}); + +router.post('/login', async (req: Request, res: Response) => { + await AuthController.login(req, res); +}); + +export default router; From dc436d4b1ff154ac8227512522a870df36266303 Mon Sep 17 00:00:00 2001 From: AhmedFatthy1040 Date: Thu, 28 Nov 2024 20:28:03 +0200 Subject: [PATCH 4/8] feat(api): update app configuration for auth routes feat(cors): add CORS configuration for frontend requests --- api/src/app.ts | 16 +++++++++++++++- app/package-lock.json | 26 +++++++++++++++++++++++--- 2 files changed, 38 insertions(+), 4 deletions(-) diff --git a/api/src/app.ts b/api/src/app.ts index 6c691b2..84dafef 100644 --- a/api/src/app.ts +++ b/api/src/app.ts @@ -1,11 +1,25 @@ import express from 'express'; +import cors from 'cors'; import imageRoutes from "./routes/imageRoutes"; +import authRoutes from "./routes/authRoutes"; +import { authenticateToken } from './middlewares/authMiddleware'; const app = express(); +// Enable CORS for frontend requests +app.use(cors({ + origin: 'http://localhost:3000', // Your frontend URL + credentials: true +})); + app.use(express.json()); app.use(express.urlencoded({ extended: true })); -app.use("/api/images", imageRoutes); +// Public routes +app.use("/api/auth", authRoutes); + +// Protected routes - ensure authenticateToken is applied to all image routes +app.use("/api/images", authenticateToken); // Add authentication middleware first +app.use("/api/images", imageRoutes); // Then add the routes export default app; diff --git a/app/package-lock.json b/app/package-lock.json index 2a8c55f..f424448 100644 --- a/app/package-lock.json +++ b/app/package-lock.json @@ -8,6 +8,7 @@ "name": "app", "version": "0.1.0", "dependencies": { + "@babel/plugin-proposal-private-property-in-object": "^7.16.7", "@testing-library/jest-dom": "^5.17.0", "@testing-library/react": "^13.4.0", "@testing-library/user-event": "^13.5.0", @@ -672,10 +673,17 @@ } }, "node_modules/@babel/plugin-proposal-private-property-in-object": { - "version": "7.21.0-placeholder-for-preset-env.2", - "resolved": "https://registry.npmjs.org/@babel/plugin-proposal-private-property-in-object/-/plugin-proposal-private-property-in-object-7.21.0-placeholder-for-preset-env.2.tgz", - "integrity": "sha512-SOSkfJDddaM7mak6cPEpswyTRnuRltl429hMraQEglW+OkovnCzsiszTmsrlY//qLFjCpQDFRvjdm2wA5pPm9w==", + "version": "7.21.11", + "resolved": "https://registry.npmjs.org/@babel/plugin-proposal-private-property-in-object/-/plugin-proposal-private-property-in-object-7.21.11.tgz", + "integrity": "sha512-0QZ8qP/3RLDVBwBFoWAwCtgcDZJVwA5LUJRZU8x2YFfKNuFq161wK3cuGrALu5yiPu+vzwTAg/sMWVNeWeNyaw==", + "deprecated": "This proposal has been merged to the ECMAScript standard and thus this plugin is no longer maintained. Please use @babel/plugin-transform-private-property-in-object instead.", "license": "MIT", + "dependencies": { + "@babel/helper-annotate-as-pure": "^7.18.6", + "@babel/helper-create-class-features-plugin": "^7.21.0", + "@babel/helper-plugin-utils": "^7.20.2", + "@babel/plugin-syntax-private-property-in-object": "^7.14.5" + }, "engines": { "node": ">=6.9.0" }, @@ -1982,6 +1990,18 @@ "@babel/core": "^7.0.0-0" } }, + "node_modules/@babel/preset-env/node_modules/@babel/plugin-proposal-private-property-in-object": { + "version": "7.21.0-placeholder-for-preset-env.2", + "resolved": "https://registry.npmjs.org/@babel/plugin-proposal-private-property-in-object/-/plugin-proposal-private-property-in-object-7.21.0-placeholder-for-preset-env.2.tgz", + "integrity": "sha512-SOSkfJDddaM7mak6cPEpswyTRnuRltl429hMraQEglW+OkovnCzsiszTmsrlY//qLFjCpQDFRvjdm2wA5pPm9w==", + "license": "MIT", + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, "node_modules/@babel/preset-env/node_modules/semver": { "version": "6.3.1", "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", From 1714d07f9b74eaa89fe5eb81b9b0d5f6e2002996 Mon Sep 17 00:00:00 2001 From: AhmedFatthy1040 Date: Thu, 28 Nov 2024 20:28:22 +0200 Subject: [PATCH 5/8] feat(auth): create authentication service for API integration feat(auth): implement login component with error handling feat(auth): implement signup component with validation feat(upload): add token authentication to image upload refactor(components): update form handling and error states --- app/src/Pages/Annotate.tsx | 33 ++++++++++-- app/src/Pages/Login.tsx | 56 +++++++++++--------- app/src/Pages/Signup.tsx | 105 +++++++++++++++++++++---------------- 3 files changed, 121 insertions(+), 73 deletions(-) diff --git a/app/src/Pages/Annotate.tsx b/app/src/Pages/Annotate.tsx index d3f1378..ddffd74 100644 --- a/app/src/Pages/Annotate.tsx +++ b/app/src/Pages/Annotate.tsx @@ -2,39 +2,66 @@ import React, { useState, useRef } from 'react'; import Button from '../Components/Button'; import { Upload, Loader } from 'lucide-react'; +const API_URL = process.env.REACT_APP_API_URL || 'http://localhost:5000/api'; + const Annotate = () => { const [selectedImage, setSelectedImage] = useState(null); const [uploadedImage, setUploadedImage] = useState(null); const [annotations, setAnnotations] = useState>([]); const [isUploading, setIsUploading] = useState(false); const [isProcessing, setIsProcessing] = useState(false); + const [error, setError] = useState(null); const fileInputRef = useRef(null); const imageRef = useRef(null); + const selectedFileRef = useRef(null); const handleImageSelect = (e: React.ChangeEvent) => { const file = e.target.files?.[0]; if (file) { + selectedFileRef.current = file; const reader = new FileReader(); reader.onload = (e) => { setSelectedImage(e.target?.result as string); setUploadedImage(null); setAnnotations([]); + setError(null); }; reader.readAsDataURL(file); } }; const handleUpload = async () => { - if (!selectedImage) return; + if (!selectedImage || !selectedFileRef.current) return; setIsUploading(true); + setError(null); + try { - // TODO: Implement actual backend upload - await new Promise(resolve => setTimeout(resolve, 1500)); // Simulate upload + const formData = new FormData(); + formData.append('image', selectedFileRef.current); + + const token = localStorage.getItem('token'); // Get the auth token if you have authentication + + const response = await fetch(`${API_URL}/images/upload`, { + method: 'POST', + headers: { + ...(token ? { Authorization: `Bearer ${token}` } : {}), + }, + body: formData, + }); + + if (!response.ok) { + const errorData = await response.json(); + throw new Error(errorData.message || 'Upload failed'); + } + + const data = await response.json(); setUploadedImage(selectedImage); setSelectedImage(null); + selectedFileRef.current = null; } catch (error) { console.error('Upload failed:', error); + setError(error instanceof Error ? error.message : 'Upload failed'); } finally { setIsUploading(false); } diff --git a/app/src/Pages/Login.tsx b/app/src/Pages/Login.tsx index a3ac7d9..3927a8c 100644 --- a/app/src/Pages/Login.tsx +++ b/app/src/Pages/Login.tsx @@ -2,6 +2,7 @@ import React, { useState } from 'react'; import { Link, useNavigate } from 'react-router-dom'; import Input from '../Components/Input'; import Button from '../Components/Button'; +import { authService } from '../services/authService'; const Login = () => { const navigate = useNavigate(); @@ -10,11 +11,25 @@ const Login = () => { password: '', rememberMe: false }); + const [error, setError] = useState(null); + const [isLoading, setIsLoading] = useState(false); - const handleSubmit = (e: React.FormEvent) => { + const handleSubmit = async (e: React.FormEvent) => { e.preventDefault(); - // TODO: Implement login logic - navigate('/annotate'); + setError(null); + setIsLoading(true); + + try { + await authService.login({ + email: formData.email, + password: formData.password, + }); + navigate('/annotate'); + } catch (err) { + setError(err instanceof Error ? err.message : 'Login failed'); + } finally { + setIsLoading(false); + } }; return ( @@ -23,6 +38,12 @@ const Login = () => {

Welcome back

+ {error && ( +
+ {error} +
+ )} +
{ /> Remember me - - - Forgot password? - -
- - - -
-
-
-
-
- Or continue with -
- -

+

Don't have an account?{' '} - + Sign up

diff --git a/app/src/Pages/Signup.tsx b/app/src/Pages/Signup.tsx index 92afa68..54f5045 100644 --- a/app/src/Pages/Signup.tsx +++ b/app/src/Pages/Signup.tsx @@ -2,21 +2,47 @@ import React, { useState } from 'react'; import { Link, useNavigate } from 'react-router-dom'; import Input from '../Components/Input'; import Button from '../Components/Button'; +import { authService } from '../services/authService'; const Signup = () => { const navigate = useNavigate(); const [formData, setFormData] = useState({ - firstName: '', - lastName: '', + username: '', email: '', password: '', - rememberMe: false + confirmPassword: '', }); + const [error, setError] = useState(null); + const [isLoading, setIsLoading] = useState(false); - const handleSubmit = (e: React.FormEvent) => { + const handleSubmit = async (e: React.FormEvent) => { e.preventDefault(); - // TODO: Implement signup logic - navigate('/annotate'); + setError(null); + + if (formData.password !== formData.confirmPassword) { + setError("Passwords don't match"); + return; + } + + if (formData.password.length < 6) { + setError("Password must be at least 6 characters long"); + return; + } + + setIsLoading(true); + + try { + await authService.signup({ + username: formData.username, + email: formData.email, + password: formData.password, + }); + navigate('/annotate'); + } catch (err) { + setError(err instanceof Error ? err.message : 'Signup failed'); + } finally { + setIsLoading(false); + } }; return ( @@ -41,21 +67,19 @@ const Signup = () => {

Create your account

- -
- setFormData({ ...formData, firstName: e.target.value })} - /> - setFormData({ ...formData, lastName: e.target.value })} - /> + {error && ( +
+ {error}
+ )} + + + setFormData({ ...formData, username: e.target.value })} + /> { onChange={(e) => setFormData({ ...formData, password: e.target.value })} /> - - - - -
-
-
-
-
- Or continue with -
-
+ setFormData({ ...formData, confirmPassword: e.target.value })} + /> - -

+

Already have an account?{' '} - + Sign in

From 255dbb120557d087f06c99836105f5252e7e4b91 Mon Sep 17 00:00:00 2001 From: AhmedFatthy1040 Date: Thu, 28 Nov 2024 20:29:54 +0200 Subject: [PATCH 6/8] feat(auth): add user model and database schema feat(auth): implement authentication controller and service --- api/src/controllers/authController.ts | 60 ++++++++++++++++++++ api/src/middlewares/multerConfig.ts | 30 ---------- api/src/models/user.ts | 14 +++++ app/src/services/authService.ts | 80 +++++++++++++++++++++++++++ 4 files changed, 154 insertions(+), 30 deletions(-) create mode 100644 api/src/controllers/authController.ts delete mode 100644 api/src/middlewares/multerConfig.ts create mode 100644 api/src/models/user.ts create mode 100644 app/src/services/authService.ts diff --git a/api/src/controllers/authController.ts b/api/src/controllers/authController.ts new file mode 100644 index 0000000..ce91e9c --- /dev/null +++ b/api/src/controllers/authController.ts @@ -0,0 +1,60 @@ +import { Request, Response } from 'express'; +import { AuthService } from '../services/authService'; + +export class AuthController { + static async register(req: Request, res: Response): Promise { + try { + const { username, email, password } = req.body; + + // Validate input + if (!username || !email || !password) { + return res.status(400).json({ message: 'All fields are required' }); + } + + // Validate email format + const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; + if (!emailRegex.test(email)) { + return res.status(400).json({ message: 'Invalid email format' }); + } + + // Validate password strength + if (password.length < 6) { + return res.status(400).json({ message: 'Password must be at least 6 characters long' }); + } + + const user = await AuthService.registerUser(username, email, password); + return res.status(201).json({ + message: 'User registered successfully', + user + }); + } catch (error: unknown) { + if (error instanceof Error) { + return res.status(400).json({ message: error.message }); + } + return res.status(500).json({ message: 'An unknown error occurred' }); + } + } + + static async login(req: Request, res: Response): Promise { + try { + const { email, password } = req.body; + + if (!email || !password) { + return res.status(400).json({ message: 'Email and password are required' }); + } + + const { user, token } = await AuthService.loginUser(email, password); + + return res.status(200).json({ + message: 'Login successful', + user, + token + }); + } catch (error: unknown) { + if (error instanceof Error) { + return res.status(401).json({ message: error.message }); + } + return res.status(500).json({ message: 'An unknown error occurred' }); + } + } +} diff --git a/api/src/middlewares/multerConfig.ts b/api/src/middlewares/multerConfig.ts deleted file mode 100644 index 4ff8de8..0000000 --- a/api/src/middlewares/multerConfig.ts +++ /dev/null @@ -1,30 +0,0 @@ -import multer from "multer"; -import path from "path"; -import { Request } from "express"; - -const storage = multer.diskStorage({ - destination: (req, file, cb) => { - cb(null, "uploads/"); // Directory to save images - }, - filename: (req, file, cb) => { - const uniqueSuffix = `${Date.now()}-${Math.round(Math.random() * 1e9)}`; - const ext = path.extname(file.originalname); - cb(null, `${file.fieldname}-${uniqueSuffix}${ext}`); - }, -}); - -const fileFilter = (req: Request, file: Express.Multer.File, cb: multer.FileFilterCallback) => { - const allowedTypes = /jpeg|jpg|png|gif/; - const ext = path.extname(file.originalname).toLowerCase(); - if (allowedTypes.test(ext)) { - cb(null, true); - } else { - cb(new Error("Only image files are allowed!")); - } -}; - -export const upload = multer({ - storage, - limits: { fileSize: 5 * 1024 * 1024 }, // 5 MB limit - fileFilter, -}); diff --git a/api/src/models/user.ts b/api/src/models/user.ts new file mode 100644 index 0000000..9a2f5fa --- /dev/null +++ b/api/src/models/user.ts @@ -0,0 +1,14 @@ +export interface User { + id: number; + username: string; + email: string; + password: string; + createdAt: Date; +} + +export interface UserResponse { + id: number; + username: string; + email: string; + createdAt: Date; +} diff --git a/app/src/services/authService.ts b/app/src/services/authService.ts new file mode 100644 index 0000000..9b40c8f --- /dev/null +++ b/app/src/services/authService.ts @@ -0,0 +1,80 @@ +const API_URL = process.env.REACT_APP_API_URL || 'http://localhost:5000/api'; + +export interface LoginCredentials { + email: string; + password: string; +} + +export interface SignupCredentials { + username: string; + email: string; + password: string; +} + +export interface AuthResponse { + message: string; + token?: string; + user?: { + id: number; + email: string; + username: string; + }; +} + +export const authService = { + async login(credentials: LoginCredentials): Promise { + const response = await fetch(`${API_URL}/auth/login`, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + }, + body: JSON.stringify(credentials), + credentials: 'include', + }); + + if (!response.ok) { + const error = await response.json(); + throw new Error(error.message || 'Login failed'); + } + + const data = await response.json(); + if (data.token) { + localStorage.setItem('token', data.token); + } + return data; + }, + + async signup(credentials: SignupCredentials): Promise { + const response = await fetch(`${API_URL}/auth/register`, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + }, + body: JSON.stringify(credentials), + credentials: 'include', + }); + + if (!response.ok) { + const error = await response.json(); + throw new Error(error.message || 'Signup failed'); + } + + const data = await response.json(); + if (data.token) { + localStorage.setItem('token', data.token); + } + return data; + }, + + logout() { + localStorage.removeItem('token'); + }, + + getToken() { + return localStorage.getItem('token'); + }, + + isAuthenticated() { + return !!this.getToken(); + } +}; From cc85205f4da821d073e0213787d45f6a5870a971 Mon Sep 17 00:00:00 2001 From: AhmedFatthy1040 Date: Thu, 28 Nov 2024 21:03:15 +0200 Subject: [PATCH 7/8] refactor(upload): simplify multer configuration and improve type safety --- api/src/middlewares/multerConfig.ts | 30 +++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 api/src/middlewares/multerConfig.ts diff --git a/api/src/middlewares/multerConfig.ts b/api/src/middlewares/multerConfig.ts new file mode 100644 index 0000000..4ff8de8 --- /dev/null +++ b/api/src/middlewares/multerConfig.ts @@ -0,0 +1,30 @@ +import multer from "multer"; +import path from "path"; +import { Request } from "express"; + +const storage = multer.diskStorage({ + destination: (req, file, cb) => { + cb(null, "uploads/"); // Directory to save images + }, + filename: (req, file, cb) => { + const uniqueSuffix = `${Date.now()}-${Math.round(Math.random() * 1e9)}`; + const ext = path.extname(file.originalname); + cb(null, `${file.fieldname}-${uniqueSuffix}${ext}`); + }, +}); + +const fileFilter = (req: Request, file: Express.Multer.File, cb: multer.FileFilterCallback) => { + const allowedTypes = /jpeg|jpg|png|gif/; + const ext = path.extname(file.originalname).toLowerCase(); + if (allowedTypes.test(ext)) { + cb(null, true); + } else { + cb(new Error("Only image files are allowed!")); + } +}; + +export const upload = multer({ + storage, + limits: { fileSize: 5 * 1024 * 1024 }, // 5 MB limit + fileFilter, +}); From 0a935d88b0961e7b8197019db526ac77d48ca0c5 Mon Sep 17 00:00:00 2001 From: AhmedFatthy1040 Date: Thu, 28 Nov 2024 21:06:31 +0200 Subject: [PATCH 8/8] feat(auth): implement JWT authentication middleware --- api/src/middlewares/authMiddleware.ts | 31 +++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 api/src/middlewares/authMiddleware.ts diff --git a/api/src/middlewares/authMiddleware.ts b/api/src/middlewares/authMiddleware.ts new file mode 100644 index 0000000..c6e60cb --- /dev/null +++ b/api/src/middlewares/authMiddleware.ts @@ -0,0 +1,31 @@ +import { Request, Response, NextFunction } from 'express'; +import { AuthService } from '../services/authService'; + +declare global { + namespace Express { + interface Request { + user?: { + userId: number; + email: string; + }; + } + } +} + +export const authenticateToken = (req: Request, res: Response, next: NextFunction): void => { + const authHeader = req.headers['authorization']; + const token = authHeader && authHeader.split(' ')[1]; // Bearer TOKEN + + if (!token) { + res.status(401).json({ message: 'Authentication token is required' }); + return; + } + + try { + const user = AuthService.verifyToken(token); + req.user = user; + next(); + } catch (error) { + res.status(403).json({ message: 'Invalid or expired token' }); + } +};