2814 timebox create a poc to test the gmail api (#2868)

* create gmail strategy and controller

* gmail button connect

* wip

* trying to fix error { error: 'invalid_grant', error_description: 'Bad Request' }

* access token working

* refresh token working

* Getting the short term token from the front is working

* working

* rename token

* remove comment

* rename env var

* move file

* Fix

* Fix

---------

Co-authored-by: Charles Bochet <charles@twenty.com>
This commit is contained in:
bosiraphael
2023-12-08 13:13:56 +01:00
committed by GitHub
parent d4613c87f6
commit 7535c84e3d
26 changed files with 660 additions and 89 deletions

View File

@ -12,15 +12,16 @@ import { DataSourceModule } from 'src/metadata/data-source/data-source.module';
import { UserModule } from 'src/core/user/user.module';
import { WorkspaceManagerModule } from 'src/workspace/workspace-manager/workspace-manager.module';
import { TypeORMModule } from 'src/database/typeorm/typeorm.module';
import { GoogleAuthController } from 'src/core/auth/controllers/google-auth.controller';
import { GoogleGmailAuthController } from 'src/core/auth/controllers/google-gmail-auth.controller';
import { VerifyAuthController } from 'src/core/auth/controllers/verify-auth.controller';
import { TokenService } from 'src/core/auth/services/token.service';
import { GoogleGmailService } from 'src/core/auth/services/google-gmail.service';
import { AuthResolver } from './auth.resolver';
import { JwtAuthStrategy } from './strategies/jwt.auth.strategy';
import { AuthService } from './services/auth.service';
import { GoogleAuthController } from './controllers/google-auth.controller';
import { VerifyAuthController } from './controllers/verify-auth.controller';
import { TokenService } from './services/token.service';
const jwtModule = JwtModule.registerAsync({
useFactory: async (environmentService: EnvironmentService) => {
return {
@ -43,8 +44,18 @@ const jwtModule = JwtModule.registerAsync({
TypeORMModule,
TypeOrmModule.forFeature([Workspace, User, RefreshToken], 'core'),
],
controllers: [GoogleAuthController, VerifyAuthController],
providers: [AuthService, TokenService, JwtAuthStrategy, AuthResolver],
controllers: [
GoogleAuthController,
GoogleGmailAuthController,
VerifyAuthController,
],
providers: [
AuthService,
TokenService,
JwtAuthStrategy,
AuthResolver,
GoogleGmailService,
],
exports: [jwtModule, TokenService],
})
export class AuthModule {}

View File

@ -15,6 +15,8 @@ import { Workspace } from 'src/core/workspace/workspace.entity';
import { AuthWorkspace } from 'src/decorators/auth-workspace.decorator';
import { User } from 'src/core/user/user.entity';
import { ApiKeyTokenInput } from 'src/core/auth/dto/api-key-token.input';
import { TransientToken } from 'src/core/auth/dto/transient-token.entity';
import { UserService } from 'src/core/user/services/user.service';
import { ApiKeyToken, AuthTokens } from './dto/token.entity';
import { TokenService } from './services/token.service';
@ -38,6 +40,7 @@ export class AuthResolver {
private readonly workspaceRepository: Repository<Workspace>,
private authService: AuthService,
private tokenService: TokenService,
private userService: UserService,
) {}
@Query(() => UserExists)
@ -85,6 +88,20 @@ export class AuthResolver {
return { loginToken };
}
@Mutation(() => TransientToken)
@UseGuards(JwtAuthGuard)
async generateTransientToken(
@AuthUser() user: User,
): Promise<TransientToken | void> {
const workspaceMember = await this.userService.loadWorkspaceMember(user);
const transientToken = await this.tokenService.generateTransientToken(
workspaceMember.id,
user.defaultWorkspace.id,
);
return { transientToken };
}
@Mutation(() => Verify)
async verify(@Args() verifyInput: VerifyInput): Promise<Verify> {
const email = await this.tokenService.verifyLoginToken(

View File

@ -0,0 +1,48 @@
import { Controller, Get, Req, Res, UseGuards } from '@nestjs/common';
import { Response } from 'express';
import { GoogleGmailProviderEnabledGuard } from 'src/core/auth/guards/google-gmail-provider-enabled.guard';
import { GoogleGmailOauthGuard } from 'src/core/auth/guards/google-gmail-oauth.guard';
import { GoogleGmailRequest } from 'src/core/auth/strategies/google-gmail.auth.strategy';
import { GoogleGmailService } from 'src/core/auth/services/google-gmail.service';
import { TokenService } from 'src/core/auth/services/token.service';
@Controller('auth/google-gmail')
export class GoogleGmailAuthController {
constructor(
private readonly googleGmailService: GoogleGmailService,
private readonly tokenService: TokenService,
) {}
@Get()
@UseGuards(GoogleGmailProviderEnabledGuard, GoogleGmailOauthGuard)
async googleAuth() {
// As this method is protected by Google Auth guard, it will trigger Google SSO flow
return;
}
@Get('get-access-token')
@UseGuards(GoogleGmailProviderEnabledGuard, GoogleGmailOauthGuard)
async googleAuthGetAccessToken(
@Req() req: GoogleGmailRequest,
@Res() res: Response,
) {
const { user: gmailUser } = req;
const { accessToken, refreshToken, transientToken } = gmailUser;
const { workspaceMemberId, workspaceId } =
await this.tokenService.verifyTransientToken(transientToken);
this.googleGmailService.saveConnectedAccount({
workspaceMemberId: workspaceMemberId,
workspaceId: workspaceId,
type: 'gmail',
accessToken,
refreshToken,
});
return res.redirect('http://localhost:3001');
}
}

View File

@ -0,0 +1,31 @@
import { ArgsType, Field } from '@nestjs/graphql';
import { IsNotEmpty, IsString } from 'class-validator';
@ArgsType()
export class SaveConnectedAccountInput {
@Field(() => String)
@IsNotEmpty()
@IsString()
workspaceMemberId: string;
@Field(() => String)
@IsNotEmpty()
@IsString()
workspaceId: string;
@Field(() => String)
@IsNotEmpty()
@IsString()
type: string;
@Field(() => String)
@IsNotEmpty()
@IsString()
accessToken: string;
@Field(() => String)
@IsNotEmpty()
@IsString()
refreshToken: string;
}

View File

@ -0,0 +1,9 @@
import { Field, ObjectType } from '@nestjs/graphql';
import { AuthToken } from './token.entity';
@ObjectType()
export class TransientToken {
@Field(() => AuthToken)
transientToken: AuthToken;
}

View File

@ -0,0 +1,27 @@
import { ExecutionContext, Injectable } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
@Injectable()
export class GoogleGmailOauthGuard extends AuthGuard('google-gmail') {
constructor() {
super({
prompt: 'select_account',
});
}
async canActivate(context: ExecutionContext) {
try {
const request = context.switchToHttp().getRequest();
const transientToken = request.query.transientToken;
if (transientToken && typeof transientToken === 'string') {
request.params.transientToken = transientToken;
}
const activate = (await super.canActivate(context)) as boolean;
return activate;
} catch (ex) {
throw ex;
}
}
}

View File

@ -0,0 +1,21 @@
import { Injectable, CanActivate, NotFoundException } from '@nestjs/common';
import { Observable } from 'rxjs';
import { GoogleGmailStrategy } from 'src/core/auth/strategies/google-gmail.auth.strategy';
import { EnvironmentService } from 'src/integrations/environment/environment.service';
@Injectable()
export class GoogleGmailProviderEnabledGuard implements CanActivate {
constructor(private readonly environmentService: EnvironmentService) {}
canActivate(): boolean | Promise<boolean> | Observable<boolean> {
if (!this.environmentService.isMessagingProviderGmailEnabled()) {
throw new NotFoundException('Gmail auth is not enabled');
}
new GoogleGmailStrategy(this.environmentService);
return true;
}
}

View File

@ -0,0 +1,35 @@
import { Injectable } from '@nestjs/common';
import { DataSourceService } from 'src/metadata/data-source/data-source.service';
import { TypeORMService } from 'src/database/typeorm/typeorm.service';
import { SaveConnectedAccountInput } from 'src/core/auth/dto/save-connected-account';
@Injectable()
export class GoogleGmailService {
constructor(
private readonly dataSourceService: DataSourceService,
private readonly typeORMService: TypeORMService,
) {}
async saveConnectedAccount(
saveConnectedAccountInput: SaveConnectedAccountInput,
) {
const { workspaceId, type, accessToken, refreshToken } =
saveConnectedAccountInput;
const dataSourceMetadata =
await this.dataSourceService.getLastDataSourceMetadataFromWorkspaceIdOrFail(
workspaceId,
);
const workspaceDataSource = await this.typeORMService.connectToDataSource(
dataSourceMetadata,
);
await workspaceDataSource?.query(
`INSERT INTO ${dataSourceMetadata.schema}."connectedAccount" ("type", "accessToken", "refreshToken") VALUES ('${type}', '${accessToken}', '${refreshToken}')`,
);
return;
}
}

View File

@ -114,6 +114,29 @@ export class TokenService {
};
}
async generateTransientToken(
workspaceMemberId: string,
workspaceId: string,
): Promise<AuthToken> {
const secret = this.environmentService.getLoginTokenSecret();
const expiresIn = this.environmentService.getTransientTokenExpiresIn();
assert(expiresIn, '', InternalServerErrorException);
const expiresAt = addMilliseconds(new Date().getTime(), ms(expiresIn));
const jwtPayload = {
sub: workspaceMemberId,
workspaceId,
};
return {
token: this.jwtService.sign(jwtPayload, {
secret,
expiresIn,
}),
expiresAt,
};
}
async generateApiKeyToken(
workspaceId: string,
apiKeyId?: string,
@ -166,6 +189,20 @@ export class TokenService {
return payload.sub;
}
async verifyTransientToken(transientToken: string): Promise<{
workspaceMemberId: string;
workspaceId: string;
}> {
const transientTokenSecret = this.environmentService.getLoginTokenSecret();
const payload = await this.verifyJwt(transientToken, transientTokenSecret);
return {
workspaceMemberId: payload.sub,
workspaceId: payload.workspaceId,
};
}
async verifyRefreshToken(refreshToken: string) {
const secret = this.environmentService.getRefreshTokenSecret();
const coolDown = this.environmentService.getRefreshTokenCoolDown();

View File

@ -0,0 +1,80 @@
import { PassportStrategy } from '@nestjs/passport';
import { Injectable } from '@nestjs/common';
import { Strategy, VerifyCallback } from 'passport-google-oauth20';
import { Request } from 'express';
import { EnvironmentService } from 'src/integrations/environment/environment.service';
export type GoogleGmailRequest = Request & {
user: {
firstName?: string | null;
lastName?: string | null;
email: string;
picture: string | null;
workspaceInviteHash?: string;
accessToken: string;
refreshToken: string;
transientToken: string;
};
};
@Injectable()
export class GoogleGmailStrategy extends PassportStrategy(
Strategy,
'google-gmail',
) {
constructor(environmentService: EnvironmentService) {
super({
clientID: environmentService.getAuthGoogleClientId(),
clientSecret: environmentService.getAuthGoogleClientSecret(),
callbackURL: environmentService.getMessagingProviderGmailCallbackUrl(),
scope: [
'email',
'profile',
'https://www.googleapis.com/auth/gmail.readonly',
],
passReqToCallback: true,
});
}
authenticate(req: any, options: any) {
options = {
...options,
accessType: 'offline',
prompt: 'consent',
state: JSON.stringify({
transientToken: req.params.transientToken,
}),
};
return super.authenticate(req, options);
}
async validate(
request: GoogleGmailRequest,
accessToken: string,
refreshToken: string,
profile: any,
done: VerifyCallback,
): Promise<void> {
const { name, emails, photos } = profile;
const state =
typeof request.query.state === 'string'
? JSON.parse(request.query.state)
: undefined;
const user: GoogleGmailRequest['user'] = {
email: emails[0].value,
firstName: name.givenName,
lastName: name.familyName,
picture: photos?.[0]?.value,
accessToken,
refreshToken,
transientToken: state.transientToken,
};
done(null, user);
}
}

View File

@ -69,8 +69,9 @@ export class JwtAuthStrategy extends PassportStrategy(Strategy, 'jwt') {
let user;
if (payload.workspaceId) {
user = await this.userRepository.findOneBy({
id: payload.sub,
user = await this.userRepository.findOne({
where: { id: payload.sub },
relations: ['defaultWorkspace'],
});
if (!user) {
throw new UnauthorizedException();

View File

@ -84,6 +84,12 @@ export class EnvironmentService {
return this.configService.get<string>('LOGIN_TOKEN_EXPIRES_IN') ?? '15m';
}
getTransientTokenExpiresIn(): string {
return (
this.configService.get<string>('SHORT_TERM_TOKEN_EXPIRES_IN') ?? '5m'
);
}
getApiTokenExpiresIn(): string {
return this.configService.get<string>('API_TOKEN_EXPIRES_IN') ?? '1000y';
}
@ -95,6 +101,19 @@ export class EnvironmentService {
);
}
isMessagingProviderGmailEnabled(): boolean {
return (
this.configService.get<boolean>('MESSAGING_PROVIDER_GMAIL_ENABLED') ??
false
);
}
getMessagingProviderGmailCallbackUrl(): string | undefined {
return this.configService.get<string>(
'MESSAGING_PROVIDER_GMAIL_CALLBACK_URL',
);
}
isAuthGoogleEnabled(): boolean {
return this.configService.get<boolean>('AUTH_GOOGLE_ENABLED') ?? false;
}

View File

@ -26,60 +26,60 @@ const connectedAccountMetadata = {
defaultValue: { value: '' },
},
{
isCustom: false,
isActive: true,
type: FieldMetadataType.TEXT,
name: 'accessToken',
label: 'accessToken',
targetColumnMap: {
value: 'accessToken',
},
description: 'Messaging provider access token',
icon: 'IconKey',
isNullable: false,
defaultValue: { value: '' },
isCustom: false,
isActive: true,
type: FieldMetadataType.TEXT,
name: 'accessToken',
label: 'accessToken',
targetColumnMap: {
value: 'accessToken',
},
description: 'Messaging provider access token',
icon: 'IconKey',
isNullable: false,
defaultValue: { value: '' },
},
{
isCustom: false,
isActive: true,
type: FieldMetadataType.TEXT,
name: 'refreshToken',
label: 'refreshToken',
targetColumnMap: {
value: 'refreshToken',
},
description: 'Messaging provider refresh token',
icon: 'IconKey',
isNullable: false,
defaultValue: { value: '' },
isCustom: false,
isActive: true,
type: FieldMetadataType.TEXT,
name: 'refreshToken',
label: 'refreshToken',
targetColumnMap: {
value: 'refreshToken',
},
description: 'Messaging provider refresh token',
icon: 'IconKey',
isNullable: false,
defaultValue: { value: '' },
},
{
isCustom: false,
isActive: true,
type: FieldMetadataType.TEXT, // Should be an array of strings
name: 'externalScopes',
label: 'externalScopes',
targetColumnMap: {
value: 'externalScopes',
},
description: 'External scopes',
icon: 'IconCircle',
isNullable: false,
defaultValue: { value: '' },
isCustom: false,
isActive: true,
type: FieldMetadataType.TEXT, // Should be an array of strings
name: 'externalScopes',
label: 'externalScopes',
targetColumnMap: {
value: 'externalScopes',
},
description: 'External scopes',
icon: 'IconCircle',
isNullable: false,
defaultValue: { value: '' },
},
{
isCustom: false,
isActive: true,
type: FieldMetadataType.BOOLEAN, // Should be an array of strings
name: 'hasEmailScope',
label: 'hasEmailScope',
targetColumnMap: {
value: 'hasEmailScope',
},
description: 'Has email scope',
icon: 'IconMail',
isNullable: false,
defaultValue: { value: '' },
isCustom: false,
isActive: true,
type: FieldMetadataType.BOOLEAN, // Should be an array of strings
name: 'hasEmailScope',
label: 'hasEmailScope',
targetColumnMap: {
value: 'hasEmailScope',
},
description: 'Has email scope',
icon: 'IconMail',
isNullable: false,
defaultValue: { value: '' },
},
],
};