Migrate to a monorepo structure (#2909)
This commit is contained in:
61
packages/twenty-server/src/core/auth/auth.module.ts
Normal file
61
packages/twenty-server/src/core/auth/auth.module.ts
Normal file
@ -0,0 +1,61 @@
|
||||
/* eslint-disable no-restricted-imports */
|
||||
import { Module } from '@nestjs/common';
|
||||
import { JwtModule } from '@nestjs/jwt';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
|
||||
import { EnvironmentService } from 'src/integrations/environment/environment.service';
|
||||
import { FileModule } from 'src/core/file/file.module';
|
||||
import { Workspace } from 'src/core/workspace/workspace.entity';
|
||||
import { User } from 'src/core/user/user.entity';
|
||||
import { RefreshToken } from 'src/core/refresh-token/refresh-token.entity';
|
||||
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';
|
||||
const jwtModule = JwtModule.registerAsync({
|
||||
useFactory: async (environmentService: EnvironmentService) => {
|
||||
return {
|
||||
secret: environmentService.getAccessTokenSecret(),
|
||||
signOptions: {
|
||||
expiresIn: environmentService.getAccessTokenExpiresIn(),
|
||||
},
|
||||
};
|
||||
},
|
||||
inject: [EnvironmentService],
|
||||
});
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
jwtModule,
|
||||
FileModule,
|
||||
DataSourceModule,
|
||||
UserModule,
|
||||
WorkspaceManagerModule,
|
||||
TypeORMModule,
|
||||
TypeOrmModule.forFeature([Workspace, User, RefreshToken], 'core'),
|
||||
],
|
||||
controllers: [
|
||||
GoogleAuthController,
|
||||
GoogleGmailAuthController,
|
||||
VerifyAuthController,
|
||||
],
|
||||
providers: [
|
||||
AuthService,
|
||||
TokenService,
|
||||
JwtAuthStrategy,
|
||||
AuthResolver,
|
||||
GoogleGmailService,
|
||||
],
|
||||
exports: [jwtModule, TokenService],
|
||||
})
|
||||
export class AuthModule {}
|
||||
39
packages/twenty-server/src/core/auth/auth.resolver.spec.ts
Normal file
39
packages/twenty-server/src/core/auth/auth.resolver.spec.ts
Normal file
@ -0,0 +1,39 @@
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { getRepositoryToken } from '@nestjs/typeorm';
|
||||
|
||||
import { Workspace } from 'src/core/workspace/workspace.entity';
|
||||
|
||||
import { AuthResolver } from './auth.resolver';
|
||||
|
||||
import { TokenService } from './services/token.service';
|
||||
import { AuthService } from './services/auth.service';
|
||||
|
||||
describe('AuthResolver', () => {
|
||||
let resolver: AuthResolver;
|
||||
|
||||
beforeEach(async () => {
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
providers: [
|
||||
AuthResolver,
|
||||
{
|
||||
provide: getRepositoryToken(Workspace, 'core'),
|
||||
useValue: {},
|
||||
},
|
||||
{
|
||||
provide: AuthService,
|
||||
useValue: {},
|
||||
},
|
||||
{
|
||||
provide: TokenService,
|
||||
useValue: {},
|
||||
},
|
||||
],
|
||||
}).compile();
|
||||
|
||||
resolver = module.get<AuthResolver>(AuthResolver);
|
||||
});
|
||||
|
||||
it('should be defined', () => {
|
||||
expect(resolver).toBeDefined();
|
||||
});
|
||||
});
|
||||
153
packages/twenty-server/src/core/auth/auth.resolver.ts
Normal file
153
packages/twenty-server/src/core/auth/auth.resolver.ts
Normal file
@ -0,0 +1,153 @@
|
||||
import { Args, Mutation, Query, Resolver } from '@nestjs/graphql';
|
||||
import {
|
||||
BadRequestException,
|
||||
ForbiddenException,
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
import { InjectRepository } from '@nestjs/typeorm';
|
||||
|
||||
import { Repository } from 'typeorm';
|
||||
|
||||
import { JwtAuthGuard } from 'src/guards/jwt.auth.guard';
|
||||
import { AuthUser } from 'src/decorators/auth-user.decorator';
|
||||
import { assert } from 'src/utils/assert';
|
||||
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';
|
||||
import { RefreshTokenInput } from './dto/refresh-token.input';
|
||||
import { Verify } from './dto/verify.entity';
|
||||
import { VerifyInput } from './dto/verify.input';
|
||||
import { AuthService } from './services/auth.service';
|
||||
import { LoginToken } from './dto/login-token.entity';
|
||||
import { ChallengeInput } from './dto/challenge.input';
|
||||
import { UserExists } from './dto/user-exists.entity';
|
||||
import { CheckUserExistsInput } from './dto/user-exists.input';
|
||||
import { WorkspaceInviteHashValid } from './dto/workspace-invite-hash-valid.entity';
|
||||
import { WorkspaceInviteHashValidInput } from './dto/workspace-invite-hash.input';
|
||||
import { SignUpInput } from './dto/sign-up.input';
|
||||
import { ImpersonateInput } from './dto/impersonate.input';
|
||||
|
||||
@Resolver()
|
||||
export class AuthResolver {
|
||||
constructor(
|
||||
@InjectRepository(Workspace, 'core')
|
||||
private readonly workspaceRepository: Repository<Workspace>,
|
||||
private authService: AuthService,
|
||||
private tokenService: TokenService,
|
||||
private userService: UserService,
|
||||
) {}
|
||||
|
||||
@Query(() => UserExists)
|
||||
async checkUserExists(
|
||||
@Args() checkUserExistsInput: CheckUserExistsInput,
|
||||
): Promise<UserExists> {
|
||||
const { exists } = await this.authService.checkUserExists(
|
||||
checkUserExistsInput.email,
|
||||
);
|
||||
|
||||
return { exists };
|
||||
}
|
||||
|
||||
@Query(() => WorkspaceInviteHashValid)
|
||||
async checkWorkspaceInviteHashIsValid(
|
||||
@Args() workspaceInviteHashValidInput: WorkspaceInviteHashValidInput,
|
||||
): Promise<WorkspaceInviteHashValid> {
|
||||
return await this.authService.checkWorkspaceInviteHashIsValid(
|
||||
workspaceInviteHashValidInput.inviteHash,
|
||||
);
|
||||
}
|
||||
|
||||
@Query(() => Workspace)
|
||||
async findWorkspaceFromInviteHash(
|
||||
@Args() workspaceInviteHashValidInput: WorkspaceInviteHashValidInput,
|
||||
) {
|
||||
return await this.workspaceRepository.findOneBy({
|
||||
inviteHash: workspaceInviteHashValidInput.inviteHash,
|
||||
});
|
||||
}
|
||||
|
||||
@Mutation(() => LoginToken)
|
||||
async challenge(@Args() challengeInput: ChallengeInput): Promise<LoginToken> {
|
||||
const user = await this.authService.challenge(challengeInput);
|
||||
const loginToken = await this.tokenService.generateLoginToken(user.email);
|
||||
|
||||
return { loginToken };
|
||||
}
|
||||
|
||||
@Mutation(() => LoginToken)
|
||||
async signUp(@Args() signUpInput: SignUpInput): Promise<LoginToken> {
|
||||
const user = await this.authService.signUp(signUpInput);
|
||||
const loginToken = await this.tokenService.generateLoginToken(user.email);
|
||||
|
||||
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(
|
||||
verifyInput.loginToken,
|
||||
);
|
||||
|
||||
const result = await this.authService.verify(email);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
@Mutation(() => AuthTokens)
|
||||
async renewToken(@Args() args: RefreshTokenInput): Promise<AuthTokens> {
|
||||
if (!args.refreshToken) {
|
||||
throw new BadRequestException('Refresh token is mendatory');
|
||||
}
|
||||
|
||||
const tokens = await this.tokenService.generateTokensFromRefreshToken(
|
||||
args.refreshToken,
|
||||
);
|
||||
|
||||
return { tokens: tokens };
|
||||
}
|
||||
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@Mutation(() => Verify)
|
||||
async impersonate(
|
||||
@Args() impersonateInput: ImpersonateInput,
|
||||
@AuthUser() user: User,
|
||||
): Promise<Verify> {
|
||||
// Check if user can impersonate
|
||||
assert(user.canImpersonate, 'User cannot impersonate', ForbiddenException);
|
||||
|
||||
return this.authService.impersonate(impersonateInput.userId);
|
||||
}
|
||||
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@Mutation(() => ApiKeyToken)
|
||||
async generateApiKeyToken(
|
||||
@Args() args: ApiKeyTokenInput,
|
||||
@AuthWorkspace() { id: workspaceId }: Workspace,
|
||||
): Promise<ApiKeyToken | undefined> {
|
||||
return await this.tokenService.generateApiKeyToken(
|
||||
workspaceId,
|
||||
args.apiKeyId,
|
||||
args.expiresAt,
|
||||
);
|
||||
}
|
||||
}
|
||||
15
packages/twenty-server/src/core/auth/auth.util.ts
Normal file
15
packages/twenty-server/src/core/auth/auth.util.ts
Normal file
@ -0,0 +1,15 @@
|
||||
import * as bcrypt from 'bcrypt';
|
||||
|
||||
export const PASSWORD_REGEX = /^.{8,}$/;
|
||||
|
||||
const saltRounds = 10;
|
||||
|
||||
export const hashPassword = async (password: string) => {
|
||||
const hash = await bcrypt.hash(password, saltRounds);
|
||||
|
||||
return hash;
|
||||
};
|
||||
|
||||
export const compareHash = async (password: string, passwordHash: string) => {
|
||||
return bcrypt.compare(password, passwordHash);
|
||||
};
|
||||
@ -0,0 +1,70 @@
|
||||
import { Controller, Get, Req, Res, UseGuards } from '@nestjs/common';
|
||||
import { InjectRepository } from '@nestjs/typeorm';
|
||||
|
||||
import { Response } from 'express';
|
||||
import { Repository } from 'typeorm';
|
||||
|
||||
import { GoogleRequest } from 'src/core/auth/strategies/google.auth.strategy';
|
||||
import { TokenService } from 'src/core/auth/services/token.service';
|
||||
import { GoogleProviderEnabledGuard } from 'src/core/auth/guards/google-provider-enabled.guard';
|
||||
import { GoogleOauthGuard } from 'src/core/auth/guards/google-oauth.guard';
|
||||
import { User } from 'src/core/user/user.entity';
|
||||
import { Workspace } from 'src/core/workspace/workspace.entity';
|
||||
import { AuthService } from 'src/core/auth/services/auth.service';
|
||||
import { TypeORMService } from 'src/database/typeorm/typeorm.service';
|
||||
import { EnvironmentService } from 'src/integrations/environment/environment.service';
|
||||
|
||||
@Controller('auth/google')
|
||||
export class GoogleAuthController {
|
||||
constructor(
|
||||
private readonly tokenService: TokenService,
|
||||
private readonly environmentService: EnvironmentService,
|
||||
private readonly typeORMService: TypeORMService,
|
||||
private readonly authService: AuthService,
|
||||
@InjectRepository(Workspace, 'core')
|
||||
@InjectRepository(User, 'core')
|
||||
private readonly userRepository: Repository<User>,
|
||||
) {}
|
||||
|
||||
@Get()
|
||||
@UseGuards(GoogleProviderEnabledGuard, GoogleOauthGuard)
|
||||
async googleAuth() {
|
||||
// As this method is protected by Google Auth guard, it will trigger Google SSO flow
|
||||
return;
|
||||
}
|
||||
|
||||
@Get('redirect')
|
||||
@UseGuards(GoogleProviderEnabledGuard, GoogleOauthGuard)
|
||||
async googleAuthRedirect(@Req() req: GoogleRequest, @Res() res: Response) {
|
||||
const { firstName, lastName, email, picture, workspaceInviteHash } =
|
||||
req.user;
|
||||
|
||||
const mainDataSource = await this.typeORMService.getMainDataSource();
|
||||
|
||||
const existingUser = await mainDataSource
|
||||
.getRepository(User)
|
||||
.findOneBy({ email: email });
|
||||
|
||||
if (existingUser) {
|
||||
const loginToken = await this.tokenService.generateLoginToken(
|
||||
existingUser.email,
|
||||
);
|
||||
|
||||
return res.redirect(
|
||||
this.tokenService.computeRedirectURI(loginToken.token),
|
||||
);
|
||||
}
|
||||
|
||||
const user = await this.authService.signUp({
|
||||
email,
|
||||
firstName,
|
||||
lastName,
|
||||
picture,
|
||||
workspaceInviteHash,
|
||||
});
|
||||
|
||||
const loginToken = await this.tokenService.generateLoginToken(user.email);
|
||||
|
||||
return res.redirect(this.tokenService.computeRedirectURI(loginToken.token));
|
||||
}
|
||||
}
|
||||
@ -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');
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,32 @@
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
|
||||
import { AuthService } from 'src/core/auth/services/auth.service';
|
||||
import { TokenService } from 'src/core/auth/services/token.service';
|
||||
|
||||
import { VerifyAuthController } from './verify-auth.controller';
|
||||
|
||||
describe('VerifyAuthController', () => {
|
||||
let controller: VerifyAuthController;
|
||||
|
||||
beforeEach(async () => {
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
controllers: [VerifyAuthController],
|
||||
providers: [
|
||||
{
|
||||
provide: AuthService,
|
||||
useValue: {},
|
||||
},
|
||||
{
|
||||
provide: TokenService,
|
||||
useValue: {},
|
||||
},
|
||||
],
|
||||
}).compile();
|
||||
|
||||
controller = module.get<VerifyAuthController>(VerifyAuthController);
|
||||
});
|
||||
|
||||
it('should be defined', () => {
|
||||
expect(controller).toBeDefined();
|
||||
});
|
||||
});
|
||||
@ -0,0 +1,24 @@
|
||||
import { Body, Controller, Post } from '@nestjs/common';
|
||||
|
||||
import { AuthService } from 'src/core/auth/services/auth.service';
|
||||
import { VerifyInput } from 'src/core/auth/dto/verify.input';
|
||||
import { Verify } from 'src/core/auth/dto/verify.entity';
|
||||
import { TokenService } from 'src/core/auth/services/token.service';
|
||||
|
||||
@Controller('auth/verify')
|
||||
export class VerifyAuthController {
|
||||
constructor(
|
||||
private readonly authService: AuthService,
|
||||
private readonly tokenService: TokenService,
|
||||
) {}
|
||||
|
||||
@Post()
|
||||
async verify(@Body() verifyInput: VerifyInput): Promise<Verify> {
|
||||
const email = await this.tokenService.verifyLoginToken(
|
||||
verifyInput.loginToken,
|
||||
);
|
||||
const result = await this.authService.verify(email);
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,15 @@
|
||||
import { ArgsType, Field } from '@nestjs/graphql';
|
||||
|
||||
import { IsNotEmpty, IsString } from 'class-validator';
|
||||
|
||||
@ArgsType()
|
||||
export class ApiKeyTokenInput {
|
||||
@Field(() => String)
|
||||
@IsNotEmpty()
|
||||
@IsString()
|
||||
apiKeyId: string;
|
||||
|
||||
@Field(() => String)
|
||||
@IsNotEmpty()
|
||||
expiresAt: string;
|
||||
}
|
||||
16
packages/twenty-server/src/core/auth/dto/challenge.input.ts
Normal file
16
packages/twenty-server/src/core/auth/dto/challenge.input.ts
Normal file
@ -0,0 +1,16 @@
|
||||
import { ArgsType, Field } from '@nestjs/graphql';
|
||||
|
||||
import { IsEmail, IsNotEmpty, IsString } from 'class-validator';
|
||||
|
||||
@ArgsType()
|
||||
export class ChallengeInput {
|
||||
@Field(() => String)
|
||||
@IsNotEmpty()
|
||||
@IsEmail()
|
||||
email: string;
|
||||
|
||||
@Field(() => String)
|
||||
@IsNotEmpty()
|
||||
@IsString()
|
||||
password: string;
|
||||
}
|
||||
@ -0,0 +1,11 @@
|
||||
import { ArgsType, Field } from '@nestjs/graphql';
|
||||
|
||||
import { IsNotEmpty, IsString } from 'class-validator';
|
||||
|
||||
@ArgsType()
|
||||
export class ImpersonateInput {
|
||||
@Field(() => String)
|
||||
@IsNotEmpty()
|
||||
@IsString()
|
||||
userId: string;
|
||||
}
|
||||
@ -0,0 +1,9 @@
|
||||
import { Field, ObjectType } from '@nestjs/graphql';
|
||||
|
||||
import { AuthToken } from './token.entity';
|
||||
|
||||
@ObjectType()
|
||||
export class LoginToken {
|
||||
@Field(() => AuthToken)
|
||||
loginToken: AuthToken;
|
||||
}
|
||||
@ -0,0 +1,11 @@
|
||||
import { ArgsType, Field } from '@nestjs/graphql';
|
||||
|
||||
import { IsNotEmpty, IsString } from 'class-validator';
|
||||
|
||||
@ArgsType()
|
||||
export class RefreshTokenInput {
|
||||
@Field(() => String)
|
||||
@IsNotEmpty()
|
||||
@IsString()
|
||||
refreshToken: string;
|
||||
}
|
||||
@ -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;
|
||||
}
|
||||
21
packages/twenty-server/src/core/auth/dto/sign-up.input.ts
Normal file
21
packages/twenty-server/src/core/auth/dto/sign-up.input.ts
Normal file
@ -0,0 +1,21 @@
|
||||
import { ArgsType, Field } from '@nestjs/graphql';
|
||||
|
||||
import { IsEmail, IsNotEmpty, IsOptional, IsString } from 'class-validator';
|
||||
|
||||
@ArgsType()
|
||||
export class SignUpInput {
|
||||
@Field(() => String)
|
||||
@IsNotEmpty()
|
||||
@IsEmail()
|
||||
email: string;
|
||||
|
||||
@Field(() => String)
|
||||
@IsNotEmpty()
|
||||
@IsString()
|
||||
password: string;
|
||||
|
||||
@Field(() => String, { nullable: true })
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
workspaceInviteHash?: string;
|
||||
}
|
||||
31
packages/twenty-server/src/core/auth/dto/token.entity.ts
Normal file
31
packages/twenty-server/src/core/auth/dto/token.entity.ts
Normal file
@ -0,0 +1,31 @@
|
||||
import { Field, ObjectType } from '@nestjs/graphql';
|
||||
|
||||
@ObjectType()
|
||||
export class AuthToken {
|
||||
@Field(() => String)
|
||||
token: string;
|
||||
|
||||
@Field(() => Date)
|
||||
expiresAt: Date;
|
||||
}
|
||||
|
||||
@ObjectType()
|
||||
export class ApiKeyToken {
|
||||
@Field(() => String)
|
||||
token: string;
|
||||
}
|
||||
|
||||
@ObjectType()
|
||||
export class AuthTokenPair {
|
||||
@Field(() => AuthToken)
|
||||
accessToken: AuthToken;
|
||||
|
||||
@Field(() => AuthToken)
|
||||
refreshToken: AuthToken;
|
||||
}
|
||||
|
||||
@ObjectType()
|
||||
export class AuthTokens {
|
||||
@Field(() => AuthTokenPair)
|
||||
tokens: AuthTokenPair;
|
||||
}
|
||||
@ -0,0 +1,9 @@
|
||||
import { Field, ObjectType } from '@nestjs/graphql';
|
||||
|
||||
import { AuthToken } from './token.entity';
|
||||
|
||||
@ObjectType()
|
||||
export class TransientToken {
|
||||
@Field(() => AuthToken)
|
||||
transientToken: AuthToken;
|
||||
}
|
||||
@ -0,0 +1,7 @@
|
||||
import { Field, ObjectType } from '@nestjs/graphql';
|
||||
|
||||
@ObjectType()
|
||||
export class UserExists {
|
||||
@Field(() => Boolean)
|
||||
exists: boolean;
|
||||
}
|
||||
@ -0,0 +1,11 @@
|
||||
import { ArgsType, Field } from '@nestjs/graphql';
|
||||
|
||||
import { IsNotEmpty, IsString } from 'class-validator';
|
||||
|
||||
@ArgsType()
|
||||
export class CheckUserExistsInput {
|
||||
@Field(() => String)
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
email: string;
|
||||
}
|
||||
11
packages/twenty-server/src/core/auth/dto/verify.entity.ts
Normal file
11
packages/twenty-server/src/core/auth/dto/verify.entity.ts
Normal file
@ -0,0 +1,11 @@
|
||||
import { Field, ObjectType } from '@nestjs/graphql';
|
||||
|
||||
import { User } from 'src/core/user/user.entity';
|
||||
|
||||
import { AuthTokens } from './token.entity';
|
||||
|
||||
@ObjectType()
|
||||
export class Verify extends AuthTokens {
|
||||
@Field(() => User)
|
||||
user: DeepPartial<User>;
|
||||
}
|
||||
11
packages/twenty-server/src/core/auth/dto/verify.input.ts
Normal file
11
packages/twenty-server/src/core/auth/dto/verify.input.ts
Normal file
@ -0,0 +1,11 @@
|
||||
import { ArgsType, Field } from '@nestjs/graphql';
|
||||
|
||||
import { IsNotEmpty, IsString } from 'class-validator';
|
||||
|
||||
@ArgsType()
|
||||
export class VerifyInput {
|
||||
@Field(() => String)
|
||||
@IsNotEmpty()
|
||||
@IsString()
|
||||
loginToken: string;
|
||||
}
|
||||
@ -0,0 +1,7 @@
|
||||
import { Field, ObjectType } from '@nestjs/graphql';
|
||||
|
||||
@ObjectType()
|
||||
export class WorkspaceInviteHashValid {
|
||||
@Field(() => Boolean)
|
||||
isValid: boolean;
|
||||
}
|
||||
@ -0,0 +1,12 @@
|
||||
import { ArgsType, Field } from '@nestjs/graphql';
|
||||
|
||||
import { IsNotEmpty, IsString, MinLength } from 'class-validator';
|
||||
|
||||
@ArgsType()
|
||||
export class WorkspaceInviteHashValidInput {
|
||||
@Field(() => String)
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
@MinLength(10)
|
||||
inviteHash: string;
|
||||
}
|
||||
@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -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;
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,27 @@
|
||||
import { ExecutionContext, Injectable } from '@nestjs/common';
|
||||
import { AuthGuard } from '@nestjs/passport';
|
||||
|
||||
@Injectable()
|
||||
export class GoogleOauthGuard extends AuthGuard('google') {
|
||||
constructor() {
|
||||
super({
|
||||
prompt: 'select_account',
|
||||
});
|
||||
}
|
||||
|
||||
async canActivate(context: ExecutionContext) {
|
||||
try {
|
||||
const request = context.switchToHttp().getRequest();
|
||||
const workspaceInviteHash = request.query.inviteHash;
|
||||
|
||||
if (workspaceInviteHash && typeof workspaceInviteHash === 'string') {
|
||||
request.params.workspaceInviteHash = workspaceInviteHash;
|
||||
}
|
||||
const activate = (await super.canActivate(context)) as boolean;
|
||||
|
||||
return activate;
|
||||
} catch (ex) {
|
||||
throw ex;
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,21 @@
|
||||
import { Injectable, CanActivate, NotFoundException } from '@nestjs/common';
|
||||
|
||||
import { Observable } from 'rxjs';
|
||||
|
||||
import { EnvironmentService } from 'src/integrations/environment/environment.service';
|
||||
import { GoogleStrategy } from 'src/core/auth/strategies/google.auth.strategy';
|
||||
|
||||
@Injectable()
|
||||
export class GoogleProviderEnabledGuard implements CanActivate {
|
||||
constructor(private readonly environmentService: EnvironmentService) {}
|
||||
|
||||
canActivate(): boolean | Promise<boolean> | Observable<boolean> {
|
||||
if (!this.environmentService.isAuthGoogleEnabled()) {
|
||||
throw new NotFoundException('Google auth is not enabled');
|
||||
}
|
||||
|
||||
new GoogleStrategy(this.environmentService);
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,53 @@
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { getRepositoryToken } from '@nestjs/typeorm';
|
||||
|
||||
import { UserService } from 'src/core/user/services/user.service';
|
||||
import { WorkspaceManagerService } from 'src/workspace/workspace-manager/workspace-manager.service';
|
||||
import { FileUploadService } from 'src/core/file/services/file-upload.service';
|
||||
import { Workspace } from 'src/core/workspace/workspace.entity';
|
||||
import { User } from 'src/core/user/user.entity';
|
||||
|
||||
import { AuthService } from './auth.service';
|
||||
import { TokenService } from './token.service';
|
||||
|
||||
describe('AuthService', () => {
|
||||
let service: AuthService;
|
||||
|
||||
beforeEach(async () => {
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
providers: [
|
||||
AuthService,
|
||||
{
|
||||
provide: TokenService,
|
||||
useValue: {},
|
||||
},
|
||||
{
|
||||
provide: UserService,
|
||||
useValue: {},
|
||||
},
|
||||
{
|
||||
provide: WorkspaceManagerService,
|
||||
useValue: {},
|
||||
},
|
||||
{
|
||||
provide: FileUploadService,
|
||||
useValue: {},
|
||||
},
|
||||
{
|
||||
provide: getRepositoryToken(Workspace, 'core'),
|
||||
useValue: {},
|
||||
},
|
||||
{
|
||||
provide: getRepositoryToken(User, 'core'),
|
||||
useValue: {},
|
||||
},
|
||||
],
|
||||
}).compile();
|
||||
|
||||
service = module.get<AuthService>(AuthService);
|
||||
});
|
||||
|
||||
it('should be defined', () => {
|
||||
expect(service).toBeDefined();
|
||||
});
|
||||
});
|
||||
230
packages/twenty-server/src/core/auth/services/auth.service.ts
Normal file
230
packages/twenty-server/src/core/auth/services/auth.service.ts
Normal file
@ -0,0 +1,230 @@
|
||||
import {
|
||||
BadRequestException,
|
||||
ForbiddenException,
|
||||
Injectable,
|
||||
NotFoundException,
|
||||
} from '@nestjs/common';
|
||||
import { InjectRepository } from '@nestjs/typeorm';
|
||||
|
||||
import FileType from 'file-type';
|
||||
import { Repository } from 'typeorm';
|
||||
import { v4 } from 'uuid';
|
||||
|
||||
import { FileFolder } from 'src/core/file/interfaces/file-folder.interface';
|
||||
|
||||
import { ChallengeInput } from 'src/core/auth/dto/challenge.input';
|
||||
import { assert } from 'src/utils/assert';
|
||||
import {
|
||||
PASSWORD_REGEX,
|
||||
compareHash,
|
||||
hashPassword,
|
||||
} from 'src/core/auth/auth.util';
|
||||
import { Verify } from 'src/core/auth/dto/verify.entity';
|
||||
import { UserExists } from 'src/core/auth/dto/user-exists.entity';
|
||||
import { WorkspaceInviteHashValid } from 'src/core/auth/dto/workspace-invite-hash-valid.entity';
|
||||
import { User } from 'src/core/user/user.entity';
|
||||
import { Workspace } from 'src/core/workspace/workspace.entity';
|
||||
import { UserService } from 'src/core/user/services/user.service';
|
||||
import { WorkspaceManagerService } from 'src/workspace/workspace-manager/workspace-manager.service';
|
||||
import { getImageBufferFromUrl } from 'src/utils/image';
|
||||
import { FileUploadService } from 'src/core/file/services/file-upload.service';
|
||||
|
||||
import { TokenService } from './token.service';
|
||||
|
||||
export type UserPayload = {
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
email: string;
|
||||
};
|
||||
|
||||
@Injectable()
|
||||
export class AuthService {
|
||||
constructor(
|
||||
private readonly tokenService: TokenService,
|
||||
private readonly userService: UserService,
|
||||
private readonly workspaceManagerService: WorkspaceManagerService,
|
||||
private readonly fileUploadService: FileUploadService,
|
||||
@InjectRepository(Workspace, 'core')
|
||||
private readonly workspaceRepository: Repository<Workspace>,
|
||||
@InjectRepository(User, 'core')
|
||||
private readonly userRepository: Repository<User>,
|
||||
) {}
|
||||
|
||||
async challenge(challengeInput: ChallengeInput) {
|
||||
const user = await this.userRepository.findOneBy({
|
||||
email: challengeInput.email,
|
||||
});
|
||||
|
||||
assert(user, "This user doesn't exist", NotFoundException);
|
||||
assert(user.passwordHash, 'Incorrect login method', ForbiddenException);
|
||||
|
||||
const isValid = await compareHash(
|
||||
challengeInput.password,
|
||||
user.passwordHash,
|
||||
);
|
||||
|
||||
assert(isValid, 'Wrong password', ForbiddenException);
|
||||
|
||||
return user;
|
||||
}
|
||||
|
||||
async signUp({
|
||||
email,
|
||||
password,
|
||||
workspaceInviteHash,
|
||||
firstName,
|
||||
lastName,
|
||||
picture,
|
||||
}: {
|
||||
email: string;
|
||||
password?: string;
|
||||
firstName?: string | null;
|
||||
lastName?: string | null;
|
||||
workspaceInviteHash?: string | null;
|
||||
picture?: string | null;
|
||||
}) {
|
||||
if (!firstName) firstName = '';
|
||||
if (!lastName) lastName = '';
|
||||
|
||||
const existingUser = await this.userRepository.findOneBy({
|
||||
email: email,
|
||||
});
|
||||
|
||||
assert(!existingUser, 'This user already exists', ForbiddenException);
|
||||
|
||||
if (password) {
|
||||
const isPasswordValid = PASSWORD_REGEX.test(password);
|
||||
|
||||
assert(isPasswordValid, 'Password too weak', BadRequestException);
|
||||
}
|
||||
|
||||
const passwordHash = password ? await hashPassword(password) : undefined;
|
||||
let workspace: Workspace | null;
|
||||
|
||||
if (workspaceInviteHash) {
|
||||
workspace = await this.workspaceRepository.findOneBy({
|
||||
inviteHash: workspaceInviteHash,
|
||||
});
|
||||
|
||||
assert(
|
||||
workspace,
|
||||
'This workspace inviteHash is invalid',
|
||||
ForbiddenException,
|
||||
);
|
||||
} else {
|
||||
const workspaceToCreate = this.workspaceRepository.create({
|
||||
displayName: '',
|
||||
domainName: '',
|
||||
inviteHash: v4(),
|
||||
});
|
||||
|
||||
workspace = await this.workspaceRepository.save(workspaceToCreate);
|
||||
await this.workspaceManagerService.init(workspace.id);
|
||||
}
|
||||
|
||||
const userToCreate = this.userRepository.create({
|
||||
email: email,
|
||||
firstName: firstName,
|
||||
lastName: lastName,
|
||||
canImpersonate: false,
|
||||
passwordHash,
|
||||
defaultWorkspace: workspace,
|
||||
});
|
||||
const user = await this.userRepository.save(userToCreate);
|
||||
let imagePath: string | undefined = undefined;
|
||||
|
||||
if (picture) {
|
||||
const buffer = await getImageBufferFromUrl(picture);
|
||||
|
||||
const type = await FileType.fromBuffer(buffer);
|
||||
|
||||
const { paths } = await this.fileUploadService.uploadImage({
|
||||
file: buffer,
|
||||
filename: `${v4()}.${type?.ext}`,
|
||||
mimeType: type?.mime,
|
||||
fileFolder: FileFolder.ProfilePicture,
|
||||
});
|
||||
|
||||
imagePath = paths[0];
|
||||
}
|
||||
await this.userService.createWorkspaceMember(user, imagePath);
|
||||
|
||||
return user;
|
||||
}
|
||||
|
||||
async verify(email: string): Promise<Verify> {
|
||||
const user = await this.userRepository.findOne({
|
||||
where: {
|
||||
email,
|
||||
},
|
||||
relations: ['defaultWorkspace'],
|
||||
});
|
||||
|
||||
assert(user, "This user doesn't exist", NotFoundException);
|
||||
|
||||
assert(
|
||||
user.defaultWorkspace,
|
||||
'User has no default workspace',
|
||||
NotFoundException,
|
||||
);
|
||||
|
||||
// passwordHash is hidden for security reasons
|
||||
user.passwordHash = '';
|
||||
user.workspaceMember = await this.userService.loadWorkspaceMember(user);
|
||||
|
||||
const accessToken = await this.tokenService.generateAccessToken(user.id);
|
||||
const refreshToken = await this.tokenService.generateRefreshToken(user.id);
|
||||
|
||||
return {
|
||||
user,
|
||||
tokens: {
|
||||
accessToken,
|
||||
refreshToken,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async checkUserExists(email: string): Promise<UserExists> {
|
||||
const user = await this.userRepository.findOneBy({
|
||||
email,
|
||||
});
|
||||
|
||||
return { exists: !!user };
|
||||
}
|
||||
|
||||
async checkWorkspaceInviteHashIsValid(
|
||||
inviteHash: string,
|
||||
): Promise<WorkspaceInviteHashValid> {
|
||||
const workspace = await this.workspaceRepository.findOneBy({
|
||||
inviteHash,
|
||||
});
|
||||
|
||||
return { isValid: !!workspace };
|
||||
}
|
||||
|
||||
async impersonate(userId: string) {
|
||||
const user = await this.userRepository.findOne({
|
||||
where: {
|
||||
id: userId,
|
||||
},
|
||||
relations: ['defaultWorkspace'],
|
||||
});
|
||||
|
||||
assert(user, "This user doesn't exist", NotFoundException);
|
||||
|
||||
if (!user.defaultWorkspace.allowImpersonation) {
|
||||
throw new ForbiddenException('Impersonation not allowed');
|
||||
}
|
||||
|
||||
const accessToken = await this.tokenService.generateAccessToken(user.id);
|
||||
const refreshToken = await this.tokenService.generateRefreshToken(user.id);
|
||||
|
||||
return {
|
||||
user,
|
||||
tokens: {
|
||||
accessToken,
|
||||
refreshToken,
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
@ -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;
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,48 @@
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { JwtService } from '@nestjs/jwt';
|
||||
import { getRepositoryToken } from '@nestjs/typeorm';
|
||||
|
||||
import { EnvironmentService } from 'src/integrations/environment/environment.service';
|
||||
import { RefreshToken } from 'src/core/refresh-token/refresh-token.entity';
|
||||
import { User } from 'src/core/user/user.entity';
|
||||
import { JwtAuthStrategy } from 'src/core/auth/strategies/jwt.auth.strategy';
|
||||
|
||||
import { TokenService } from './token.service';
|
||||
|
||||
describe('TokenService', () => {
|
||||
let service: TokenService;
|
||||
|
||||
beforeEach(async () => {
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
providers: [
|
||||
TokenService,
|
||||
{
|
||||
provide: JwtService,
|
||||
useValue: {},
|
||||
},
|
||||
{
|
||||
provide: JwtAuthStrategy,
|
||||
useValue: {},
|
||||
},
|
||||
{
|
||||
provide: EnvironmentService,
|
||||
useValue: {},
|
||||
},
|
||||
{
|
||||
provide: getRepositoryToken(User, 'core'),
|
||||
useValue: {},
|
||||
},
|
||||
{
|
||||
provide: getRepositoryToken(RefreshToken, 'core'),
|
||||
useValue: {},
|
||||
},
|
||||
],
|
||||
}).compile();
|
||||
|
||||
service = module.get<TokenService>(TokenService);
|
||||
});
|
||||
|
||||
it('should be defined', () => {
|
||||
expect(service).toBeDefined();
|
||||
});
|
||||
});
|
||||
309
packages/twenty-server/src/core/auth/services/token.service.ts
Normal file
309
packages/twenty-server/src/core/auth/services/token.service.ts
Normal file
@ -0,0 +1,309 @@
|
||||
import {
|
||||
ForbiddenException,
|
||||
Injectable,
|
||||
InternalServerErrorException,
|
||||
NotFoundException,
|
||||
UnauthorizedException,
|
||||
UnprocessableEntityException,
|
||||
} from '@nestjs/common';
|
||||
import { JwtService } from '@nestjs/jwt';
|
||||
import { InjectRepository } from '@nestjs/typeorm';
|
||||
|
||||
import { addMilliseconds } from 'date-fns';
|
||||
import ms from 'ms';
|
||||
import { JsonWebTokenError, TokenExpiredError } from 'jsonwebtoken';
|
||||
import { Repository } from 'typeorm';
|
||||
import { Request } from 'express';
|
||||
import { ExtractJwt } from 'passport-jwt';
|
||||
|
||||
import {
|
||||
JwtAuthStrategy,
|
||||
JwtPayload,
|
||||
} from 'src/core/auth/strategies/jwt.auth.strategy';
|
||||
import { assert } from 'src/utils/assert';
|
||||
import { ApiKeyToken, AuthToken } from 'src/core/auth/dto/token.entity';
|
||||
import { EnvironmentService } from 'src/integrations/environment/environment.service';
|
||||
import { User } from 'src/core/user/user.entity';
|
||||
import { RefreshToken } from 'src/core/refresh-token/refresh-token.entity';
|
||||
import { Workspace } from 'src/core/workspace/workspace.entity';
|
||||
|
||||
@Injectable()
|
||||
export class TokenService {
|
||||
constructor(
|
||||
private readonly jwtService: JwtService,
|
||||
private readonly jwtStrategy: JwtAuthStrategy,
|
||||
private readonly environmentService: EnvironmentService,
|
||||
@InjectRepository(User, 'core')
|
||||
private readonly userRepository: Repository<User>,
|
||||
@InjectRepository(RefreshToken, 'core')
|
||||
private readonly refreshTokenRepository: Repository<RefreshToken>,
|
||||
) {}
|
||||
|
||||
async generateAccessToken(userId: string): Promise<AuthToken> {
|
||||
const expiresIn = this.environmentService.getAccessTokenExpiresIn();
|
||||
|
||||
assert(expiresIn, '', InternalServerErrorException);
|
||||
const expiresAt = addMilliseconds(new Date().getTime(), ms(expiresIn));
|
||||
|
||||
const user = await this.userRepository.findOne({
|
||||
where: { id: userId },
|
||||
relations: ['defaultWorkspace'],
|
||||
});
|
||||
|
||||
if (!user) {
|
||||
throw new NotFoundException('User is not found');
|
||||
}
|
||||
|
||||
if (!user.defaultWorkspace) {
|
||||
throw new NotFoundException('User does not have a default workspace');
|
||||
}
|
||||
|
||||
const jwtPayload: JwtPayload = {
|
||||
sub: user.id,
|
||||
workspaceId: user.defaultWorkspace.id,
|
||||
};
|
||||
|
||||
return {
|
||||
token: this.jwtService.sign(jwtPayload),
|
||||
expiresAt,
|
||||
};
|
||||
}
|
||||
|
||||
async generateRefreshToken(userId: string): Promise<AuthToken> {
|
||||
const secret = this.environmentService.getRefreshTokenSecret();
|
||||
const expiresIn = this.environmentService.getRefreshTokenExpiresIn();
|
||||
|
||||
assert(expiresIn, '', InternalServerErrorException);
|
||||
const expiresAt = addMilliseconds(new Date().getTime(), ms(expiresIn));
|
||||
|
||||
const refreshTokenPayload = {
|
||||
userId,
|
||||
expiresAt,
|
||||
};
|
||||
const jwtPayload = {
|
||||
sub: userId,
|
||||
};
|
||||
|
||||
const refreshToken =
|
||||
this.refreshTokenRepository.create(refreshTokenPayload);
|
||||
|
||||
await this.refreshTokenRepository.save(refreshToken);
|
||||
|
||||
return {
|
||||
token: this.jwtService.sign(jwtPayload, {
|
||||
secret,
|
||||
expiresIn,
|
||||
// Jwtid will be used to link RefreshToken entity to this token
|
||||
jwtid: refreshToken.id,
|
||||
}),
|
||||
expiresAt,
|
||||
};
|
||||
}
|
||||
|
||||
async generateLoginToken(email: string): Promise<AuthToken> {
|
||||
const secret = this.environmentService.getLoginTokenSecret();
|
||||
const expiresIn = this.environmentService.getLoginTokenExpiresIn();
|
||||
|
||||
assert(expiresIn, '', InternalServerErrorException);
|
||||
const expiresAt = addMilliseconds(new Date().getTime(), ms(expiresIn));
|
||||
const jwtPayload = {
|
||||
sub: email,
|
||||
};
|
||||
|
||||
return {
|
||||
token: this.jwtService.sign(jwtPayload, {
|
||||
secret,
|
||||
expiresIn,
|
||||
}),
|
||||
expiresAt,
|
||||
};
|
||||
}
|
||||
|
||||
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,
|
||||
expiresAt?: Date | string,
|
||||
): Promise<Pick<ApiKeyToken, 'token'> | undefined> {
|
||||
if (!apiKeyId) {
|
||||
return;
|
||||
}
|
||||
const jwtPayload = {
|
||||
sub: workspaceId,
|
||||
};
|
||||
const secret = this.environmentService.getAccessTokenSecret();
|
||||
let expiresIn: string | number;
|
||||
|
||||
if (expiresAt) {
|
||||
expiresIn = Math.floor(
|
||||
(new Date(expiresAt).getTime() - new Date().getTime()) / 1000,
|
||||
);
|
||||
} else {
|
||||
expiresIn = this.environmentService.getApiTokenExpiresIn();
|
||||
}
|
||||
const token = this.jwtService.sign(jwtPayload, {
|
||||
secret,
|
||||
expiresIn,
|
||||
jwtid: apiKeyId,
|
||||
});
|
||||
|
||||
return { token };
|
||||
}
|
||||
|
||||
async validateToken(request: Request): Promise<Workspace> {
|
||||
const token = ExtractJwt.fromAuthHeaderAsBearerToken()(request);
|
||||
|
||||
if (!token) {
|
||||
throw new UnauthorizedException('missing authentication token');
|
||||
}
|
||||
const decoded = await this.verifyJwt(
|
||||
token,
|
||||
this.environmentService.getAccessTokenSecret(),
|
||||
);
|
||||
|
||||
const { workspace } = await this.jwtStrategy.validate(
|
||||
decoded as JwtPayload,
|
||||
);
|
||||
|
||||
return workspace;
|
||||
}
|
||||
|
||||
async verifyLoginToken(loginToken: string): Promise<string> {
|
||||
const loginTokenSecret = this.environmentService.getLoginTokenSecret();
|
||||
|
||||
const payload = await this.verifyJwt(loginToken, loginTokenSecret);
|
||||
|
||||
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();
|
||||
const jwtPayload = await this.verifyJwt(refreshToken, secret);
|
||||
|
||||
assert(
|
||||
jwtPayload.jti && jwtPayload.sub,
|
||||
'This refresh token is malformed',
|
||||
UnprocessableEntityException,
|
||||
);
|
||||
|
||||
const token = await this.refreshTokenRepository.findOneBy({
|
||||
id: jwtPayload.jti,
|
||||
});
|
||||
|
||||
assert(token, "This refresh token doesn't exist", NotFoundException);
|
||||
|
||||
const user = await this.userRepository.findOneBy({
|
||||
id: jwtPayload.sub,
|
||||
});
|
||||
|
||||
assert(user, 'User not found', NotFoundException);
|
||||
|
||||
// Check if revokedAt is less than coolDown
|
||||
if (
|
||||
token.revokedAt &&
|
||||
token.revokedAt.getTime() <= Date.now() - ms(coolDown)
|
||||
) {
|
||||
// Revoke all user refresh tokens
|
||||
await Promise.all(
|
||||
user.refreshTokens.map(
|
||||
async ({ id }) =>
|
||||
await this.refreshTokenRepository.update(
|
||||
{ id },
|
||||
{
|
||||
revokedAt: new Date(),
|
||||
},
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
throw new ForbiddenException(
|
||||
'Suspicious activity detected, this refresh token has been revoked. All tokens has been revoked.',
|
||||
);
|
||||
}
|
||||
|
||||
return { user, token };
|
||||
}
|
||||
|
||||
async generateTokensFromRefreshToken(token: string): Promise<{
|
||||
accessToken: AuthToken;
|
||||
refreshToken: AuthToken;
|
||||
}> {
|
||||
const {
|
||||
user,
|
||||
token: { id },
|
||||
} = await this.verifyRefreshToken(token);
|
||||
|
||||
// Revoke old refresh token
|
||||
await this.refreshTokenRepository.update(
|
||||
{
|
||||
id,
|
||||
},
|
||||
{
|
||||
revokedAt: new Date(),
|
||||
},
|
||||
);
|
||||
|
||||
const accessToken = await this.generateAccessToken(user.id);
|
||||
const refreshToken = await this.generateRefreshToken(user.id);
|
||||
|
||||
return {
|
||||
accessToken,
|
||||
refreshToken,
|
||||
};
|
||||
}
|
||||
|
||||
computeRedirectURI(loginToken: string): string {
|
||||
return `${this.environmentService.getFrontAuthCallbackUrl()}?loginToken=${loginToken}`;
|
||||
}
|
||||
|
||||
async verifyJwt(token: string, secret?: string) {
|
||||
try {
|
||||
return this.jwtService.verify(token, secret ? { secret } : undefined);
|
||||
} catch (error) {
|
||||
if (error instanceof TokenExpiredError) {
|
||||
throw new UnauthorizedException('Token has expired.');
|
||||
} else if (error instanceof JsonWebTokenError) {
|
||||
throw new UnauthorizedException('Token invalid.');
|
||||
} else {
|
||||
throw new UnprocessableEntityException();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -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);
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,65 @@
|
||||
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 GoogleRequest = Request & {
|
||||
user: {
|
||||
firstName?: string | null;
|
||||
lastName?: string | null;
|
||||
email: string;
|
||||
picture: string | null;
|
||||
workspaceInviteHash?: string;
|
||||
};
|
||||
};
|
||||
|
||||
@Injectable()
|
||||
export class GoogleStrategy extends PassportStrategy(Strategy, 'google') {
|
||||
constructor(environmentService: EnvironmentService) {
|
||||
super({
|
||||
clientID: environmentService.getAuthGoogleClientId(),
|
||||
clientSecret: environmentService.getAuthGoogleClientSecret(),
|
||||
callbackURL: environmentService.getAuthGoogleCallbackUrl(),
|
||||
scope: ['email', 'profile'],
|
||||
passReqToCallback: true,
|
||||
});
|
||||
}
|
||||
|
||||
authenticate(req: any, options: any) {
|
||||
options = {
|
||||
...options,
|
||||
state: JSON.stringify({
|
||||
workspaceInviteHash: req.params.workspaceInviteHash,
|
||||
}),
|
||||
};
|
||||
|
||||
return super.authenticate(req, options);
|
||||
}
|
||||
|
||||
async validate(
|
||||
request: GoogleRequest,
|
||||
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: GoogleRequest['user'] = {
|
||||
email: emails[0].value,
|
||||
firstName: name.givenName,
|
||||
lastName: name.familyName,
|
||||
picture: photos?.[0]?.value,
|
||||
workspaceInviteHash: state.workspaceInviteHash,
|
||||
};
|
||||
|
||||
done(null, user);
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,83 @@
|
||||
import { PassportStrategy } from '@nestjs/passport';
|
||||
import {
|
||||
ForbiddenException,
|
||||
Injectable,
|
||||
UnauthorizedException,
|
||||
} from '@nestjs/common';
|
||||
import { InjectRepository } from '@nestjs/typeorm';
|
||||
|
||||
import { Strategy, ExtractJwt } from 'passport-jwt';
|
||||
import { Repository } from 'typeorm';
|
||||
|
||||
import { assert } from 'src/utils/assert';
|
||||
import { EnvironmentService } from 'src/integrations/environment/environment.service';
|
||||
import { Workspace } from 'src/core/workspace/workspace.entity';
|
||||
import { User } from 'src/core/user/user.entity';
|
||||
import { TypeORMService } from 'src/database/typeorm/typeorm.service';
|
||||
import { DataSourceService } from 'src/metadata/data-source/data-source.service';
|
||||
|
||||
export type JwtPayload = { sub: string; workspaceId: string; jti?: string };
|
||||
export type PassportUser = { user?: User; workspace: Workspace };
|
||||
|
||||
@Injectable()
|
||||
export class JwtAuthStrategy extends PassportStrategy(Strategy, 'jwt') {
|
||||
constructor(
|
||||
private readonly environmentService: EnvironmentService,
|
||||
private readonly typeORMService: TypeORMService,
|
||||
private readonly dataSourceService: DataSourceService,
|
||||
@InjectRepository(Workspace, 'core')
|
||||
private readonly workspaceRepository: Repository<Workspace>,
|
||||
@InjectRepository(User, 'core')
|
||||
private readonly userRepository: Repository<User>,
|
||||
) {
|
||||
super({
|
||||
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
|
||||
ignoreExpiration: false,
|
||||
secretOrKey: environmentService.getAccessTokenSecret(),
|
||||
});
|
||||
}
|
||||
|
||||
async validate(payload: JwtPayload): Promise<PassportUser> {
|
||||
const workspace = await this.workspaceRepository.findOneBy({
|
||||
id: payload.workspaceId ?? payload.sub,
|
||||
});
|
||||
|
||||
if (!workspace) {
|
||||
throw new UnauthorizedException();
|
||||
}
|
||||
if (payload.jti) {
|
||||
const dataSourceMetadata =
|
||||
await this.dataSourceService.getLastDataSourceMetadataFromWorkspaceIdOrFail(
|
||||
workspace.id,
|
||||
);
|
||||
|
||||
const workspaceDataSource = await this.typeORMService.connectToDataSource(
|
||||
dataSourceMetadata,
|
||||
);
|
||||
|
||||
const apiKey = await workspaceDataSource?.query(
|
||||
`SELECT * FROM ${dataSourceMetadata.schema}."apiKey" WHERE id = '${payload.jti}'`,
|
||||
);
|
||||
|
||||
assert(
|
||||
apiKey.length === 1 && !apiKey?.[0].revokedAt,
|
||||
'This API Key is revoked',
|
||||
ForbiddenException,
|
||||
);
|
||||
}
|
||||
|
||||
let user;
|
||||
|
||||
if (payload.workspaceId) {
|
||||
user = await this.userRepository.findOne({
|
||||
where: { id: payload.sub },
|
||||
relations: ['defaultWorkspace'],
|
||||
});
|
||||
if (!user) {
|
||||
throw new UnauthorizedException();
|
||||
}
|
||||
}
|
||||
|
||||
return { user, workspace };
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user