Skip to content

Commit

Permalink
inital commit
Browse files Browse the repository at this point in the history
  • Loading branch information
Dani723 committed Feb 23, 2015
0 parents commit 7e05a30
Show file tree
Hide file tree
Showing 4 changed files with 373 additions and 0 deletions.
19 changes: 19 additions & 0 deletions LICENSE.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
Copyright (c) n-fuse GmbH and other contributors.

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
49 changes: 49 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
# token-authn

Allows OAuth 2 token based user log-in and log-out against an Invend API.

### Installation
```
jspm install github:n-fuse/token-authn
```

### Usage

```
import TokenAuthN from 'token-authn';
var authN = new TokenAuthN(oAuthURL);
authN.login(username, password, rememberMe).then(...);
authN.logout().then(...);
authN.tokenInfo; // Contains access and refresh token
```

### Additional information

Stores a token info object in local storage under the following key:
'oAuthURL + _ + tokenInfo'.

All API operations are promise based.

On initialization:
- See if persisted token info exists in local storage and read token info
- See if the 'access_token' is not expired yet
- If it is, see if a refresh token exists an use it to get a new access token
- If it fails, the promise rejects

On successful authentication:
- Persist the token info
- If 'remember me' has not been requested, persist anyways but
omit the refresh token as this is only relevant in case of a browser crash

On log-out:
- Perform DELETE against token end-point to invalidate the session
- Delete any persisted token info from local storage


### License

[MIT license](LICENSE.txt)
31 changes: 31 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
{
"name": "token-authn",
"version": "0.1.0",
"keywords": ["token", "authentication"],
"main": "token-authn.js",
"author": {
"name": "n-fuse GmbH",
"email": "info@n-fuse.de",
"url": "www.n-fuse.de"
},
"contributors": [],
"license": {
"type": "MIT"
},
"repository": {
"type": "git",
"url": "git://github.com/n-fuse/token-authn"
},
"jspm": {
"registry": "jspm",
"dependencies": {
"log": "github:n-fuse/holzfella",
"pajax": "github:n-fuse/pajax",
"moment": "^2.9.0",
"lodash": "^3.2.0",
"state-machine": "github:jakesgordon/javascript-state-machine",
"store": "npm:store@^1.3.17"
},
"format": "es6"
}
}
274 changes: 274 additions & 0 deletions token-authn.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,274 @@
import { default as PAjax, parseIRI } from 'pajax';
import _clone from 'lodash/lang/clone';
import store from 'store';
import StateMachine from 'state-machine';
import log from 'log';
import moment from 'moment';

