Skip to content

Commit

Permalink
finishes 187354245 logout api
Browse files Browse the repository at this point in the history
  • Loading branch information
gracemugwanezak committed Apr 29, 2024
1 parent 116a4a6 commit b8057be
Show file tree
Hide file tree
Showing 5 changed files with 122 additions and 0 deletions.
39 changes: 39 additions & 0 deletions src/controllers/logoutController.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import { Request, Response } from 'express';
import jwt from 'jsonwebtoken';
import { sendInternalErrorResponse } from '../validations';
import logger from '../logs/config';
import BlacklistedToken from '../database/models/blackListedToken';
import { extractTokenMiddleware } from '../helpers/tokenExtractor';

const logout = async (req: Request, res: Response): Promise<void> => {
try {
const token = (req as any).token;

jwt.verify(token, process.env.JWT_SECRET as string, (err: any) => {
if (err) {
res.status(401).json({
ok: false,
message: 'Invalid token',
});
return;
}

BlacklistedToken.create({ token })
.then(() => {
res.status(200).json({
ok: true,
message: 'Logged out successfully',
});
})
.catch(error => {
throw error;
});
});
} catch (err: any) {
const message = (err as Error).message;
logger.error(message);
sendInternalErrorResponse(res, err);
}
};

export { logout, extractTokenMiddleware };
28 changes: 28 additions & 0 deletions src/database/migrations/20240428210949-create-blacklisted-token.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
'use strict';
module.exports = {
up: async (queryInterface, Sequelize) => {
await queryInterface.createTable('BlacklistedTokens', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER,
},
token: {
type: Sequelize.STRING,
allowNull: false,
},
createdAt: {
allowNull: false,
type: Sequelize.DATE,
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE,
},
});
},
down: async (queryInterface, Sequelize) => {
await queryInterface.dropTable('BlacklistedTokens');
},
};
33 changes: 33 additions & 0 deletions src/database/models/blackListedToken.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { Model, DataTypes, Sequelize } from 'sequelize';
import sequelize from './index';

class BlacklistedToken extends Model {
public id!: number;
public token!: string;

// timestamps!
public readonly createdAt!: Date;
public readonly updatedAt!: Date;
}

BlacklistedToken.init(
{
id: {
type: DataTypes.INTEGER,
autoIncrement: true,
primaryKey: true,
},
token: {
type: DataTypes.STRING,
allowNull: false,
},
},
{
sequelize: sequelize as Sequelize,
modelName: 'BlacklistedToken',
tableName: 'blacklisted_tokens',
timestamps: true,
}
);

export default BlacklistedToken;
16 changes: 16 additions & 0 deletions src/helpers/tokenExtractor.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { Request, Response, NextFunction } from 'express';

const extractTokenMiddleware = (req: Request, res: Response, next: NextFunction) => {
const token = req.headers.authorization?.split(' ')[1];
if (!token) {
res.status(400).json({
ok: false,
message: 'Token not provided',
});
return;
}
(req as any).token = token;
next();
};

export { extractTokenMiddleware };
6 changes: 6 additions & 0 deletions src/routes/authRoute.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ import { Router } from 'express';
import passport from 'passport';
import { authenticateViaGoogle } from '../controllers/authController';
import { login } from '../controllers/authController';
import { logout } from '../controllers/logoutController';
import { signupUser } from '../controllers/userController';

const router = Router();
// redirect user to google for authentication
Expand All @@ -15,7 +17,11 @@ router.get(
// authenticated user and store user data
router.get('/google/callback', authenticateViaGoogle);

//signup a user
router.post('/signup', signupUser);

// Route to login a user
router.post('/login', login);
router.post('/logout', logout);

export default router;

0 comments on commit b8057be

Please sign in to comment.