convert project from microservices to rest apis

This commit is contained in:
faris Aljohari
2024-03-10 12:49:51 +03:00
parent b3179a5c1f
commit c5537b3230
72 changed files with 155 additions and 384 deletions
+120
View File
@@ -0,0 +1,120 @@
import { Injectable } from '@nestjs/common';
import * as qs from 'qs';
import * as crypto from 'crypto';
import { ConfigService } from '@nestjs/config';
import axios from 'axios';
@Injectable()
export class AuthenticationService {
private token: string;
private deviceId: string;
private accessKey: string;
private secretKey: string;
constructor(private readonly configService: ConfigService) {
(this.deviceId = this.configService.get<string>('auth-config.DEVICE_ID')),
(this.accessKey = this.configService.get<string>(
'auth-config.ACCESS_KEY',
)),
(this.secretKey = this.configService.get<string>(
'auth-config.SECRET_KEY',
));
}
async main() {
await this.getToken();
const data = await this.getDeviceInfo(this.deviceId);
console.log('fetch success: ', JSON.stringify(data));
return JSON.stringify(data);
}
async getToken() {
const method = 'GET';
const timestamp = Date.now().toString();
const signUrl = 'https://openapi.tuyaeu.com/v1.0/token?grant_type=1';
const contentHash = crypto.createHash('sha256').update('').digest('hex');
const stringToSign = [method, contentHash, '', signUrl].join('\n');
const signStr = this.accessKey + timestamp + stringToSign;
const headers = {
t: timestamp,
sign_method: 'HMAC-SHA256',
client_id: this.accessKey,
sign: await this.encryptStr(signStr, this.secretKey),
};
const { data: login } = await axios.get(
'https://openapi.tuyaeu.com/v1.0/token',
{
params: {
grant_type: 1,
},
headers,
},
);
if (!login || !login.success) {
throw new Error(`fetch failed: ${login.msg}`);
}
this.token = login.result.access_token;
}
async getDeviceInfo(deviceId: string) {
const query = {};
const method = 'POST';
const url = `https://openapi.tuyaeu.com/v1.0/devices/${deviceId}/commands`;
const reqHeaders: { [k: string]: string } = await this.getRequestSign(
url,
method,
{},
query,
);
const { data } = await axios.post(url, {}, reqHeaders);
if (!data || !data.success) {
throw new Error(`request api failed: ${data.msg}`);
}
return data;
}
async encryptStr(str: string, secret: string): Promise<string> {
return crypto
.createHmac('sha256', secret)
.update(str, 'utf8')
.digest('hex')
.toUpperCase();
}
async getRequestSign(
path: string,
method: string,
query: { [k: string]: any } = {},
body: { [k: string]: any } = {},
) {
const t = Date.now().toString();
const [uri, pathQuery] = path.split('?');
const queryMerged = Object.assign(query, qs.parse(pathQuery));
const sortedQuery: { [k: string]: string } = {};
Object.keys(queryMerged)
.sort()
.forEach((i) => (sortedQuery[i] = query[i]));
const querystring = decodeURIComponent(qs.stringify(sortedQuery));
const url = querystring ? `${uri}?${querystring}` : uri;
const contentHash = crypto
.createHash('sha256')
.update(JSON.stringify(body))
.digest('hex');
const stringToSign = [method, contentHash, '', url].join('\n');
const signStr = this.accessKey + this.token + t + stringToSign;
return {
t,
path: url,
client_id: 'this.accessKey',
sign: await this.encryptStr(signStr, this.secretKey),
sign_method: 'HMAC-SHA256',
access_token: this.token,
};
}
}
+2
View File
@@ -0,0 +1,2 @@
export * from './authentication.service';
export * from './user-auth.service';
+151
View File
@@ -0,0 +1,151 @@
import { UserRepository } from '../../../libs/common/src/modules/user/repositories';
import {
BadRequestException,
Injectable,
UnauthorizedException,
} from '@nestjs/common';
import { UserSignUpDto } from '../dtos/user-auth.dto';
import { HelperHashService } from '../../../libs/common/src/helper/services';
import { UserLoginDto } from '../dtos/user-login.dto';
import { AuthService } from '../../../libs/common/src/auth/services/auth.service';
import { UserSessionRepository } from '../../../libs/common/src/modules/session/repositories/session.repository';
import { UserOtpRepository } from '../../../libs/common/src/modules/user-otp/repositories/user-otp.repository';
import { ForgetPasswordDto, UserOtpDto, VerifyOtpDto } from '../dtos';
import { EmailService } from '../../../libs/common/src/util/email.service';
import { OtpType } from '../../../libs/common/src/constants/otp-type.enum';
import { UserEntity } from '../../../libs/common/src/modules/user/entities/user.entity';
import { ILoginResponse } from '../constants/login.response.constant';
@Injectable()
export class UserAuthService {
constructor(
private readonly userRepository: UserRepository,
private readonly sessionRepository: UserSessionRepository,
private readonly otpRepository: UserOtpRepository,
private readonly helperHashService: HelperHashService,
private readonly authService: AuthService,
private readonly emailService: EmailService,
) {}
async signUp(userSignUpDto: UserSignUpDto): Promise<UserEntity> {
const findUser = await this.findUser(userSignUpDto.email);
if (findUser) {
throw new BadRequestException('User already registered with given email');
}
const salt = this.helperHashService.randomSalt(10);
const password = this.helperHashService.bcrypt(
userSignUpDto.password,
salt,
);
return await this.userRepository.save({ ...userSignUpDto, password });
}
async findUser(email: string) {
return await this.userRepository.findOne({
where: {
email,
},
});
}
async forgetPassword(forgetPasswordDto: ForgetPasswordDto) {
const findUser = await this.findUser(forgetPasswordDto.email);
if (!findUser) {
throw new BadRequestException('User not found');
}
const salt = this.helperHashService.randomSalt(10);
const password = this.helperHashService.bcrypt(
forgetPasswordDto.password,
salt,
);
return await this.userRepository.update(
{ uuid: findUser.uuid },
{ password },
);
}
async userLogin(data: UserLoginDto): Promise<ILoginResponse> {
const user = await this.authService.validateUser(data.email, data.password);
if (!user) {
throw new UnauthorizedException('Invalid login credentials.');
}
const session = await Promise.all([
await this.sessionRepository.update(
{ userId: user.id },
{
isLoggedOut: true,
},
),
await this.authService.createSession({
userId: user.uuid,
loginTime: new Date(),
isLoggedOut: false,
}),
]);
return await this.authService.login({
email: user.email,
userId: user.id,
uuid: user.uuid,
sessionId: session[1].uuid,
});
}
async deleteUser(uuid: string) {
const user = await this.findOneById(uuid);
if (!user) {
throw new BadRequestException('User does not found');
}
return await this.userRepository.delete({ uuid });
}
async findOneById(id: string): Promise<UserEntity> {
return await this.userRepository.findOne({ where: { uuid: id } });
}
async generateOTP(data: UserOtpDto): Promise<string> {
await this.otpRepository.delete({ email: data.email, type: data.type });
const otpCode = Math.floor(100000 + Math.random() * 900000).toString();
const expiryTime = new Date();
expiryTime.setMinutes(expiryTime.getMinutes() + 1);
await this.otpRepository.save({
email: data.email,
otpCode,
expiryTime,
type: data.type,
});
const subject = 'OTP send successfully';
const message = `Your OTP code is ${otpCode}`;
this.emailService.sendOTPEmail(data.email, subject, message);
return otpCode;
}
async verifyOTP(data: VerifyOtpDto): Promise<boolean> {
const otp = await this.otpRepository.findOne({
where: { email: data.email, type: data.type },
});
if (!otp) {
throw new BadRequestException('this email is not registered');
}
if (otp.otpCode !== data.otpCode) {
throw new BadRequestException('You entered wrong otp');
}
if (otp.expiryTime < new Date()) {
await this.otpRepository.delete(otp.id);
throw new BadRequestException('OTP expired');
}
if (data.type == OtpType.VERIFICATION) {
await this.userRepository.update(
{ email: data.email },
{ isUserVerified: true },
);
}
return true;
}
}