class TokenAuthN {
constructor(oAuthURL) {
this.oAuthURL = oAuthURL;
this.loginAjax = new PAjax({
contentType: 'application/x-www-form-urlencoded',
responseType: 'json',
headers: {
Accept: 'application/json'
}
});

this.logoutAjax = new PAjax('json-ld');
this.logoutAjax.use(this);

StateMachine.create({
target: this,
initial: 'unkown',
events: [
{ name: 'useToken', from: ['loggedOut', 'unkown'], to: 'loggingIn' },
{ name: 'useCredentials', from: ['loggedOut', 'unkown'], to: 'loggingIn' },
{ name: 'tokenValid', from: '*', to: 'loggedIn' },
{ name: 'tokenExpired', from: '*', to: 'loggedOut' },
{ name: 'tokenInvalidated', from: '*', to: 'loggedOut' }
]
});

// Validate saved token when initializing
this.promise = new Promise((resolve, reject) => {
var p;

var tokenInfo = this.readToken();
if (tokenInfo && tokenInfo.accessTokenExp) {
this.useToken();

var now = moment();
if (now.isBefore(tokenInfo.accessTokenExp)) {
// Access token exists and is still valid
this.tokenInfo = tokenInfo;
this.tokenValid();
if(tokenInfo.refreshToken) {
this.scheduleTokenRefresh();
}
} else if (tokenInfo.refreshToken) { // Refresh token exists
// Try to get a new access token
p = this.tryTokenRefresh(tokenInfo);
} else {
this.tokenExpired();
}
} else {
this.tokenInvalidated();
}
resolve(p);
});
}

on(event, cb) {
this._handlers = this._handlers || {};
this._handlers[event] = this._handlers[event] || [];
this._handlers[event].push(cb);
}

trigger(event, data) {
if(this._handlers && this._handlers[event]) {
this._handlers[event].forEach(cb=> {
cb(data);
});
}
}

get loggedIn() {
return this.current === 'loggedIn';
}

get username() {
return this.tokenInfo ? this.tokenInfo.username : null;
}

onenterstate() {
log.debug(`${this.oAuthURL}: authN state changed to "${this.current}"`);
this.trigger('stateChanged', this.current);
}
ontokenExpired() {
this.tokenInfo = null;
}

ontokenInvalidated() {
this.tokenInfo = null;
}

login(username, password, rememberMe) {
var self = this;

this.useCredentials();

return this.loginAjax.post(this.oAuthURL, {
'grant_type': 'password',
'password': password,
'username': username
},
{
repsonseType: 'json'
}).then(function(data) {
var now = moment();
var accessTokenExp = now.add(data.expires_in, 'seconds');

self.tokenInfo = {
username: username,
rememberMe: rememberMe,
accessToken: data.access_token,
accessTokenExp: accessTokenExp,
refreshToken: data.refresh_token
};
self.tokenValid();
self.scheduleTokenRefresh(25);
self.saveToken();
}).catch( function(err) {
self.tokenInvalidated();
return Promise.reject(err);
});
}

logout() {
var self = this;
var tokenInfo = this.tokenInfo;
if(!tokenInfo || !tokenInfo.accessToken) {
log.warn('No access token found');
}

this.unSchedule();

var invalidate = function() {
self.tokenInvalidated();
self.clearToken(); // Delete ´remember me´ data
};

// delete token regardless of the outcome
return this.logoutAjax.del(this.oAuthURL).then(invalidate, invalidate);
}

/* ------------- Token operations (internal) ------------ */
/**
@private
*/
tryTokenRefresh(tokenInfo) {
var self = this;

tokenInfo = tokenInfo || this.tokenInfo || {};

if(!tokenInfo.refreshToken) {
log.debug('No refresh token found');
return Promise.resolve();
}

return this.loginAjax.post(this.oAuthURL, {
grant_type: 'refresh_token',
client_id: 'res_owner@invend.eu',
client_secret: 'res_owner',
refresh_token: tokenInfo.refreshToken
}).then(function(data) {
var now = moment();
var accessTokenExp = now.add(data.expires_in, 'seconds');

tokenInfo.accessToken = data.access_token;
tokenInfo.accessTokenExp = accessTokenExp;
tokenInfo.refreshToken = data.refresh_token;

self.tokenInfo = tokenInfo;
self.saveToken();
// Schedule token refresh trial 25 min before expiration
self.scheduleTokenRefresh();
self.tokenValid();

log.debug(this.oAuthURL + ': authN token refreshed');
}).catch(function(err) {
self.tokenExpired();
log.error('Token refresh error', err);
// Only retry if we have a non-auth error
if (!(err.status === 400 || err.status === 401)) {
// Schedule retry token refresh in 5 min from now
self.refreshTimeoutFn = setTimeout(function() {
self.tryTokenRefresh();
}, 300 * 1000);
}
});
}

// Schedule token refresh and logout timers
/**
@private
*/
scheduleTokenRefresh(expiryDistance) {
var self = this;

expiryDistance = expiryDistance || 25;

var tokenInfo = this.tokenInfo;

this.unSchedule();

var accessTokenExp = tokenInfo.accessTokenExp;
var timeOutMilis;
var accessTokenExpOffset;

// Schedule token refresh in ´expiry date´ - ´expiryDistance min´
accessTokenExpOffset = moment(accessTokenExp).subtract(expiryDistance, 'minutes');
timeOutMilis = accessTokenExpOffset.diff(moment());
this.refreshTimeoutFn = setTimeout(function() {
self.tryTokenRefresh();
}, timeOutMilis);

// Schedule logout state shortly before the token expires
accessTokenExpOffset = moment(accessTokenExp).subtract(5, 'seconds');
timeOutMilis = accessTokenExpOffset.diff(moment());
this.expireTimeoutFn = setTimeout(function() {
self.tokenExpired();
}, timeOutMilis);
}

unSchedule() {
clearTimeout(this.refreshTimeoutFn); // Stop automatic token refresh
clearTimeout(this.expireTimeoutFn); // Stop automatic logout
}

readToken() {
return store.get(this.oAuthURL + '_tokenInfo');
}

clearToken(){
store.remove(this.oAuthURL + '_tokenInfo');
}

saveToken() {
var tokenInfo = this.tokenInfo;
if(tokenInfo) {
var tkiClone = _clone(tokenInfo);
// Don't persist the refresh token if the user wishes not to be remembered
if (!tokenInfo.rememberMe) {
tkiClone.refreshToken = null;
}
store.set(this.oAuthURL + '_tokenInfo', tkiClone);
}
}

// Inject the l10n info to the ajax as soon as it is available
beforeSend(req, xhr) {
if(parseIRI(req.url).hostname===parseIRI(this.oAuthURL).hostname) {
return this.promise.then(() => {
var tokenInfo = this.tokenInfo;
if (tokenInfo && tokenInfo.accessToken) {
xhr.setRequestHeader('Authorization', 'Bearer ' + tokenInfo.accessToken);
}
});
}
}

afterSend(req, xhr, result) {
// delete token when 40? invalid token
if(result.status===401) {
// TODO: Not sure if needed
this.tokenInvalidated();
this.clearToken(); // Delete ´remember me´ data
}
}
}


export default TokenAuthN;

0 comments on commit 7e05a30

Please sign in to comment.