mirror of
https://github.com/SyncrowIOT/backend.git
synced 2025-07-16 18:56:22 +00:00
Merge pull request #325 from SyncrowIOT/SP-1306-be-implement-client-credential-flow-that-accept-client-id-and-client-secret-from-3rd-party-applications-and-issue-o-auth-jwt-tokens
SP-1306-be-implement-client-credential-flow-that-accept-client-id-and-client-secret-from-3rd-party-applications-and-issue-o-auth-jwt-tokens
This commit is contained in:
@ -29,11 +29,13 @@ import { RoleModule } from './role/role.module';
|
||||
import { TermsConditionsModule } from './terms-conditions/terms-conditions.module';
|
||||
import { PrivacyPolicyModule } from './privacy-policy/privacy-policy.module';
|
||||
import { TagModule } from './tags/tags.module';
|
||||
import { ClientModule } from './client/client.module';
|
||||
@Module({
|
||||
imports: [
|
||||
ConfigModule.forRoot({
|
||||
load: config,
|
||||
}),
|
||||
ClientModule,
|
||||
AuthenticationModule,
|
||||
UserModule,
|
||||
InviteUserModule,
|
||||
|
@ -1,17 +1,18 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { ConfigModule } from '@nestjs/config';
|
||||
import { UserRepositoryModule } from '@app/common/modules/user/user.repository.module';
|
||||
import { CommonModule } from '../../libs/common/src';
|
||||
import { UserAuthController } from './controllers';
|
||||
import { UserAuthService } from './services';
|
||||
import { UserRepository } from '@app/common/modules/user/repositories';
|
||||
import { UserSessionRepository } from '@app/common/modules/session/repositories/session.repository';
|
||||
import { UserOtpRepository } from '@app/common/modules/user/repositories';
|
||||
import { RoleTypeRepository } from '@app/common/modules/role-type/repositories';
|
||||
import { RoleService } from 'src/role/services';
|
||||
import { UserAuthController } from './controllers';
|
||||
import { UserAuthService } from './services';
|
||||
import { AuthService } from '@app/common/auth/services/auth.service';
|
||||
import { EmailService } from '@app/common/util/email.service';
|
||||
import { JwtService } from '@nestjs/jwt';
|
||||
|
||||
@Module({
|
||||
imports: [ConfigModule, UserRepositoryModule, CommonModule],
|
||||
imports: [ConfigModule],
|
||||
controllers: [UserAuthController],
|
||||
providers: [
|
||||
UserAuthService,
|
||||
@ -20,6 +21,9 @@ import { RoleService } from 'src/role/services';
|
||||
UserOtpRepository,
|
||||
RoleTypeRepository,
|
||||
RoleService,
|
||||
AuthService,
|
||||
EmailService,
|
||||
JwtService,
|
||||
],
|
||||
exports: [UserAuthService],
|
||||
})
|
||||
|
@ -19,6 +19,7 @@ import { SuperAdminRoleGuard } from 'src/guards/super.admin.role.guard';
|
||||
import { EnableDisableStatusEnum } from '@app/common/constants/days.enum';
|
||||
import { OtpType } from '@app/common/constants/otp-type.enum';
|
||||
import { ControllerRoute } from '@app/common/constants/controller-route';
|
||||
import { ClientGuard } from 'src/guards/client.guard';
|
||||
|
||||
@Controller({
|
||||
version: EnableDisableStatusEnum.ENABLED,
|
||||
@ -29,13 +30,19 @@ export class UserAuthController {
|
||||
constructor(private readonly userAuthService: UserAuthService) {}
|
||||
|
||||
@ResponseMessage('User Registered Successfully')
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(ClientGuard)
|
||||
@Post('user/signup')
|
||||
@ApiOperation({
|
||||
summary: ControllerRoute.AUTHENTICATION.ACTIONS.SIGN_UP_SUMMARY,
|
||||
description: ControllerRoute.AUTHENTICATION.ACTIONS.SIGN_UP_DESCRIPTION,
|
||||
})
|
||||
async signUp(@Body() userSignUpDto: UserSignUpDto) {
|
||||
const signupUser = await this.userAuthService.signUp(userSignUpDto);
|
||||
async signUp(@Body() userSignUpDto: UserSignUpDto, @Req() req: any) {
|
||||
const clientUuid = req.client.uuid;
|
||||
const signupUser = await this.userAuthService.signUp(
|
||||
userSignUpDto,
|
||||
clientUuid,
|
||||
);
|
||||
return {
|
||||
statusCode: HttpStatus.CREATED,
|
||||
data: {
|
||||
|
@ -34,7 +34,10 @@ export class UserAuthService {
|
||||
private readonly configService: ConfigService,
|
||||
) {}
|
||||
|
||||
async signUp(userSignUpDto: UserSignUpDto): Promise<UserEntity> {
|
||||
async signUp(
|
||||
userSignUpDto: UserSignUpDto,
|
||||
clientUuid?: string,
|
||||
): Promise<UserEntity> {
|
||||
const findUser = await this.findUser(userSignUpDto.email);
|
||||
|
||||
if (findUser) {
|
||||
@ -63,6 +66,7 @@ export class UserAuthService {
|
||||
hasAcceptedAppAgreement,
|
||||
password: hashedPassword,
|
||||
roleType: { uuid: spaceMemberRole.uuid },
|
||||
client: { uuid: clientUuid },
|
||||
region: regionUuid
|
||||
? {
|
||||
uuid: regionUuid,
|
||||
|
24
src/client/client.module.ts
Normal file
24
src/client/client.module.ts
Normal file
@ -0,0 +1,24 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { ClientController } from './controllers';
|
||||
import { ClientService } from './services';
|
||||
import { ClientRepositoryModule } from '@app/common/modules/client/client.repository.module';
|
||||
import { ClientRepository } from '@app/common/modules/client/repositories';
|
||||
import { AuthService } from '@app/common/auth/services/auth.service';
|
||||
import { JwtService } from '@nestjs/jwt';
|
||||
import { UserRepository } from '@app/common/modules/user/repositories';
|
||||
import { UserSessionRepository } from '@app/common/modules/session/repositories/session.repository';
|
||||
|
||||
@Module({
|
||||
imports: [ClientRepositoryModule],
|
||||
controllers: [ClientController],
|
||||
providers: [
|
||||
ClientService,
|
||||
ClientRepository,
|
||||
AuthService,
|
||||
JwtService,
|
||||
UserRepository,
|
||||
UserSessionRepository,
|
||||
],
|
||||
exports: [ClientService],
|
||||
})
|
||||
export class ClientModule {}
|
33
src/client/controllers/client.controller.ts
Normal file
33
src/client/controllers/client.controller.ts
Normal file
@ -0,0 +1,33 @@
|
||||
import { Controller, Post, Body } from '@nestjs/common';
|
||||
import { ApiOperation, ApiTags } from '@nestjs/swagger';
|
||||
import { RegisterClientDto } from '../dtos/register-client.dto';
|
||||
import { ClientService } from '../services';
|
||||
import { ControllerRoute } from '@app/common/constants/controller-route';
|
||||
import { ClientTokenDto } from '../dtos/token-client.dto';
|
||||
import { EnableDisableStatusEnum } from '@app/common/constants/days.enum';
|
||||
|
||||
@ApiTags('OAuth Clients')
|
||||
@Controller({
|
||||
version: EnableDisableStatusEnum.ENABLED,
|
||||
path: ControllerRoute.CLIENT.ROUTE,
|
||||
})
|
||||
export class ClientController {
|
||||
constructor(private readonly clientService: ClientService) {}
|
||||
|
||||
@Post('register')
|
||||
@ApiOperation({
|
||||
summary: ControllerRoute.CLIENT.ACTIONS.REGISTER_NEW_CLIENT_SUMMARY,
|
||||
description: ControllerRoute.CLIENT.ACTIONS.REGISTER_NEW_CLIENT_DESCRIPTION,
|
||||
})
|
||||
async registerClient(@Body() dto: RegisterClientDto) {
|
||||
return this.clientService.registerClient(dto);
|
||||
}
|
||||
@Post('token')
|
||||
@ApiOperation({
|
||||
summary: ControllerRoute.CLIENT.ACTIONS.LOGIN_CLIENT_SUMMARY,
|
||||
description: ControllerRoute.CLIENT.ACTIONS.LOGIN_CLIENT_DESCRIPTION,
|
||||
})
|
||||
async login(@Body() dto: ClientTokenDto) {
|
||||
return this.clientService.loginWithClientCredentials(dto);
|
||||
}
|
||||
}
|
1
src/client/controllers/index.ts
Normal file
1
src/client/controllers/index.ts
Normal file
@ -0,0 +1 @@
|
||||
export * from './client.controller';
|
1
src/client/dtos/index.ts
Normal file
1
src/client/dtos/index.ts
Normal file
@ -0,0 +1 @@
|
||||
export * from './register-client.dto';
|
31
src/client/dtos/register-client.dto.ts
Normal file
31
src/client/dtos/register-client.dto.ts
Normal file
@ -0,0 +1,31 @@
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
import { IsNotEmpty, IsString } from 'class-validator';
|
||||
|
||||
export class RegisterClientDto {
|
||||
@ApiProperty({
|
||||
example: 'SmartHomeApp',
|
||||
description: 'The name of the client',
|
||||
required: true,
|
||||
})
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
name: string;
|
||||
|
||||
@ApiProperty({
|
||||
example: 'https://client-app.com/callback',
|
||||
description: 'The redirect URI of the client',
|
||||
required: true,
|
||||
})
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
redirectUri: string;
|
||||
|
||||
@ApiProperty({
|
||||
example: ['DEVICE_SINGLE_CONTROL', 'DEVICE_VIEW'],
|
||||
description: 'The scopes of the client',
|
||||
required: true,
|
||||
})
|
||||
@IsString({ each: true })
|
||||
@IsNotEmpty({ each: true })
|
||||
scopes: string[];
|
||||
}
|
22
src/client/dtos/token-client.dto.ts
Normal file
22
src/client/dtos/token-client.dto.ts
Normal file
@ -0,0 +1,22 @@
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
import { IsNotEmpty, IsString } from 'class-validator';
|
||||
|
||||
export class ClientTokenDto {
|
||||
@ApiProperty({
|
||||
example: 'abcd1234xyz',
|
||||
description: 'The client ID of the client',
|
||||
required: true,
|
||||
})
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
clientId: string;
|
||||
|
||||
@ApiProperty({
|
||||
example: 'secureSecret123',
|
||||
description: 'The client secret of the client',
|
||||
required: true,
|
||||
})
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
clientSecret: string;
|
||||
}
|
68
src/client/services/client.service.ts
Normal file
68
src/client/services/client.service.ts
Normal file
@ -0,0 +1,68 @@
|
||||
import { HttpStatus, Injectable, NotFoundException } from '@nestjs/common';
|
||||
import { InjectRepository } from '@nestjs/typeorm';
|
||||
import { Repository } from 'typeorm';
|
||||
|
||||
import * as crypto from 'crypto';
|
||||
import { RegisterClientDto } from '../dtos/register-client.dto';
|
||||
import { ClientEntity } from '@app/common/modules/client/entities';
|
||||
import { ClientTokenDto } from '../dtos/token-client.dto';
|
||||
import { AuthService } from '@app/common/auth/services/auth.service';
|
||||
import { SuccessResponseDto } from '@app/common/dto/success.response.dto';
|
||||
|
||||
@Injectable()
|
||||
export class ClientService {
|
||||
constructor(
|
||||
@InjectRepository(ClientEntity)
|
||||
private clientRepository: Repository<ClientEntity>,
|
||||
private readonly authService: AuthService,
|
||||
) {}
|
||||
async loginWithClientCredentials(dto: ClientTokenDto) {
|
||||
const client = await this.validateClient(dto.clientId, dto.clientSecret);
|
||||
const payload = {
|
||||
client: {
|
||||
clientId: client.clientId,
|
||||
uuid: client.uuid,
|
||||
scopes: client.scopes,
|
||||
},
|
||||
};
|
||||
const tokens = await this.authService.getTokens(payload, false, '5m');
|
||||
return new SuccessResponseDto({
|
||||
message: `Client logged in successfully`,
|
||||
data: tokens,
|
||||
statusCode: HttpStatus.CREATED,
|
||||
});
|
||||
}
|
||||
async registerClient(dto: RegisterClientDto) {
|
||||
const clientId = crypto.randomBytes(16).toString('hex');
|
||||
const clientSecret = crypto.randomBytes(32).toString('hex');
|
||||
|
||||
const client = this.clientRepository.create({
|
||||
name: dto.name,
|
||||
clientId,
|
||||
clientSecret,
|
||||
redirectUri: dto.redirectUri,
|
||||
scopes: dto.scopes,
|
||||
});
|
||||
|
||||
await this.clientRepository.save(client);
|
||||
|
||||
return new SuccessResponseDto({
|
||||
message: `Client registered successfully`,
|
||||
data: { clientId, clientSecret },
|
||||
statusCode: HttpStatus.CREATED,
|
||||
});
|
||||
}
|
||||
|
||||
async validateClient(
|
||||
clientId: string,
|
||||
clientSecret: string,
|
||||
): Promise<ClientEntity | null> {
|
||||
const client = await this.clientRepository.findOne({
|
||||
where: { clientId, clientSecret },
|
||||
});
|
||||
if (!client) {
|
||||
throw new NotFoundException('Invalid client credentials');
|
||||
}
|
||||
return client;
|
||||
}
|
||||
}
|
1
src/client/services/index.ts
Normal file
1
src/client/services/index.ts
Normal file
@ -0,0 +1 @@
|
||||
export * from './client.service';
|
43
src/guards/client.guard.ts
Normal file
43
src/guards/client.guard.ts
Normal file
@ -0,0 +1,43 @@
|
||||
import { UnauthorizedException } from '@nestjs/common';
|
||||
import { AuthGuard } from '@nestjs/passport';
|
||||
import * as jwt from 'jsonwebtoken';
|
||||
|
||||
export class ClientGuard extends AuthGuard('jwt') {
|
||||
handleRequest(err, user, info, context) {
|
||||
if (err || !user) {
|
||||
throw err || new UnauthorizedException();
|
||||
}
|
||||
|
||||
const request = context.switchToHttp().getRequest();
|
||||
const token = this.extractTokenFromHeader(request);
|
||||
|
||||
if (!token) {
|
||||
throw new UnauthorizedException('Token not found');
|
||||
}
|
||||
|
||||
try {
|
||||
const decoded = jwt.decode(token);
|
||||
if (!this.validateToken(decoded)) {
|
||||
throw new UnauthorizedException('Invalid token');
|
||||
}
|
||||
|
||||
request.client = (decoded as jwt.JwtPayload).client;
|
||||
} catch (err) {
|
||||
throw new UnauthorizedException('Invalid token');
|
||||
}
|
||||
|
||||
return user;
|
||||
}
|
||||
|
||||
private extractTokenFromHeader(request): string | null {
|
||||
const authHeader = request.headers.authorization;
|
||||
if (authHeader && authHeader.startsWith('Bearer ')) {
|
||||
return authHeader.split(' ')[1];
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private validateToken(decoded: any): boolean {
|
||||
return decoded?.client?.clientId && decoded?.client?.uuid;
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user