Skip to content

Commit

Permalink
fix(redis_auth): stored, get & verifyed
Browse files Browse the repository at this point in the history
fixing #67
  • Loading branch information
roman-ojha committed Jun 8, 2022
1 parent 600db61 commit a24edd4
Show file tree
Hide file tree
Showing 5 changed files with 92 additions and 24 deletions.
26 changes: 15 additions & 11 deletions controllers/userAuth.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import {
UserDocumentNotification,
} from "../interface/userDocument.js";
import { redisClient } from "../middleware/auth/authUsingRedis.js";
import RedisUserDetail from "../interface/redisUserDetail.js";

export default {
register: async (req: Request, res: Response): Promise<object> => {
Expand Down Expand Up @@ -244,7 +245,7 @@ export default {
password: 1,
userID: 1,
name: 1,
tokens: 1,
tokens: { $slice: -5 },
id: 1,
}
);
Expand Down Expand Up @@ -279,16 +280,19 @@ export default {
}

// Storing User Data in redis
// await redisClient.lPush("userDetail", JSON.stringify(userLogin));

redisClient
.lRange("userDetail", 0, 1)
.then((data) => {
// console.log(data);
})
.catch((err) => {
console.log(err);
});
const redisUserDetail: RedisUserDetail = {
id: userLogin.id,
email: userLogin.email,
name: userLogin.name,
tokens: userLogin.tokens,
userID: userLogin.userID,
};
await redisClient.setEx(
userLogin.id,
864000,
// for 10 days
JSON.stringify(redisUserDetail)
);

// NOTE: if we would host hosted client app on vercel and server on heroku and Cookies are not cross-domain compatible. if it was, it would be a serious security issue. So that we have to pass the token as response object
return res.status(200).json(<ResponseObject>{
Expand Down
11 changes: 11 additions & 0 deletions interface/redisUserDetail.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
type RedisUserDetail = {
id: string;
name: string;
email: string;
userID: string;
tokens: {
token: string;
}[];
};

export default RedisUserDetail;
67 changes: 57 additions & 10 deletions middleware/auth/authUsingRedis.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,11 @@ import UserDetail from "../../models/userDetail_model.js";
import redis, { RedisClientType } from "redis";
import { RequestHandler, Request, Response, NextFunction } from "express";
import jwt from "jsonwebtoken";
import ExtendJWTPayload from "../../types/jsonwebtoken/extend-jwt-payload.js";
import ResponseObject from "../../interface/responseObject.js";

const REDIS_PORT = process.env.REDIS_PORT || 6379;
let isRedisConnected: boolean = false;

const redisClient = redis.createClient({
socket: { port: REDIS_PORT as number, host: "localhost" },
Expand All @@ -13,22 +16,66 @@ const connectRedis = async (): Promise<boolean> => {
try {
await redisClient.connect();
console.log("Redis Connection Successful");
isRedisConnected = true;
return true;
} catch (err) {
console.log("Err: Can't be able to connect with redis");
isRedisConnected = false;
return false;
}
};

// const authenticate: RequestHandler = async (
// req: Request,
// res: Response,
// next: NextFunction
// ) => {
// const token = req.cookies.AuthToken;
// const verifyToken = jwt.verify(token, process.env.SECRET_KEY);
// console.log(verifyToken);
// };
const authenticate: RequestHandler = async (
req: Request,
res: Response,
next: NextFunction
) => {
try {
const token = req.cookies.AuthToken;
const verifyToken = jwt.verify(
token,
process.env.SECRET_KEY!
) as ExtendJWTPayload;
console.log(isRedisConnected);
const userFromRedis = await redisClient.get(verifyToken.id);
// .then((data) => {
// console.log(data);
// })
// .catch((err) => {
// console.log(err);
// });
if (userFromRedis === null) {
// next();
const getUser = await UserDetail.findOne(
{
id: verifyToken.id,
"tokens.token": token,
},
// filtering to get only data that is need when page load
{
userID: 1,
name: 1,
id: 1,
email: 1,
_id: 0,
}
);
if (!getUser) {
return res.status(401).send(<ResponseObject>{
success: false,
msg: "User not found, sorry not a valid token",
});
}
req.token = token;
req.rootUser = getUser;
req.userID = getUser.userID;
next();
return;
}
// console.log(JSON.parse(userFromRedis));
next();
} catch (err) {}
};

// export default authenticate;
export default authenticate;
export { redisClient, connectRedis };
4 changes: 2 additions & 2 deletions middleware/auth/authenticate.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import jwt from "jsonwebtoken";
import userDetail from "../../models/userDetail_model.js";
import { RequestHandler, Request, Response, NextFunction } from "express";
import ExtendJWTPayload from "types/jsonwebtoken/extend-jwt-payload.js";
import ExtendJWTPayload from "../../types/jsonwebtoken/extend-jwt-payload.js";
import ResponseObject from "../../interface/responseObject";

const authenticate: RequestHandler = async (
Expand Down Expand Up @@ -37,7 +37,7 @@ const authenticate: RequestHandler = async (
}
req.token = token;
req.rootUser = rootUser;
req.userID = <any>rootUser._id;
req.userID = rootUser.userID;
next();
} catch (err) {
return res.status(401).send(<ResponseObject>{
Expand Down
8 changes: 7 additions & 1 deletion routes/user.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,15 @@
import express from "express";
import authenticate from "../middleware/auth/authenticate.js";
import userController from "../controllers/user.controller.js";
import authenticateWitRedis from "../middleware/auth/authUsingRedis.js";
const userRoute = express.Router();

userRoute.get("/index", authenticate, userController.main);
userRoute.get(
"/index",
authenticateWitRedis,
authenticate,
userController.main
);

userRoute.get("/u", authenticate, userController.homeUser);

Expand Down

0 comments on commit a24edd4

Please sign in to comment.