Skip to content

Commit

Permalink
✔ Test Ilangin Return Res.XXX ~
Browse files Browse the repository at this point in the history
  • Loading branch information
bifeldy committed Jan 20, 2024
1 parent 5e4aa1c commit 8e1f28b
Show file tree
Hide file tree
Showing 15 changed files with 99 additions and 77 deletions.
2 changes: 1 addition & 1 deletion dist/main-site/server/main.js

Large diffs are not rendered by default.

3 changes: 2 additions & 1 deletion projects/main-site/src/api/app.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,13 +65,14 @@ export class AppController {
}

@Get('/img-seasonal-backdrop')
@HttpCode(200)
@FilterApiKeyAccess()
async resetPassword(@Req() req: Request, @Res( /* { passthrough: true } */ ) res: Response): Promise<any> {
const currDate = new Date();
const season = this.gs.seasonal.find(sB => sB.id === Math.ceil((currDate.getMonth() + 1) / 3)).name;
const files = readdirSync(`${environment.viewFolder}/assets/img/backdrop/`, { withFileTypes: true });
const fIdx = files.findIndex(f => f.name.includes(`${season}`));
return res.download(`${environment.viewFolder}/assets/img/backdrop/${files[fIdx].name}`, files[fIdx].name, async (e) => {
res.download(`${environment.viewFolder}/assets/img/backdrop/${files[fIdx].name}`, files[fIdx].name, async (e) => {
if (e) {
this.gs.log('[RES_DOWNLOAD_IMAGE_BACKDROP-ERROR] 🔻', e, 'error');
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -216,7 +216,7 @@ export class AttachmentController {
delete ddlFile.user_.updated_at;
}
}
return res.status(HttpStatus.OK).json(classToPlain({
res.status(HttpStatus.OK).json(classToPlain({
info: `😅 200 - Attachment API :: DDL List 🤣`,
results: ddlFiles,
count,
Expand Down Expand Up @@ -271,15 +271,15 @@ export class AttachmentController {
this.gs.log('[DDL-ERROR] 💽', e, 'error');
}
const ddl = await this.aws.getDdl(resSaveAttachment.aws_s3, user, expiredSeconds);
return res.redirect(301, ddl.toString());
res.redirect(301, ddl.toString());
} else {
const files = readdirSync(`${environment.uploadFolder}`, { withFileTypes: true });
const fIdx = files.findIndex(f => f.name === attachment.name || f.name === `${attachment.name}.${attachment.ext}`);
if (fIdx < 0) {
throw new Error('Lampiran Tidak Ditemukan!');
}
res.setHeader('content-type', attachment.mime);
return res.download(
res.download(
`${environment.uploadFolder}/${files[fIdx].name}`,
`${attachment.orig || attachment.name + '.' + attachment.ext}`,
async (e) => {
Expand All @@ -293,7 +293,7 @@ export class AttachmentController {
);
}
} catch (error) {
return res.status(HttpStatus.NOT_FOUND).json(classToPlain({
res.status(HttpStatus.NOT_FOUND).json(classToPlain({
info: `🙄 404 - Attachment API :: Gagal Mencari Lampiran ${req.params['id']} 😪`,
result: {
message: 'Lampiran Tidak Ditemukan!'
Expand Down
4 changes: 2 additions & 2 deletions projects/main-site/src/api/controllers/crawl.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -118,12 +118,12 @@ export class CrawlController {
}
await page.close();
this.cm.set(req.originalUrl, { status: response.status(), body: responseData }, { ttl: CONSTANTS.externalApiCacheTime });
return res.send(responseData);
res.send(responseData);
} catch (error) {
if (page) {
await page.close();
}
return res.status(HttpStatus.BAD_REQUEST).json(classToPlain({
res.status(HttpStatus.BAD_REQUEST).json(classToPlain({
info: '🙄 400 - Crawl API :: UR[I/L] Tidak Valid 😪',
result: {
message: 'Data Tidak Lengkap!'
Expand Down
12 changes: 6 additions & 6 deletions projects/main-site/src/api/controllers/ddl-file.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ export class DdlGenerateController {
@ApiParam({ name: 'id', type: 'string' })
@VerifiedOnly()
@Roles(RoleModel.ADMIN, RoleModel.MODERATOR, RoleModel.FANSUBBER, RoleModel.USER)
async generateDdl(@Req() req: Request, @Res({ passthrough: true }) res: Response): Promise<any> {
async generateDdl(@Req() req: Request, @Res( /* { passthrough: true } */ ) res: Response): Promise<any> {
try {
const user: UserModel = res.locals['user'];
const attachment = await this.attachmentRepo.findOneOrFail({
Expand Down Expand Up @@ -75,14 +75,14 @@ export class DdlGenerateController {
this.gs.log('[DDL-ERROR] 💽', e, 'error');
}
const ddl = await this.aws.getDdl(resSaveAttachment.aws_s3, user, expiredSeconds);
return {
res.status(HttpStatus.OK).json(classToPlain({
info: `😅 200 - DDL File API :: Generate URL 🤣`,
result: resSaveAttachment,
ddl: ddl.toString(),
expired: new Date(Number(ddl.searchParams.get('Expires')) * 1000)
};
}));
} catch (error) {
return res.status(HttpStatus.NOT_FOUND).json(classToPlain({
res.status(HttpStatus.NOT_FOUND).json(classToPlain({
info: `🙄 404 - DDL File API :: Gagal Mencari Lampiran ${req.params['id']} 😪`,
result: {
message: 'Lampiran Tidak Ditemukan!'
Expand Down Expand Up @@ -158,7 +158,7 @@ export class DdlPartController {
`, [ddlFile.msg_parent, ddlFile.msg_parent]);
}).pipe(res);
} catch (error) {
return res.status(HttpStatus.NOT_FOUND).json(classToPlain({
res.status(HttpStatus.NOT_FOUND).json(classToPlain({
info: `🙄 404 - DDL File API :: Gagal Mencari Lampiran ${req.params['id']} 😪`,
result: {
message: 'Lampiran Tidak Ditemukan!'
Expand Down Expand Up @@ -282,7 +282,7 @@ export class DdlSeekController {
`, [ddlFile.msg_parent, ddlFile.msg_parent]);
}).pipe(res);
} catch (error) {
return res.status(HttpStatus.NOT_FOUND).json(classToPlain({
res.status(HttpStatus.NOT_FOUND).json(classToPlain({
info: `🙄 404 - DDL File API :: Gagal Mencari Lampiran ${req.params['id']} 😪`,
result: {
message: 'Lampiran Tidak Ditemukan!'
Expand Down
6 changes: 3 additions & 3 deletions projects/main-site/src/api/controllers/torrent.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,14 +27,14 @@ export class TorrentController {
timeout: req.body.trackTimeout || 1234
}, (err, data) => {
if (err) {
return res.status(HttpStatus.BAD_REQUEST).json(classToPlain({
res.status(HttpStatus.BAD_REQUEST).json(classToPlain({
info: `🙄 400 - Torrent Tracker API :: Gagal Mendapatkan Torrent 😪`,
result: {
message: err.message
}
}));
} else {
return res.status(HttpStatus.CREATED).json(classToPlain({
res.status(HttpStatus.CREATED).json(classToPlain({
info: `😅 200 - Torrent Tracker API :: Berhasil Mendapatkan ${req.body.magnetHash} 🤣`,
result: data
}));
Expand All @@ -44,7 +44,7 @@ export class TorrentController {
throw new Error('Data Tidak Lengkap!');
}
} catch (error) {
return res.status(HttpStatus.BAD_REQUEST).json(classToPlain({
res.status(HttpStatus.BAD_REQUEST).json(classToPlain({
info: '🙄 400 - Torrent Tracker API :: Gagal Mendapatkan Torrent 😪',
result: {
message: 'Data Tidak Lengkap!'
Expand Down
4 changes: 2 additions & 2 deletions projects/main-site/src/api/filters/http-exception.filter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ export class HttpExceptionFilter implements ExceptionFilter {
//
}

async catch(exception: HttpException, host: ArgumentsHost) {
async catch(exception: HttpException, host: ArgumentsHost): Promise<any> {
const ctx = host.switchToHttp();
const req = ctx.getRequest<Request>();
const res = ctx.getResponse<Response>();
Expand All @@ -39,7 +39,7 @@ export class HttpExceptionFilter implements ExceptionFilter {
});
}

return res.status(statusCode).send(body);
res.status(statusCode).send(body);
}

}
2 changes: 1 addition & 1 deletion projects/main-site/src/api/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,7 @@ export async function app(httpAdapter: AbstractHttpAdapter = null): Promise<INes
gs.log('[RESPONSE_ON_CLOSED] ❌', e, 'error');
}
});
return next();
next();
});
const swaggerCfg = new DocumentBuilder()
.setTitle(environment.siteName)
Expand Down
56 changes: 29 additions & 27 deletions projects/main-site/src/api/middlewares/api-key.middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,36 +28,38 @@ export class ApiKeyMiddleware implements NestMiddleware {
this.gs.log('[API_KEY_MIDDLEWARE-ORIGIN_KEY] 🌸', `${key} @ ${clientOriginIpCc.origin_ip}`);
if (!req.originalUrl.includes('/api')) {
res.locals['user'] = null;
return next();
}
res.locals['key'] = key;
const check = await this.aks.checkKey(clientOriginIpCc.origin_ip, key);
if (check.allowed) {
let user: UserModel = check.user;
if (user) {
try {
user = await this.userRepo.findOneOrFail({
where: [
{ id: Equal(user.id) }
],
relations: ['kartu_tanda_penduduk_', 'profile_']
});
} catch (error) {
user = null;
next();
} else {
res.locals['key'] = key;
const check = await this.aks.checkKey(clientOriginIpCc.origin_ip, key);
if (check.allowed) {
let user: UserModel = check.user;
if (user) {
try {
user = await this.userRepo.findOneOrFail({
where: [
{ id: Equal(user.id) }
],
relations: ['kartu_tanda_penduduk_', 'profile_']
});
} catch (error) {
user = null;
}
}
res.locals['user'] = user;
next();
} else {
throw new HttpException({
info: '🙄 401 - API Key :: Kunci Tidak Dapat Digunakan 😪',
result: {
key,
origin: clientOriginIpCc.origin_ip,
country: clientOriginIpCc.country_code,
message: `Api Key Salah / Tidak Terdaftar!`
}
}, HttpStatus.UNAUTHORIZED);
}
res.locals['user'] = user;
return next();
}
throw new HttpException({
info: '🙄 401 - API Key :: Kunci Tidak Dapat Digunakan 😪',
result: {
key,
origin: clientOriginIpCc.origin_ip,
country: clientOriginIpCc.country_code,
message: `Api Key Salah / Tidak Terdaftar!`
}
}, HttpStatus.UNAUTHORIZED);
}

}
46 changes: 31 additions & 15 deletions projects/main-site/src/api/middlewares/banned.middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ export class BannedMiddleware implements NestMiddleware {
let user: UserModel = res.locals['user'];
const key = res.locals['key'];
const token = (req.cookies[environment.tokenName] || req.headers.authorization || req.headers['x-access-token'] || req.body.token || req.query['token'] || '').toString();
let suspicious = false;
try {
if (!key) {
const decoded = this.cs.credentialDecode(token);
Expand All @@ -41,30 +42,45 @@ export class BannedMiddleware implements NestMiddleware {
maxAge: 0,
domain: environment.domain
});
return res.redirect(301, `${environment.baseUrl}/?ngsw-bypass=true`);
suspicious = true;
}
}
}
this.gs.log('[BANNED_MIDDLEWARE-USER] 🧨', user);
if (!user) {
throw new Error('User Not Login!');
if (!suspicious) {
this.gs.log('[BANNED_MIDDLEWARE-USER] 🧨', user);
if (!user) {
throw new Error('User Not Login!');
}
const banned = await this.as.isAccountBanned(user.id);
if (banned) {
throw new HttpException({
info: '🙄 403 - Banned :: Akun Dikunci 😪',
result: {
message: `Akun Tidak Dapat Digunakan :: ${banned.reason}`
}
}, HttpStatus.FORBIDDEN);
}
}
const banned = await this.as.isAccountBanned(user.id);
if (banned) {
} catch (error) {
if (error instanceof HttpException) throw error;
res.locals['error'] = error;
}
if (suspicious) {
if (req.headers.accept.includes('application/json')) {
throw new HttpException({
info: '🙄 403 - Banned :: Akun Dikunci 😪',
info: '💩 401 - Rate Limit :: Sesi Mencurigakan 🤬',
result: {
message: `Akun Tidak Dapat Digunakan :: ${banned.reason}`
message: 'Silahkan Login Ulang!'
}
}, HttpStatus.FORBIDDEN);
}, HttpStatus.UNAUTHORIZED);
} else {
res.redirect(301, `${environment.baseUrl}/?ngsw-bypass=true`);
}
} catch (error) {
if (error instanceof HttpException) throw error;
res.locals['error'] = error;
} else {
res.locals['user'] = user;
res.locals['token'] = token;
next();
}
res.locals['user'] = user;
res.locals['token'] = token;
return next();
}

}
4 changes: 2 additions & 2 deletions projects/main-site/src/api/middlewares/cache.middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,9 @@ export class CacheMiddleware implements NestMiddleware {
const cacheData: ResponseCache = await this.cm.get(req.originalUrl);
if (cacheData) {
this.gs.log(`[CACHE_MIDDLEWARE-${req.originalUrl}] ✨`, cacheData);
return res.status(cacheData.status).send(cacheData.body);
res.status(cacheData.status).send(cacheData.body);
} else {
return next();
next();
}
}

Expand Down
5 changes: 3 additions & 2 deletions projects/main-site/src/api/middlewares/login.middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -113,9 +113,10 @@ export class LoginMiddleware implements NestMiddleware {
expires: new Date(this.cs.jwtView(resUserSave.session_token).exp * 1000),
domain: environment.domain
});
return next();
next();
} else {
throw new Error('Username, Email, atau Password tidak tepat!');
}
throw new Error('Username, Email, atau Password tidak tepat!');
} catch (error) {
this.gs.log('[LOGIN_MIDDLEWARE-ERROR] 🎃', error, 'error');
if (error instanceof HttpException) throw error;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ export class LogoutMiddleware implements NestMiddleware {
maxAge: 0,
domain: environment.domain
});
return next();
next();
} catch (error) {
this.gs.log('[LOGOUT_MIDDLEWARE-ERROR] 🔪', error, 'error');
if (error instanceof HttpException) throw error;
Expand Down
18 changes: 10 additions & 8 deletions projects/main-site/src/api/middlewares/register.middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,7 @@ export class RegisterMiddleware implements NestMiddleware {
}
}, CONSTANTS.timeoutCancelRegisterTime)
);
return next();
next();
} else {
const result: any = {};
for (const user of userNotAvailable) {
Expand All @@ -160,15 +160,17 @@ export class RegisterMiddleware implements NestMiddleware {
result
}, HttpStatus.BAD_REQUEST);
}
} else {
throw new HttpException({
info: `🙄 ${res_raw.status || 400} - Google API :: Captcha Bermasalah 😪`,
result: {
message: 'Captcha Salah / Expired / Google API Down!'
}
}, res_raw.status || HttpStatus.BAD_REQUEST);
}
throw new HttpException({
info: `🙄 ${res_raw.status || 400} - Google API :: Captcha Bermasalah 😪`,
result: {
message: 'Captcha Salah / Expired / Google API Down!'
}
}, res_raw.status || HttpStatus.BAD_REQUEST);
} else {
throw new Error('Data Tidak Lengkap!');
}
throw new Error('Data Tidak Lengkap!');
} catch (error) {
this.gs.log('[REGISTER_MIDDLEWARE-ERROR] 🎃', error, 'error');
if (error instanceof HttpException) throw error;
Expand Down
4 changes: 2 additions & 2 deletions projects/main-site/src/api/middlewares/url-path.middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ export class UrlPathMiddleware implements NestMiddleware {
//
}

async use(@Req() req: Request, @Res({ passthrough: true }) res: Response, @Next() next: NextFunction): Promise<void> {
async use(@Req() req: Request, @Res({ passthrough: true }) res: Response, @Next() next: NextFunction): Promise<void | Response<any, Record<string, any>>> {
const urlPath = req.originalUrl.split('?');
if (urlPath.length === 1) {
req.originalUrl = urlPath[0];
Expand All @@ -21,7 +21,7 @@ export class UrlPathMiddleware implements NestMiddleware {
req.originalUrl = urlPath[0] + '?' + urlQuery.join('&');
}
this.gs.log(`[URL_PATH_MIDDLEWARE] ⚡`, req.originalUrl);
return next();
next();
}

}

0 comments on commit 8e1f28b

Please sign in to comment.