Skip to content

Commit

Permalink
fix(auth): auth from id rather then _id
Browse files Browse the repository at this point in the history
  • Loading branch information
roman-ojha committed Jun 8, 2022
1 parent 1e06008 commit 600db61
Show file tree
Hide file tree
Showing 7 changed files with 45 additions and 16 deletions.
14 changes: 14 additions & 0 deletions controllers/userAuth.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import {
UserDocumentMessages,
UserDocumentNotification,
} from "../interface/userDocument.js";
import { redisClient } from "../middleware/auth/authUsingRedis.js";

export default {
register: async (req: Request, res: Response): Promise<object> => {
Expand Down Expand Up @@ -244,6 +245,7 @@ export default {
userID: 1,
name: 1,
tokens: 1,
id: 1,
}
);
if (!userLogin) {
Expand Down Expand Up @@ -276,6 +278,18 @@ 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);
});

// 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>{
success: true,
Expand Down
2 changes: 1 addition & 1 deletion funcs/varifyUser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ export default async function varifyUser(token: string) {
) as ExtendJWTPayload;
const rootUser = await userDetail.findOne(
{
_id: verifyToken._id,
id: verifyToken.id,
"tokens.token": token,
},
{
Expand Down
37 changes: 25 additions & 12 deletions middleware/auth/authUsingRedis.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,34 @@
import UserDetail from "../../models/userDetail_model.js";
import redis, { RedisClientType } from "redis";
import { RequestHandler, Request, Response, NextFunction } from "express";
import jwt from "jsonwebtoken";

const REDIS_PORT = process.env.REDIS_PORT || 6379;

const redisClient = redis.createClient({
socket: { port: REDIS_PORT as number },
socket: { port: REDIS_PORT as number, host: "localhost" },
});

const connectRedis = async () => {
await redisClient
.connect()
.then(() => {
console.log("Redis Connection Successful");
return true;
})
.catch((err) => {
console.log("Err: Can't be able to connect with redis");
return false;
});
const connectRedis = async (): Promise<boolean> => {
try {
await redisClient.connect();
console.log("Redis Connection Successful");
return true;
} catch (err) {
console.log("Err: Can't be able to connect with redis");
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);
// };

// export default authenticate;
export { redisClient, connectRedis };
2 changes: 1 addition & 1 deletion middleware/auth/authenticate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ const authenticate: RequestHandler = async (
) as ExtendJWTPayload;
const rootUser = await userDetail.findOne(
{
_id: verifyToken._id,
id: verifyToken.id,
"tokens.token": token,
},
// filtering to get only data that is need when page load
Expand Down
2 changes: 1 addition & 1 deletion models/userDetail_model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -237,7 +237,7 @@ userDetailSchema.methods.generateAuthToken = async function (): Promise<
string | null
> {
try {
let token: string = jwt.sign({ _id: this._id }, process.env.SECRET_KEY!);
let token: string = jwt.sign({ id: this.id }, process.env.SECRET_KEY!);
this.tokens = this.tokens.concat({ token: token });
await this.save();
return token;
Expand Down
2 changes: 2 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ 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";
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 Expand Up @@ -55,6 +56,7 @@ app.use(bodyParser.json() as RequestHandler);
// Database connection
import("../db/userDataConnection.js");
import("../db/userStorageConnection.js");
await connectRedis();

// Connection router
app.use(indexRouter);
Expand Down
2 changes: 1 addition & 1 deletion types/jsonwebtoken/extend-jwt-payload.d.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
export default interface ExtendJWTPayload {
_id: string;
id: string;
}

0 comments on commit 600db61

Please sign in to comment.