Skip to content

Commit

Permalink
Merge branch 'develop' into ft/add-bulk-meter-api
Browse files Browse the repository at this point in the history
  • Loading branch information
Kingcedru authored Dec 10, 2024
2 parents 4aa27fe + e20668c commit 914788b
Show file tree
Hide file tree
Showing 34 changed files with 17,806 additions and 1,533 deletions.
16,609 changes: 16,609 additions & 0 deletions apps/drec-api/pnpm-lock.yaml

Large diffs are not rendered by default.

32 changes: 16 additions & 16 deletions apps/drec-api/src/auth/auth.service.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,8 @@ describe('AuthService', () => {
getUserAndPasswordByEmail: jest.fn(), // Mock method
findById: jest.fn(), // Include other methods if needed
createUserSession: jest.fn(),
removeUsersession: jest.fn(),
hasgetUserTokenvalid: jest.fn(),
removeUserSession: jest.fn(),
hasValidUserSession: jest.fn(),
} as any,
},
{
Expand Down Expand Up @@ -145,7 +145,7 @@ describe('AuthService', () => {
});

describe('logout', () => {
it('should call removeUsersession with correct parameters', async () => {
it('should call removeUserSession with correct parameters', async () => {
const payload: IJWTPayload = {
id: 1,
email: 'test@example.com',
Expand All @@ -155,12 +155,12 @@ describe('AuthService', () => {

const deleteResult = { affected: 1, raw: [] };
jest
.spyOn(userService, 'removeUsersession')
.spyOn(userService, 'removeUserSession')
.mockResolvedValue(deleteResult);

await service.logout(payload, token);

expect(userService.removeUsersession).toHaveBeenCalledWith(
expect(userService.removeUserSession).toHaveBeenCalledWith(
payload.id,
token,
);
Expand All @@ -176,15 +176,15 @@ describe('AuthService', () => {

const deleteResult = { affected: 1, raw: [] };
jest
.spyOn(userService, 'removeUsersession')
.spyOn(userService, 'removeUserSession')
.mockResolvedValue(deleteResult);

const result = await service.logout(payload, token);

expect(result).toBe(deleteResult);
});

it('should handle errors thrown by removeUsersession', async () => {
it('should handle errors thrown by removeUserSession', async () => {
const payload: IJWTPayload = {
id: 1,
email: 'test@example.com',
Expand All @@ -193,7 +193,7 @@ describe('AuthService', () => {
const token = 'fake-jwt-token';

const error = new Error('Unable to remove user session');
jest.spyOn(userService, 'removeUsersession').mockRejectedValue(error);
jest.spyOn(userService, 'removeUserSession').mockRejectedValue(error);

await expect(service.logout(payload, token)).rejects.toThrow(
'Unable to remove user session',
Expand All @@ -210,7 +210,7 @@ describe('AuthService', () => {

const deleteResult = { affected: 0, raw: [] };
jest
.spyOn(userService, 'removeUsersession')
.spyOn(userService, 'removeUserSession')
.mockResolvedValue(deleteResult);

const result = await service.logout(payload, token);
Expand All @@ -221,7 +221,7 @@ describe('AuthService', () => {
});

describe('isTokenBlacklisted', () => {
it('should call hasgetUserTokenvalid with correct parameters', async () => {
it('should call hasValidUserSession with correct parameters', async () => {
const token = 'fake-jwt-token';
const payload: IJWTPayload = {
id: 1,
Expand All @@ -231,12 +231,12 @@ describe('AuthService', () => {

const tokeninvalidate = true;
jest
.spyOn(userService, 'hasgetUserTokenvalid')
.spyOn(userService, 'hasValidUserSession')
.mockResolvedValue(tokeninvalidate);

await service.isTokenBlacklisted(token, payload);

expect(userService.hasgetUserTokenvalid).toHaveBeenCalledWith({
expect(userService.hasValidUserSession).toHaveBeenCalledWith({
accesstoken_hash: token,
userId: payload.id,
});
Expand All @@ -250,7 +250,7 @@ describe('AuthService', () => {
role: Role.Buyer,
};

jest.spyOn(userService, 'hasgetUserTokenvalid').mockResolvedValue(true);
jest.spyOn(userService, 'hasValidUserSession').mockResolvedValue(false);

const result = await service.isTokenBlacklisted(token, payload);

Expand All @@ -265,14 +265,14 @@ describe('AuthService', () => {
role: Role.OrganizationAdmin,
};

jest.spyOn(userService, 'hasgetUserTokenvalid').mockResolvedValue(false);
jest.spyOn(userService, 'hasValidUserSession').mockResolvedValue(true);

const result = await service.isTokenBlacklisted(token, payload);

expect(result).toBe(false);
});

it('should handle errors thrown by hasgetUserTokenvalid', async () => {
it('should handle errors thrown by hasValidUserSession', async () => {
const token = 'fake-jwt-token';
const payload: IJWTPayload = {
id: 1,
Expand All @@ -281,7 +281,7 @@ describe('AuthService', () => {
};

const error = new Error('Error checking token validity');
jest.spyOn(userService, 'hasgetUserTokenvalid').mockRejectedValue(error);
jest.spyOn(userService, 'hasValidUserSession').mockRejectedValue(error);

await expect(service.isTokenBlacklisted(token, payload)).rejects.toThrow(
'Error checking token validity',
Expand Down
10 changes: 5 additions & 5 deletions apps/drec-api/src/auth/auth.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,25 +49,25 @@ export class AuthService {
role: user.role,
};
const token = this.jwtService.sign(payload);
this.userService.createUserSession(user, token);
await this.userService.createUserSession(user, token);
return {
accessToken: token,
};
}

async logout(payload: IJWTPayload, token: string): Promise<DeleteResult> {
return await this.userService.removeUsersession(payload.id, token);
return await this.userService.removeUserSession(payload.id, token);
}

async isTokenBlacklisted(
token: string,
payload: IJWTPayload,
): Promise<boolean> {
//hasUser({ email })
const tokeninvalidate = await this.userService.hasgetUserTokenvalid({
const session = await this.userService.hasValidUserSession({
accesstoken_hash: token,
userId: payload.id,
});
return tokeninvalidate;
return !session;
}

async generateToken(
Expand Down
11 changes: 5 additions & 6 deletions apps/drec-api/src/auth/jwt.strategy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,17 +36,16 @@ export class JwtStrategy extends PassportStrategy(Strategy, 'jwt') {
const token = (
request.headers as { authorization?: string }
).authorization?.split(' ')[1];
const tokeninvalidate = await this.authService.isTokenBlacklisted(
const invalidToken = await this.authService.isTokenBlacklisted(
token,
payload,
);
if (token && !tokeninvalidate) {
if (token && invalidToken) {
throw new UnauthorizedException('Token revoked. Please log in again.');
}

const user = await this.userService.findByEmail(payload.email);
if (user) {
return user;
}
return null;

return user || null;
}
}
3 changes: 1 addition & 2 deletions apps/drec-api/src/auth/local.strategy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ export class LocalStrategy extends PassportStrategy(Strategy) {

async validate(email: string, password: string): Promise<UserDTO> {
this.logger.verbose('With in validate');
const user = await this.authService.validateUser(email, password);
return user;
return await this.authService.validateUser(email, password);
}
}
11 changes: 11 additions & 0 deletions apps/drec-api/src/lib/helpers/parseMetadata.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
export const parseMetadata = (
metadata: Record<string, unknown>,
): any | null => {
try {
if (typeof metadata !== 'string') return metadata;
return JSON.parse(metadata);
} catch (e) {
console.error(e, `certificate doesnt contains valid metadata ${metadata}`);
return null;
}
};
36 changes: 36 additions & 0 deletions apps/drec-api/src/lib/influx-db.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import {
InfluxDB,
Point,
QueryApi,
WriteApi,
} from '@influxdata/influxdb-client';

const dbConfig = {
url: process.env.INFLUXDB_URL || 'http://localhost:8086',
token: process.env.INFLUXDB_TOKEN || 'admin:admin',
};

const dbWriter = (): WriteApi => {
return new InfluxDB(dbConfig).getWriteApi(
process.env.INFLUXDB_ORG || '',
process.env.INFLUXDB_BUCKET,
);
};

const dbReader = (): QueryApi => {
return new InfluxDB(dbConfig).getQueryApi(process.env.INFLUXDB_ORG || '');
};

const writePoints = async (points: Point[]): Promise<void> => {
const writer = dbWriter();
writer.writePoints(points);
await writer.close();
};

const executeQuery = async (query: string): Promise<any[]> => {
const reader = dbReader();
const results = await reader.collectRows(query);
return results;
};

export { dbReader, dbWriter, writePoints, executeQuery };
29 changes: 29 additions & 0 deletions apps/drec-api/src/lib/organization.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { Role } from '../utils/enums';
import { ILoggedInUser, IUser } from '../models';
import { Organization } from '../pods/organization/organization.entity';

export const canManageOrganization = ({
user,
organization,
organizationAdmin,
}: {
user: ILoggedInUser;
organizationAdmin: IUser;
organization: Organization;
}): boolean => {
if (!organization) return false;

if (user.role !== Role.ApiUser) {
return user.organizationId === organization.id;
}

if (organizationAdmin.api_user_id !== user.api_user_id) {
return false;
}

if (organizationAdmin.role !== Role.OrganizationAdmin) {
return false;
}

return true;
};
4 changes: 2 additions & 2 deletions apps/drec-api/src/pods/admin/admin.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -181,7 +181,7 @@ export class AdminController {
@UserDecorator() { api_user_id }: LoggedInUser,
): Promise<UserDTO> {
newUser.api_user_id = api_user_id;
return await this.userService.adminnewcreate(newUser);
return await this.userService.createUserByAdmin(newUser);
}

@Post('/seed/users')
Expand Down Expand Up @@ -321,7 +321,7 @@ export class AdminController {
throw new NotFoundException('Does not exist');
}
const manyotheruserinorg =
await this.userService.getatleastoneotheruserinOrg(
await this.userService.getAnotherUserInOrganization(
user.organization.id,
user.id,
);
Expand Down
Loading

0 comments on commit 914788b

Please sign in to comment.