#11 made logout on backend

parent de9a973f
import {Request, Response} from 'express'; import {Request, Response} from 'express';
import {getErrorMessage} from '../utils/errors.util'; import {getErrorMessage} from '../utils/errors.util';
import * as userServices from '../services/user'; import * as userServices from '../services/user';
import jwt from 'jsonwebtoken';
export const loginOne = async (req: Request, res: Response) => { export const loginOne = async (req: Request, res: Response) => {
try { try {
...@@ -19,3 +20,16 @@ export const registerOne = async (req: Request, res: Response) => { ...@@ -19,3 +20,16 @@ export const registerOne = async (req: Request, res: Response) => {
return res.status(500).send(getErrorMessage(error)); return res.status(500).send(getErrorMessage(error));
} }
}; };
export const logout = async (req: Request, res: Response) => {
try {
const authHeader = req.headers['authorization'];
jwt.sign(authHeader!, '', {expiresIn: 1}, (logout, err) => {
if (logout) {
res.send('You have been logged out');
}
});
} catch (err: unknown) {
throw err;
}
};
import mongoose from 'mongoose'; import mongoose from 'mongoose';
export default interface IUser extends mongoose.Document { export default interface IUser extends mongoose.Document {
_id: string;
username: string; username: string;
password: string; password: string;
token: string; token: string;
......
...@@ -5,5 +5,6 @@ const router: Router = Router(); ...@@ -5,5 +5,6 @@ const router: Router = Router();
router.post('/', userController.registerOne); router.post('/', userController.registerOne);
router.post('/sessions', userController.loginOne); router.post('/sessions', userController.loginOne);
router.put('/logout', userController.logout);
export {router as UsersRouter}; export {router as UsersRouter};
...@@ -30,7 +30,11 @@ export async function login(user: IUser) { ...@@ -30,7 +30,11 @@ export async function login(user: IUser) {
} }
); );
await UserModel.findOneAndUpdate({username: user.username}, {token}); await UserModel.findOneAndUpdate({username: user.username}, {token});
return {token: token}; return {
token: token,
username: user.username,
id: foundUser._id.toString(),
};
} else { } else {
throw new Error('Password is not correct'); throw new Error('Password is not correct');
} }
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment