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

refactor: enable safe index access by setting noUncheckedIndexedAccess #78

Open
wants to merge 3 commits into
base: dev
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
35 changes: 17 additions & 18 deletions src/auth/session.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,21 @@ export class SessionService {
);
}

private async getSessionIdByRefreshToken(
refreshToken: string,
): Promise<number> {
const auth = this.authService.verify(refreshToken);
const permissions = auth.permissions;
if (permissions[0] == null || permissions.length > 1) {
throw new NotRefreshTokenError();
}
const resouceIds = permissions[0].authorizedResource.resourceIds;
if (resouceIds == null || resouceIds[0] == null || resouceIds.length > 1) {
throw new NotRefreshTokenError();
}
return resouceIds[0];
}

// After refreshing the session, the old refresh token is revoked.
// Returns:
// item1: A new refresh token.
Expand All @@ -83,15 +98,7 @@ export class SessionService {
refreshTokenValidSeconds: number = this.defaultRefreshTokenValidSeconds,
accessTokenValidSeconds: number = this.defaultAccessTokenValidSeconds,
): Promise<[string, string]> {
const auth = this.authService.verify(oldRefreshToken);
if (
auth.permissions.length !== 1 ||
auth.permissions[0].authorizedResource.resourceIds == undefined ||
auth.permissions[0].authorizedResource.resourceIds.length !== 1
) {
throw new NotRefreshTokenError();
}
const sessionId = auth.permissions[0].authorizedResource.resourceIds[0];
const sessionId = await this.getSessionIdByRefreshToken(oldRefreshToken);
this.authService.audit(
oldRefreshToken,
AuthorizedAction.other,
Expand Down Expand Up @@ -157,15 +164,7 @@ export class SessionService {
}

async revokeSession(refreshToken: string): Promise<void> {
const auth = this.authService.verify(refreshToken);
if (
auth.permissions.length !== 1 ||
auth.permissions[0].authorizedResource.resourceIds == undefined ||
auth.permissions[0].authorizedResource.resourceIds.length !== 1
) {
throw new NotRefreshTokenError();
}
const sessionId = auth.permissions[0].authorizedResource.resourceIds[0];
const sessionId = await this.getSessionIdByRefreshToken(refreshToken);
this.authService.audit(
refreshToken,
AuthorizedAction.other,
Expand Down
2 changes: 1 addition & 1 deletion src/common/helper/page.helper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ export class PageHelper {
prevStart: number,
idGetter: (item: TData) => number,
): [TData[], PageRespondDto] {
if (data.length == 0 || pageSize < 0) {
if (data[0] == null || pageSize < 0) {
Copy link
Contributor Author

@andylizf andylizf Mar 8, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

TData maybe T | undefined

return [
[],
{
Expand Down
40 changes: 21 additions & 19 deletions src/users/users.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -159,13 +159,9 @@ export class UsersController {
.json(data);
}

@Post('/auth/refresh-token')
async refreshToken(
@Headers('cookie') cookieHeader: string,
@Res() res: Response,
@Ip() ip: string,
@Headers('User-Agent') userAgent: string,
): Promise<Response> {
private async getRefreshTokenFromCookieHeader(
cookieHeader: string | undefined,
): Promise<string> {
if (cookieHeader == undefined) {
throw new AuthenticationRequiredError();
}
Expand All @@ -177,6 +173,21 @@ export class UsersController {
throw new AuthenticationRequiredError();
}
const refreshToken = refreshTokenCookie.split('=')[1];
if (refreshToken == undefined) {
throw new AuthenticationRequiredError();
}
return refreshToken;
}

@Post('/auth/refresh-token')
async refreshToken(
@Headers('cookie') cookieHeader: string | undefined,
@Res() res: Response,
@Ip() ip: string,
@Headers('User-Agent') userAgent: string | undefined,
): Promise<Response> {
const refreshToken =
await this.getRefreshTokenFromCookieHeader(cookieHeader);
const [newRefreshToken, accessToken] =
await this.sessionService.refreshSession(refreshToken);
const newRefreshTokenExpire = new Date(
Expand Down Expand Up @@ -209,19 +220,10 @@ export class UsersController {

@Post('/auth/logout')
async logout(
@Headers('cookie') cookieHeader: string,
@Headers('cookie') cookieHeader: string | undefined,
): Promise<BaseRespondDto> {
if (cookieHeader == undefined) {
throw new AuthenticationRequiredError();
}
const cookies = cookieHeader.split(';').map((cookie) => cookie.trim());
const refreshTokenCookie = cookies.find((cookie) =>
cookie.startsWith('REFRESH_TOKEN='),
);
if (refreshTokenCookie == undefined) {
throw new AuthenticationRequiredError();
}
const refreshToken = refreshTokenCookie.split('=')[1];
const refreshToken =
await this.getRefreshTokenFromCookieHeader(cookieHeader);
await this.sessionService.revokeSession(refreshToken);
return {
code: 201,
Expand Down
24 changes: 10 additions & 14 deletions test/answer.e2e-spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ describe('Answers Module', () => {
.send({ email });
expect(respond.status).toBe(201);
const verificationCode = (
MockedEmailService.mock.instances[0].sendRegisterCode as jest.Mock
MockedEmailService.mock.instances[0]?.sendRegisterCode as jest.Mock
).mock.calls.at(-1)[1];
const respond2 = await request(app.getHttpServer())
.post('/users')
Expand All @@ -60,17 +60,13 @@ describe('Answers Module', () => {
}, 20000);

beforeEach(() => {
const mockedEmailService = MockedEmailService.mock.instances[0]!;
(mockedEmailService.sendRegisterCode as jest.Mock).mock.calls.length = 0;
(mockedEmailService.sendRegisterCode as jest.Mock).mock.results.length = 0;
(mockedEmailService.sendPasswordResetEmail as jest.Mock).mock.calls.length =
0;
(
MockedEmailService.mock.instances[0].sendRegisterCode as jest.Mock
).mock.calls.length = 0;
(
MockedEmailService.mock.instances[0].sendRegisterCode as jest.Mock
).mock.results.length = 0;
(
MockedEmailService.mock.instances[0].sendPasswordResetEmail as jest.Mock
).mock.calls.length = 0;
(
MockedEmailService.mock.instances[0].sendPasswordResetEmail as jest.Mock
mockedEmailService.sendPasswordResetEmail as jest.Mock
).mock.results.length = 0;
});

Expand All @@ -88,13 +84,13 @@ describe('Answers Module', () => {
});
expect(respond1.status).toBe(201);
expect(
MockedEmailService.mock.instances[0].sendRegisterCode,
MockedEmailService.mock.instances[0]?.sendRegisterCode,
).toHaveReturnedTimes(1);
expect(
MockedEmailService.mock.instances[0].sendRegisterCode,
MockedEmailService.mock.instances[0]?.sendRegisterCode,
).toHaveBeenCalledWith(TestEmail, expect.any(String));
const verificationCode = (
MockedEmailService.mock.instances[0].sendRegisterCode as jest.Mock
MockedEmailService.mock.instances[0]?.sendRegisterCode as jest.Mock
).mock.calls[0][1];
const req = request(app.getHttpServer())
.post('/users')
Expand Down
Loading
Loading