Skip to content

Commit

Permalink
working backend
Browse files Browse the repository at this point in the history
  • Loading branch information
Bot-Rakshit committed Jun 26, 2024
1 parent d636424 commit 25063f6
Show file tree
Hide file tree
Showing 10 changed files with 128 additions and 20 deletions.
32 changes: 32 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,8 @@
"@types/cors": "^2.8.12",
"@types/express": "^4.17.13",
"@types/express-session": "^1.18.0",
"@types/gapi": "^0.0.47",
"@types/gapi.auth2": "^0.0.60",
"@types/jsonwebtoken": "^8.5.8",
"@types/node": "^18.0.0",
"@types/node-cron": "^3.0.11",
Expand Down
11 changes: 8 additions & 3 deletions src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,18 @@ import compression from 'compression';
import session from 'express-session';
import { errorHandler } from './middlewares/errorHandler';
import authRoutes from './routes/auth';
import chessRoutes from './routes/chess';
import chessRoutes from './routes/chess';// Import the test routes
import './config/passport';
import './utils/scheduler';

const app = express();

app.use(cors());
// Configure CORS to allow requests from the frontend
app.use(cors({
origin: process.env.FRONTEND || 'http://localhost:5173', // Use the FRONTEND environment variable or default to localhost
credentials: true // Allow credentials (cookies, authorization headers, etc.)
}));

app.use(helmet());
app.use(compression());
app.use(express.json());
Expand All @@ -30,7 +35,7 @@ app.use(passport.initialize());
app.use(passport.session());

app.use('/api/auth', authRoutes);
app.use('/api/chess', chessRoutes);
app.use('/api/chess', chessRoutes);// Use the test routes

app.use(errorHandler);

Expand Down
24 changes: 21 additions & 3 deletions src/controllers/authController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { User } from '../models/User';
import jwt from 'jsonwebtoken';
import { createOrUpdateChessInfo } from '../services/chessInfoService';
import winston from 'winston';

const prisma = new PrismaClient();

export class AuthController {
Expand Down Expand Up @@ -47,10 +48,17 @@ export class AuthController {
return;
}

// Check if the Chess.com ID is already linked to another user
const existingUser = await prisma.user.findUnique({ where: { chessUsername } });
if (existingUser && existingUser.id !== user.id) {
res.status(400).json({ error: 'Chess.com ID is already linked to another account' });
return;
}

let verificationCode: string | undefined;
const decoded = jwt.verify(token, process.env.JWT_SECRET as string) as { [key: string]: any };
verificationCode = decoded.verificationCode;
winston.info('verificationCode', verificationCode);
logger.info(`verificationCode: ${verificationCode}`);
if (!verificationCode) {
res.status(400).json({ error: 'Verification token not found in JWT' });
return;
Expand All @@ -71,19 +79,29 @@ export class AuthController {
res.status(400).json({ error: 'Verification failed' });
}
} catch (error) {
next(error);
if (error instanceof jwt.JsonWebTokenError) {
res.status(400).json({ error: 'Invalid token' });
} else if (error instanceof jwt.TokenExpiredError) {
res.status(400).json({ error: 'Token expired' });
} else {
next(error);
}
}
};

public googleCallback = async (req: Request, res: Response, next: NextFunction): Promise<void> => {
try {
const user = req.user as User;
if (!user) {
throw new Error('User not found in request');
}
const token = await this.authService.generateToken(user);
let stats;
if (user.chessUsername) {
stats = await createOrUpdateChessInfo(user.chessUsername, user.id);
}
res.json({ token, stats });

res.redirect(`${process.env.FRONTEND}/signupcallback?token=${token}`);
} catch (error) {
next(error);
}
Expand Down
18 changes: 16 additions & 2 deletions src/routes/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,21 +11,35 @@ const chessVerificationSchema = Joi.object({
chessUsername: Joi.string().required(),
});

router.post(
'/chess-verify',
passport.authenticate('jwt', { session: false }),
validateRequest(chessVerificationSchema),
authController.initiateChessVerification
);

router.post(
'/chess-verify/confirm',
passport.authenticate('jwt', { session: false }), // Ensure user is authenticated
passport.authenticate('jwt', { session: false }),
validateRequest(chessVerificationSchema),
authController.confirmChessVerification
);

router.get(
'/test',
(req, res) => {
res.send('test');
}
);

router.get(
'/google',
passport.authenticate('google', { scope: ['profile', 'email', 'https://www.googleapis.com/auth/youtube.readonly'] })
);

router.get(
'/google/callback',
passport.authenticate('google', { failureRedirect: '/login' }),
passport.authenticate('google', { failureRedirect: '/' }), // Ensure Passport sets the user
authController.googleCallback
);

Expand Down
13 changes: 10 additions & 3 deletions src/services/authService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,16 @@ import { generateVerificationCode } from '../utils/generator';

export class AuthService {
public async generateToken(user: User): Promise<string> {
if (!user || !user.id) {
throw new Error('Invalid user object');
}
const verificationCode = await generateVerificationCode();
return jwt.sign({ id: user.id, verificationCode:verificationCode, chessUsername: user.chessUsername }, process.env.JWT_SECRET as string, {
expiresIn: '1d',
});
return jwt.sign(
{ id: user.id, verificationCode: verificationCode, chessUsername: user.chessUsername },
process.env.JWT_SECRET as string,
{
expiresIn: '1d',
}
);
}
}
15 changes: 15 additions & 0 deletions src/types/global.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
declare module 'googleapis/build/src/apis/aiplatform/v1beta1' {
export * from 'googleapis/build/src/apis/aiplatform/v1beta1';
}

declare module 'googleapis/build/src/apis/compute/alpha' {
export * from 'googleapis/build/src/apis/compute/alpha';
}

declare module 'googleapis/build/src/apis/compute/beta' {
export * from 'googleapis/build/src/apis/compute/beta';
}

declare module 'googleapis/build/src/apis/compute/v1' {
export * from 'googleapis/build/src/apis/compute/v1';
}
18 changes: 17 additions & 1 deletion src/types/googleapis.d.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,19 @@
declare module 'googleapis' {
export * from 'googleapis/build/src/index';
}
}

declare module 'googleapis/build/src/apis/compute/v1' {
export const compute_v1: any;
}

declare module 'googleapis/build/src/apis/compute/alpha' {
export const compute_alpha: any;
}

declare module 'googleapis/build/src/apis/compute/beta' {
export const compute_beta: any;
}

declare module 'googleapis/build/src/apis/aiplatform/v1beta1' {
export const aiplatform_v1beta1: any;
}
11 changes: 4 additions & 7 deletions src/utils/logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,10 @@ import winston from 'winston';

export const logger = winston.createLogger({
level: 'info',
format: winston.format.combine(
winston.format.timestamp(),
winston.format.json()
),
format: winston.format.json(),
transports: [
new winston.transports.Console(),
new winston.transports.File({ filename: 'error.log', level: 'error' }),
new winston.transports.File({ filename: 'combined.log' }),
new winston.transports.Console({
format: winston.format.simple(),
}),
],
});
4 changes: 3 additions & 1 deletion tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
"target": "es6",
"noImplicitAny": true,
"moduleResolution": "node",
"skipLibCheck": true,
"sourceMap": true,
"outDir": "dist",
"baseUrl": ".",
Expand All @@ -18,6 +19,7 @@
"typeRoots": ["node_modules/@types", "src/types"]
},
"include": [
"src/**/*"
"src/**/*",
"global.d.ts"
]
}

0 comments on commit 25063f6

Please sign in to comment.