Skip to content

Commit bffb75f

Browse files
set cookies in response
1 parent e0c6af7 commit bffb75f

File tree

4 files changed

+33
-14
lines changed

4 files changed

+33
-14
lines changed

src/auth/auth.controller.ts

Lines changed: 14 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -22,23 +22,32 @@ export class AuthController {
2222
@Public()
2323
@HttpCode(HttpStatus.OK)
2424
@Post('login')
25-
signIn(@Body() signInDto: Record<string, any>, @Res({ passthrough: true }) res: Response) {
26-
const access_token = this.authService.signIn(signInDto.email, signInDto.password);
27-
res.cookie('access_cookies', access_token, {
25+
async signIn(@Body() signInDto: Record<string, any>, @Res({ passthrough: true }) res: Response) {
26+
const token = await this.authService.signIn(signInDto.email, signInDto.password);
27+
28+
res.cookie('access_token',token.access_token, {
2829
httpOnly: true,
2930
expires: new Date(Date.now() + 1 * 24 * 60 * 60 * 1000),
3031
path: '/',
3132
sameSite: 'none',
3233
secure: true,
3334
});
34-
return access_token;
35+
36+
res.cookie('refresh_token', token.refresh_token, {
37+
httpOnly: true,
38+
expires: new Date(Date.now() + 1 * 24 * 60 * 60 * 1000),
39+
path: '/',
40+
sameSite: 'none',
41+
secure: true,
42+
});
43+
44+
return token;
3545
}
3646

3747
// @Public()
3848
@UseGuards(AuthGuard)
3949
@Post('/refresh')
4050
@UseFilters(new HttpExceptionFilter())
41-
@HttpCode(HttpStatus.OK)
4251
async refreshTokens(
4352
@Res() request:Request,
4453
@Res() res: Response

src/auth/auth.guard.ts

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,24 +29,28 @@ export class AuthGuard implements CanActivate {
2929

3030
const request = context.switchToHttp().getRequest();
3131
const token = this.extractTokenFromHeader(request);
32+
console.log('@@@@@@@token',token)
3233
if (!token) {
3334
throw new UnauthorizedException();
3435
}
3536
try {
3637
const payload = await this.jwtService.verifyAsync(token, {
3738
secret: jwtConstants.secret,
3839
});
40+
console.log(payload)
3941
// 💡 We're assigning the payload to the request object here
4042
// so that we can access it in our route handlers
4143
request['user'] = payload;
42-
} catch {
44+
} catch(err) {
45+
console.log(err)
4346
throw new UnauthorizedException();
4447
}
4548
return true;
4649
}
4750

4851
private extractTokenFromHeader(request: Request): string | undefined {
4952
const [type, token] = request.headers.authorization?.split(' ') ?? [];
53+
console.log(type, token)
5054
return type === 'Bearer' ? token : undefined;
5155
}
5256
}

src/auth/auth.service.ts

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import { ForbiddenException, Injectable, UnauthorizedException } from '@nestjs/c
22
import { UserService } from '../users/users.service';
33
import { JwtService } from '@nestjs/jwt';
44
import * as bcrypt from 'bcrypt';
5+
import { jwtConstants } from '../auth/constants';
56

67

78
@Injectable()
@@ -17,10 +18,9 @@ export class AuthService {
1718

1819
if (match) {
1920
const payload = { email: user.email, userId: user._id };
20-
const access_token = await this.jwtService.signAsync(payload);
2121
const tokens = await this.getTokens(user);
2222
return {
23-
access_token
23+
...tokens
2424
};
2525
}
2626
throw new UnauthorizedException();
@@ -48,21 +48,21 @@ export class AuthService {
4848
const [at, rt] = await Promise.all([
4949
this.jwtService.signAsync(
5050
{
51-
sub: user._id,
51+
sub: user.userId,
5252
email: user.email,
5353
},
5454
{
55-
secret: 'at-secret',
55+
secret: jwtConstants.secret,
5656
expiresIn: '24h',
5757
},
5858
),
5959
this.jwtService.signAsync(
6060
{
61-
sub: user._id,
61+
sub: user.userId,
6262
email: user.email,
6363
},
6464
{
65-
secret: 'rt-secret',
65+
secret: jwtConstants.secret,
6666
expiresIn: '30d',
6767
},
6868
),

src/users/users.controller.ts

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { Body, Controller, Delete, Get, HttpStatus, Param, Post, Res, UseFilters, UsePipes, ValidationPipe } from '@nestjs/common';
1+
import { Body, Controller, Delete, Get, HttpCode, HttpStatus, Param, Post, Res, UseFilters, UseGuards, UsePipes, ValidationPipe } from '@nestjs/common';
22
import { Public } from '../auth/decorators/public.decorator';
33
import { UserService } from './users.service';
44
import { CreateUserDto } from './dto/create-user.dto';
@@ -7,13 +7,15 @@ import { sendResponse } from '../utils';
77
import {statusMessage} from '../constant/statusMessage'
88
import { HttpExceptionFilter } from '../utils/http-exception.filter';
99
import { responseData, userData } from '../interface/common';
10+
import { AuthGuard } from '../common/guards/at.guard';
11+
1012

1113

12-
@Public()
1314
@Controller("v1/users")
1415
export class UserController {
1516
constructor(private readonly userService: UserService) {}
1617

18+
@Public()
1719
@Post()
1820
@UseFilters(new HttpExceptionFilter())
1921
@UsePipes(new ValidationPipe({ transform: true }))
@@ -22,7 +24,11 @@ export class UserController {
2224
return sendResponse(res,HttpStatus.CREATED,statusMessage[HttpStatus.CREATED],true,user);
2325
}
2426
// get user
27+
28+
29+
@UseGuards(AuthGuard)
2530
@Get()
31+
@UseFilters(new HttpExceptionFilter())
2632
async findAll(): Promise<userData[]> {
2733
return this.userService.findAll();
2834
}

0 commit comments

Comments
 (0)