📈 Open source, privacy-first web analytics — a cookie-less Google Analytics alternative with built-in error tracking and performance monitoring. Self-host it or use our cloud. Get started for free!
TypeScript chartsclickhousedockergdprgoogle-analyticsmetricsmonitoringmysqlnestjsprivacyredisself-hostedselfhostedstatisticstailwindcssweb-analyticswebanalyticswebsite
implemented github sso
Blue Mouse23b53d7c1b9b
diff --git a/src/auth/auth.controller.ts b/src/auth/auth.controller.tsindex ef6b03106..f913d7385 100644--- a/src/auth/auth.controller.ts+++ b/src/auth/auth.controller.ts@@ -49,8 +49,12 @@ import {SSOUnlinkDto,} from './dtos'import { SSOProviders } from './dtos/sso-generate.dto'+import { isDevelopment } from 'src/common/constants'import { JwtAccessTokenGuard, JwtRefreshTokenGuard, RolesGuard } from './guards'+const LOCAL_OAUTH_RATE_LIMIT = 2000+const PRODUCTION_OAUTH_RATE_LIMIT = 15+@ApiTags('Auth')@Controller({ path: 'auth', version: '1' })@UseFilters(new I18nValidationExceptionFilter())@@ -427,7 +431,7 @@ export class AuthController {@Body() body: SSOGenerateDto,@Ip() ip: string,): Promise<any> {- await checkRateLimit(ip, 'sso-generate', 15, 1800)+ await checkRateLimit(ip, 'sso-generate', isDevelopment ? LOCAL_OAUTH_RATE_LIMIT : PRODUCTION_OAUTH_RATE_LIMIT, 1800)const { provider } = body@@ -447,7 +451,7 @@ export class AuthController {@Body() body: ProcessSSOCodeDto,@Ip() ip: string,): Promise<any> {- await checkRateLimit(ip, 'sso-process', 15, 1800)+ await checkRateLimit(ip, 'sso-process', isDevelopment ? LOCAL_OAUTH_RATE_LIMIT : PRODUCTION_OAUTH_RATE_LIMIT, 1800)const { token, hash } = body@@ -455,7 +459,7 @@ export class AuthController {}@ApiOperation({ summary: 'Auth user' })- @Post('google/hash')+ @Post('sso/hash')@Public()// Validates the authorisation code and returns the JWT tokensasync getJWTByHash(@@ -463,7 +467,7 @@ export class AuthController {@Headers() headers: unknown,@Ip() ip: string,): Promise<any> {- await checkRateLimit(ip, 'sso-hash', 15, 1800)+ await checkRateLimit(ip, 'sso-hash', isDevelopment ? LOCAL_OAUTH_RATE_LIMIT : PRODUCTION_OAUTH_RATE_LIMIT, 1800)const { hash, provider } = body@@ -482,7 +486,7 @@ export class AuthController {@CurrentUserId() userId: string,@Ip() ip: string,): Promise<void> {- await checkRateLimit(ip, 'sso-link', 15, 1800)+ await checkRateLimit(ip, 'sso-link', isDevelopment ? LOCAL_OAUTH_RATE_LIMIT : PRODUCTION_OAUTH_RATE_LIMIT, 1800)const { hash, provider } = bodydiff --git a/src/auth/auth.service.ts b/src/auth/auth.service.tsindex b7932ee32..e8129c6f3 100644--- a/src/auth/auth.service.ts+++ b/src/auth/auth.service.ts@@ -18,6 +18,8 @@ import { Telegraf } from 'telegraf'import { UAParser } from 'ua-parser-js'import * as _pick from 'lodash/pick'import * as _split from 'lodash/split'+import * as _isEmpty from 'lodash/isEmpty'+import * as _find from 'lodash/find'import { v4 as uuidv4 } from 'uuid'import {@@ -43,6 +45,7 @@ import {} from 'src/common/constants'import { SSOProviders } from './dtos/sso-generate.dto'import { UserGoogleDTO } from '../user/dto/user-google.dto'+import { UserGithubDTO } from '../user/dto/user-github.dto'const REDIS_SSO_SESSION_TIMEOUT = 60 * 5 // 5 minutesconst getSSORedisKey = (uuid: string) => `${REDIS_SSO_UUID}:${uuid}`@@ -53,6 +56,9 @@ const OAUTH_REDIRECT_URL = isDevelopment? 'http://localhost:3000/socialised': `${PRODUCTION_ORIGIN}/socialised`+const GITHUB_OAUTH2_CLIENT_ID = process.env.GITHUB_OAUTH2_CLIENT_ID+const GITHUB_OAUTH2_CLIENT_SECRET = process.env.GITHUB_OAUTH2_CLIENT_SECRET+@Injectable()export class AuthService {oauth2Client: Auth.OAuth2Client@@ -72,8 +78,6 @@ export class AuthService {this.configService.get('GOOGLE_OAUTH2_CLIENT_ID'),this.configService.get('GOOGLE_OAUTH2_CLIENT_SECRET'),)- this.githubOAuthClientID = this.configService.get('GITHUB_OAUTH2_CLIENT_ID')- this.githubOAuthClientSecret = this.configService.get('GITHUB_OAUTH2_CLIENT_SECRET')}private async createSha1Hash(password: string): Promise<string> {@@ -461,7 +465,7 @@ export class AuthService {*/async handleExistingUserGoogle(user: User, headers: unknown, ip: string) {if (!user.googleId) {- throw new UnauthorizedException()+ throw new BadRequestException()}await this.sendTelegramNotification(user.id, headers, ip)@@ -505,14 +509,13 @@ export class AuthService {const user = await this.userService.create(query)- const { accessToken, refreshToken } = await this.generateJwtTokens(+ const jwtTokens = await this.generateJwtTokens(user.id,true,)return {- accessToken,- refreshToken,+ ...jwtTokens,user: this.userService.omitSensitiveData(user),}}@@ -539,13 +542,10 @@ export class AuthService {)}- let sub: string- let email: string+ let payloadtry {- const payload = JSON.parse(data)- sub = payload.sub- email = payload.email+ payload = JSON.parse(data)} catch (reason) {console.error(`[ERROR][AuthService -> authenticateGoogle -> JSON.parse]: ${reason} - ${data}`,@@ -557,7 +557,7 @@ export class AuthService {await redis.del(ssoRedisKey)- return { sub, email }+ return payload}async authenticateSSO(ssoHash: string, headers: unknown, ip: string, provider: SSOProviders) {@@ -641,7 +641,6 @@ export class AuthService {const { sub, email } = tokenInfo- // TODO: Only store the email if email_verified is trueconst dataToStore = JSON.stringify({ sub, email })// Storing the session identifier in redis@@ -723,14 +722,7 @@ export class AuthService {async generateGithubURL() {// Generating SSO session identifier and authorisation URLconst uuid = generateSSOState(SSOProviders.GITHUB)- const authUrl = await axios.get('https://github.com/login/oauth/authorize', {- params: {- client_id: this.githubOAuthClientID,- state: uuid,- redirect_uri: OAUTH_REDIRECT_URL,- scope: 'user:email',- },- })+ const authUrl = `https://github.com/login/oauth/authorize?client_id=${GITHUB_OAUTH2_CLIENT_ID}&state=${uuid}&redirect_uri=${OAUTH_REDIRECT_URL}&scope=user:email`// Storing the session identifier in redisawait redis.set(getSSORedisKey(uuid), '', 'EX', REDIS_SSO_SESSION_TIMEOUT)@@ -750,8 +742,8 @@ export class AuthService {const response = await axios.post('https://github.com/login/oauth/access_token',{- client_id: this.githubOAuthClientID,- client_secret: this.githubOAuthClientSecret,+ client_id: GITHUB_OAUTH2_CLIENT_ID,+ client_secret: GITHUB_OAUTH2_CLIENT_SECRET,code,},{@@ -784,31 +776,159 @@ export class AuthService {throw new BadRequestException('Invalid Github token')}- // const { sub, email } = tokenInfo+ const { id } = tokenInfo+ let { email } = tokenInfo- console.log(tokenInfo)+ if (!email) {+ try {+ const response = await axios.get('https://api.github.com/user/emails', {+ headers: {+ Authorization: `token ${token}`,+ },+ })++ const emails = response.data++ if (_isEmpty(emails)) {+ console.error(+ '[ERROR][AuthService -> processGithubCode]: No email address found',+ )+ throw new BadRequestException('No email address found')+ }++ email = _find(emails, (e) => e.primary).email+ } catch (reason) {+ console.error(+ `[ERROR][AuthService -> processGithubCode -> axios.get (emails)]: ${reason}`,+ )+ throw new BadRequestException('Invalid Github token')+ }+ }- // TODO: Only store the email if email_verified is true- // const dataToStore = JSON.stringify({ sub, email })+ const dataToStore = JSON.stringify({ id, email })// Storing the session identifier in redis- // await redis.set(- // getSSORedisKey(ssoHash),- // dataToStore,- // 'EX',- // REDIS_SSO_SESSION_TIMEOUT,- // )+ await redis.set(+ getSSORedisKey(ssoHash),+ dataToStore,+ 'EX',+ REDIS_SSO_SESSION_TIMEOUT,+ )+ }++ async registerUserGithub(id: number, email: string) {+ const query: UserGithubDTO = {+ githubId: id,+ trialEndDate: dayjs+ .utc()+ .add(TRIAL_DURATION, 'day')+ .format('YYYY-MM-DD HH:mm:ss'),+ registeredWithGithub: true,+ isActive: true,+ emailRequests: 0,+ }++ const userWithSameEmail = await this.userService.findOneWhere({+ email,+ })++ if (!userWithSameEmail) {+ query.email = email+ }++ const user = await this.userService.create(query)++ const jwtTokens = await this.generateJwtTokens(+ user.id,+ true,+ )++ return {+ ...jwtTokens,+ user: this.userService.omitSensitiveData(user),+ }+ }++ async handleExistingUserGithub(user: User, headers: unknown, ip: string) {+ if (!user.githubId) {+ throw new BadRequestException()+ }++ await this.sendTelegramNotification(user.id, headers, ip)++ const jwtTokens = await this.generateJwtTokens(+ user.id,+ !user.isTwoFactorAuthenticationEnabled,+ )++ if (user.isTwoFactorAuthenticationEnabled) {+ user = _pick(user, ['isTwoFactorAuthenticationEnabled', 'email'])+ } else {+ user = await this.getSharedProjectsForUser(user)+ }++ return {+ ...jwtTokens,+ user: this.userService.omitSensitiveData(user),+ }}async unlinkGithubAccount(userId: string) {- // TODO+ const user = await this.userService.findUserById(userId)++ if (!user) {+ throw new BadRequestException('User not found')+ }++ if (user.registeredWithGithub) {+ throw new BadRequestException(+ 'You cannot unlink your Google account if you registered with it',+ )+ }++ await this.userService.updateUser(userId, {+ githubId: null,+ })}async linkGithubAccount(userId: string, ssoHash: string) {- // TODO+ const { id } = await this.processHash(ssoHash)++ if (!id) {+ throw new BadRequestException(+ 'Github ID is missing in the authentication session',+ )+ }++ const user = await this.userService.findUserById(userId)++ if (!user) {+ throw new BadRequestException('User not found')+ }++ await this.userService.updateUser(userId, {+ githubId: id,+ })}async authenticateGithub(ssoHash: string, headers: unknown, ip: string) {- // TODO+ const { id, email } = await this.processHash(ssoHash)++ try {+ const user = await this.userService.findOneWhere({+ githubId: id,+ })++ if (!user) {+ return await this.registerUserGithub(id, email)+ }++ return await this.handleExistingUserGithub(user, headers, ip)+ } catch (error) {+ console.error(`[ERROR][AuthService -> authenticateGithub]: ${error}`)+ throw new InternalServerErrorException(+ 'Something went wrong while authenticating user with Github',+ )+ }}}diff --git a/src/auth/dtos/google-auth-user.dto.ts b/src/auth/dtos/google-auth-user.dto.tsnew file mode 100644index 000000000..fd143693b--- /dev/null+++ b/src/auth/dtos/google-auth-user.dto.ts@@ -0,0 +1,11 @@+import { ApiProperty } from '@nestjs/swagger'+import { IsUUID } from 'class-validator'++export class AuthUserGoogleDto {+ @ApiProperty({+ description: 'SSO session identifier',+ example: '123e4567-e89b-12d3-a456-426614174000',+ })+ @IsUUID()+ hash: string+}diff --git a/src/user/dto/user-github.dto.ts b/src/user/dto/user-github.dto.tsnew file mode 100644index 000000000..9a205397a--- /dev/null+++ b/src/user/dto/user-github.dto.ts@@ -0,0 +1,26 @@+import { ApiProperty } from '@nestjs/swagger'+import { IsBoolean, IsEmail, IsString } from 'class-validator'++export class UserGithubDTO {+ @ApiProperty({ example: 12345, required: true })+ @IsString()+ githubId: number++ @ApiProperty({ required: true })+ @IsBoolean()+ registeredWithGithub: boolean++ @ApiProperty({ example: '2023-01-01 23:12:55', required: true })+ @IsString()+ trialEndDate: string++ @ApiProperty({ example: '[email protected]', required: false })+ @IsEmail()+ email?: string++ @ApiProperty({ example: 1, required: false })+ emailRequests: number++ @ApiProperty({ example: true, required: false })+ isActive: boolean+}diff --git a/src/user/entities/user.entity.ts b/src/user/entities/user.entity.tsindex d086d717d..a36d5075b 100644--- a/src/user/entities/user.entity.ts+++ b/src/user/entities/user.entity.ts@@ -289,6 +289,18 @@ export class User {@Column({ default: false })registeredWithGoogle: boolean+ // Github SSO+ @Column({+ type: 'int',+ nullable: true,+ default: null,+ })+ // Github user: id value -> https://developer.github.com/v3/users/#get-the-authenticated-user+ githubId: number | null++ @Column({ default: false })+ registeredWithGithub: boolean+@OneToMany(() => ExtensionToUser, extensionToUser => extensionToUser.user)@JoinTable()extensions: ExtensionToUser[]diff --git a/src/user/user.controller.ts b/src/user/user.controller.tsindex 853145930..096391771 100644--- a/src/user/user.controller.ts+++ b/src/user/user.controller.ts@@ -580,6 +580,8 @@ export class UserController {'trialReminderSent','googleId','registeredWithGoogle',+ 'githubId',+ 'registeredWithGithub',])await this.userService.update(id, userToUpdate)diff --git a/src/user/user.service.ts b/src/user/user.service.tsindex 07e7a75ab..2a6c778c2 100644--- a/src/user/user.service.ts+++ b/src/user/user.service.ts@@ -11,6 +11,7 @@ import { User, ACCOUNT_PLANS, TRIAL_DURATION } from './entities/user.entity'import { UserProfileDTO } from './dto/user.dto'import { RefreshToken } from './entities/refresh-token.entity'import { UserGoogleDTO } from './dto/user-google.dto'+import { UserGithubDTO } from './dto/user-github.dto'@Injectable()export class UserService {@@ -21,7 +22,7 @@ export class UserService {private readonly refreshTokenRepository: Repository<RefreshToken>,) {}- async create(userDTO: UserProfileDTO | User | UserGoogleDTO): Promise<User> {+ async create(userDTO: UserProfileDTO | User | UserGoogleDTO | UserGithubDTO): Promise<User> {return this.usersRepository.save(userDTO)}