Skip to content

Commit

Permalink
Merge pull request #264 from fenichelar/master
Browse files Browse the repository at this point in the history
Cleanup comments and documentation and new release
  • Loading branch information
jpadilla authored Apr 19, 2019
2 parents 1f88b4e + 011743f commit e10f86c
Show file tree
Hide file tree
Showing 7 changed files with 44 additions and 92 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ Ember Simple Auth Token can be installed with [Ember CLI][ember-cli] by running:
ember install ember-simple-auth-token
```

If using FastBoot, `node-fetch` must be added to your `fastbootDependencies`. If using FastBoot and the JWT authenticator, `node-fetch` and `buffer` must be added to you `fastbootDependencies`.
If using FastBoot, `ember-fetch` must be installed as a direct dependency and `node-fetch` must be added to your `fastbootDependencies`. If using FastBoot and the JWT authenticator, `node-fetch` and `buffer` must be added to you `fastbootDependencies`.

## Setup

Expand Down
87 changes: 30 additions & 57 deletions addon/authenticators/jwt.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,7 @@ const decode = str => {
Inspired by [ember-simple-auth-oauth2](https://github.com/simplabs/ember-simple-auth/tree/master/packages/ember-simple-auth-oauth2)
The factory for this authenticator is registered as
'authenticator:jwt` in Ember's container.
The factory for this authenticator is registered as 'authenticator:jwt` in Ember's container.
@class JWT
@namespace SimpleAuth.Authenticators
Expand All @@ -39,7 +38,6 @@ const decode = str => {
export default TokenAuthenticator.extend({
/**
@method init
@private
*/
init() {
this._super(...arguments);
Expand All @@ -58,18 +56,14 @@ export default TokenAuthenticator.extend({
It will return a resolving promise if one of two conditions is met:
1) Both `data.token` and `data.expiresAt` are non-empty and `expiresAt`
is greater than the calculated `now`.
2) If `data.token` is non-empty and the decoded token has a key for
`tokenExpireName`.
1) Both `data.token` and `data.expiresAt` are non-empty and `expiresAt` is greater than the calculated `now`.
2) If `data.token` is non-empty and the decoded token has a key for `tokenExpireName`.
If `refreshAccessTokens` is true, `scheduleAccessTokenRefresh` will
be called and an automatic token refresh will be initiated.
If `refreshAccessTokens` is true, `scheduleAccessTokenRefresh` will be called and an automatic token refresh will be initiated.
@method restore
@param {Object} data The data to restore the session from
@return {Promise} A promise that when it resolves results
in the session being authenticated
@return {Promise} A promise that when it resolves results in the session being authenticated
*/
restore(data) {
const dataObject = EmberObject.create(data);
Expand All @@ -85,8 +79,7 @@ export default TokenAuthenticator.extend({
}

if (isEmpty(expiresAt)) {
// Fetch the expire time from the token data since `expiresAt`
// wasn't included in the data object that was passed in.
// Fetch the expire time from the token data since `expiresAt` wasn't included in the data object that was passed in.
const tokenData = this.getTokenData(token);
expiresAt = tokenData[this.tokenExpireName];
if (isEmpty(expiresAt)) {
Expand All @@ -112,9 +105,7 @@ export default TokenAuthenticator.extend({
return reject(new Error('unable to refresh token'));
}
} else {
// the refresh token might not be expired,
// we can't test this on the client so attempt to refresh the token.
// If the server rejects the token the user session will be invalidated
// The refresh token might not be expired, we can't test this on the client so attempt to refresh the token. If the server rejects the token the user session will be invalidated
if (this.refreshAccessTokens) {
return resolve(this.refreshAccessToken(refreshToken));
} else {
Expand All @@ -127,35 +118,27 @@ export default TokenAuthenticator.extend({
/**
Authenticates the session with the specified `credentials`.
It will return a resolving promise if it successfully posts a request
to the `JWT.serverTokenEndpoint` with the valid credentials.
It will return a resolving promise if it successfully posts a request to the `JWT.serverTokenEndpoint` with the valid credentials.
An automatic token refresh will be scheduled with the new expiration date
from the returned refresh token. That expiration will be merged with the
response and the promise resolved.
An automatic token refresh will be scheduled with the new expiration date from the returned refresh token. That expiration will be merged with the response and the promise resolved.
@method authenticate
@param {Object} credentials The credentials to authenticate the session with
@param {Object} headers Optional headers to send with the authentication request
@return {Promise} A promise that resolves when an auth token is
successfully acquired from the server and rejects
otherwise
@return {Promise} A promise that resolves when an auth token is successfully acquired from the server and rejects otherwise
*/
authenticate(credentials, headers) {
return this.makeRequest(this.serverTokenEndpoint, credentials, assign({}, this.headers, headers))
.then(response => this.handleAuthResponse(response.json));
return this.makeRequest(this.serverTokenEndpoint, credentials, assign({}, this.headers, headers)).then(response => {
return this.handleAuthResponse(response.json);
});
},

/**
Schedules a token refresh request to be sent to the backend after a calculated
`wait` time has passed.
Schedules a token refresh request to be sent to the backend after a calculated `wait` time has passed.
If both `token` and `expiresAt` are non-empty, and `expiresAt` minus the optional
refres leeway is greater than the calculated `now`, the token refresh will be scheduled
through later.
If both `token` and `expiresAt` are non-empty, and `expiresAt` minus the optional refres leeway is greater than the calculated `now`, the token refresh will be scheduled through later.
@method scheduleAccessTokenRefresh
@private
*/
scheduleAccessTokenRefresh(expiresAt, refreshToken) {
if (this.refreshAccessTokens) {
Expand All @@ -178,30 +161,25 @@ export default TokenAuthenticator.extend({
/**
Makes a refresh token request to grab a new authenticated JWT token from the server.
It will return a resolving promise if a successful POST is made to the
`JWT.serverTokenRefreshEndpoint`.
It will return a resolving promise if a successful POST is made to the `JWT.serverTokenRefreshEndpoint`.
After the new token is obtained it will schedule the next automatic token refresh
based on the new `expiresAt` time.
After the new token is obtained it will schedule the next automatic token refresh based on the new `expiresAt` time.
The session will be updated via the trigger `sessionDataUpdated`.
@method refreshAccessToken
@private
*/
refreshAccessToken(token) {
const data = this.makeRefreshData(token);

return this.makeRequest(this.serverTokenRefreshEndpoint, data, this.headers)
.then(response => {
const sessionData = this.handleAuthResponse(response.json);
this.trigger('sessionDataUpdated', sessionData);
return sessionData;
})
.catch(error => {
this.handleTokenRefreshFail(error.status);
return Promise.reject(error);
});
return this.makeRequest(this.serverTokenRefreshEndpoint, data, this.headers).then(response => {
const sessionData = this.handleAuthResponse(response.json);
this.trigger('sessionDataUpdated', sessionData);
return sessionData;
}).catch(error => {
this.handleTokenRefreshFail(error.status);
return Promise.reject(error);
});
},

/**
Expand Down Expand Up @@ -246,8 +224,8 @@ export default TokenAuthenticator.extend({
},

/**
Cancels any outstanding automatic token refreshes and returns a resolving
promise.
Cancels any outstanding automatic token refreshes and returns a resolving promise.
@method invalidate
@param {Object} data The data of the session to be invalidated
@return {Promise} A resolving promise
Expand All @@ -262,6 +240,7 @@ export default TokenAuthenticator.extend({

/**
Returns the current time as a timestamp in seconds
@method getCurrentTime
@return {Integer} timestamp
*/
Expand All @@ -273,8 +252,7 @@ export default TokenAuthenticator.extend({
Handles authentication response from server, and returns session data
@method handleAuthResponse
@private
*/
*/
handleAuthResponse(response) {
const token = get(response, this.tokenPropertyName);

Expand Down Expand Up @@ -306,13 +284,10 @@ export default TokenAuthenticator.extend({
},

/**
Handles token refresh fail status. If the server response to a token refresh has a
status of 401 or 403 then the token in the session will be invalidated and
the sessionInvalidated provided by ember-simple-auth will be triggered.
Handles token refresh fail status. If the server response to a token refresh has a status of 401 or 403 then the token in the session will be invalidated and the sessionInvalidated provided by ember-simple-auth will be triggered.
@method handleTokenRefreshFail
*/

handleTokenRefreshFail(refreshStatus) {
if (refreshStatus === 401 || refreshStatus === 403) {
return this.invalidate().then(() => {
Expand All @@ -325,7 +300,6 @@ export default TokenAuthenticator.extend({
Schedules session invalidation at the time token expires.
@method scheduleAccessTokenExpiration
@private
*/
scheduleAccessTokenExpiration(expiresAt) {
const now = this.getCurrentTime();
Expand All @@ -342,7 +316,6 @@ export default TokenAuthenticator.extend({
Handles access token expiration
@method handleAccessTokenExpiration
@private
*/
handleAccessTokenExpiration() {
return this.invalidate().then(() => {
Expand Down
26 changes: 9 additions & 17 deletions addon/authenticators/token.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,7 @@ import config from 'ember-get-config';
/**
Authenticator that works with token-based authentication like JWT.
_The factory for this authenticator is registered as
`'authenticator:token'` in Ember's container._
_The factory for this authenticator is registered as `'authenticator:token'` in Ember's container._
@class Token
@namespace SimpleAuth.Authenticators
Expand All @@ -20,7 +19,6 @@ import config from 'ember-get-config';
export default Base.extend({
/**
@method init
@private
*/
init() {
this._super(...arguments);
Expand All @@ -31,9 +29,7 @@ export default Base.extend({
},

/**
Restores the session from a set of session properties; __will return a
resolving promise when there's a non-empty `token` in the
`properties`__ and a rejecting promise otherwise.
Restores the session from a set of session properties; __will return a resolving promise when there's a non-empty `token` in the `properties`__ and a rejecting promise otherwise.
@method restore
@param {Object} properties The properties to restore the session from
Expand All @@ -52,22 +48,17 @@ export default Base.extend({
},

/**
Authenticates the session with the specified `credentials`; the credentials
are `POST`ed to the
[`Authenticators.Token#serverTokenEndpoint`](#SimpleAuth-Authenticators-Token-serverTokenEndpoint)
and if they are valid the server returns an auth token in
response. __If the credentials are valid and authentication succeeds, a
promise that resolves with the server's response is returned__, otherwise a
promise that rejects with the server error is returned.
Authenticates the session with the specified `credentials`; the credentials are `POST`ed to the [`Authenticators.Token#serverTokenEndpoint`](#SimpleAuth-Authenticators-Token-serverTokenEndpoint) and if they are valid the server returns an auth token in response. __If the credentials are valid and authentication succeeds, a promise that resolves with the server's response is returned__, otherwise a promise that rejects with the server error is returned.
@method authenticate
@param {Object} credentials The credentials to authenticate the session with
@param {Object} headers Optional headers to send with the authentication request
@return {Promise} A promise that resolves when an auth token is successfully acquired from the server and rejects otherwise
*/
authenticate(credentials, headers) {
return this.makeRequest(this.serverTokenEndpoint, credentials, assign({}, this.headers, headers))
.then(response => response.json);
return this.makeRequest(this.serverTokenEndpoint, credentials, assign({}, this.headers, headers)).then(response => {
return response.json;
});
},

/**
Expand All @@ -85,7 +76,6 @@ export default Base.extend({
@param {Object} url Server endpoint
@param {Object} data Object that will be sent to server
@param {Object} headers Additional headers that will be sent to server
@private
*/
makeRequest(url, data, headers) {
return fetch(url, {
Expand Down Expand Up @@ -115,7 +105,9 @@ export default Base.extend({
} else {
return reject(res);
}
}).catch(() => reject(res));
}).catch(() => {
return reject(res);
});
});
}
});
7 changes: 2 additions & 5 deletions addon/mixins/token-authorizer.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,7 @@ import DataAdapterMixin from 'ember-simple-auth/mixins/data-adapter-mixin';
import config from 'ember-get-config';

/**
Authorizer Mixin that works with token-based authentication like JWT
by sending the `token` properties from the session in the `Authorization` header.
Authorizer Mixin that works with token-based authentication like JWT by sending the `token` properties from the session in the `Authorization` header.
@class TokenAuthorizer
@module ember-simple-auth-token/mixins/token-authorizer
Expand All @@ -18,7 +17,6 @@ export default Mixin.create(DataAdapterMixin, {

/**
@method init
@private
*/
init() {
this._super(...arguments);
Expand All @@ -29,8 +27,7 @@ export default Mixin.create(DataAdapterMixin, {
},

/**
Authorizes an XHR request by sending the `token`
properties from the session in the `Authorization` header:
Authorizes an XHR request by sending the `token` properties from the session in the `Authorization` header:
```
Authorization: Bearer <token>
Expand Down
2 changes: 1 addition & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "ember-simple-auth-token",
"version": "4.0.6",
"version": "4.0.7",
"description": "An authenticator and authorizer for Ember Simple Auth that is compatible with token-based authentication like JWT in Ember CLI applications.",
"directories": {
"doc": "doc",
Expand Down
10 changes: 0 additions & 10 deletions server/index.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,3 @@
// To use it create some files under `mocks/`
// e.g. `server/mocks/ember-hamsters.js`
//
// module.exports = function(app) {
// app.get('/ember-hamsters', function(req, res) {
// res.send('hello');
// });
// };

module.exports = function(app) {
var globSync = require('glob').sync;
var mocks = globSync('./mocks/**/*.js', { cwd: __dirname }).map(require);
Expand All @@ -18,5 +9,4 @@ module.exports = function(app) {

mocks.forEach(function(route) { route(app); });
proxies.forEach(function(route) { route(app); });

};

0 comments on commit e10f86c

Please sign in to comment.