Skip to content

Commit

Permalink
Merge pull request #155 from paulcwatts/more-updates
Browse files Browse the repository at this point in the history
Convert to native classes, async/await
  • Loading branch information
paulcwatts committed Aug 20, 2020
2 parents 2e0e90f + 89e4b55 commit 731db93
Show file tree
Hide file tree
Showing 6 changed files with 122 additions and 143 deletions.
93 changes: 41 additions & 52 deletions addon/authenticators/cognito.js
Original file line number Diff line number Diff line change
@@ -1,43 +1,39 @@
import { readOnly } from '@ember/object/computed';
import { inject as service } from '@ember/service';
import Base from 'ember-simple-auth/authenticators/base';
import { reject } from 'rsvp';

export default Base.extend({
cognito: service(),
auth: readOnly('cognito.auth'),
poolId: readOnly('cognito.poolId'),
clientId: readOnly('cognito.clientId'),
authenticationFlowType: readOnly('cognito.authenticationFlowType'),
export default class CognitoAuthenticator extends Base {
@service cognito;
@readOnly('cognito.auth') auth;
@readOnly('cognito.poolId') poolId;
@readOnly('cognito.clientId') clientId;
@readOnly('cognito.authenticationFlowType') authenticationFlowType;

restore({ poolId, clientId }) {
async restore({ poolId, clientId }) {
this.cognito.configure({
userPoolId: poolId,
userPoolWebClientId: clientId
});
return this.auth.currentAuthenticatedUser().then((user) => {
return this._resolveAuth(user);
});
},
const user = await this.auth.currentAuthenticatedUser();
return this._resolveAuth(user);
}

_makeAuthData(user, session) {
return {
poolId: user.pool.getUserPoolId(),
clientId: user.pool.getClientId(),
access_token: session.getIdToken().getJwtToken()
};
},
}

_resolveAuth(user) {
async _resolveAuth(user) {
const { cognito } = this;
cognito._setUser(user);
// Now pull out the (promisified) user
return cognito.user.getSession().then((session) => {
/* eslint-disable camelcase */
cognito.startRefreshTask(session);
return this._makeAuthData(user, session);
});
},
const session = await cognito.user.getSession();
cognito.startRefreshTask(session);
return this._makeAuthData(user, session);
}

_handleSignIn(user) {
// console.log(user);
Expand All @@ -51,31 +47,26 @@ export default Base.extend({
} else {
return this._resolveAuth(user);
}
},
}

_handleNewPasswordRequired({ password, state: { user } }) {
return this.auth.completeNewPassword(user, password).then((user) => {
return this._handleSignIn(user);
});
},
async _handleNewPasswordRequired({ password, state: { user } }) {
const user2 = await this.auth.completeNewPassword(user, password);
return this._handleSignIn(user2);
}

_handleRefresh() {
async _handleRefresh() {
const { cognito } = this;
const { auth, user } = cognito;
// Get the session, which will refresh it if necessary
return user.getSession().then((session) => {
if (session.isValid()) {
/* eslint-disable camelcase */

cognito.startRefreshTask(session);
return auth.currentAuthenticatedUser().then((awsUser) => {
return this._makeAuthData(awsUser, session);
});
} else {
return reject('session is invalid');
}
});
},
const session = await user.getSession();
if (session.isValid()) {
cognito.startRefreshTask(session);
const awsUser = await auth.currentAuthenticatedUser();
return this._makeAuthData(awsUser, session);
} else {
throw new Error('session is invalid');
}
}

_handleState(name, params) {
if (name === 'refresh') {
Expand All @@ -85,9 +76,9 @@ export default Base.extend({
} else {
throw new Error('invalid state');
}
},
}

authenticate(params) {
async authenticate(params) {
const { username, password, state } = params;
if (state) {
return this._handleState(state.name, params);
Expand All @@ -96,15 +87,13 @@ export default Base.extend({
const { auth, authenticationFlowType, cognito } = this;
cognito.configure({ authenticationFlowType });

return auth.signIn(username, password).then((user) => {
return this._handleSignIn(user);
});
},
const user = await auth.signIn(username, password);
return this._handleSignIn(user);
}

invalidate(data) {
return this.cognito.user.signOut().then(() => {
this.set('cognito.user', undefined);
return data;
});
async invalidate(data) {
await this.cognito.user.signOut();
this.set('cognito.user', undefined);
return data;
}
});
}
51 changes: 24 additions & 27 deletions addon/services/cognito.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,14 @@ import { reject } from 'rsvp';
* This is a container for easily accessing the logged-in CognitoUser object,
* as well as creating others using signUp().
*/
export default Service.extend({
session: service(),
auth: Auth,
export default class CognitoService extends Service {
@service session;
auth = Auth;

willDestroy() {
this._super(...arguments);
super.willDestroy(...arguments);
this.stopRefreshTask();
},
}

/**
* Configures the Amplify library with the pool & client IDs, and any additional
Expand All @@ -32,7 +32,7 @@ export default Service.extend({
}, awsconfig);

this.auth.configure(params);
},
}

/**
* Method for signing up a user.
Expand All @@ -42,20 +42,18 @@ export default Service.extend({
* @param attributes New user attributes.
* @param validationData Application metadata.
*/
signUp(username, password, attributes, validationData) {
async signUp(username, password, attributes, validationData) {
this.configure();

return this.auth.signUp({
const result = await this.auth.signUp({
username,
password,
attributes: normalizeAttributes(attributes),
validationData
}).then((result) => {
// Replace the user with a wrapped user.
result.user = this._setUser(result.user);
return result;
});
},
// Replace the user with a wrapped user.
result.user = this._setUser(result.user);
return result;
}

/**
* Confirm signup for user.
Expand All @@ -66,7 +64,7 @@ export default Service.extend({
confirmSignUp(username, code, options) {
this.configure();
return this.auth.confirmSignUp(username, code, options);
},
}

/**
* Resends the sign up code.
Expand All @@ -76,7 +74,7 @@ export default Service.extend({
resendSignUp(username) {
this.configure();
return this.auth.resendSignUp(username);
},
}

/**
* Sends a user a code to reset their password.
Expand All @@ -86,7 +84,7 @@ export default Service.extend({
forgotPassword(username) {
this.configure();
return this.auth.forgotPassword(username);
},
}

/**
* Submits a new password.
Expand All @@ -98,7 +96,7 @@ export default Service.extend({
forgotPasswordSubmit(username, code, newPassword) {
this.configure();
return this.auth.forgotPasswordSubmit(username, code, newPassword);
},
}

/**
* Enable the token refresh timer.
Expand All @@ -114,7 +112,7 @@ export default Service.extend({
const duration = (exp - adjusted) * 1000 + 100;
this.set('_taskDuration', duration);
this.set('task', later(this, 'refreshSession', duration));
},
}

/**
* Disable the token refresh timer.
Expand All @@ -123,33 +121,32 @@ export default Service.extend({
cancel(this.task);
this.set('task', undefined);
this.set('_taskDuration', undefined);
},
}

refreshSession() {
let user = this.user;
if (user) {
return this.session.authenticate('authenticator:cognito', { state: { name: 'refresh' } });
}
},
}

/**
* A helper that resolves to the logged in user's id token.
*/
getIdToken() {
async getIdToken() {
const user = this.user;
if (user) {
return user.getSession().then((session) => {
return session.getIdToken().getJwtToken();
})
const session = await user.getSession();
return session.getIdToken().getJwtToken();
} else {
return reject('user not authenticated');
}
},
}

_setUser(awsUser) {
// Creates and sets the Cognito user.
const user = CognitoUser.create({ auth: this.auth, user: awsUser });
this.set('user', user);
return user;
}
});
}
Loading

0 comments on commit 731db93

Please sign in to comment.