BE/src/auth/auth.service.ts
2025-06-09 10:55:50 +05:30

76 lines
2.1 KiB
TypeScript

import { BadRequestException, Injectable } from '@nestjs/common';
import { OracleDBService } from 'src/db/db.service';
import { AuthLoginDTO } from './auth.dto';
import * as oracledb from 'oracledb';
@Injectable()
export class AuthService {
constructor(private readonly oracleDBService: OracleDBService) { }
async login(body: AuthLoginDTO) {
let connection;
let rows = [];
try {
connection = await this.oracleDBService.getConnection();
if (!connection) {
throw new Error('No DB Connected');
}
const result = await connection.execute(
`BEGIN
USERLOGIN_PKG.ValidateUser(:P_EMAILADDR,:P_PASSWORD,:p_login_cursor);
END;`,
{
P_EMAILADDR: {
val: body.P_EMAILADDR,
type: oracledb.DB_TYPE_NVARCHAR,
},
P_PASSWORD: {
val: body.P_PASSWORD,
type: oracledb.DB_TYPE_NVARCHAR,
},
p_login_cursor: {
type: oracledb.CURSOR,
dir: oracledb.BIND_OUT,
},
},
{
outFormat: oracledb.OUT_FORMAT_OBJECT,
},
);
if (result.outBinds && result.outBinds.p_login_cursor) {
const cursor = result.outBinds.p_login_cursor;
let rowsBatch;
do {
rowsBatch = await cursor.getRows(100);
rows = rows.concat(rowsBatch);
} while (rowsBatch.length > 0);
await cursor.close();
} else {
throw new BadRequestException({
Error: 'Error executing request try after some time!',
});
}
if (rows[0]['ERRORMESG']) {
throw new BadRequestException({ error: 'Invalid username or password!' });
}
return { msg: 'Logged in successfully' };
} catch (err) {
throw new BadRequestException({ error: 'Invalid username or password' });
}
finally {
if (connection) {
try {
await connection.close();
} catch (closeErr) {
console.error('Failed to close connection:', closeErr);
}
}
}
}
}