📈 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
added some basic github sso support & generalised the api to support multiple providers without additional endpoints
Blue Mouse8186828e3e40
diff --git a/.env.example b/.env.exampleindex a1958574c..fb9db0e40 100644--- a/.env.example+++ b/.env.example@@ -59,3 +59,7 @@ CAPTCHA_ENCRYPTION_KEY=# Google SSOGOOGLE_OAUTH2_CLIENT_ID=GOOGLE_OAUTH2_CLIENT_SECRET=++# Github SSO+GITHUB_OAUTH2_CLIENT_ID=+GITHUB_OAUTH2_CLIENT_SECRET=diff --git a/src/auth/auth.controller.ts b/src/auth/auth.controller.tsindex 1e2abeebf..8343adc3e 100644--- a/src/auth/auth.controller.ts+++ b/src/auth/auth.controller.ts@@ -43,8 +43,10 @@ import {ConfirmChangeEmailDto,RequestChangeEmailDto,AuthUserGoogleDto,- AuthUserGoogleProcessCodeDto,+ ProcessSSOCodeDto,+ SSOGenerateDto,} from './dtos'+import { SSOProviders } from './dtos/sso-generate.dto'import { JwtAccessTokenGuard, JwtRefreshTokenGuard, RolesGuard } from './guards'@ApiTags('Auth')@@ -415,28 +417,39 @@ export class AuthController {await this.authService.logout(user.id, refreshToken)}- // Google SSO- @ApiOperation({ summary: 'Auth user' })- @Post('google/generate')+ // SSO section+ @ApiOperation({ summary: 'Generate SSO authentication URL' })+ @Post('sso/generate')@Public()- async generateAuthURL(@Ip() ip: string): Promise<any> {- await checkRateLimit(ip, 'g-sso-generate', 15, 1800)+ async generateAuthURL(+ @Body() body: SSOGenerateDto,+ @Ip() ip: string,+ ): Promise<any> {+ await checkRateLimit(ip, 'sso-generate', 15, 1800)++ const { provider } = body- return this.authService.generateGoogleURL()+ if (provider === SSOProviders.GOOGLE) {+ return this.authService.generateGoogleURL()+ }++ if (provider === SSOProviders.GITHUB) {+ return this.authService.generateGithubURL()+ }}- @ApiOperation({ summary: 'Auth user' })- @Post('google/process-token')+ @ApiOperation({ summary: 'Process authentication token (or code)' })+ @Post('sso/process-token')@Public()- async processGoogleCode(- @Body() body: AuthUserGoogleProcessCodeDto,+ async processSSOToken(+ @Body() body: ProcessSSOCodeDto,@Ip() ip: string,): Promise<any> {- await checkRateLimit(ip, 'g-sso-process', 15, 1800)+ await checkRateLimit(ip, 'sso-process', 15, 1800)const { token, hash } = body- return this.authService.processGoogleToken(token, hash)+ return this.authService.processSSOToken(token, hash)}@ApiOperation({ summary: 'Auth user' })diff --git a/src/auth/auth.service.ts b/src/auth/auth.service.tsindex 8370627fa..c86722b5a 100644--- a/src/auth/auth.service.ts+++ b/src/auth/auth.service.ts@@ -17,6 +17,7 @@ import { InjectBot } from 'nestjs-telegraf'import { Telegraf } from 'telegraf'import { UAParser } from 'ua-parser-js'import _pick from 'lodash/pick'+import _split from 'lodash/split'import { v4 as uuidv4 } from 'uuid'import {@@ -40,18 +41,23 @@ import {PRODUCTION_ORIGIN,isDevelopment,} from 'src/common/constants'+import { SSOProviders } from './dtos/sso-generate.dto'import { UserGoogleDTO } from '../user/dto/user-google.dto'const REDIS_SSO_SESSION_TIMEOUT = 60 * 5 // 5 minutesconst getSSORedisKey = (uuid: string) => `${REDIS_SSO_UUID}:${uuid}`+const generateSSOState = (provider: SSOProviders) => `${provider}:${uuidv4()}`+const getSSOSessionProvider = (state: string): SSOProviders => _split(state, ':')[0] as SSOProviders-const GOOGLE_OAUTH_REDIRECT_URL = isDevelopment+const OAUTH_REDIRECT_URL = isDevelopment? 'http://localhost:3000/socialised': `${PRODUCTION_ORIGIN}/socialised`@Injectable()export class AuthService {oauth2Client: Auth.OAuth2Client+ githubOAuthClientID: string+ githubOAuthClientSecret: stringconstructor(@InjectBot() private readonly telegramBot: Telegraf<TelegrafContext>,@@ -66,6 +72,8 @@ 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> {@@ -575,10 +583,10 @@ export class AuthService {async generateGoogleURL() {// Generating SSO session identifier and authorisation URL- const uuid = uuidv4()+ const uuid = generateSSOState(SSOProviders.GOOGLE)const authUrl = await this.oauth2Client.generateAuthUrl({state: uuid,- redirect_uri: GOOGLE_OAUTH_REDIRECT_URL,+ redirect_uri: OAUTH_REDIRECT_URL,scope: 'email',response_type: 'token',})@@ -593,6 +601,20 @@ export class AuthService {}}+ async processSSOToken(token: string, ssoHash: string) {+ const provider = getSSOSessionProvider(ssoHash)++ if (provider === SSOProviders.GOOGLE) {+ await this.processGoogleToken(token, ssoHash)+ }++ if (provider === SSOProviders.GITHUB) {+ await this.processGithubCode(token, ssoHash)+ }++ throw new BadRequestException('Unknown SSO provider supplied')+ }+async processGoogleToken(token: string, ssoHash: string) {let tokenInfo@@ -602,7 +624,7 @@ export class AuthService {console.error(`[ERROR][AuthService -> processGoogleCode -> oauth2Client.getTokenInfo]: ${reason}`,)- throw new BadRequestException('Invalid Google code supplied')+ throw new BadRequestException('Invalid Google token supplied')}const { sub, email } = tokenInfo@@ -656,4 +678,89 @@ export class AuthService {googleId: null,})}++ /*+ --------------------------------+ Github SSO section+ --------------------------------+ */+ async generateGithubURL() {+ // Generating SSO session identifier and authorisation URL+ const 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',+ },+ })++ // Storing the session identifier in redis+ await redis.set(getSSORedisKey(uuid), '', 'EX', REDIS_SSO_SESSION_TIMEOUT)++ return {+ uuid,+ auth_url: authUrl,+ expires_in: REDIS_SSO_SESSION_TIMEOUT * 1000, // milliseconds+ }+ }++ async processGithubCode(code: string, ssoHash: string) {+ let token+ let tokenInfo++ try {+ const response = await axios.post(+ 'https://github.com/login/oauth/access_token',+ {+ client_id: this.githubOAuthClientID,+ client_secret: this.githubOAuthClientSecret,+ code,+ },+ {+ headers: {+ Accept: 'application/json',+ },+ },+ )++ token = response.data.access_token+ } catch (reason) {+ console.error(+ `[ERROR][AuthService -> processGithubCode -> axios.post]: ${reason}`,+ )+ throw new BadRequestException('Invalid Github code supplied')+ }++ try {+ const response = await axios.get('https://api.github.com/user', {+ headers: {+ Authorization: `token ${token}`,+ },+ })++ tokenInfo = response.data+ } catch (reason) {+ console.error(+ `[ERROR][AuthService -> processGithubCode -> axios.get]: ${reason}`,+ )+ throw new BadRequestException('Invalid Github token')+ }++ // const { sub, email } = tokenInfo++ console.log(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(ssoHash),+ // dataToStore,+ // 'EX',+ // REDIS_SSO_SESSION_TIMEOUT,+ // )+ }}diff --git a/src/auth/dtos/index.ts b/src/auth/dtos/index.tsindex 5b6aeb351..eec02f96d 100644--- a/src/auth/dtos/index.ts+++ b/src/auth/dtos/index.ts@@ -8,4 +8,5 @@ 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'+export * from './process-sso-code.dto'+export * from './sso-generate.dto'diff --git a/src/auth/dtos/google-auth-process-code.dto.ts b/src/auth/dtos/process-sso-code.dto.tssimilarity index 89%rename from src/auth/dtos/google-auth-process-code.dto.tsrename to src/auth/dtos/process-sso-code.dto.tsindex 15c0e3d7a..d87b341be 100644--- a/src/auth/dtos/google-auth-process-code.dto.ts+++ b/src/auth/dtos/process-sso-code.dto.ts@@ -1,7 +1,7 @@import { ApiProperty } from '@nestjs/swagger'import { IsString, IsUUID } from 'class-validator'-export class AuthUserGoogleProcessCodeDto {+export class ProcessSSOCodeDto {@ApiProperty({description: 'Google auth token',example: '4/0AVHE...',diff --git a/src/auth/dtos/sso-generate.dto.ts b/src/auth/dtos/sso-generate.dto.tsnew file mode 100644index 000000000..85949e99c--- /dev/null+++ b/src/auth/dtos/sso-generate.dto.ts@@ -0,0 +1,16 @@+import { ApiProperty } from '@nestjs/swagger'+import { IsEnum } from 'class-validator'++export enum SSOProviders {+ GOOGLE = 'google',+ GITHUB = 'github',+}++export class SSOGenerateDto {+ @ApiProperty({+ description: 'SSO provider name',+ enum: SSOProviders,+ })+ @IsEnum(SSOProviders)+ provider: string+}