fm-odata-client
Version:
FileMaker OData client developed by Soliant Consulting
108 lines • 3.2 kB
JavaScript
// src/ClarisId.ts
import { AuthenticationDetails, CognitoUser, CognitoUserPool } from "amazon-cognito-identity-js";
var ClarisId = class {
username;
password;
authenticationDetails;
userPool = null;
cognitoUser = null;
userSession = null;
idTokenPromise = null;
constructor(username, password) {
this.username = username;
this.password = password;
}
async getAuthorizationHeader() {
if (this.idTokenPromise) {
return `FMID ${await this.idTokenPromise}`;
}
this.idTokenPromise = this.getIdToken();
const idToken = await this.idTokenPromise;
this.idTokenPromise = null;
return `FMID ${idToken}`;
}
getAuthenticationDetails() {
if (!this.authenticationDetails) {
this.authenticationDetails = new AuthenticationDetails({
Username: this.username,
Password: this.password
});
}
return this.authenticationDetails;
}
async getIdToken() {
if (this.userSession) {
return this.getStoredIdToken(this.userSession);
}
const userSession = await this.retrieveNewSession();
return userSession.getIdToken().getJwtToken();
}
async getStoredIdToken(userSession) {
const currentUserSession = !userSession.isValid() ? await this.refreshSession(userSession) : userSession;
return currentUserSession.getIdToken().getJwtToken();
}
async refreshSession(userSession) {
const cognitoUser = await this.getCognitoUser();
this.userSession = await new Promise((resolve, reject) => {
cognitoUser.refreshSession(userSession.getRefreshToken(), async (error, session) => {
if (error) {
try {
resolve(await this.retrieveNewSession());
return;
} catch (e) {
reject(e);
}
}
resolve(session);
});
});
return this.userSession;
}
async retrieveNewSession() {
const cognitoUser = await this.getCognitoUser();
const authenticationDetails = this.getAuthenticationDetails();
this.userSession = await new Promise((resolve, reject) => {
cognitoUser.authenticateUser(authenticationDetails, {
onSuccess: (result) => {
resolve(result);
},
onFailure: (error) => {
reject(error);
}
});
});
return this.userSession;
}
async getCognitoUser() {
if (this.cognitoUser) {
return this.cognitoUser;
}
this.cognitoUser = new CognitoUser({
Username: this.getAuthenticationDetails().getUsername(),
Pool: await this.getUserPool()
});
return this.cognitoUser;
}
async getUserPool() {
if (this.userPool) {
return this.userPool;
}
const response = await fetch(
"https://www.ifmcloud.com/endpoint/userpool/2.2.0.my.claris.com.json"
);
if (!response.ok) {
throw new Error("Could not fetch user pool config");
}
const config = await response.json();
this.userPool = new CognitoUserPool({
UserPoolId: config.data.UserPool_ID,
ClientId: config.data.Client_ID
});
return this.userPool;
}
};
var ClarisId_default = ClarisId;
export {
ClarisId_default as default
};
//# sourceMappingURL=ClarisId.js.map