Skip to content

Commit

Permalink
ft storing token in cookies and adding token validator
Browse files Browse the repository at this point in the history
  • Loading branch information
Ndevu12 committed May 6, 2024
1 parent 0a75be4 commit daf808c
Show file tree
Hide file tree
Showing 5 changed files with 63 additions and 1 deletion.
2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
"axios": "^1.6.8",
"bcrypt": "^5.1.1",
"class-validator": "^0.14.1",
"cookie-parser": "^1.4.6",
"cors": "^2.8.5",
"cross-env": "^7.0.3",
"dotenv": "^16.4.5",
Expand Down Expand Up @@ -54,6 +55,7 @@
"@eslint/js": "^9.1.1",
"@types/bcrypt": "^5.0.2",
"@types/body-parser": "^1.19.5",
"@types/cookie-parser": "^1.4.7",
"@types/cors": "^2.8.17",
"@types/dotenv": "^8.2.0",
"@types/eslint": "^8.56.10",
Expand Down
19 changes: 19 additions & 0 deletions src/helper/verify.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import jwt from 'jsonwebtoken';
import dotenv from 'dotenv';

dotenv.config();

const jwtSecretKey = process.env.JWT_SECRETKEY;

if (!jwtSecretKey) {
throw new Error('JWT_SECRETKEY is not defined in the environment variables.');
}

export const verifiedToken = (token: string): any => {
try {
return jwt.verify(token, jwtSecretKey);
} catch (err) {
console.error(err);
return null;
}
};
3 changes: 2 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import dotenv from 'dotenv';
import router from './routes';
import { addDocumentation } from './startups/docs';
import 'reflect-metadata';
import cookieParser from 'cookie-parser';

import { CustomError, errorHandler } from './middlewares/errorHandler';
import morgan from 'morgan';
Expand All @@ -13,7 +14,7 @@ dotenv.config();
export const app = express();
const port = process.env.PORT || 8000;
app.use(express.json());

app.use(cookieParser());
app.use(cors({ origin: '*' }));
app.use(router);
addDocumentation(app);
Expand Down
33 changes: 33 additions & 0 deletions src/middlewares/isValide.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { Request, Response, NextFunction, RequestHandler } from 'express';
import { verifiedToken } from '../helper/verify';

export interface DecodedUser {
userType: string;
id: string;
email: string;
}

export interface CustomeRequest extends Request {
user?: DecodedUser;
}

export const isTokenValide: RequestHandler = async (
req: CustomeRequest,
res: Response,
next: NextFunction
): Promise<void> => {
try {
const token = req.cookies.token;
const user = verifiedToken(token) as DecodedUser;
if (!user) {
res.status(401).json({ Message: 'Sorry, You are not authorized' });
return;
}
req.user = user;
return next();
} catch (error) {
console.error('Error in token Validation middleware:\n', error);
res.status(401).json({ Message: 'Sorry, Something went wrong' });
return;
}
};
7 changes: 7 additions & 0 deletions src/services/userServices/userLoginService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,13 @@ export const userLoginService = async (req: Request, res: Response) => {
process.env.JWT_SECRET as string,
{ expiresIn: '24h' }
);

if (process.env.APP_ENV === 'production') {
res.cookie('token', token, { httpOnly: true, sameSite: false, secure: true });
} else {
res.cookie('token', token, { httpOnly: true, sameSite: 'lax', secure: false });
}

return res.status(200).json({
status: 'success',
data: {
Expand Down

0 comments on commit daf808c

Please sign in to comment.