Skip to content

Commit

Permalink
fix(redis_auth): auth usign mongo if not connected
Browse files Browse the repository at this point in the history
fixing #67
  • Loading branch information
roman-ojha committed Jun 8, 2022
1 parent d536397 commit 104cb7e
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 4 deletions.
43 changes: 40 additions & 3 deletions middleware/auth/authUsingRedis.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ const redisClient = redis.createClient({
const connectRedis = async (): Promise<boolean> => {
try {
await redisClient.connect();
console.log("Redis Connection Successful");
console.log("Redis Connected Successfully");
isRedisConnected = true;
return true;
} catch (err) {
Expand All @@ -26,6 +26,14 @@ const connectRedis = async (): Promise<boolean> => {
}
};

redisClient.on("error", function (err) {
// if redis disconnected or throw error
if (isRedisConnected === true) {
isRedisConnected = false;
console.log(isRedisConnected);
}
});

const authenticate: RequestHandler = async (
req: Request,
res: Response,
Expand Down Expand Up @@ -109,9 +117,38 @@ const authenticate: RequestHandler = async (
req.userID = parsedUserDetail.userID;
next();
} else {
// redis is not connected
// redis is not connected then we have to authenticate using mongodb
const rootUser = 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 (!rootUser) {
return res.status(401).send(<ResponseObject>{
success: false,
msg: "User not found, sorry not a valid token",
});
}
req.token = token;
req.rootUser = rootUser;
req.userID = rootUser.userID;
next();
}
} catch (err) {}
} catch (err) {
return res.status(500).json(<ResponseObject>{
success: false,
msg: "Server Error!!, Please Try again later",
});
}
};

export default authenticate;
Expand Down
5 changes: 4 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,10 @@ import cors from "cors";
import bodyParser from "body-parser";
import { httpServer, app } from "../socket/io.js";
import AuthAdmin from "../funcs/AuthAdmin.js";
import { connectRedis } from "../middleware/auth/authUsingRedis.js";
import {
connectRedis,
redisClient,
} from "../middleware/auth/authUsingRedis.js";
const PORT = process.env.PORT;

// warning: connect.session() MemoryStorage is not designed for a production environment as it will leak memory, and will not scale past a single process.
Expand Down

0 comments on commit 104cb7e

Please sign in to comment.