BE/src/auth/auth.service.ts
2025-05-02 14:50:19 +05:30

77 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) {
console.error('Error fetching users: ', err.message);
throw new BadRequestException({ error: 'Invalid username or password' });
}
finally {
if (connection) {
try {
await connection.close();
} catch (closeErr) {
console.error('Failed to close connection:', closeErr);
}
}
}
}
}