Skip to content

Commit

Permalink
ft logout feature
Browse files Browse the repository at this point in the history
  • Loading branch information
Ndevu12 committed May 6, 2024
1 parent daf808c commit 15d543a
Show file tree
Hide file tree
Showing 5 changed files with 100 additions and 0 deletions.
74 changes: 74 additions & 0 deletions src/__test__/logout.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
import request from 'supertest';
import { app, server } from '../index';
import { createConnection, getConnection, getConnectionOptions, getRepository } from 'typeorm';
import { User } from '../entities/User';

beforeAll(async () => {
// Connect to the test database
const connectionOptions = await getConnectionOptions();
await createConnection({ ...connectionOptions, name: 'testConnection' });
});

afterAll(async () => {
await getConnection('testConnection').close();
server.close();
});

describe('POST /user/logout', () => {
it('should logout a user', async () => {
// sign up a user
const registerUser = {
firstName: 'Ndevu',
lastName: 'Elisa',
email: 'ndevukumurindi@gmail.com',
gender: 'male',
phoneNumber: '078907987443',
photoUrl: 'https://example.com/images/photo.jpg',
userType: 'vender',
verified: true,
status: 'active',
password: process.env.TEST_USER_LOGIN_PASS,
};

await request(app).post('/user/register').send(registerUser);

const loginUser = {
email: registerUser.email,
password: process.env.TEST_USER_LOGIN_PASS,
};

const userRepository = getRepository(User);
const user = await userRepository.findOne({ where: { email: registerUser.email } });
if (user) {
const verifyRes = await request(app).get(`/user/verify/${user.id}`);

if (!verifyRes) throw new Error(`Test User verification failed for ${user.email}`);

const loginResponse = await request(app).post('/user/login').send(loginUser);
const setCookie = loginResponse.headers['set-cookie'];

if (!setCookie) {
throw new Error('No cookies set in login response');
}

const resp = await request(app).post('/user/logout').set('Cookie', setCookie);
expect(resp.status).toBe(200);
expect(resp.body).toEqual({ Message: 'Logged out successfully' });

// Clean up: delete the test user
await userRepository.remove(user);
}
});

it('should not logout a user who is not logged in or with no token', async () => {
const fakeEmail = 'ndevukkkk@gmail.com';
const loginUser = {
email: fakeEmail,
password: process.env.TEST_USER_LOGIN_PASS,
};
const token = '';
const res = await request(app).post('/user/logout').send(loginUser).set('Cookie', token);
expect(res.status).toBe(400);
expect(res.body).toEqual({ Message: 'Access denied. You must be logged in' });
});
});
5 changes: 5 additions & 0 deletions src/controllers/authController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
userDisableTwoFactorAuth,
userValidateOTP,
userResendOtpService,
logoutService,
} from '../services';

export const userRegistration = async (req: Request, res: Response) => {

Check warning on line 13 in src/controllers/authController.ts

View workflow job for this annotation

GitHub Actions / build-lint-test-coverage

Missing return type on function

Check warning on line 13 in src/controllers/authController.ts

View workflow job for this annotation

GitHub Actions / build-lint-test-coverage

Missing return type on function
Expand Down Expand Up @@ -36,3 +37,7 @@ export const verifyOTP = async (req: Request, res: Response) => {
export const resendOTP = async (req: Request, res: Response) => {
await userResendOtpService(req, res);
};

export const logout = async (req: Request, res: Response) => {
await logoutService(req, res);
};
2 changes: 2 additions & 0 deletions src/routes/UserRoutes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,15 @@ import {
disable2FA,
verifyOTP,
resendOTP,
logout,
} from '../controllers/authController';

const router = Router();

router.post('/register', userRegistration);
router.get('/verify/:id', userVerification);
router.post('/login', login);
router.post('/logout', logout);
router.post('/enable-2fa', enable2FA);
router.post('/disable-2fa', disable2FA);
router.post('/verify-otp', verifyOTP);
Expand Down
1 change: 1 addition & 0 deletions src/services/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,4 @@ export * from './userServices/userDisableTwoFactorAuth';
export * from './userServices/userValidateOTP';
export * from './userServices/userLoginService';
export * from './userServices/userResendOTP';
export * from './userServices/logoutServices';
18 changes: 18 additions & 0 deletions src/services/userServices/logoutServices.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { Request, Response } from 'express';

// logout method
export const logoutService = async (req: Request, res: Response): Promise<void> => {
try {
const token = req.cookies['token'] || null;
if (!token) {
res.status(400).json({ Message: 'Access denied. You must be logged in' });
return;
}

res.clearCookie('token');
res.status(200).json({ Message: 'Logged out successfully' });
} catch (error) {
console.error('Error logging out:', error);
res.status(500).json({ error: 'Sorry, Token required.' });
}
};

0 comments on commit 15d543a

Please sign in to comment.