Skip to content

Commit

Permalink
Merge pull request #154 from Exlint/auth-page
Browse files Browse the repository at this point in the history
Auth page
  • Loading branch information
tal-rofe authored Jul 16, 2022
2 parents 7c69926 + ca92876 commit b9203b4
Show file tree
Hide file tree
Showing 131 changed files with 15,713 additions and 10,298 deletions.
13 changes: 11 additions & 2 deletions .eslintrc.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,10 @@ module.exports = {
sourceType: 'module',
extraFileExtensions: ['.cjs'],
},
plugins: ['@typescript-eslint', 'unused-imports', 'import'],
plugins: ['@typescript-eslint', 'unused-imports', 'import', 'deprecation'],
rules: {
'max-lines': ['error', { max: 100, skipBlankLines: true, skipComments: true }],
'indent': ['error', 'tab'],
'indent': ['error', 'tab', { SwitchCase: 1 }],
'quotes': ['error', 'single', { avoidEscape: true }],
'semi': ['error', 'always'],
'no-empty': [
Expand Down Expand Up @@ -155,6 +155,8 @@ module.exports = {
groups: ['builtin', 'external', 'internal', 'parent', 'sibling', 'index', 'object'],
},
],

'deprecation/deprecation': 'error',
},
overrides: [
{
Expand All @@ -177,5 +179,12 @@ module.exports = {
'no-console': 'off',
},
},
{
files: ['./inflint.config.ts'],
rules: {
'quotes': 'off',
'no-useless-escape': 'off',
},
},
],
};
3 changes: 2 additions & 1 deletion .prettierignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
node_modules
build
pnpm-worksapce.yaml
dist
dist
pnpm-lock.yaml
7 changes: 6 additions & 1 deletion .vscode/extensions.json
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
{
"recommendations": ["esbenp.prettier-vscode", "dbaeumer.vscode-eslint", "aaron-bond.better-comments"]
"recommendations": [
"esbenp.prettier-vscode",
"dbaeumer.vscode-eslint",
"aaron-bond.better-comments",
"stylelint.vscode-stylelint"
]
}
8 changes: 7 additions & 1 deletion .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
{
"editor.formatOnSave": true,
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.codeActionsOnSave": {
"source.fixAll.stylelint": true
},
"stylelint.validate": ["css", "scss"],
"typescript.tsdk": "node_modules/typescript/lib",
"search.exclude": {
"**/node_modules": true
},
Expand Down Expand Up @@ -28,5 +33,6 @@
"queries": "shader",
"secrets": "keys",
"user": "client"
}
},
"material-icon-theme.activeIconPack": "nest"
}
1 change: 1 addition & 0 deletions apps/backend/@types/global/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ declare global {
readonly GITHUB_OAUTH_CLIENT_SECRET: string;
readonly GITHUB_OAUTH_REDIRECT_URI: string;
readonly MIXPANEL_TOKEN: string;
readonly FRONTEND_URL: string;
}
}
}
Expand Down
5 changes: 3 additions & 2 deletions apps/backend/envs/.env.development
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ GOOGLE_OAUTH_CLIENT_ID="DUMMY"
GOOGLE_OAUTH_CLIENT_SECRET="DUMMY"
GOOGLE_OAUTH_REDIRECT_URI="http://localhost:3000/user/auth/google-redirect"
GITHUB_OAUTH_CLIENT_ID="DUMMY"
GITHUB_OAUTH_CLIENT_SECRET="DUMMY"
GITHUB_OAUTH_CLIENT_SECRET="DUMYM"
GITHUB_OAUTH_REDIRECT_URI="http://localhost:3000/user/auth/github-redirect"
MIXPANEL_TOKEN="XOMBILLAH"
MIXPANEL_TOKEN="XOMBILLAH"
FRONTEND_URL="http://localhost:8080"
2 changes: 2 additions & 0 deletions apps/backend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@
"@nestjs/schematics": "9.0.1",
"@nestjs/swagger": "6.0.4",
"@types/bcryptjs": "2.4.2",
"@types/express": "4.17.13",
"@types/passport-github2": "1.2.5",
"@types/passport-google-oauth20": "2.0.11",
"@types/passport-jwt": "3.0.6",
Expand All @@ -56,6 +57,7 @@
"dotenv-cli": "6.0.0",
"eslint": "8.19.0",
"eslint-config-prettier": "8.5.0",
"eslint-plugin-deprecation": "1.3.2",
"eslint-plugin-import": "2.26.0",
"eslint-plugin-node": "11.1.0",
"eslint-plugin-unused-imports": "2.0.0",
Expand Down
1 change: 1 addition & 0 deletions apps/backend/src/config/configuration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ const EnvConfiguration = (): IEnvironment => ({
githubOAuthClientSecret: process.env.GITHUB_OAUTH_CLIENT_SECRET,
githubOAuthRedirectUri: process.env.GITHUB_OAUTH_REDIRECT_URI,
mixpanelToken: process.env.MIXPANEL_TOKEN,
frontendUrl: process.env.FRONTEND_URL,
});

