diff --git a/backend/package-lock.json b/backend/package-lock.json index 265275f..e87692c 100644 --- a/backend/package-lock.json +++ b/backend/package-lock.json @@ -18,6 +18,7 @@ "@nestjs/platform-express": "^11.0.1", "@nestjs/swagger": "^11.1.5", "@nestjs/typeorm": "^11.0.0", + "axios": "^1.9.0", "bcrypt": "^5.1.1", "bcryptjs": "^3.0.2", "class": "^0.1.4", @@ -4783,9 +4784,19 @@ "version": "0.4.0", "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==", - "dev": true, "license": "MIT" }, + "node_modules/axios": { + "version": "1.9.0", + "resolved": "https://registry.npmjs.org/axios/-/axios-1.9.0.tgz", + "integrity": "sha512-re4CqKTJaURpzbLHtIi6XpDv20/CnpXOtjRY5/CU32L8gU8ek9UIivcfvSWvmKEngmVbrUtPpdDwWDWL7DNHvg==", + "license": "MIT", + "dependencies": { + "follow-redirects": "^1.15.6", + "form-data": "^4.0.0", + "proxy-from-env": "^1.1.0" + } + }, "node_modules/b4a": { "version": "1.6.7", "resolved": "https://registry.npmjs.org/b4a/-/b4a-1.6.7.tgz", @@ -5716,7 +5727,6 @@ "version": "1.0.8", "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz", "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==", - "dev": true, "license": "MIT", "dependencies": { "delayed-stream": "~1.0.0" @@ -6114,7 +6124,6 @@ "version": "1.0.0", "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", "integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==", - "dev": true, "license": "MIT", "engines": { "node": ">=0.4.0" @@ -6548,7 +6557,6 @@ "version": "2.1.0", "resolved": "https://registry.npmjs.org/es-set-tostringtag/-/es-set-tostringtag-2.1.0.tgz", "integrity": "sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==", - "dev": true, "license": "MIT", "dependencies": { "es-errors": "^1.3.0", @@ -7392,6 +7400,26 @@ "dev": true, "license": "ISC" }, + "node_modules/follow-redirects": { + "version": "1.15.9", + "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.9.tgz", + "integrity": "sha512-gew4GsXizNgdoRyqmyfMHyAmXsZDk6mHkSxZFCzW9gwlbtOW44CDtYavM+y+72qD/Vq2l550kMF52DT8fOLJqQ==", + "funding": [ + { + "type": "individual", + "url": "https://github.com/sponsors/RubenVerborgh" + } + ], + "license": "MIT", + "engines": { + "node": ">=4.0" + }, + "peerDependenciesMeta": { + "debug": { + "optional": true + } + } + }, "node_modules/foreground-child": { "version": "3.3.1", "resolved": "https://registry.npmjs.org/foreground-child/-/foreground-child-3.3.1.tgz", @@ -7505,7 +7533,6 @@ "version": "4.0.2", "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.2.tgz", "integrity": "sha512-hGfm/slu0ZabnNt4oaRZ6uREyfCj6P4fT/n6A1rGV+Z0VdGXjfOhVUpkn6qVQONHGIFwmveGXyDs75+nr6FM8w==", - "dev": true, "license": "MIT", "dependencies": { "asynckit": "^0.4.0", @@ -7531,7 +7558,6 @@ "version": "1.52.0", "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", - "dev": true, "license": "MIT", "engines": { "node": ">= 0.6" @@ -7541,7 +7567,6 @@ "version": "2.1.35", "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz", "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", - "dev": true, "license": "MIT", "dependencies": { "mime-db": "1.52.0" @@ -8007,7 +8032,6 @@ "version": "1.0.2", "resolved": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.2.tgz", "integrity": "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==", - "devOptional": true, "license": "MIT", "dependencies": { "has-symbols": "^1.0.3" @@ -12047,6 +12071,12 @@ "node": ">= 0.10" } }, + "node_modules/proxy-from-env": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-1.1.0.tgz", + "integrity": "sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg==", + "license": "MIT" + }, "node_modules/pug": { "version": "3.0.3", "resolved": "https://registry.npmjs.org/pug/-/pug-3.0.3.tgz", diff --git a/backend/package.json b/backend/package.json index 644a233..09a10da 100644 --- a/backend/package.json +++ b/backend/package.json @@ -30,6 +30,7 @@ "@nestjs/platform-express": "^11.0.1", "@nestjs/swagger": "^11.1.5", "@nestjs/typeorm": "^11.0.0", + "axios": "^1.9.0", "bcrypt": "^5.1.1", "bcryptjs": "^3.0.2", "class": "^0.1.4", diff --git a/backend/src/auth/auth.controller.ts b/backend/src/auth/auth.controller.ts index dcf2653..ce4ec6b 100644 --- a/backend/src/auth/auth.controller.ts +++ b/backend/src/auth/auth.controller.ts @@ -14,7 +14,7 @@ export class AuthController { async login( @Body('email') email: string, @Body('password') password: string, - @Body('role') role: string, // expects 'ADMIN', 'STUDENT', or 'TUTOR' + @Body('role') role: string, ) { const user = await this.authService.validateUser(email, password, role); if (!user) throw new UnauthorizedException('Invalid credentials'); diff --git a/backend/src/auth/auth.module.ts b/backend/src/auth/auth.module.ts index ac73022..b6bab30 100644 --- a/backend/src/auth/auth.module.ts +++ b/backend/src/auth/auth.module.ts @@ -1,4 +1,4 @@ -import { Module } from '@nestjs/common'; +import { Module, MiddlewareConsumer } from '@nestjs/common'; import { TypeOrmModule } from '@nestjs/typeorm'; import { AuthController } from './auth.controller'; import { AuthService } from './auth.service'; @@ -7,6 +7,8 @@ import { EmailVerification } from './entities/email-verification.entity'; import { PasswordReset } from './entities/password-reset.entity'; import { Admin } from '../admin/entities/admin.entity'; import { EmailService } from './services/email.service'; +import { WorldcoinService } from './services/worldcoin.service'; +import { WorldcoinVerificationMiddleware } from './middleware/worldcoin-verification.middleware'; @Module({ imports: [ @@ -19,6 +21,12 @@ import { EmailService } from './services/email.service'; ], providers: [AuthService, EmailService], controllers: [AuthController], - exports: [AuthService], + exports: [AuthService, WorldcoinService], }) -export class AuthModule {} +export class AuthModule { + configure(consumer: MiddlewareConsumer) { + consumer + .apply(WorldcoinVerificationMiddleware) + .forRoutes('auth/register/student', 'auth/register/tutor'); + } +} diff --git a/backend/src/auth/auth.service.ts b/backend/src/auth/auth.service.ts index 1ec5fa3..c285782 100644 --- a/backend/src/auth/auth.service.ts +++ b/backend/src/auth/auth.service.ts @@ -1,4 +1,8 @@ -import { Injectable, UnauthorizedException, BadRequestException } from '@nestjs/common'; +import { + Injectable, + UnauthorizedException, + BadRequestException, +} from '@nestjs/common'; import { InjectRepository } from '@nestjs/typeorm'; import { Repository } from 'typeorm'; import { RefreshToken } from './entities/refresh-token.entity'; @@ -73,9 +77,8 @@ export class AuthService { } async refresh(refreshToken: string) { - let payload: any; try { - payload = jwt.verify(refreshToken, process.env.REFRESH_TOKEN_SECRET); + jwt.verify(refreshToken, process.env.REFRESH_TOKEN_SECRET); } catch { throw new UnauthorizedException('Invalid refresh token'); } @@ -117,7 +120,8 @@ export class AuthService { default: return 7 * 24 * 60 * 60 * 1000; } - } async requestEmailVerification(email: string): Promise { + } + async requestEmailVerification(email: string): Promise { const user = await this.adminRepo.findOne({ where: { email } }); if (!user) { throw new BadRequestException('User not found'); @@ -126,7 +130,7 @@ export class AuthService { // Invalidate any existing verification tokens await this.emailVerificationRepo.update( { email, verified: false }, - { verified: true } + { verified: true }, ); const token = randomBytes(32).toString('hex'); @@ -174,10 +178,7 @@ export class AuthService { } // Invalidate any existing reset tokens - await this.passwordResetRepo.update( - { email, used: false }, - { used: true } - ); + await this.passwordResetRepo.update({ email, used: false }, { used: true }); const token = randomBytes(32).toString('hex'); const expiresAt = new Date(Date.now() + 60 * 60 * 1000); // 1 hour @@ -219,4 +220,3 @@ export class AuthService { await this.passwordResetRepo.save(reset); } } - diff --git a/backend/src/auth/dto/email-verification.dto.ts b/backend/src/auth/dto/email-verification.dto.ts index c1ebbdf..a22085e 100644 --- a/backend/src/auth/dto/email-verification.dto.ts +++ b/backend/src/auth/dto/email-verification.dto.ts @@ -10,4 +10,4 @@ export class RequestEmailVerificationDto { @IsEmail() @IsNotEmpty() email: string; -} \ No newline at end of file +} diff --git a/backend/src/auth/dto/password-reset.dto.ts b/backend/src/auth/dto/password-reset.dto.ts index 0549f5e..b5986a0 100644 --- a/backend/src/auth/dto/password-reset.dto.ts +++ b/backend/src/auth/dto/password-reset.dto.ts @@ -15,4 +15,4 @@ export class ResetPasswordDto { @IsNotEmpty() @MinLength(8) newPassword: string; -} \ No newline at end of file +} diff --git a/backend/src/auth/dto/worldcoin-proof.dto.ts b/backend/src/auth/dto/worldcoin-proof.dto.ts new file mode 100644 index 0000000..11c0f74 --- /dev/null +++ b/backend/src/auth/dto/worldcoin-proof.dto.ts @@ -0,0 +1,23 @@ +import { IsString, IsNotEmpty } from 'class-validator'; + +export class WorldcoinProofDto { + @IsString() + @IsNotEmpty() + signal: string; + + @IsString() + @IsNotEmpty() + proof: string; + + @IsString() + @IsNotEmpty() + merkle_root: string; + + @IsString() + @IsNotEmpty() + nullifier_hash: string; + + @IsString() + @IsNotEmpty() + action: string; +} diff --git a/backend/src/auth/entities/password-reset.entity.ts b/backend/src/auth/entities/password-reset.entity.ts index a81c33c..9aa2b66 100644 --- a/backend/src/auth/entities/password-reset.entity.ts +++ b/backend/src/auth/entities/password-reset.entity.ts @@ -1,4 +1,10 @@ -import { Entity, Column, PrimaryGeneratedColumn, ManyToOne, CreateDateColumn } from 'typeorm'; +import { + Entity, + Column, + PrimaryGeneratedColumn, + ManyToOne, + CreateDateColumn, +} from 'typeorm'; import { Admin } from '../../admin/entities/admin.entity'; @Entity() @@ -23,4 +29,4 @@ export class PasswordReset { @ManyToOne(() => Admin) user: Admin; -} \ No newline at end of file +} diff --git a/backend/src/auth/middleware/worldcoin-verification.middleware.ts b/backend/src/auth/middleware/worldcoin-verification.middleware.ts new file mode 100644 index 0000000..ccada94 --- /dev/null +++ b/backend/src/auth/middleware/worldcoin-verification.middleware.ts @@ -0,0 +1,44 @@ +import { + Injectable, + NestMiddleware, + BadRequestException, + UnauthorizedException, +} from '@nestjs/common'; +import { Request, Response, NextFunction } from 'express'; +import { WorldcoinService } from '../services/worldcoin.service'; + +interface WorldcoinProofBody { + signal: string; + proof: string; + merkle_root: string; + nullifier_hash: string; + action: string; +} + +@Injectable() +export class WorldcoinVerificationMiddleware implements NestMiddleware { + constructor(private readonly worldcoinService: WorldcoinService) {} + + async use(req: Request, res: Response, next: NextFunction) { + const { signal, proof, merkle_root, nullifier_hash, action } = + req.body as WorldcoinProofBody; + + if (!signal || !proof || !merkle_root || !nullifier_hash || !action) { + throw new BadRequestException('Missing Worldcoin proof data'); + } + + const isValid = await this.worldcoinService.verifyProof({ + signal, + proof, + merkle_root, + nullifier_hash, + action, + }); + + if (!isValid) { + throw new UnauthorizedException('Invalid Worldcoin proof'); + } + + next(); + } +} diff --git a/backend/src/auth/services/email.service.ts b/backend/src/auth/services/email.service.ts index 9f1fd74..723df0f 100644 --- a/backend/src/auth/services/email.service.ts +++ b/backend/src/auth/services/email.service.ts @@ -19,7 +19,7 @@ export class EmailService { async sendVerificationEmail(email: string, token: string): Promise { const verificationUrl = `${process.env.FRONTEND_URL}/verify-email?token=${token}`; - + await this.transporter.sendMail({ from: process.env.SMTP_FROM, to: email, @@ -35,7 +35,7 @@ export class EmailService { async sendPasswordResetEmail(email: string, token: string): Promise { const resetUrl = `${process.env.FRONTEND_URL}/reset-password?token=${token}`; - + await this.transporter.sendMail({ from: process.env.SMTP_FROM, to: email, @@ -49,4 +49,4 @@ export class EmailService { `, }); } -} \ No newline at end of file +} diff --git a/backend/src/auth/services/worldcoin.service.ts b/backend/src/auth/services/worldcoin.service.ts new file mode 100644 index 0000000..6fb70de --- /dev/null +++ b/backend/src/auth/services/worldcoin.service.ts @@ -0,0 +1,43 @@ +import { Injectable, HttpException, HttpStatus } from '@nestjs/common'; +import axios, { AxiosResponse } from 'axios'; +import { WorldcoinProofDto } from '../dto/worldcoin-proof.dto'; + +interface WorldcoinVerifyResponse { + success: boolean; + [key: string]: unknown; +} + +@Injectable() +export class WorldcoinService { + private readonly VERIFY_ENDPOINT = + 'https://developer.worldcoin.org/api/v1/verify'; + + async verifyProof(proofDto: WorldcoinProofDto): Promise { + try { + const response: AxiosResponse = await axios.post( + this.VERIFY_ENDPOINT, + { + signal: proofDto.signal, + proof: proofDto.proof, + merkle_root: proofDto.merkle_root, + nullifier_hash: proofDto.nullifier_hash, + action: proofDto.action, + }, + ); + + if (response.data && typeof response.data.success === 'boolean') { + return response.data.success; + } else { + throw new HttpException( + 'Invalid response from Worldcoin verification', + HttpStatus.INTERNAL_SERVER_ERROR, + ); + } + } catch { + throw new HttpException( + 'Worldcoin verification failed', + HttpStatus.UNAUTHORIZED, + ); + } + } +}