Skip to content

Commit

Permalink
feat-#3: Made the entire backend code from javascript to typescript (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
krishnaacharyaa authored Aug 27, 2024
2 parents e298b45 + ee63d77 commit 778bec3
Show file tree
Hide file tree
Showing 43 changed files with 472 additions and 298 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,5 @@ backend/node_modules
/node_modules
coverage/
.idea/
backend/dist
package-lock.json
File renamed without changes.
4 changes: 2 additions & 2 deletions backend/app.js → backend/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,20 +2,20 @@ import compression from 'compression';
import cookieParser from 'cookie-parser';
import cors from 'cors';
import express from 'express';
import { FRONTEND_URL } from './config/utils.js';
import authRouter from './routes/auth.js';
import postsRouter from './routes/posts.js';
import userRouter from './routes/user.js';
import errorMiddleware from './middlewares/error-middleware.js';
import passport from './config/passport.js';
import session from 'express-session';
import { FRONTEND_URL } from './config/utils.js';

const app = express();

app.use(
cors({
// added origin
origin: [FRONTEND_URL, 'http://localhost:3000'],
origin: [FRONTEND_URL as string, 'http://localhost:3000'],
credentials: true,
})
);
Expand Down
6 changes: 3 additions & 3 deletions backend/config/db.js → backend/config/db.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import mongoose from 'mongoose';
import mongoose, { AnyArray } from 'mongoose';
import { MONGODB_URI } from './utils.js';