export default EnvConfiguration;
1 change: 1 addition & 0 deletions apps/backend/src/config/env.interface.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,5 @@ export interface IEnvironment {
readonly githubOAuthClientSecret: string;
readonly githubOAuthRedirectUri: string;
readonly mixpanelToken: string;
readonly frontendUrl: string;
}
3 changes: 3 additions & 0 deletions apps/backend/src/config/env.validation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,9 @@ class EnvironmentVariables {

@IsString()
public MIXPANEL_TOKEN!: string;

@IsString()
public FRONTEND_URL!: string;
}

export const validate = (config: Record<string, unknown>) => {
Expand Down
3 changes: 3 additions & 0 deletions apps/backend/src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,9 @@ async function bootstrap() {

const config = app.get<ConfigService<IEnvironment, true>>(ConfigService);
const nodeEnv = config.get('nodeEnv', { infer: true });
const frontendUrl = config.get('frontendUrl', { infer: true });

app.enableCors({ origin: frontendUrl });

if (nodeEnv === 'development') {
const swaggerConfig = new DocumentBuilder()
Expand Down
17 changes: 0 additions & 17 deletions apps/backend/src/modules/database/user.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,23 +29,6 @@ export class DBUserService {
select: {
id: true,
authType: true,
clientSecrets: { select: { createdAt: true, expiration: true, id: true, label: true } },
groups: {
select: {
id: true,
label: true,
createdAt: true,
inlinePolicies: {
select: {
id: true,
label: true,
library: true,
configuration: true,
rules: true,
},
},
},
},
},
});
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
import { AddRefreshTokenHandler } from './add-refresh-token.handler';
import { DeleteUserHandler } from './delete-user.handler';
import { RemoveOldRefreshTokensHandler } from './remove-old-refresh-tokens.handler';
import { UpdateExternalTokenHandler } from './update-external-token.handler';

export const CommandHandlers = [AddRefreshTokenHandler, RemoveOldRefreshTokensHandler, DeleteUserHandler];
export const CommandHandlers = [
AddRefreshTokenHandler,
RemoveOldRefreshTokensHandler,
DeleteUserHandler,
UpdateExternalTokenHandler,
];
50 changes: 19 additions & 31 deletions apps/backend/src/modules/user/modules/auth/github.controller.ts
Original file line number Diff line number Diff line change
@@ -1,30 +1,24 @@
import {
BadRequestException,
Controller,
Get,
HttpCode,
HttpStatus,
Logger,
UseGuards,
} from '@nestjs/common';
import { BadRequestException, Controller, Get, Logger, Redirect, UseGuards } from '@nestjs/common';
import { CommandBus, EventBus, QueryBus } from '@nestjs/cqrs';
import { RealIP } from 'nestjs-real-ip';
import { ConfigService } from '@nestjs/config';

import { Public } from '@/decorators/public.decorator';
import { ExternalAuthUser } from '@/decorators/external-auth-user.decorator';
import { IEnvironment } from '@/config/env.interface';

import { AuthService } from './auth.service';
import { AddRefreshTokenContract } from './commands/contracts/add-refresh-token.contract';
import { RemoveOldRefreshTokensContract } from './commands/contracts/remove-old-refresh-tokens.contract';
import { GithubAuthGuard } from './guards/github-auth.guard';
import { IGithubRedirectResponse } from './interfaces/responses';
import { GetGithubUserContract } from './queries/contracts/get-github-user.contract';
import { CreateGithubUserContract } from './queries/contracts/create-github-user.contract';
import { UpdateExternalTokenContract } from './commands/contracts/update-external-token.contract';
import Routes from './auth.routes';
import { IExternalAuthUser } from './interfaces/external-auth-user';
import { IExternalLoggedUser } from './interfaces/user';
import { LoginMixpanelContract } from './events/contracts/login-mixpanel.contract';
import { JwtTokenType } from './models/jwt-token';

@Controller(Routes.CONTROLLER)
export class GithubController {
Expand All @@ -35,6 +29,7 @@ export class GithubController {
private readonly commandBus: CommandBus,
private readonly eventBus: EventBus,
private readonly authService: AuthService,
private readonly configService: ConfigService<IEnvironment, true>,
) {}

@Public()
Expand All @@ -47,11 +42,8 @@ export class GithubController {
@Public()
@UseGuards(GithubAuthGuard)
@Get(Routes.GITHUB_REDIRECT)
@HttpCode(HttpStatus.OK)
public async githubRedirect(
@ExternalAuthUser() user: IExternalAuthUser,
@RealIP() ip: string,
): Promise<IGithubRedirectResponse> {
@Redirect(undefined, 301)
public async githubRedirect(@ExternalAuthUser() user: IExternalAuthUser, @RealIP() ip: string) {
this.logger.log(
`User with an email "${user.email}" tries to login. Will check if already exists in DB`,
);
Expand All @@ -74,12 +66,13 @@ export class GithubController {

this.logger.log(`Successfully created a user with Id: "${createdGithubUserId}"`);

const [accessToken, refreshToken] = await this.authService.generateJwtTokens(
const refreshToken = await this.authService.generateJwtToken(
createdGithubUserId,
user.email,
JwtTokenType.Refresh,
);

this.logger.log('Successfully generated both access and refresh tokens');
this.logger.log('Successfully generated both refresh token');

await this.commandBus.execute<AddRefreshTokenContract, void>(
new AddRefreshTokenContract(createdGithubUserId, refreshToken),
Expand All @@ -88,12 +81,9 @@ export class GithubController {
this.logger.log("Successfully stored the user's refresh token");

return {
accessToken,
refreshToken,
name: user.name,
id: createdGithubUserId,
clientSecrets: [],
groupsData: [],
url: `${this.configService.get(
'frontendUrl',
)}/external-auth-redirect?refreshToken=${encodeURIComponent(refreshToken)}`,
};
}

Expand All @@ -113,12 +103,13 @@ export class GithubController {
);
}

const [accessToken, refreshToken] = await this.authService.generateJwtTokens(
const refreshToken = await this.authService.generateJwtToken(
githubUser.id,
user.email,
JwtTokenType.Refresh,
);

this.logger.log('Successfully generated both access and refresh tokens');
this.logger.log('Successfully generated refresh token');

await Promise.all([
storeAccessTokenPromise,
Expand All @@ -135,12 +126,9 @@ export class GithubController {
this.eventBus.publish(new LoginMixpanelContract(githubUser.id, ip));

return {
accessToken,
refreshToken,
name: user.name,
id: githubUser.id,
clientSecrets: githubUser.clientSecrets,
groupsData: githubUser.groupsData,
url: `${this.configService.get(
'frontendUrl',
)}/external-auth-redirect?refreshToken=${encodeURIComponent(refreshToken)}`,
};
}
}
Loading

0 comments on commit b9203b4

Please sign in to comment.