|
| 1 | +import { Body, Controller, Get, Post, Req, Res } from '@nestjs/common'; |
| 2 | +import { Response, Request } from 'express'; |
| 3 | +import { AuthService } from './auth.service'; |
| 4 | +import { MiniAppWalletAuthSuccessPayload } from '@worldcoin/minikit-js'; |
| 5 | + |
| 6 | +interface IRequestPayload { |
| 7 | + payload: MiniAppWalletAuthSuccessPayload; |
| 8 | +} |
| 9 | +@Controller('auth') |
| 10 | +export class AuthController { |
| 11 | + constructor(private readonly authService: AuthService) {} |
| 12 | + |
| 13 | + @Get('nonce') |
| 14 | + async generateNonce(@Res() res: Response): Promise<any> { |
| 15 | + const nonce = this.authService.generateNonce(); |
| 16 | + res.cookie('siwe', nonce, { |
| 17 | + httpOnly: true, |
| 18 | + secure: process.env.NODE_ENV === 'production', |
| 19 | + sameSite: 'strict', |
| 20 | + maxAge: 2 * 60 * 1000, //2 minutes |
| 21 | + }); |
| 22 | + |
| 23 | + return res.json({ nonce }); |
| 24 | + } |
| 25 | + |
| 26 | + @Post('verifyPayload') |
| 27 | + async verifyPayload( |
| 28 | + @Req() req: Request, |
| 29 | + @Body() body: IRequestPayload, |
| 30 | + @Res() res: Response, |
| 31 | + ) { |
| 32 | + const { payload } = body; |
| 33 | + const storedNonce = req.cookies?.siwe; |
| 34 | + if (!storedNonce) { |
| 35 | + return res.status(400).json({ |
| 36 | + status: 'error', |
| 37 | + isValid: false, |
| 38 | + message: 'No nonce found in cookies', |
| 39 | + }); |
| 40 | + } |
| 41 | + try { |
| 42 | + const validMessage = await this.authService.verifyPayload( |
| 43 | + payload, |
| 44 | + storedNonce, |
| 45 | + ); |
| 46 | + return res.status(200).json({ isValid: validMessage }); |
| 47 | + } catch (error: any) { |
| 48 | + return res |
| 49 | + .status(400) |
| 50 | + .json({ status: 'error', isValid: false, message: error.message }); |
| 51 | + } |
| 52 | + } |
| 53 | +} |
0 commit comments