Skip to content

Commit 16c4ec0

Browse files
feat: implement StorX authentication flow and service integration #TODO
1 parent 1a544f7 commit 16c4ec0

File tree

7 files changed

+352
-369
lines changed

7 files changed

+352
-369
lines changed

backend/src/modules/device/controllers/device-log.controller.ts

Lines changed: 14 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -29,16 +29,14 @@ import { ErrorTypeEnum } from 'src/modules/utility/enums/error-type.enum';
2929
import { GeneralException } from 'src/modules/utility/exceptions/general.exception';
3030
import { DeviceLogService } from '../services/device-log.service';
3131
import { DeviceService } from '../services/device.service';
32-
import storxController from './storx.controller';
3332
import { UserService } from 'src/modules/user/services/user/user.service';
3433

3534
@ApiTags('Manage Device Logs')
3635
@Controller('app')
3736
export class DeviceLogController {
3837
private result;
3938
private storxBucket = process.env.STORX_BUCKET_NAME || '';
40-
private logKeepDays =
41-
Number(process.env.LOG_RETENTION_DAYS ?? '14');
39+
private logKeepDays = Number(process.env.LOG_RETENTION_DAYS ?? '14');
4240

4341
constructor(
4442
@Inject(UserService)
@@ -47,8 +45,9 @@ export class DeviceLogController {
4745
private readonly deviceService: DeviceService,
4846
) {
4947
setInterval(async () => {
50-
51-
await this.deviceLogService.removeAllDeviceLogsBeforeDaysAgo(this.logKeepDays)
48+
await this.deviceLogService.removeAllDeviceLogsBeforeDaysAgo(
49+
this.logKeepDays,
50+
);
5251

5352
/* const usersRes = await this.userService.getAllUsers();
5453
const devicesRes = await this.deviceService.getAllDevices();
@@ -471,7 +470,7 @@ export class DeviceLogController {
471470

472471
return this.result;
473472
}
474-
473+
475474
@Get('v1/device-log/get-device-log-by-encrypted-deviceid-and-date-range')
476475
@HttpCode(200)
477476
@UseGuards(JwtAuthGuard)
@@ -523,14 +522,15 @@ export class DeviceLogController {
523522
const isAdmin = await this.isAdmin(request.user.userId);
524523

525524
try {
526-
const result = await this.deviceLogService.getDeviceLogByEncryptedDeviceIdAndDateRange(
527-
deviceEncryptedId,
528-
new Date(startDate),
529-
new Date(endDate),
530-
type,
531-
request.user.userId,
532-
(isSharedWithUser || isAdmin),
533-
);
525+
const result =
526+
await this.deviceLogService.getDeviceLogByEncryptedDeviceIdAndDateRange(
527+
deviceEncryptedId,
528+
new Date(startDate),
529+
new Date(endDate),
530+
type,
531+
request.user.userId,
532+
isSharedWithUser || isAdmin,
533+
);
534534

535535
return result;
536536
} catch (error) {
@@ -541,5 +541,4 @@ export class DeviceLogController {
541541
);
542542
}
543543
}
544-
545544
}
Lines changed: 26 additions & 285 deletions
Original file line numberDiff line numberDiff line change
@@ -1,289 +1,30 @@
1-
import {
2-
S3Client,
3-
CreateBucketCommand,
4-
ListObjectsCommand,
5-
GetObjectCommand,
6-
PutObjectCommand,
7-
DeleteObjectsCommand,
8-
} from '@aws-sdk/client-s3';
9-
10-
let bucketProps = {
11-
region: 'auto',
12-
endpoint: '', //https://gateway.storx.io
13-
credentials: {
14-
accessKeyId: '', //jv3vsap36i6rnzctvpmw33zhg5qa
15-
secretAccessKey: '', //jz3qahozyd7ukcg3i2omkt37ee75mjkjs575657v7qwzi7czgibjq
16-
},
17-
forcePathStyle: true,
18-
};
19-
20-
let client;
21-
22-
async function setBucketProps(
23-
endPoint: string,
24-
accessKeyId: string,
25-
secretAccessKey: string,
26-
) {
27-
bucketProps = {
28-
region: 'auto',
29-
endpoint: endPoint, //https://gateway.storx.io
30-
credentials: {
31-
accessKeyId: accessKeyId, //jv3vsap36i6rnzctvpmw33zhg5qa
32-
secretAccessKey: secretAccessKey, //jz3qahozyd7ukcg3i2omkt37ee75mjkjs575657v7qwzi7czgibjq
33-
},
34-
forcePathStyle: true,
35-
};
36-
client = new S3Client(bucketProps);
37-
}
38-
39-
function getStorxBucket() {
40-
return bucketProps;
41-
}
42-
43-
const CreateBucket = async (bucketName) => {
44-
try {
45-
const command = new CreateBucketCommand({ Bucket: bucketName });
46-
await client.send(command);
47-
console.log('Bucket created successfully.\n');
48-
} catch (error) {
49-
//console.log(error.message);
50-
console.log(`Store X Bucket: ${bucketName} Founded Successfully`);
51-
}
52-
return bucketName;
53-
};
54-
55-
const EmptyBucket = async ({ bucketName }) => {
56-
const listObjectsCommand = new ListObjectsCommand({ Bucket: bucketName });
57-
const { Contents } = await client.send(listObjectsCommand);
58-
const keys = Contents.map((c) => c.Key);
59-
60-
const deleteObjectsCommand = new DeleteObjectsCommand({
61-
Bucket: bucketName,
62-
Delete: { Objects: keys.map((key) => ({ Key: key })) },
63-
});
64-
await client.send(deleteObjectsCommand);
65-
console.log(`${bucketName} emptied successfully.\n`);
66-
};
67-
68-
const UploadFile = async ({
69-
reader,
70-
bucketName,
71-
deviceID,
72-
}: {
73-
reader: string;
74-
bucketName: string;
75-
deviceID: string;
76-
}) => {
77-
const now = new Date();
78-
const year = now.getFullYear();
79-
const month = now.getMonth() + 1;
80-
const day = now.getDate();
81-
const hour = now.getHours();
82-
const timestamp = now.getTime();
83-
84-
const key = `${deviceID}/${year}/${month}/${day}/${hour}/${timestamp}.log`;
85-
86-
const params = {
87-
Bucket: bucketName,
88-
Key: key,
89-
Body: reader, // Assuming reader is a readable stream or Buffer
90-
};
91-
92-
try {
93-
const data = await client.send(new PutObjectCommand(params));
94-
console.log(`${key} uploaded successfully.`);
95-
return { data: data, success: true };
96-
} catch (err) {
97-
console.error('Error uploading file:', err);
98-
return { data: null, success: false };
1+
import { Controller, Get, HttpCode, Post, Query } from '@nestjs/common';
2+
import { ApiOperation, ApiQuery, ApiTags } from '@nestjs/swagger';
3+
import { StorxService } from '../services/storx.service';
4+
5+
@ApiTags('StorX')
6+
@Controller('app')
7+
export class StorXController {
8+
constructor(private readonly storxService: StorxService) {}
9+
10+
@Get('v1/storx/construct-uri')
11+
@HttpCode(200)
12+
@ApiOperation({
13+
summary: 'Construct StorX Authentication URI',
14+
description: 'Construct StorX Authentication URI',
15+
})
16+
async constructUrl() {
17+
return {
18+
uri: await this.storxService.constructUri(),
19+
};
9920
}
100-
};
101-
102-
const DownloadFiles = async ({
103-
writer,
104-
bucketName,
105-
deviceID,
106-
startTime,
107-
endTime,
108-
}: {
109-
writer: any[];
110-
bucketName: string;
111-
deviceID: string;
112-
startTime: Date;
113-
endTime: Date;
114-
}) => {
115-
const startPath = `${deviceID}/${startTime.getFullYear()}/${
116-
startTime.getMonth() + 1
117-
}/${startTime.getDate()}/${startTime.getHours()}`;
118-
const endPath = `${deviceID}/${endTime.getFullYear()}/${
119-
endTime.getMonth() + 1
120-
}/${endTime.getDate()}/${endTime.getHours()}`;
121-
122-
// Determine common prefix
123-
const commonPrefix = startPath
124-
.split('/')
125-
.filter((part, i) => part === endPath.split('/')[i])
126-
.join('/');
127-
128-
try {
129-
const command = new ListObjectsCommand({
130-
Bucket: bucketName,
131-
Prefix: commonPrefix,
132-
});
133-
const { Contents } = await client.send(command);
13421

135-
if (Contents) {
136-
for (const file of Contents) {
137-
const obj = await client.send(
138-
new GetObjectCommand({ Bucket: bucketName, Key: file.Key }),
139-
);
140-
const data = await obj.Body.transformToByteArray();
141-
const jsonData = JSON.parse(new TextDecoder().decode(data));
142-
writer.push({
143-
key: file.Key,
144-
data: jsonData,
145-
});
146-
}
147-
}
148-
149-
console.log('Files downloaded successfully.');
150-
} catch (err) {
151-
console.error('Error downloading files:', err);
152-
throw err;
22+
@Get('v1/storx/callback')
23+
@HttpCode(200)
24+
async callback(@Query('access_grant') accessGrant: string) {
25+
await this.storxService.handleCallback(accessGrant);
26+
return {
27+
message: 'Callback received',
28+
};
15329
}
154-
};
155-
156-
const axios = require('axios');
157-
158-
let developer_data = {
159-
token: '',
160-
expire: '',
161-
};
162-
163-
function isExpired(expiresAt: string | Date): boolean {
164-
const expiresAtDate = new Date(expiresAt);
165-
const now = new Date();
166-
const remainingTime = expiresAtDate.getTime() - now.getTime();
167-
console.log('remaining time is:', remainingTime);
168-
return remainingTime <= 0;
16930
}
170-
171-
async function checkDeveloperToken() {
172-
if (developer_data.token && developer_data.expire) {
173-
if (isExpired(developer_data.expire) == false) {
174-
console.log('Developer token is not expired');
175-
} else {
176-
return await developerLogin();
177-
}
178-
} else {
179-
return await developerLogin();
180-
}
181-
}
182-
183-
async function developerLogin() {
184-
const { data } = await axios.post(
185-
`${process.env.STORX_HOST}/api/v0/developer/auth/token`,
186-
{
187-
email: 'prince.soamedi12334@gmail.com',
188-
password: 'Prince@143$',
189-
},
190-
);
191-
developer_data = {
192-
token: data.token,
193-
expire: data.expiresAt,
194-
};
195-
196-
//console.log('Developer data is:', developer_data);
197-
198-
return developer_data;
199-
}
200-
201-
async function createUserAndGenerateStorXKey(email: string, fullName: string) {
202-
await checkDeveloperToken();
203-
204-
console.log('We are in createUserAndGenerateStorXKey');
205-
206-
const { data } = await axios.post(
207-
`${process.env.STORX_HOST}/api/v0/developer/auth/create-user`,
208-
{
209-
email,
210-
fullName,
211-
},
212-
{
213-
headers: {
214-
Cookie: `_developer_tokenKey=${developer_data.token}`,
215-
},
216-
},
217-
);
218-
219-
const userData = data.data;
220-
221-
console.log('User Data is:', userData);
222-
223-
const { data: tokenData } = await axios.post(
224-
`${process.env.STORX_HOST}/api/v0/developer/auth/user-token`,
225-
{
226-
email,
227-
},
228-
{
229-
headers: {
230-
Cookie: `_developer_tokenKey=${developer_data.token}`,
231-
},
232-
},
233-
);
234-
235-
const userToken = tokenData.token;
236-
237-
const { data: initialApiData } = await axios.post(
238-
`${process.env.STORX_HOST}/api/v0/api-keys/create/${userData.projectId}`,
239-
'userkey',
240-
{
241-
headers: {
242-
Cookie: `_developer_tokenKey=${developer_data.token}; _tokenKey=${userToken}`,
243-
},
244-
},
245-
);
246-
247-
const apiData = {
248-
...initialApiData.keyInfo,
249-
key: initialApiData.key,
250-
};
251-
252-
const { data: grantData } = await axios.get(
253-
`${process.env.STORX_HOST}/api/v0/api-keys/${apiData.projectId}/access-grant?api-key=${apiData.key}&passphrase=userkey`,
254-
{
255-
headers: {
256-
Cookie: `_developer_tokenKey=${developer_data.token}; _tokenKey=${userToken}`,
257-
},
258-
},
259-
);
260-
261-
const { data: accessData } = await axios.post(
262-
`${process.env.STORX_AUTH_HOST}/v1/access`,
263-
{
264-
access_grant: grantData,
265-
public: false,
266-
},
267-
);
268-
269-
return accessData;
270-
271-
/*
272-
{
273-
access_key_id: 'jvdbfnaloekozsxj7sl23lqnobkq',
274-
secret_key: 'j37ljdviecfb4qldccdx5kbadg7cq3ekyb6o76bawincsvchwl3bw',
275-
endpoint: 'https://gateway.storx.io'
276-
}
277-
*/
278-
}
279-
280-
export default {
281-
getStorxBucket,
282-
CreateBucket,
283-
setBucketProps,
284-
EmptyBucket,
285-
UploadFile,
286-
DownloadFiles,
287-
developerLogin,
288-
createUserAndGenerateStorXKey,
289-
};

0 commit comments

Comments
 (0)