Skip to content

Commit

Permalink
feat-#3: made the login, signup and add-blog workflow correctly
Browse files Browse the repository at this point in the history
  • Loading branch information
Ameerjafar committed Aug 19, 2024
1 parent 2a8a535 commit 4a7d159
Show file tree
Hide file tree
Showing 9 changed files with 21 additions and 21 deletions.
2 changes: 1 addition & 1 deletion backend/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ const app = express();
app.use(
cors({
// added origin
origin: ['http://localhost:3000'],
origin: [FRONTEND_URL as string, 'http://localhost:3000'],
credentials: true,
})
);
Expand Down
9 changes: 4 additions & 5 deletions backend/controllers/posts-controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ export const createPostHandler = async (req: Request, res: Response) => {
description,
isFeaturedPost = false,
} = req.body;

const userId = req.user._id;

// Validation - check if all fields are filled
Expand Down Expand Up @@ -50,17 +49,17 @@ export const createPostHandler = async (req: Request, res: Response) => {

const [savedPost] = await Promise.all([
post.save(), // Save the post
deleteDataFromCache(REDIS_KEYS.ALL_POSTS), // Invalidate cache for all posts
deleteDataFromCache(REDIS_KEYS.FEATURED_POSTS), // Invalidate cache for featured posts
deleteDataFromCache(REDIS_KEYS.LATEST_POSTS), // Invalidate cache for latest posts
// deleteDataFromCache(REDIS_KEYS.ALL_POSTS), // Invalidate cache for all posts
// deleteDataFromCache(REDIS_KEYS.FEATURED_POSTS), // Invalidate cache for featured posts
// deleteDataFromCache(REDIS_KEYS.LATEST_POSTS), // Invalidate cache for latest posts
]);

// updating user doc to include the ObjectId of the created post
await User.findByIdAndUpdate(userId, { $push: { posts: savedPost._id } });

res.status(HTTP_STATUS.OK).json(savedPost);
} catch (err: any) {
res.status(HTTP_STATUS.INTERNAL_SERVER_ERROR).json({ message: err.message });
res.status(HTTP_STATUS.INTERNAL_SERVER_ERROR).json({ message: err });
}
};

Expand Down
8 changes: 4 additions & 4 deletions backend/middlewares/auth-middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,14 @@ import { Role } from '../types/role-type';
import User from '../models/user';

import { Request, Response, NextFunction } from 'express';
import { ObjectId } from 'mongoose';

interface JwtPayload {
_id: string;
_id: ObjectId;
}

export const authMiddleware = async (req: Request, res: Response, next: NextFunction) => {
const token = req.cookies?.access_token;
const token = await req.cookies.access_token;
if (!token) {
return next(
new ApiError({
Expand All @@ -24,11 +25,10 @@ export const authMiddleware = async (req: Request, res: Response, next: NextFunc

try {
const { _id } = jwt.verify(token, JWT_SECRET as string) as JwtPayload;

req.user = await User.findById(_id);
next();
} catch (error: any) {
console.log('Token verification error:', error.message);
console.log('Token verification error:', error);
return next(
new ApiError({
status: HTTP_STATUS.FORBIDDEN,
Expand Down
1 change: 0 additions & 1 deletion backend/models/user.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import { ACCESS_TOKEN_EXPIRES_IN, JWT_SECRET, REFRESH_TOKEN_EXPIRES_IN } from '.
import { Role } from '../types/role-type';

interface UserObject extends Document {
id: number;
userName: string;
fullName: string;
email: string;
Expand Down
2 changes: 2 additions & 0 deletions backend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,11 @@
"@types/cors": "^2.8.17",
"@types/express": "^4.17.21",
"@types/express-session": "^1.18.0",
"@types/ioredis": "^5.0.0",
"@types/jsonwebtoken": "^9.0.6",
"@types/passport": "^1.0.16",
"@types/passport-google-oauth20": "^2.0.16",
"@types/redis": "^4.0.11",
"@types/supertest": "^6.0.2",
"axios": "^1.6.8",
"bcryptjs": "^2.4.3",
Expand Down
3 changes: 1 addition & 2 deletions backend/services/redis.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import { createClient } from 'redis';
import { REDIS_URL } from '../config/utils';

let redis: any = null;

export async function connectToRedis() {
try {
if (REDIS_URL) {
Expand All @@ -19,6 +18,6 @@ export async function connectToRedis() {
}
}

export function getRedisClient() {
export function getRedisClient(): any {
return redis;
}
4 changes: 2 additions & 2 deletions backend/types/types.d.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
declare namespace Express {
export interface Request {
user?: any;
user: any;
}
export interface Response {
user?: any;
user: any;
}
}
11 changes: 6 additions & 5 deletions backend/utils/cache-posts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ function isRedisEnabled() {
return getRedisClient() !== null;
}

export async function retrieveDataFromCache(key: string) {
export async function retrieveDataFromCache(key: any) {
if (!isRedisEnabled()) return null; // Skip cache if Redis is not available

const cacheKey = `${REDIS_PREFIX}:${key}`;
Expand All @@ -17,16 +17,17 @@ export async function retrieveDataFromCache(key: string) {
return null;
}

export async function storeDataInCache(key: string, data: any) {
export async function storeDataInCache(key: any, data: any) {
if (!isRedisEnabled()) return; // Skip cache if Redis is not available

const cacheKey = `${REDIS_PREFIX}:${key}`;
await getRedisClient().set(cacheKey, JSON.stringify(data));
}

export async function deleteDataFromCache(key: string) {
export async function deleteDataFromCache(key: any): Promise<void> {
if (!isRedisEnabled()) return; // Skip cache if Redis is not available

const cacheKey = `${REDIS_PREFIX}:${key}`;
await getRedisClient().del(cacheKey);
if (getRedisClient().exists(cacheKey)) {
await getRedisClient().del(cacheKey);
}
}
2 changes: 1 addition & 1 deletion backend/utils/cookie_options.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ interface CookieObject {
httpOnly: boolean;
sameSite: 'lax' | 'strict' | 'none';
secure: boolean;
maxAge?: number | undefined;
maxAge: number;
}
const maxAge =
typeof ACCESS_COOKIE_MAXAGE === 'string' ? parseInt(ACCESS_COOKIE_MAXAGE, 10) : defaultMaxAge;
Expand Down

0 comments on commit 4a7d159

Please sign in to comment.