Skip to content

Commit

Permalink
Fix logout
Browse files Browse the repository at this point in the history
  • Loading branch information
anqqa committed Jun 5, 2019
1 parent 42cc505 commit d12147b
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 5 deletions.
27 changes: 24 additions & 3 deletions api/src/auth/auth.controller.ts
@@ -1,4 +1,13 @@
import { Body, Controller, Get, Post, Req, UseGuards, UseInterceptors } from '@nestjs/common';
import {
Body,
Controller,
Get,
Headers,
Post,
Req,
UseGuards,
UseInterceptors,
} from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
import {
ApiBearerAuth,
Expand Down Expand Up @@ -30,14 +39,26 @@ export class AuthController {
return { token, user };
}

@ApiOperation({ title: 'Logout' })
@ApiOkResponse({ description: 'Success' })
@ApiUnauthorizedResponse({ description: 'Not authenticated' })
@ApiBearerAuth()
@UseGuards(AuthGuard())
@Post('logout')
async logout(@Headers('authorization') authorization: string): Promise<any> {
const [bearer, token] = authorization.split(' ');

await this.authService.deleteToken(token);
}

@ApiOperation({ title: 'Get authenticated user info' })
@ApiOkResponse({ description: 'Success', type: User })
@ApiUnauthorizedResponse({ description: 'Not authenticated' })
@ApiBearerAuth()
@UseGuards(AuthGuard())
@UseInterceptors(new TransformerInterceptor(User))
@Get('me')
me(@Req() req: any): User {
return req.user;
me(@Req() { user }: any): User {
return user;
}
}
12 changes: 12 additions & 0 deletions api/src/auth/auth.service.ts
Expand Up @@ -18,6 +18,18 @@ export class AuthService {
@InjectRepository(User) private readonly userRepository: Repository<User>,
) {}

async deleteToken(token: string): Promise<boolean> {
const userToken = await this.tokenRepository.findOne({ token });

if (userToken) {
await this.tokenRepository.remove(userToken);

return true;
}

return false;
}

async generateToken(user: User): Promise<string> {
// Generate session token, valid for 30 days
const token = randomBytes(16).toString('hex');
Expand Down
6 changes: 4 additions & 2 deletions client/src/store/auth.js
Expand Up @@ -23,9 +23,11 @@ export const actions = {
},

async logout({ dispatch }) {
dispatch('reset');
try {
await this.$axios.post('auth/logout');
} catch (error) {}

await this.$axios.post('auth/logout');
dispatch('reset');
},

async me({ commit }) {
Expand Down

0 comments on commit d12147b

Please sign in to comment.