Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(api): add logout endpoint to clear token cookie #581

Merged
merged 3 commits into from
Dec 8, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions api-collection/Auth Controller/Logout.bru
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
meta {
name: Logout
type: http
seq: 6
}

post {
url: {{BASE_URL}}/api/auth/logout
body: none
auth: none
}


docs {
## Description

This endpoint clears the token cookie, ensuring the user is logged out securely.
}
6 changes: 6 additions & 0 deletions apps/api/src/auth/controller/auth.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -207,4 +207,10 @@ export class AuthController {
)
}
}

@Post('logout')
async logout(@Res() res: Response): Promise<void> {
await this.authService.logout(res)
res.status(HttpStatus.OK).send({ message: 'Logged out successfully' })
}
}
12 changes: 12 additions & 0 deletions apps/api/src/auth/service/auth.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import { CacheService } from '@/cache/cache.service'
import { generateOtp } from '@/common/util'
import { createUser, getUserByEmailOrId } from '@/common/user'
import { UserWithWorkspace } from '@/user/user.types'
import { Response } from 'express'

@Injectable()
export class AuthService {
Expand Down Expand Up @@ -219,4 +220,15 @@ export class AuthService {
private async generateToken(id: string) {
return await this.jwt.signAsync({ id })
}

/**
* Clears the token cookie on logout
* @param res The response object
*/
async logout(res: Response): Promise<void> {
res.clearCookie('token', {
domain: process.env.DOMAIN ?? 'localhost'
})
this.logger.log('User logged out and token cookie cleared.')
}
}
Loading