Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implemented settings page and better error handling #313

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
131 changes: 131 additions & 0 deletions apps/backend/src/controllers/auth.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
import { Request, Response, Router } from 'express';
import jwt from 'jsonwebtoken';
import { db } from '../db';
import { AppError } from '../utils/error';

interface User {
id: string;
}

const JWT_SECRET = process.env.JWT_SECRET || 'your_secret_key';

export const getToken = async (req: Request, res: Response) => {
if (req.user) {
const user = req.user as User;

// Token is issued so it can be shared b/w HTTP and ws server
// Todo: Make this temporary and add refresh logic here

const userDb = await db.user.findFirst({
where: {
id: user.id,
},
});

const token = jwt.sign({ userId: user.id }, JWT_SECRET);
return res.json({
token,
id: user.id,
name: userDb?.name,
});
} else {
throw new AppError({ name: 'UNAUTHORIZED', message: 'Unauthorized!' });
}
};

export const getUserInfo = async (req: Request, res: Response) => {
if (req.user) {
const user = req.user as User;
const userDb = await db.user.findFirst({
where: {
id: user.id,
},
include: {
gamesAsBlack: {
include: {
whitePlayer: true,
blackPlayer: true,
},
},
gamesAsWhite: {
include: {
whitePlayer: true,
blackPlayer: true,
},
},
},
});

return res.status(200).json({
email: userDb?.email,
rating: userDb?.rating,
username: userDb?.username,
name: userDb?.name,
gamesAsBlack: userDb?.gamesAsBlack,
gamesAsWhite: userDb?.gamesAsWhite,
});
} else {
throw new AppError({ name: 'UNAUTHORIZED', message: 'Unauthorized!' });
}
};

export const deleteAccount = async (req: Request, res: Response) => {
if (req.user) {
const user = req.user as User;
const deletedUser = await db.user.delete({
where: {
id: user.id,
},
});

if (deletedUser) {
return res.status(200).json({ success: true });
}
throw new AppError({
name: 'INTERNAL_SERVER_ERROR',
message: 'Some error occurred!',
});
}
};

export const updateUserInfo = async (req: Request, res: Response) => {
if (req.user) {
const user = req.user as User;
const { username } = req.body;
const updatedUser = await db.user.update({
where: {
id: user.id,
},
data: {
username: username,
},
});

if (updatedUser) {
return res.status(200).json({ success: true });
}

throw new AppError({
name: 'INTERNAL_SERVER_ERROR',
message: 'Some error occurred!',
});
} else {
throw new AppError({ name: 'UNAUTHORIZED', message: 'Unauthorized!' });
}
};

export const logout = async (req: Request, res: Response) => {
req.logout((err) => {
if (err) {
console.error('Error logging out:', err);
res.status(500).json({ error: 'Failed to log out' });
} else {
res.clearCookie('jwt');
res.redirect('http://localhost:5173/');
}
});
};

export const fail = async (req: Request, res: Response) => {
throw new AppError({ name: 'UNAUTHORIZED', message: 'Failed!' });
};
1 change: 1 addition & 0 deletions apps/backend/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ app.use(
);

initPassport();
app.use(express.json());
app.use(passport.initialize());
app.use(passport.authenticate('session'));

Expand Down
21 changes: 21 additions & 0 deletions apps/backend/src/middleware/errorHandling.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { NextFunction, Request, Response } from 'express';
import { AppError } from '../utils/error';
import { HttpStatus } from '../utils/statusCodes';

export const errorHandler = (
err: Error,
req: Request,
res: Response,
next: NextFunction,
) => {
if (err instanceof AppError) {
console.log(err);
return res
.status(err.statusCode)
.json({ success: false, error: err.message });
}
return res.status(HttpStatus.INTERNAL_SERVER_ERROR).json({
success: false,
error: err,
});
};
62 changes: 16 additions & 46 deletions apps/backend/src/router/auth.ts
Original file line number Diff line number Diff line change
@@ -1,56 +1,26 @@
import { Request, Response, Router } from 'express';
import passport from 'passport';
import jwt from 'jsonwebtoken';
import { db } from '../db';
import { asyncHandler } from '../utils/handlers';
import {
deleteAccount,
fail,
getToken,
getUserInfo,
logout,
updateUserInfo,
} from '../controllers/auth';

const router = Router();

const CLIENT_URL =
process.env.AUTH_REDIRECT_URL ?? 'http://localhost:5173/game/random';
const JWT_SECRET = process.env.JWT_SECRET || 'your_secret_key';

interface User {
id: string;
}

router.get('/refresh', async (req: Request, res: Response) => {
if (req.user) {
const user = req.user as User;

// Token is issued so it can be shared b/w HTTP and ws server
// Todo: Make this temporary and add refresh logic here

const userDb = await db.user.findFirst({
where: {
id: user.id,
},
});

const token = jwt.sign({ userId: user.id }, JWT_SECRET);
res.json({
token,
id: user.id,
name: userDb?.name,
});
} else {
res.status(401).json({ success: false, message: 'Unauthorized' });
}
});

router.get('/login/failed', (req: Request, res: Response) => {
res.status(401).json({ success: false, message: 'failure' });
});

router.get('/logout', (req: Request, res: Response) => {
req.logout((err) => {
if (err) {
console.error('Error logging out:', err);
res.status(500).json({ error: 'Failed to log out' });
} else {
res.clearCookie('jwt');
res.redirect('http://localhost:5173/');
}
});
});
router.get('/refresh', asyncHandler(getToken));
router.get('/userInfo', asyncHandler(getUserInfo));
router.get('/login/failed', asyncHandler(fail));
router.get('/logout', asyncHandler(logout));
router.post('/updateUser', asyncHandler(updateUserInfo));
router.delete('/deleteAccount', asyncHandler(deleteAccount));

router.get(
'/google',
Expand Down
16 changes: 16 additions & 0 deletions apps/backend/src/utils/error.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { HttpStatus } from './statusCodes';
type AppErrorParameters = {
name: keyof typeof HttpStatus;
message: string;
};
export class AppError extends Error {
message: string;
statusCode: number;

constructor({ name, message }: AppErrorParameters) {
const statusCode = HttpStatus[name];
super(message);
this.statusCode = statusCode;
this.message = message;
}
}
12 changes: 12 additions & 0 deletions apps/backend/src/utils/handlers.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { Request, Response, NextFunction } from 'express';

type AsyncHandlerCallback = (
req: Request,
res: Response,
next: NextFunction,
) => any;
export function asyncHandler(cb: AsyncHandlerCallback) {
return (req: Request, res: Response, next: NextFunction) => {
return cb(req, res, next)?.catch(next);
};
}
10 changes: 10 additions & 0 deletions apps/backend/src/utils/statusCodes.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
export const HttpStatus = {
OK: 200,
INTERNAL_SERVER_ERROR: 500,
UNAUTHORIZED: 401,
UNPROCESSABLE_ENTITY: 422,
NOT_FOUND: 404,
TO_MANY_REQUEST: 429,
BAD_REQUEST: 400,
CONFLICT: 409,
} as const;
1 change: 1 addition & 0 deletions apps/frontend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
"@radix-ui/react-slot": "^1.0.2",
"@repo/store": "*",
"@repo/ui": "*",
"axios": "^1.6.8",
"chess.js": "^1.0.0-beta.8",
"class-variance-authority": "^0.7.0",
"clsx": "^2.1.0",
Expand Down
12 changes: 4 additions & 8 deletions apps/frontend/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { RecoilRoot } from 'recoil';
import { useUser } from '@repo/store/useUser';
import { Loader } from './components/Loader';
import { Layout } from './layout';
import Settings from './screens/Settings';

function App() {
return (
Expand All @@ -27,14 +28,9 @@ function AuthApp() {
<BrowserRouter>
<Routes>
<Route path="/" element={<Layout children={<Landing />} />} />
<Route
path="/login"
element={<Login />}
/>
<Route
path="/game/:gameId"
element={<Layout children={<Game />} />}
/>
<Route path="/login" element={<Login />} />
<Route path="/game/:gameId" element={<Layout children={<Game />} />} />
<Route path="/settings" element={<Layout children={<Settings />} />} />
</Routes>
</BrowserRouter>
);
Expand Down
6 changes: 3 additions & 3 deletions apps/frontend/src/components/Card.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import {
CardDescription,
CardHeader,
CardTitle,
} from '@/components/ui/card';
} from '../components/ui/card';
import chessIcon from '../../public/chess.png';
import computerIcon from '../../public/computer.png';
import lightningIcon from '../../public/lightning-bolt.png';
Expand Down Expand Up @@ -84,13 +84,13 @@ export function PlayCard() {
const navigate = useNavigate();
return (
<Card className="bg-transparent border-none">
<CardHeader className="pb-3 text-center text-white shadow-md">
<CardHeader className="pb-3 text-center text-white">
<CardTitle className="font-semibold tracking-wide flex flex-col items-center justify-center">
<p>
Play
<span className="text-green-700 font-bold pt-1"> Chess</span>
</p>
<img className="pl-1 w-1/2 mt-4" src={chessIcon} alt="chess" />
<img className="pl-1 w-1/4 mt-4" src={chessIcon} alt="chess" />
</CardTitle>
<CardDescription></CardDescription>
</CardHeader>
Expand Down
Loading