Skip to content
This repository has been archived by the owner on Oct 4, 2024. It is now read-only.

Commit

Permalink
Merge pull request #95 from MiroBenicio/feat/rlogout-method
Browse files Browse the repository at this point in the history
Feat/logout method
  • Loading branch information
ricardobrg authored Apr 16, 2024
2 parents 64c10e8 + c5518f4 commit 4fdb314
Show file tree
Hide file tree
Showing 5 changed files with 148 additions and 111 deletions.
66 changes: 61 additions & 5 deletions src/auth/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ export default class Auth {
secret: string,
scopes: Array<string>,
address?: string
): Promise<string | undefined> {
): Promise<{token: string, refreshToken?: string} | undefined> {
const data = {
grant_type: "client_credentials",
client_id:
Expand Down Expand Up @@ -63,8 +63,14 @@ export default class Auth {

const responseData = await response.json();

const { access_token } = responseData;
return access_token;

const { access_token, refresh_token } = responseData;

if(address){
localStorage.setItem('accessToken', access_token)
localStorage.setItem('refreshToken', refresh_token)
}
return {token: access_token, refreshToken: refresh_token};
} catch (error) {
console.error(`Error fetching token: ${error}`);
return
Expand All @@ -86,7 +92,7 @@ export default class Auth {
const accessToken = await this.getToken(providerId, pubKey, [
"account:provider",
]);
if (!accessToken) {
if (!accessToken || !accessToken.token) {
console.error("Error generating the provider accessToken");
return;
}
Expand Down Expand Up @@ -129,7 +135,7 @@ export default class Auth {
const headers = new Headers();
headers.append("accept", "application/json");
headers.append("content-type", "application/json");
headers.append("authorization", "Bearer " + accessToken);
headers.append("authorization", "Bearer " + accessToken.token);
const response = await fetch(url, {
method: "POST",
headers: headers,
Expand All @@ -152,4 +158,54 @@ export default class Auth {
return
}
}

public static async refreshToken(refreshToken: string){
const data = {
grant_type: "refresh_token",
refresh_token: refreshToken
};

const headers = new Headers();
headers.append("Accept", "application/json");
headers.append("Content-Type", "application/x-www-form-urlencoded");

const requestOptions: RequestInit = {
method: "POST",
headers: headers,
body: new URLSearchParams(data),
};

try {
const response = await fetch("https://account.mytiki.com/api/latest/auth", requestOptions);

if (!response.ok) {
console.error(
`HTTP error! Status: ${response.status}, message: ${response.json()}`
);
return
}

const responseData = await response.json();

const { access_token, refresh_token } = responseData;

localStorage.setItem('accessToken', access_token)

localStorage.setItem('refreshToken', refresh_token)

return access_token;
} catch (error) {
console.error(`Error fetching token: ${error}`);
return
}

}

public logout(){
localStorage.removeItem("accessToken")

localStorage.removeItem("refreshToken")

return "Logout succesfully"
}
}
31 changes: 8 additions & 23 deletions src/capture/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,27 +37,18 @@ export default class Capture {
* @param {string} token - the address token to authenticate the request to our server.
* @returns {Promise<string>} A Promise that resolves with the ID of the request or void in case of any error.
*/
public async publish(images: string[], token: string): Promise<string | void> {
public async publish(images: string[]): Promise<string | void> {
const id = window.crypto.randomUUID();

const headers = new Headers();
headers.append("Content-Type", "image/jpeg");
headers.append("Authorization", "Bearer " + token);

for (const image of images) {
const body = Utils.base64toBlob(image, "image/jpeg");
const url = `${this.publishUrl}/receipt/${id}`;

const response = await fetch(url, {
method: "POST",
body,
headers,
});

if (!response.ok) {
console.error(`Error uploading files. Status: ${response.status}`);
await Utils.handleRequest(url, "POST", body).catch((error)=>{
console.error(`Error uploading files. Status: ${error}`);
return
}
})

}

return id;
Expand All @@ -73,15 +64,9 @@ export default class Capture {
* @returns {Promise<ReceiptResponse[]>} A Promise that resolves with an array of {@link ReceiptResponse} objects,
* each containing the structured data extracted from an image of the receipt.
*/
public async receipt(receiptId: string, token: string): Promise<ReceiptResponse[]>{
public async receipt(receiptId: string
): Promise<ReceiptResponse[]>{
const url = `${this.publishUrl}/receipt/${receiptId}`
const headers = new Headers();
headers.append("Content-Type", "application/json");
headers.append("Authorization", "Bearer " + token);
const options = {
method: "GET",
headers,
};
return (await fetch(url, options)).json()
return await Utils.handleRequest(url, "GET")
}
}
10 changes: 2 additions & 8 deletions src/license/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ import terms from '../assets/terms.md?raw';
*/
export default class License {
private baseUrl: string = "https://trail.mytiki.com"
private utils = new Utils();

/**
* Creates a license to publish data to Tiki.
Expand All @@ -25,15 +24,12 @@ export default class License {
* @returns The saved license object.
*/
public async create(
token: string,
postLicenseRequest: PostLicenseRequest
): Promise<PostLicenseRequest> {
const url = `${this.baseUrl}/license/create`;
debugger;
return this.utils.handleRequest<PostLicenseRequest>(
return Utils.handleRequest<PostLicenseRequest>(
url,
"POST",
token,
postLicenseRequest
);
}
Expand All @@ -45,13 +41,11 @@ export default class License {
* @returns An object containing a boolean and a reason message to confirm the validation or not.
*/
public async verify(
token: string
): Promise<RspGuard> {
const url = `${this.baseUrl}/license/verify`;
return this.utils.handleRequest<RspGuard>(
return Utils.handleRequest<RspGuard>(
url,
"POST",
token
);
}

Expand Down
110 changes: 44 additions & 66 deletions src/tiki_client/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,6 @@ export default class TikiClient {
instance.config.providerId,
userId
);

if (!key) {
await instance.auth.registerAddress(
instance.config.providerId,
Expand All @@ -82,6 +81,8 @@ export default class TikiClient {
}

instance.userId = userId;

await instance.saveToken()
}

/**
Expand Down Expand Up @@ -123,41 +124,7 @@ export default class TikiClient {
return;
}

const key = await instance.keyService.get(
instance.config.providerId,
instance.userId
);

if (!key) {
console.error(
"Key Pair not found. Use the TikiClient.initialize method to register the user."
);
return;
}

const address: string = Utils.arrayBufferToBase64Url(
await instance.keyService.address(key.value)
);

const signature: string = await Utils.generateSignature(
address,
key?.value.privateKey
);

const addressToken: string | undefined = await instance.auth.getToken(
instance.config.providerId,
signature,
["trail publish"],
address
);

if (!addressToken) {
console.error("Failed to get Address Token");
return;
}

const verifyLicense: RspGuard = await instance.license.verify(
addressToken!
);

if (!verifyLicense || !verifyLicense.verified) {
Expand All @@ -167,7 +134,7 @@ export default class TikiClient {
return;
}

return await instance.capture.publish(images, addressToken);
return await instance.capture.publish(images);
}

/**
Expand Down Expand Up @@ -203,27 +170,6 @@ export default class TikiClient {
return;
}

const address: string = Utils.arrayBufferToBase64Url(
await instance.keyService.address(key.value)
);

const signature: string = await Utils.generateSignature(
address,
key?.value.privateKey
);

const addressToken: string | undefined = await instance.auth.getToken(
instance.config.providerId,
signature,
["trail"],
address
);

if (!addressToken) {
console.error("It was not possible to get the token, try to inialize!");
return;
}

const terms: string = instance.license.terms(
instance.config.companyName,
instance.config.companyJurisdiction,
Expand Down Expand Up @@ -255,7 +201,7 @@ export default class TikiClient {

licenseReq.signature = licenseSignature

return await instance.license.create(addressToken, licenseReq);
return await instance.license.create(licenseReq);
}

/**
Expand Down Expand Up @@ -293,9 +239,44 @@ export default class TikiClient {
return;
}

const receipt = await instance.capture.receipt(receiptId);

return receipt;
}

public static logout(){
let instance = TikiClient.getInstance();

if (instance.config == undefined) {
console.error(
"TIKI Client is not configured. Use the TikiClient.configure method to add a configuration."
);
return;
}

if (instance.userId == undefined) {
console.error(
"No user logged in"
);
return;
}

return instance.auth.logout()
}

private async saveToken(){
let instance = TikiClient.getInstance();

if (instance.config == undefined) {
console.error(
"TIKI Client is not configured. Use the TikiClient.configure method to add a configuration."
);
return;
}

const key = await instance.keyService.get(
instance.config.providerId,
instance.userId
instance.userId!
);

if (!key) {
Expand All @@ -314,20 +295,17 @@ export default class TikiClient {
key?.value.privateKey
);

const addressToken: string | undefined = await instance.auth.getToken(
instance.config.providerId,
const addressToken = await instance.auth.getToken(
instance?.config!.providerId,
signature,
["trail publish"],
address
);

if (!addressToken) {
if (!addressToken || !addressToken.token) {
console.error("Failed to get Address Token");
return;
}

const receipt = await instance.capture.receipt(receiptId, addressToken);

return receipt;
}

}
Loading

0 comments on commit 4fdb314

Please sign in to comment.