📈 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
re-implemented the google oauth logic
Blue Mouse6a8ce43aae12
diff --git a/src/auth/auth.controller.ts b/src/auth/auth.controller.tsindex e6c973418..1615a408f 100644--- a/src/auth/auth.controller.ts+++ b/src/auth/auth.controller.ts@@ -14,7 +14,6 @@ import {Param,UnauthorizedException,Headers,- Res,} from '@nestjs/common'import {ApiTags,@@ -43,6 +42,7 @@ import {ConfirmChangeEmailDto,RequestChangeEmailDto,AuthUserGoogleDto,+ AuthUserGoogleProcessCodeDto,} from './dtos'import { JwtAccessTokenGuard, JwtRefreshTokenGuard, RolesGuard } from './guards'@@ -417,17 +417,46 @@ export class AuthController {// Google SSO@ApiOperation({ summary: 'Auth user' })- @Post('google')- async authUserGoogle(+ @Post('google/generate')+ @Public()+ async generateAuthURL(+ @Headers() headers: unknown,+ @Ip() requestIp: string,+ ): Promise<any> {+ // TODO: add rate limiting++ return await this.authService.generateGoogleURL()+ }++ @ApiOperation({ summary: 'Auth user' })+ @Post('google/process-code')+ @Public()+ async processGoogleCode(+ @Body() body: AuthUserGoogleProcessCodeDto,+ @Headers() headers: unknown,+ @Ip() requestIp: string,+ ): Promise<any> {+ // TODO: add rate limiting++ const { token, hash } = body++ return await this.authService.processGoogleToken(token, hash)+ }++ @ApiOperation({ summary: 'Auth user' })+ @Post('google/hash')+ @Public()+ // Validates the authorisation code and returns the JWT tokens+ async getJWTByHash(@Body() body: AuthUserGoogleDto,@Headers() headers: unknown,@Ip() requestIp: string,- ): Promise<RegisterResponseDto> {- // todo: add rate limiting for sign ups+ ): Promise<any> {+ // TODO: add rate limiting- const { token } = body+ const { hash } = body- return await this.authService.authenticateGoogle(token, headers, requestIp)+ return await this.authService.authenticateGoogle(hash, headers, requestIp)}@ApiOperation({ summary: 'Link Google to an existing account' })@@ -436,14 +465,14 @@ export class AuthController {})@UseGuards(RolesGuard)@Roles(UserType.CUSTOMER, UserType.ADMIN)- @Post('google/link')+ @Post('google/link_by_hash')public async linkGoogleToAccount(@Body() body: AuthUserGoogleDto,@CurrentUserId() userId: string,): Promise<void> {- const { token } = body+ const { hash } = body- await this.authService.linkGoogleAccount(userId, token)+ await this.authService.linkGoogleAccount(userId, hash)}@ApiOperation({ summary: 'Unlink Google from an existing account' })diff --git a/src/auth/auth.service.ts b/src/auth/auth.service.tsindex 77528b513..2f467d4fa 100644--- a/src/auth/auth.service.ts+++ b/src/auth/auth.service.ts@@ -1,5 +1,5 @@import {- Injectable, InternalServerErrorException, UnauthorizedException,+ Injectable, InternalServerErrorException, UnauthorizedException, BadRequestException, ConflictException,} from '@nestjs/common'import { ConfigService } from '@nestjs/config'import { JwtService } from '@nestjs/jwt'@@ -13,6 +13,7 @@ import { InjectBot } from 'nestjs-telegraf'import { Telegraf } from 'telegraf'import { UAParser } from 'ua-parser-js'import _pick from 'lodash/pick'+import { v4 as uuidv4 } from 'uuid'import {ActionToken,@@ -27,6 +28,11 @@ import {import { TelegrafContext } from 'src/user/user.controller'import { UserService } from 'src/user/user.service'import { ProjectService } from 'src/project/project.service'+import { REDIS_SSO_UUID, redis } from 'src/common/constants'+import { UserGoogleDTO } from '../user/dto/user-google.dto'++const REDIS_SSO_SESSION_TIMEOUT = 60 * 5 // 5 minutes+const getSSORedisKey = (uuid: string) => `${REDIS_SSO_UUID}:${uuid}`@Injectable()export class AuthService {@@ -459,15 +465,26 @@ export class AuthService {}}- async registerUserGoogle(sub: string) {- const user = await this.userService.create({+ async registerUserGoogle(sub: string, email: string) {+ const query: UserGoogleDTO = {googleId: sub,trialEndDate: dayjs.utc().add(TRIAL_DURATION, 'day').format('YYYY-MM-DD HH:mm:ss'),+ registeredWithGoogle: true,+ }++ const userWithSameEmail = await this.userService.findOneWhere({+ email,})+ if (!userWithSameEmail) {+ query.email = email+ }++ const user = await this.userService.create(query)+const { accessToken, refreshToken } = await this.generateJwtTokens(user.id, true)return {@@ -477,18 +494,47 @@ export class AuthService {}}+ async processHash(hash: string) {+ if (!hash) {+ throw new BadRequestException('Missing hash parameter')+ }++ const ssoRedisKey = getSSORedisKey(hash)+ const exists = await redis.exists(ssoRedisKey)++ if (!exists) {+ throw new BadRequestException('No authentication session opened for this hash')+ }++ const data = await redis.get(ssoRedisKey)++ if (!data) {+ throw new ConflictException('Authentication session is opened but no data found')+ }++ let sub: string+ let email: string++ try {+ const payload = JSON.parse(data)+ sub = payload.sub+ email = payload.email+ } catch (reason) {+ console.error(`[ERROR][AuthService -> authenticateGoogle -> JSON.parse]: ${reason} - ${data}`)+ throw new InternalServerErrorException('Session related data is corrupted')+ }++ await redis.del(ssoRedisKey)++ return { sub, email, ssoRedisKey }+ }+async authenticateGoogle(- token: string,+ hash: string,headers: unknown,ip: string,) {- const tokenInfo = await this.oauth2Client.getTokenInfo(token)-- const { sub } = tokenInfo-- if (!sub) {- throw new UnauthorizedException()- }+ const { sub, email } = await this.processHash(hash)try {const user = await this.userService.findOneWhere({@@ -496,7 +542,7 @@ export class AuthService {})if (!user) {- return this.registerUserGoogle(sub)+ return this.registerUserGoogle(sub, email)}return this.handleExistingUserGoogle(user, headers, ip)@@ -506,19 +552,57 @@ export class AuthService {}}- async linkGoogleAccount(userId: string, token: string) {- const tokenInfo = await this.oauth2Client.getTokenInfo(token)+ async generateGoogleURL() {+ // Generating SSO session identifier and authorisation URL+ const uuid = uuidv4()+ const auth_url = await this.oauth2Client.generateAuthUrl({+ state: uuid,+ redirect_uri: 'http://localhost:3000/socialised',+ scope: 'email',+ response_type: 'token',+ })++ // Storing the session identifier in redis+ await redis.set(getSSORedisKey(uuid), '', 'EX', REDIS_SSO_SESSION_TIMEOUT)- const { sub } = tokenInfo+ return {+ uuid, auth_url,+ }+ }++ async processGoogleToken(+ token: string,+ hash: string,+ ) {+ let tokenInfo++ try {+ tokenInfo = await this.oauth2Client.getTokenInfo(token)+ } catch (reason) {+ console.error(`[ERROR][AuthService -> processGoogleCode -> oauth2Client.getTokenInfo]: ${reason}`)+ throw new BadRequestException('Invalid Google code supplied')+ }++ const { sub, email } = tokenInfo++ // TODO: Only store the email if email_verified is true+ const dataToStore = JSON.stringify({ sub, email })++ // Storing the session identifier in redis+ await redis.set(getSSORedisKey(hash), dataToStore, 'EX', REDIS_SSO_SESSION_TIMEOUT)+ }++ async linkGoogleAccount(userId: string, hash: string) {+ const { sub } = await this.processHash(hash)if (!sub) {- throw new UnauthorizedException()+ throw new BadRequestException('Google ID is missing in the authentication session')}const user = await this.userService.findUserById(userId)if (!user) {- throw new UnauthorizedException()+ throw new BadRequestException('User not found')}await this.userService.updateUser(userId, {diff --git a/src/auth/dtos/google-auth-process-code.dto.ts b/src/auth/dtos/google-auth-process-code.dto.tsnew file mode 100644index 000000000..15c0e3d7a--- /dev/null+++ b/src/auth/dtos/google-auth-process-code.dto.ts@@ -0,0 +1,18 @@+import { ApiProperty } from '@nestjs/swagger'+import { IsString, IsUUID } from 'class-validator'++export class AuthUserGoogleProcessCodeDto {+ @ApiProperty({+ description: 'Google auth token',+ example: '4/0AVHE...',+ })+ @IsString()+ token: string++ @ApiProperty({+ description: 'SSO session identifier',+ example: '123e4567-e89b-12d3-a456-426614174000',+ })+ @IsUUID()+ hash: string+}diff --git a/src/auth/dtos/google-auth-user.dto.ts b/src/auth/dtos/google-auth-user.dto.tsindex 2b0b43827..fd143693b 100644--- a/src/auth/dtos/google-auth-user.dto.ts+++ b/src/auth/dtos/google-auth-user.dto.ts@@ -1,12 +1,11 @@import { ApiProperty } from '@nestjs/swagger'-import { IsNotEmpty, IsString } from 'class-validator'+import { IsUUID } from 'class-validator'export class AuthUserGoogleDto {@ApiProperty({- description: 'Google auth token',- example: 'ya29.a0 ...',+ description: 'SSO session identifier',+ example: '123e4567-e89b-12d3-a456-426614174000',})- @IsNotEmpty()- @IsString()- token: string+ @IsUUID()+ hash: string}diff --git a/src/auth/dtos/index.ts b/src/auth/dtos/index.tsindex 81a6ed447..5b6aeb351 100644--- a/src/auth/dtos/index.ts+++ b/src/auth/dtos/index.ts@@ -8,3 +8,4 @@ export * from './change-password.dto'export * from './request-change-email.dto'export * from './confirm-change-email.dto'export * from './google-auth-user.dto'+export * from './google-auth-process-code.dto'diff --git a/src/common/constants.ts b/src/common/constants.tsindex b14a1be06..8dd06e62b 100644--- a/src/common/constants.ts+++ b/src/common/constants.ts@@ -188,6 +188,7 @@ const REDIS_USERS_COUNT_KEY = 'stats:users_count'const REDIS_PROJECTS_COUNT_KEY = 'stats:projects_count'const REDIS_PAGEVIEWS_COUNT_KEY = 'stats:pageviews'const REDIS_PERFORMANCE_COUNT_KEY = 'stats:performance'+const REDIS_SSO_UUID = 'sso:uuid'// Captcha serviceconst { CAPTCHA_SALT } = process.env@@ -262,4 +263,5 @@ export {PRODUCTION_ORIGIN,isTgTokenPresent,DEFAULT_SELFHOSTED_UUID,+ REDIS_SSO_UUID,}diff --git a/src/user/dto/user-google.dto.ts b/src/user/dto/user-google.dto.tsindex b8d555464..0c25b50c6 100644--- a/src/user/dto/user-google.dto.ts+++ b/src/user/dto/user-google.dto.ts@@ -1,12 +1,20 @@import { ApiProperty } from '@nestjs/swagger'-import { IsEmail, IsString } from 'class-validator'+import { IsBoolean, IsEmail, IsString } from 'class-validator'export class UserGoogleDTO {@ApiProperty({ example: '10769150350006150715113082367', required: true })- @IsEmail()+ @IsString()googleId: string++ @ApiProperty({ required: true })+ @IsBoolean()+ registeredWithGoogle: boolean@ApiProperty({ example: '2023-01-01 23:12:55', required: true })@IsString()trialEndDate: string++ @ApiProperty({ example: '[email protected]', required: false })+ @IsEmail()+ email?: string}diff --git a/src/user/entities/user.entity.ts b/src/user/entities/user.entity.tsindex 9148c7b07..d086d717d 100644--- a/src/user/entities/user.entity.ts+++ b/src/user/entities/user.entity.ts@@ -286,6 +286,9 @@ export class User {// Google 'sub' value -> https://cloud.google.com/nodejs/docs/reference/google-auth-library/latest/google-auth-library/tokeninfo#google_auth_library_TokenInfo_sub_membergoogleId: string | null+ @Column({ default: false })+ registeredWithGoogle: boolean+@OneToMany(() => ExtensionToUser, extensionToUser => extensionToUser.user)@JoinTable()extensions: ExtensionToUser[]