Skip to content

Commit

Permalink
feat(auth): add reflexive method to instantiate UserSession from jsap…
Browse files Browse the repository at this point in the history
…i auth

AFFECTS PACKAGES:
@esri/arcgis-rest-auth

ISSUES CLOSED: #208
  • Loading branch information
jgravois committed Jun 19, 2018
1 parent 106c7b3 commit ea64da9
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 5 deletions.
33 changes: 31 additions & 2 deletions packages/arcgis-rest-auth/src/UserSession.ts
Original file line number Diff line number Diff line change
Expand Up @@ -520,8 +520,37 @@ export class UserSession implements IAuthenticationManager {
});
}

// returns authentication in a format useable in the [ArcGIS API for JavaScript](https://developers.arcgis.com/javascript/)
getCredential(): ICredential {
/**
* Translates authentication from the format used in the [ArcGIS API for JavaScript](https://developers.arcgis.com/javascript/).
*
* ```js
* UserSession.fromCredential({
* userId: "jsmith",
* token: "secret"
* });
* ```
*
* @returns UserSession
*/
static fromCredential(credential: ICredential) {
return new UserSession({
portal: credential.server,
token: credential.token,
username: credential.userId,
tokenExpires: new Date(credential.expires)
});
}

/**
* Returns authentication in a format useable in the [ArcGIS API for JavaScript](https://developers.arcgis.com/javascript/).
*
* ```js
* esriId.registerToken(session.toCredential());
* ```
*
* @returns ICredential
*/
toCredential(): ICredential {
return {
expires: this.tokenExpires.getTime(),
server: this.portal,
Expand Down
14 changes: 11 additions & 3 deletions packages/arcgis-rest-auth/test/UserSession.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -704,7 +704,7 @@ describe("UserSession", () => {
});
});

describe(".getCredential()", () => {
describe("to/fromCredential()", () => {
const MOCK_CREDENTIAL: ICredential = {
expires: TOMORROW.getTime(),
server: "https://www.arcgis.com/sharing/rest",
Expand All @@ -713,7 +713,7 @@ describe("UserSession", () => {
userId: "jsmith"
};

it("should cache metadata about the user", () => {
it("should create a credential object from a session", () => {
const session = new UserSession({
clientId: "clientId",
redirectUri: "https://example-app.com/redirect-uri",
Expand All @@ -726,8 +726,16 @@ describe("UserSession", () => {
password: "123456"
});

const creds = session.getCredential();
const creds = session.toCredential();
expect(creds).toEqual(MOCK_CREDENTIAL);
});

it("should create a UserSession from a credential", () => {
const session = UserSession.fromCredential(MOCK_CREDENTIAL);
expect(session.username).toEqual("jsmith");
expect(session.portal).toEqual("https://www.arcgis.com/sharing/rest");
expect(session.token).toEqual("token");
expect(session.tokenExpires).toEqual(new Date(TOMORROW));
});
});
});

0 comments on commit ea64da9

Please sign in to comment.