Skip to content

Instantly share code, notes, and snippets.

@code0100fun
Created June 8, 2015 20:02
Show Gist options
  • Star 30 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save code0100fun/f9b99b2a562702683602 to your computer and use it in GitHub Desktop.
Save code0100fun/f9b99b2a562702683602 to your computer and use it in GitHub Desktop.
Ember Simple AUth + Ember CLI Mirage
// app/controllers/sign-in.js
import Ember from 'ember';
export default Ember.Controller.extend({
actions: {
signIn(){
this.set('errors', null);
var params = { identification: this.get('email'), password: this.get('password') };
// Redirects to index route on success (configurable in config/environment.js)
this.get('session').authenticate('simple-auth-authenticator:oauth2-password-grant', params);
}
},
});
// app/initializers/session.js
import Ember from 'ember';
import Session from 'simple-auth/session';
export function initialize(container) {
Session.reopen({
currentUser: Ember.computed('isAuthenticated', function() {
if(this.get('isAuthenticated')){
// triggers API call to /api/v1/users/current
return container.lookup('store:main').find('user', 'current');
}
})
});
}
export default {
name: 'session',
before: 'simple-auth',
initialize: initialize
};
// app/mirage/config.js
import Mirage from 'ember-cli-mirage';
export default function() {
this.get('/api/v1/users/current', function(db, request){
if(request.requestHeaders.Authorization === "Bearer PA$$WORD") {
return { user: { id: 1, firstName: 'Chase', lastName: 'McCarthy' } };
}else{
return new Mirage.Response(401, {}, {});
}
});
function formEncodedToJson(encoded) {
var result = {};
encoded.split("&").forEach(function(part) {
var item = part.split("=");
result[item[0]] = decodeURIComponent(item[1]);
});
return result;
}
this.post('/token', function(db, request){
var params = formEncodedToJson(request.requestBody);
if(params.username === "user@email.com" && params.password === "secret") {
return {
"access_token":"PA$$WORD",
"token_type":"bearer"
};
}else{
var body = { errors: 'Email or password is invalid' };
return new Mirage.Response(401, {}, body);
}
});
}
// app/routes/application.js
import Ember from 'ember';
import ApplicationRouteMixin from 'simple-auth/mixins/application-route-mixin';
export default Ember.Route.extend(ApplicationRouteMixin, {
model(){
// If the user is already signed in this fetches the current user from the server
return this.get('session.currentUser');
}
});
@taras
Copy link

taras commented Jun 12, 2015

Your example looks really interesting. What use case does it solve?

@constantm
Copy link

Awesome! Was just wondering if there was a way to simulate auth with Mirage.

@wayne-o
Copy link

wayne-o commented Oct 1, 2015

👍

@themmer
Copy link

themmer commented Nov 11, 2016

👍

@ricardopsilva
Copy link

Amazing integration. With Ember-cli-mirage I can mock all necessary authentication stuff in my poc's at a drop of the hat! Thank you for sharing the solution!

@allthesignals
Copy link

This doesn't seem to work anymore. Try:

// app/initializers/session.js

import Ember from 'ember';
import SessionService from 'ember-simple-auth/services/session';

export function initialize(container) {
  SessionService.reopen({
    currentUser: Ember.computed('isAuthenticated', function() {
      if(this.get('isAuthenticated')){
        // triggers API call to /api/v1/users/current
        return container.lookup('store:main').find('user', 'current');
      }
    })
  });
}

export default {
  name: 'session',
  before: 'ember-simple-auth',
  initialize: initialize
};

@knownasilya
Copy link

knownasilya commented Jan 18, 2017

I do something like:

// app/services/session.js

import Ember from 'ember';
import SessionService from 'ember-simple-auth/services/session';

const { inject } = Ember;

export default SessionService.extend({
  modelStore: inject.service('store'),
 
  init() {
    this._super(...arguments);
    this.addObserver('isAuthenticated', () => {
      this.populateCurrentUser();
    }); 
  },

  populateCurrentUser() {
    //decode token, and fetch the user using `modelStore`, set on self..
  }  
});

@buckmaxwell
Copy link

@knownasilya thanks for the tip! I am using a version of your code, but my currentUser is not being populated in time -- the currentUser is not available immediately after login (to display user info on the index page), but only after a refresh of the page. Any thoughts on how to fix that?

@scottkidder
Copy link

@woosungchu
Copy link

👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment