📈 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 user sign up / sign in via Google SSO
Blue Mouse58ffc7add079
diff --git a/.env.example b/.env.exampleindex fde3ed04a..a1958574c 100644--- a/.env.example+++ b/.env.example@@ -55,3 +55,7 @@ CDN_ACCESS_TOKEN=SOME_SECRET_TOKENCAPTCHA_SALT=## We use AES-256-GCM, so the key length MUST BE 32 bytesCAPTCHA_ENCRYPTION_KEY=++# Google SSO+GOOGLE_OAUTH2_CLIENT_ID=+GOOGLE_OAUTH2_CLIENT_SECRET=diff --git a/package.json b/package.jsonindex b928e0e78..756584d88 100644--- a/package.json+++ b/package.json@@ -52,6 +52,7 @@"eslint-plugin-lodash": "^7.4.0","express": "^4.18.2","form-data": "^4.0.0",+ "googleapis": "^117.0.0","handlebars": "^4.7.7","ioredis": "^5.3.1","ip-range-check": "^0.2.0",diff --git a/src/auth/auth.controller.ts b/src/auth/auth.controller.tsindex 5e84bb013..554b9545e 100644--- a/src/auth/auth.controller.ts+++ b/src/auth/auth.controller.ts@@ -14,6 +14,7 @@ import {Param,UnauthorizedException,Headers,+ Res,} from '@nestjs/common'import {ApiTags,@@ -41,6 +42,7 @@ import {ChangePasswordDto,ConfirmChangeEmailDto,RequestChangeEmailDto,+ AuthUserGoogleDto,} from './dtos'import { JwtAccessTokenGuard, JwtRefreshTokenGuard, RolesGuard } from './guards'@@ -103,11 +105,11 @@ export class AuthController {body.password,)- const jwtTokens = await this.authService.generateJwtTokens(newUser.id, true)+ const { accessToken, refreshToken } = await this.authService.generateJwtTokens(newUser.id, true)return {- accessToken: jwtTokens.accessToken,- refreshToken: jwtTokens.refreshToken,+ accessToken,+ refreshToken,user: this.userService.omitSensitiveData(newUser),}}@@ -412,4 +414,45 @@ export class AuthController {await this.authService.logout(user.id, refreshToken)}++ // Google SSO+ @ApiOperation({ summary: 'Auth user' })+ @Post('google')+ async authUserGoogle(+ @Body() body: AuthUserGoogleDto,+ @Headers() headers: unknown,+ @Ip() requestIp: string,+ ): Promise<RegisterResponseDto> {+ // todo: add rate limiting for sign ups++ const { token } = body++ return await this.authService.authenticateGoogle(token, headers, requestIp)+ }++ @ApiOperation({ summary: 'Link Google to an existing account' })+ @ApiOkResponse({+ description: 'Google linked to an existing account',+ })+ @UseGuards(RolesGuard)+ @Roles(UserType.CUSTOMER, UserType.ADMIN)+ @Post('google/link')+ public async linkGoogleToAccount(+ @CurrentUserId() userId: string,+ ): Promise<void> {+ // TODO+ }++ @ApiOperation({ summary: 'Unlink Google from an existing account' })+ @ApiOkResponse({+ description: 'Google unlinked from an existing account',+ })+ @UseGuards(RolesGuard)+ @Roles(UserType.CUSTOMER, UserType.ADMIN)+ @Post('google/unlink')+ public async unlinkGoogleFromAccount(+ @CurrentUserId() userId: string,+ ): Promise<void> {+ // TODO+ }}diff --git a/src/auth/auth.service.ts b/src/auth/auth.service.tsindex fe957f2e3..e1a3a93ea 100644--- a/src/auth/auth.service.ts+++ b/src/auth/auth.service.ts@@ -1,12 +1,19 @@-import { Injectable, InternalServerErrorException } from '@nestjs/common'+import {+ Injectable, InternalServerErrorException, UnauthorizedException,+} from '@nestjs/common'import { ConfigService } from '@nestjs/config'import { JwtService } from '@nestjs/jwt'import axios from 'axios'import { genSalt, hash, compare } from 'bcrypt'import { getCountry } from 'countries-and-timezones'+import { Auth } from 'googleapis'import { createHash } from 'crypto'import * as dayjs from 'dayjs'import { InjectBot } from 'nestjs-telegraf'+import { Telegraf } from 'telegraf'+import { UAParser } from 'ua-parser-js'+import _pick from 'lodash/pick'+import {ActionToken,ActionTokenType,@@ -14,15 +21,17 @@ import {import { ActionTokensService } from 'src/action-tokens/action-tokens.service'import { LetterTemplate } from 'src/mailer/letter'import { MailerService } from 'src/mailer/mailer.service'-import { MAX_EMAIL_REQUESTS, User } from 'src/user/entities/user.entity'+import {+ MAX_EMAIL_REQUESTS, User, TRIAL_DURATION,+} from 'src/user/entities/user.entity'import { TelegrafContext } from 'src/user/user.controller'import { UserService } from 'src/user/user.service'import { ProjectService } from 'src/project/project.service'-import { Telegraf } from 'telegraf'-import { UAParser } from 'ua-parser-js'@Injectable()export class AuthService {+ oauth2Client: Auth.OAuth2Client+constructor(@InjectBot() private readonly telegramBot: Telegraf<TelegrafContext>,private readonly userService: UserService,@@ -31,7 +40,12 @@ export class AuthService {private readonly mailerService: MailerService,private readonly jwtService: JwtService,private readonly projectService: ProjectService,- ) {}+ ) {+ this.oauth2Client = new Auth.OAuth2Client(+ this.configService.get('GOOGLE_OAUTH2_CLIENT_ID'),+ this.configService.get('GOOGLE_OAUTH2_CLIENT_SECRET'),+ )+ }private async createSha1Hash(password: string): Promise<string> {return new Promise(resolve => {@@ -410,4 +424,81 @@ export class AuthService {async validateApiKey(apiKey: string): Promise<User | null> {return this.userService.findUserByApiKey(apiKey)}++ // Google SSO+ async handleExistingUserGoogle(+ user: User,+ headers: unknown,+ ip: string,+ ) {+ if (!user.googleId) {+ throw new UnauthorizedException()+ }++ 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 {+ accessToken: jwtTokens.accessToken,+ refreshToken: jwtTokens.refreshToken,+ user: this.userService.omitSensitiveData(user),+ }+ }++ async registerUserGoogle(sub: string) {+ const user = await this.userService.create({+ googleId: sub,+ trialEndDate: dayjs+ .utc()+ .add(TRIAL_DURATION, 'day')+ .format('YYYY-MM-DD HH:mm:ss'),+ })++ const { accessToken, refreshToken } = await this.generateJwtTokens(user.id, true)++ return {+ accessToken,+ refreshToken,+ user: this.userService.omitSensitiveData(user),+ }+ }++ async authenticateGoogle(+ token: string,+ headers: unknown,+ ip: string,+ ) {+ const tokenInfo = await this.oauth2Client.getTokenInfo(token)++ const { sub } = tokenInfo++ if (!sub) {+ throw new UnauthorizedException()+ }++ try {+ const user = await this.userService.findOneWhere({+ googleId: sub,+ })++ if (!user) {+ return this.registerUserGoogle(sub)+ }++ return this.handleExistingUserGoogle(user, headers, ip)+ } catch (error) {+ console.error(`[ERROR][AuthService -> authenticateGoogle]: ${error}`)+ throw new InternalServerErrorException('Something went wrong while authenticating user with Google')+ }+ }}diff --git a/src/auth/dtos/google-auth-user.dto.ts b/src/auth/dtos/google-auth-user.dto.tsnew file mode 100644index 000000000..2b0b43827--- /dev/null+++ b/src/auth/dtos/google-auth-user.dto.ts@@ -0,0 +1,12 @@+import { ApiProperty } from '@nestjs/swagger'+import { IsNotEmpty, IsString } from 'class-validator'++export class AuthUserGoogleDto {+ @ApiProperty({+ description: 'Google auth token',+ example: 'ya29.a0 ...',+ })+ @IsNotEmpty()+ @IsString()+ token: string+}diff --git a/src/auth/dtos/index.ts b/src/auth/dtos/index.tsindex 453aa2b4f..81a6ed447 100644--- a/src/auth/dtos/index.ts+++ b/src/auth/dtos/index.ts@@ -7,3 +7,4 @@ export * from './reset-password.dto'export * from './change-password.dto'export * from './request-change-email.dto'export * from './confirm-change-email.dto'+export * from './google-auth-user.dto'diff --git a/src/user/dto/user-google.dto.ts b/src/user/dto/user-google.dto.tsnew file mode 100644index 000000000..b8d555464--- /dev/null+++ b/src/user/dto/user-google.dto.ts@@ -0,0 +1,12 @@+import { ApiProperty } from '@nestjs/swagger'+import { IsEmail, IsString } from 'class-validator'++export class UserGoogleDTO {+ @ApiProperty({ example: '10769150350006150715113082367', required: true })+ @IsEmail()+ googleId: string++ @ApiProperty({ example: '2023-01-01 23:12:55', required: true })+ @IsString()+ trialEndDate: string+}diff --git a/src/user/entities/user.entity.ts b/src/user/entities/user.entity.tsindex 7e4f140d1..9148c7b07 100644--- a/src/user/entities/user.entity.ts+++ b/src/user/entities/user.entity.ts@@ -276,6 +276,16 @@ export class User {})timeFormat: TimeFormat+ // Google SSO+ @Column({+ type: 'varchar',+ length: 255,+ nullable: true,+ default: null,+ })+ // Google 'sub' value -> https://cloud.google.com/nodejs/docs/reference/google-auth-library/latest/google-auth-library/tokeninfo#google_auth_library_TokenInfo_sub_member+ googleId: string | null+@OneToMany(() => ExtensionToUser, extensionToUser => extensionToUser.user)@JoinTable()extensions: ExtensionToUser[]diff --git a/src/user/user.service.ts b/src/user/user.service.tsindex 14704aedc..07e7a75ab 100644--- a/src/user/user.service.ts+++ b/src/user/user.service.ts@@ -10,6 +10,7 @@ import { Pagination, PaginationOptionsInterface } from '../common/pagination'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'@Injectable()export class UserService {@@ -20,7 +21,7 @@ export class UserService {private readonly refreshTokenRepository: Repository<RefreshToken>,) {}- async create(userDTO: UserProfileDTO | User): Promise<User> {+ async create(userDTO: UserProfileDTO | User | UserGoogleDTO): Promise<User> {return this.usersRepository.save(userDTO)}