Skip to content

Instantly share code, notes, and snippets.

@jordpo
Last active February 22, 2017 00:01
Show Gist options
  • Save jordpo/b19a16928b3435215d5a to your computer and use it in GitHub Desktop.
Save jordpo/b19a16928b3435215d5a to your computer and use it in GitHub Desktop.
IcarusWorks - Single Sign On with Ember.js
// addon/services/ajax.js
// ensure custom ajax requests have the appropriate authorization headers when signed in
import Ember from 'ember';
import AjaxService from 'ember-ajax/services/ajax';
const {
computed,
inject,
get
} = Ember;
export default AjaxService.extend({
session: inject.service(),
headers: computed({
get() {
let headers = {};
get(this, 'session').authorize('authorizer:application', (headerName, headerValue) => {
headers[headerName] = headerValue;
});
return headers;
}
})
});
// app/authorizers/application.js
import OAuth2Bearer from 'ember-simple-auth/authorizers/oauth2-bearer';
export default OAuth2Bearer.extend();
// config/environment.js
// simple-auth configuration for authentication
ENV['ember-simple-auth'] = {
authenticationRoute: 'auth.login',
routeAfterAuthentication: 'dashboard',
routeIfAlreadyAuthenticated: 'dashboard'
};
// app/authenticators/oauth2.js
import OAuth2PasswordGrant from 'ember-simple-auth/authenticators/oauth2-password-grant';
import config from '../config/environment';
export default OAuth2PasswordGrant.extend({
serverTokenEndpoint: `${config.API_NAMESPACE}/core/oauth/token`
});
import Ember from 'ember';
const {
computed,
inject,
get,
set
} = Ember;
export default Ember.Service.extend({
session: inject.service(),
store: inject.service(),
accountId: computed.readOnly('session.data.authenticated.user_id'),
account: computed('accountId', function() {
if (get(this, 'accountId')) {
return get(this, 'store').findRecord('user-account', get(this, 'accountId'));
} else {
return get(this, 'store').createRecord('user-account');
}
}),
register() {
return get(this, 'account').save().then(() => {
const email = get(this, 'account.email');
const password = get(this, 'account.password');
// protect sensitive data
set(this, 'account.password', null);
return this.login(email, password);
});
},
login(email, password) {
return get(this, 'session').authenticate('authenticator:oauth2', email, password);
},
logout() {
// remove all cached data from store on logout
get(this, 'store').unloadAll();
return get(this, 'session').invalidate();
},
});
// app/session-stores/application.js
import Cookie from 'ember-simple-auth/session-stores/cookie';
import config from '../config/environment';
const oneMonth = 32 * 24 * 60 * 60;
export default Cookie.extend({
// set an explicit expiration time so session does not expire when window is closed
cookieExpirationTime: oneMonth,
cookieDomain: `.${config.APP.DOMAIN}`
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment