Skip to content

Commit

Permalink
feat: stop using cookies
Browse files Browse the repository at this point in the history
  • Loading branch information
Guilhermeasper committed Apr 28, 2024
1 parent eaec513 commit 1584e21
Show file tree
Hide file tree
Showing 9 changed files with 105 additions and 108 deletions.
61 changes: 24 additions & 37 deletions src/controllers/auth.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { Request, Response } from 'express';
import { DiscordService } from '../services/discord';
import { ApiResponse } from '../types';
import { LastfmService } from '../services/lastfm';
import { decryptToken, encryptToken } from '../utils/crypto';

class AuthController {
private discordService: DiscordService;
Expand All @@ -20,32 +21,25 @@ class AuthController {

if (!code) {
return res.status(400).json({
error: 'Code not found',
error: 'Code not provided',
});
}

try {
const response = await this.discordService.requestToken(code);
const encryptedToken = encryptToken(response.access_token);
const encryptedRefreshToken = encryptToken(response.refresh_token);

res.cookie('access_token', response.access_token, {
maxAge: Date.now() + response.expires_in,
httpOnly: true,
sameSite: 'none',
secure: true,
path: '/',
});
if (!encryptedToken || !encryptedRefreshToken) {
return res.status(500).json({ error: 'Internal Server Error' });
}

res.cookie('refresh_token', response.refresh_token, {
maxAge: Date.now() + 30 * 24 * 60 * 60 * 1000,
httpOnly: true,
sameSite: 'none',
secure: true,
path: '/',
});
res.set('Authorization', `Bearer ${encryptedToken}`);
res.set('Refresh-Token', encryptedRefreshToken);

return res.status(200).json({ message: 'Authenticated successfully' });
} catch (error) {
console.log(error);
console.error(error);
return res.status(500).json({ error: 'Internal Server Error' });
}
}
Expand All @@ -54,40 +48,33 @@ class AuthController {
req: Request,
res: Response,
): Promise<Response<ApiResponse<void>>> {
const refresh_token = req.cookies.refresh_token;
const refresh_token = req.headers['Refresh-Token'] as string;

if (!refresh_token) {
return res.status(400).json({ error: 'Refresh token not found' });
}
const decryptedRefreshToken = decryptToken(refresh_token);

if (!decryptedRefreshToken) {
return res.status(500).json({ error: 'Internal Server Error' });
}

try {
const response = await this.discordService.refreshToken(refresh_token);

res.cookie('access_token', response.access_token, {
maxAge: response.expires_in,
httpOnly: true,
sameSite: 'none',
secure: true,
path: '/',
});
const response = await this.discordService.refreshToken(
decryptedRefreshToken,
);

const encryptedToken = encryptToken(response.access_token);

res.set('Authorization', `Bearer ${encryptedToken}`);

return res.status(200).json({ message: 'Token refreshed' });
} catch (error) {
console.log(error);
console.error(error);
return res.status(500).json({ error: 'Internal Server Error' });
}
}

public async logout(
req: Request,
res: Response,
): Promise<Response<ApiResponse<void>>> {
res.clearCookie('access_token');
res.clearCookie('refresh_token');

return res.status(200).json({ message: 'Logged out successfully' });
}

public discordLoginUrl(
req: Request,
res: Response,
Expand Down
8 changes: 4 additions & 4 deletions src/controllers/scroblle.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ class ScrobbleController {
);
return res.status(200).json({ data, message: 'Scrobble added to queue' });
} catch (error: any) {
console.log(error);
console.error(error);
return res.status(500).json({ message: 'Unknown Error' });
}
}
Expand All @@ -26,7 +26,7 @@ class ScrobbleController {
const id = await this.scrobblerService.dispatchScrobble(req.params.id);
return res.status(200).json({ data: id, message: 'Scrobbled' });
} catch (error: any) {
console.log(error);
console.error(error);
return res.status(500).json({ message: 'Unknown Error' });
}
}
Expand All @@ -39,7 +39,7 @@ class ScrobbleController {
);
return res.status(200).json({ data: id, message: 'User removed' });
} catch (error: any) {
console.log(error);
console.error(error);
return res.status(500).json({ message: 'Unknown Error' });
}
}
Expand All @@ -52,7 +52,7 @@ class ScrobbleController {
);
return res.status(200).json({ data: id, message: 'User removed' });
} catch (error: any) {
console.log(error);
console.error(error);
return res.status(500).json({ message: 'Unknown Error' });
}
}
Expand Down
35 changes: 22 additions & 13 deletions src/controllers/user.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { UserService } from '../services/user';
import { Request, Response } from 'express';
import { DiscordService } from '../services/discord';
import { LastfmService } from '../services/lastfm';
import { decryptToken } from '../utils/crypto';

class UserController {
userService: UserService;
Expand All @@ -20,13 +21,21 @@ class UserController {
res: Response,
): Promise<Response<ApiResponse<void>>> {
try {
const cookies = req.cookies;
const authorization = req.headers['authorization'] as string;
const access_token = authorization && authorization.split(' ')[1];
const decryptedToken = decryptToken(access_token);

if (!decryptedToken) {
return res.status(500).json({ message: 'Internal Server Error' });
}

const discordUser = await this.discordService.getDiscordUser(
cookies.access_token,
decryptedToken,
);
console.log(req.headers);
await this.userService.create(discordUser.id);
} catch (error: any) {
console.log(error);
console.error(error);

if (error.message === 'User already exists') {
return res.status(409).json({ message: error.message });
Expand Down Expand Up @@ -54,7 +63,7 @@ class UserController {
try {
await this.userService.enableLastfm(req.user.id, token);
} catch (error: any) {
console.log(error);
console.error(error);
return res.status(500).json({ message: 'Unknown Error' });
}

Expand All @@ -72,7 +81,7 @@ class UserController {
try {
return res.status(200).json(req.user);
} catch (error: any) {
console.log(error);
console.error(error);
return res.status(500).json({ message: 'Unknown Error' });
}
}
Expand All @@ -90,7 +99,7 @@ class UserController {
.status(200)
.json(await this.userService.toggleScrobbles(req.user.id));
} catch (error: any) {
console.log(error);
console.error(error);
return res.status(500).json({ message: 'Unknown Error' });
}
}
Expand All @@ -106,7 +115,7 @@ class UserController {
try {
await this.userService.deleteLastfmData(req.user.id);
} catch (error: any) {
console.log(error);
console.error(error);
return res.status(500).json({ message: 'Unknown Error' });
}

Expand All @@ -124,7 +133,7 @@ class UserController {
try {
await this.userService.deleteAllData(req.user.id);
} catch (error: any) {
console.log(error);
console.error(error);
return res.status(500).json({ message: 'Unknown Error' });
}

Expand All @@ -145,7 +154,7 @@ class UserController {
try {
return res.status(200).json(await this.userService.exists(req.params.id));
} catch (error: any) {
console.log(error);
console.error(error);
return res.status(500).json({ message: 'Unknown Error' });
}
}
Expand All @@ -169,7 +178,7 @@ class UserController {
return res.status(404).json({ message: 'Lastfm token not found' });
}
} catch (error: any) {
console.log(error);
console.error(error);
return res.status(500).json({ message: 'Unknown Error' });
}
}
Expand All @@ -186,7 +195,7 @@ class UserController {

return res.status(200).json(topArtists);
} catch (error: any) {
console.log(error);
console.error(error);
return res.status(500).json({ message: 'Unknown Error' });
}
}
Expand All @@ -203,7 +212,7 @@ class UserController {
console.log(topAlbums);
return res.status(200).json(topAlbums);
} catch (error: any) {
console.log(error);
console.error(error);
return res.status(500).json({ message: 'Unknown Error' });
}
}
Expand All @@ -220,7 +229,7 @@ class UserController {

return res.status(200).json(topTracks);
} catch (error: any) {
console.log(error);
console.error(error);
return res.status(500).json({ message: 'Unknown Error' });
}
}
Expand Down
23 changes: 13 additions & 10 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,15 +55,18 @@ app.use('/api/scrobble', scrobble.default);
app.use('/api/privacy-policy', privacyPolicy.default);

mongoConnection().then(() => {
const httpServer = http.createServer(app);
const httpsServer = https.createServer(
{
key: fs.readFileSync('server.key').toString(),
cert: fs.readFileSync('server.crt').toString(),
},
app,
);
if (process.env.NODE_ENV === 'production') {
const httpsServer = https.createServer(
{
key: fs.readFileSync('server.key').toString(),
cert: fs.readFileSync('server.crt').toString(),
},
app,
);

httpServer.listen(process.env.HTTP_PORT || 3000);
httpsServer.listen(process.env.HTTPS_PORT || 3106);
httpsServer.listen(process.env.HTTPS_PORT || 3106);
} else {
const httpServer = http.createServer(app);
httpServer.listen(process.env.HTTP_PORT || 3000);
}
});
1 change: 0 additions & 1 deletion src/middlewares/botAuth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ export function checkToken(req: Request, res: Response, next: NextFunction) {
if (isWebRequest) {
return verifyDiscordToken(req, res, next);
}
console.log(req.headers);
const token = authorization && authorization.split(' ')[1];
if (!token) {
return res.status(401).json({ message: 'Token not provided' });
Expand Down
55 changes: 17 additions & 38 deletions src/middlewares/userAuth.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { Request, Response, NextFunction } from 'express';
import { DiscordService } from '../services/discord';
import { UserService } from '../services/user';
import { decryptToken } from '../utils/crypto';

const discordService = new DiscordService();
const userService = new UserService();
Expand All @@ -10,16 +11,25 @@ export async function verifyDiscordToken(
res: Response,
next: NextFunction,
) {
const cookies = req.cookies;
const authorization = req.headers['authorization'] as string;
const access_token = authorization && authorization.split(' ')[1];

if (!cookies.access_token) {
if (!access_token) {
return res.status(401).json({ message: 'Token not provided' });
}

const decryptedToken = decryptToken(access_token);

if (!decryptedToken) {
return res.status(500).json({ message: 'Internal Server Error' });
}

try {
const discordUser = await discordService.getDiscordUser(
cookies.access_token,
);
const discordUser = await discordService.getDiscordUser(decryptedToken);

if (!discordUser) {
return res.status(403).json({ message: 'Unauthorized' });
}

const user = await userService.userDB.findOne({
id: discordUser.id,
Expand All @@ -34,38 +44,7 @@ export async function verifyDiscordToken(
});
next();
} catch (error) {
console.log(error);
try {
const response = await discordService.refreshToken(cookies.refresh_token);

const discordUser = await discordService.getDiscordUser(
response.access_token,
);

const user = await userService.userDB.findOne({
id: discordUser.id,
});

if (!user) {
return res.status(401).json({ message: 'User not found' });
}

Object.defineProperty(req, 'user', {
value: discordUser,
});

res.cookie('access_token', response.access_token, {
maxAge: response.expires_in,
httpOnly: true,
sameSite: 'none',
secure: true,
path: '/',
});

next();
} catch (error) {
console.log(error);
return res.status(500).json({ error: 'Internal Server Error' });
}
console.error(error);
return res.status(500).json({ error: 'Internal Server Error' });
}
}
1 change: 0 additions & 1 deletion src/routes/auth.route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ const router = express.Router();
const auth = new AuthController();

router.get('/login', auth.login.bind(auth));
router.get('/logout', auth.logout.bind(auth));
router.get('/refresh_token', auth.refreshToken.bind(auth));
router.get('/discordLoginUrl', auth.discordLoginUrl.bind(auth));
router.get('/lastfmLoginUrl', auth.lastfmLoginUrl.bind(auth));
Expand Down
Loading

0 comments on commit 1584e21

Please sign in to comment.