export default async function connectDB() {
try {
await mongoose.connect(MONGODB_URI, {
await mongoose.connect(MONGODB_URI as string, {
dbName: 'wanderlust',
});
console.log(`Database connected: ${MONGODB_URI}`);
} catch (err) {
} catch (err: any) {
console.error(err.message);
process.exit(1);
}
Expand Down
9 changes: 4 additions & 5 deletions backend/config/passport.js → backend/config/passport.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,14 @@
import passport from 'passport';
import { Strategy as GoogleStrategy } from 'passport-google-oauth20';
import User from '../models/user.js';

passport.use(
new GoogleStrategy(
{
clientID: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
clientID: process.env.GOOGLE_CLIENT_ID as string,
clientSecret: process.env.GOOGLE_CLIENT_SECRET as string,
callbackURL: `${process.env.BACKEND_URL}/api/auth/google/callback`,
},
async (accessToken, refreshToken, profile, done) => {
async (accessToken: string, refreshToken: string, profile: any, done: any) => {
try {
let user = await User.findOne({ googleId: profile.id });

Expand Down Expand Up @@ -40,7 +39,7 @@ passport.use(
)
);

passport.serializeUser((user, done) => done(null, user.id));
passport.serializeUser((user: any, done) => done(null, user.id));

passport.deserializeUser(async (id, done) => {
try {
Expand Down
File renamed without changes.
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,18 @@ import { JWT_SECRET } from '../config/utils.js';
import { ApiError } from '../utils/api-error.js';
import { ApiResponse } from '../utils/api-response.js';
import { asyncHandler } from '../utils/async-handler.js';
import { NextFunction, Request, Response } from 'express';

//REGULAR EMAIL PASSWORD STRATEGY
//1.Sign Up
export const signUpWithEmail = asyncHandler(async (req, res) => {

export const signUpWithEmail = asyncHandler(async (req: Request, res: Response) => {
const { userName, fullName, email, password } = req.body;
if (!userName || !fullName || !email || !password) {
throw new ApiError(HTTP_STATUS.BAD_REQUEST, RESPONSE_MESSAGES.COMMON.REQUIRED_FIELDS);
throw new ApiError({
status: HTTP_STATUS.BAD_REQUEST,
message: RESPONSE_MESSAGES.COMMON.REQUIRED_FIELDS,
});
}

const existingUser = await User.findOne({
Expand All @@ -21,10 +26,16 @@ export const signUpWithEmail = asyncHandler(async (req, res) => {

if (existingUser) {
if (existingUser.userName === userName) {
throw new ApiError(HTTP_STATUS.BAD_REQUEST, RESPONSE_MESSAGES.USERS.USER_USERNAME_EXISTS);
throw new ApiError({
status: HTTP_STATUS.BAD_REQUEST,
message: RESPONSE_MESSAGES.USERS.USER_USERNAME_EXISTS,
});
}
if (existingUser.email === email) {
throw new ApiError(HTTP_STATUS.BAD_REQUEST, RESPONSE_MESSAGES.USERS.USER_EMAIL_EXISTS);
throw new ApiError({
status: HTTP_STATUS.BAD_REQUEST,
message: RESPONSE_MESSAGES.USERS.USER_EMAIL_EXISTS,
});
}
}

Expand All @@ -37,12 +48,15 @@ export const signUpWithEmail = asyncHandler(async (req, res) => {

try {
await user.validate();
} catch (error) {
const validationErrors = [];
} catch (error: any) {
const validationErrors: any = [];
for (const key in error.errors) {
validationErrors.push(error.errors[key].message);
validationErrors.push(error.errors[key].message as never);
}
throw new ApiError(HTTP_STATUS.BAD_REQUEST, validationErrors.join(', '));
throw new ApiError({
status: HTTP_STATUS.BAD_REQUEST,
errors: validationErrors.join(', '),
});
}

const accessToken = await user.generateAccessToken();
Expand Down Expand Up @@ -71,24 +85,33 @@ export const signUpWithEmail = asyncHandler(async (req, res) => {
});

//2.Sign In
export const signInWithEmailOrUsername = asyncHandler(async (req, res) => {
export const signInWithEmailOrUsername = asyncHandler(async (req: Request, res: Response) => {
const { userNameOrEmail, password } = req.body;
if (!userNameOrEmail || !password) {
throw new ApiError(HTTP_STATUS.BAD_REQUEST, RESPONSE_MESSAGES.COMMON.REQUIRED_FIELDS);
throw new ApiError({
status: HTTP_STATUS.BAD_REQUEST,
message: RESPONSE_MESSAGES.COMMON.REQUIRED_FIELDS,
});
}

const user = await User.findOne({
$or: [{ email: userNameOrEmail }, { userName: userNameOrEmail }],
}).select('+password');

if (!user) {
throw new ApiError(HTTP_STATUS.BAD_REQUEST, RESPONSE_MESSAGES.USERS.USER_NOT_EXISTS);
throw new ApiError({
status: HTTP_STATUS.BAD_REQUEST,
message: RESPONSE_MESSAGES.USERS.USER_NOT_EXISTS,
});
}

const isCorrectPassword = await user.isPasswordCorrect(password);

if (!isCorrectPassword) {
throw new ApiError(HTTP_STATUS.UNAUTHORIZED, RESPONSE_MESSAGES.USERS.INVALID_PASSWORD);
throw new ApiError({
status: HTTP_STATUS.UNAUTHORIZED,
message: RESPONSE_MESSAGES.USERS.INVALID_PASSWORD,
});
}
const accessToken = await user.generateAccessToken();
const refreshToken = await user.generateRefreshToken();
Expand All @@ -115,7 +138,7 @@ export const signInWithEmailOrUsername = asyncHandler(async (req, res) => {
});

//Sign Out
export const signOutUser = asyncHandler(async (req, res, next) => {
export const signOutUser = asyncHandler(async (req: Request, res: Response, next: NextFunction) => {
await User.findByIdAndUpdate(
req.user?._id,
{
Expand All @@ -129,9 +152,14 @@ export const signOutUser = asyncHandler(async (req, res, next) => {
);

// Passport.js logout
req.logout((err) => {
req.logout((err: any) => {
if (err) {
return next(new ApiError(HTTP_STATUS.INTERNAL_SERVER_ERROR, 'Logout failed'));
return next(
new ApiError({
status: HTTP_STATUS.INTERNAL_SERVER_ERROR,
message: 'Logout failed',
})
);
}

res
Expand All @@ -143,7 +171,7 @@ export const signOutUser = asyncHandler(async (req, res, next) => {
});
});
// check user
export const isLoggedIn = asyncHandler(async (req, res) => {
export const isLoggedIn = asyncHandler(async (req: Request, res: Response) => {
let access_token = req.cookies?.access_token;
let refresh_token = req.cookies?.refresh_token;
const { _id } = req.params;
Expand All @@ -155,18 +183,22 @@ export const isLoggedIn = asyncHandler(async (req, res) => {
}
if (access_token) {
try {
await jwt.verify(access_token, JWT_SECRET);
if (JWT_SECRET) {
await jwt.verify(access_token, JWT_SECRET);
}
return res
.status(HTTP_STATUS.OK)
.json(new ApiResponse(HTTP_STATUS.OK, access_token, RESPONSE_MESSAGES.USERS.VALID_TOKEN));
} catch (error) {
} catch (error: any) {
console.log('Access token verification error:', error.message);
}
}
// If access token is not valid, check the refresh token
if (refresh_token) {
try {
await jwt.verify(refresh_token, JWT_SECRET);
if (JWT_SECRET) {
await jwt.verify(refresh_token, JWT_SECRET);
}
const user = await User.findById(_id);
if (!user) {
return res
Expand All @@ -180,7 +212,7 @@ export const isLoggedIn = asyncHandler(async (req, res) => {
.status(HTTP_STATUS.OK)
.cookie('access_token', access_token, cookieOptions)
.json(new ApiResponse(HTTP_STATUS.OK, access_token, RESPONSE_MESSAGES.USERS.VALID_TOKEN));
} catch (error) {
} catch (error: any) {
console.log('Refresh token verification error:', error.message);
}
}
Expand All @@ -202,7 +234,9 @@ export const isLoggedIn = asyncHandler(async (req, res) => {
}

try {
await jwt.verify(refreshToken, JWT_SECRET);
if (JWT_SECRET) {
await jwt.verify(refreshToken, JWT_SECRET);
}
access_token = await user.generateAccessToken();
refresh_token = await user.generateRefreshToken();

Expand All @@ -213,7 +247,7 @@ export const isLoggedIn = asyncHandler(async (req, res) => {
.cookie('access_token', access_token, cookieOptions)
.cookie('refresh_token', refresh_token, cookieOptions)
.json(new ApiResponse(HTTP_STATUS.OK, access_token, RESPONSE_MESSAGES.USERS.VALID_TOKEN));
} catch (error) {
} catch (error: any) {
return res
.status(HTTP_STATUS.UNAUTHORIZED)
.json(
Expand Down
Loading

0 comments on commit 778bec3

Please sign in to comment.