Torii Configuration is not being loaded in ember cli - ember.js

I'm having a lot of trouble getting ember simple auth with torii working at all at the moment using Ember CLI.
After creating a new Ember CLI app and installing torii, ember-cli-simple-auth and ember-cli-simple-auth-torii, I have a couple of buttons on my login page
Here is the contents of my routes/login.js:
import Ember from 'ember';
export default Ember.Route.extend({
actions: {
googleLogin: function() {
this.get('session').authenticate('simple-auth-authenticator:torii', 'google-oauth2');
return;
},
facebookLogin: function() {
this.get('session').authenticate('simple-auth-authenticator:torii', 'facebook-oauth2');
return;
}
}
});
The relevant part of my environment.js file is:
var ENV = {
...
torii: {
providers: {
'google-oauth2': {
apiKey: 'api-key-here',
scope: 'profile',
redirectUri: 'http://localhost:4200'
},
'facebook-oauth2': {
apiKey: 'api-key-here',
redirectUri: 'http://localhost:4200'
}
}
},
...
};
When I hit the actions in my login.js, I get the following error:
Error: Expected configuration value providers.facebook-oauth2.apiKey to be defined!
or
Error: Expected configuration value providers.google-oauth2.apiKey to be defined!
Why is torii not picking up my environment.js configuration?

You need to create the app in facebook and google, get the api key and place it where it says:
apiKey: 'api-key-here'
in your environment.js

Turns out my problem was a simple one, the ember serve process needed to be restarted (Ctrl + c, and then re run ember serve).

Related

ember-simple-auth: Persisting session in localstorage using custom authenticator

Setup:
Ember : 2.0.2
Ember Data : 2.0.1
jQuery : 1.11.3
Ember Simple Auth : 1.0.0 (jjAbrams Branch)
Ember CLI : 1.13.8
I'm using pretender to mock a server.
Usecase:
Using a custom authenticator to interface with the server.
Have 2 routes: login, protected (and by default index,application)
When I login with the right credentials, the authenticate method of the authenticator gets called and successfully logs the response object which is passed to resolve().
Observations:
After logging in and being directed to the protected page, Refreshing the protected route (Which has AuthenticatedRouteMixin) leads back to login page.
Localstorage has no values bound to it even after successful login.
Before login: ember_simple_auth:session -> {"authenticated":{}}
restore() method of authenticator never called.
Going to another route from the protected route after auth and coming back goest to login page again.
//authenticators/custom.js
import Ember from 'ember';
import Base from 'ember-simple-auth/authenticators/base';
export default Base.extend({
restore: function (data) {
return new Ember.RSVP.Promise(function (resolve, reject) {
console.log("RESOLVE",data);
if (!Ember.isEmpty(data.token)) {
//TODO Remove log
resolve(data);
} else {
console.log("REJECTING",data);
reject();
}
});
},
authenticate(credentials) {
return new Ember.RSVP.Promise((resolve, reject) =>
Ember.$.ajax({
url: '/token',
type: 'POST',
data: JSON.stringify({
email: credentials.identification,
password: credentials.password
}),
contentType: 'application/json;charset=utf-8',
dataType: 'json'
}).then(function (response) {
Ember.run(function () {
//This logs the expected information
console.log("Response", response, response.token, response.user);
resolve(response);
});
}, function (xhr, status, error) {
console.log("error", error, xhr.responseText);
var response = xhr.responseText;
Ember.run(function () {
reject(response);
});
}));
},
invalidate(token) {
return API.logout(token);
}
});
//environment.js
ENV['ember-simple-auth'] = {
store: 'session-store:local-storage',
routeAfterAuthentication: '/protected'
};
TLDR;
How do I make the session persist?
I got it all working together finally. Ember 2.0 and ESA 1.0
Here are the steps I took:
Create a new ember cli project
Update Ember and ember data values to ^2.0.0 in bower.json Source
Add ESA jjAbrams dep to package.json Source
run npm install && bower install
Gotchas: (This was the original problem which caused the problems described in the question)
If you're upgrading from older versions of ESA, all references to 'simple-auth/..' should be updated to refer 'ember-simple-auth/..' instead..
.. This include imports for authenticators, authorizers, stores, mixins and the Config key in the config/environment.js file.
All this shouldn't be an issue once ESA 1.0 and Ember Cli for Ember 2.0 comes out :)

How to do dependency injection in Ember with Ember CLI?

First, I made a small Ember app without Ember CLI.
I had this piece of code.
window.MyApp = Ember.Application.create({
ready: function() {
this.register('session:current', MyApp.SessionController, { singleton: true });
this.inject('controller', 'session', 'session:current');
}
});
This worked.
Then I decided to rewrite everything from scratch with Ember CLI.
I edited the file app/app.js and added the ready hook just like in my previous version.
var App = Ember.Application.extend({
modulePrefix: config.modulePrefix,
podModulePrefix: config.podModulePrefix,
Resolver: Resolver,
ready: function() {
this.register('session:current', App.SessionController, { singleton: true });
this.inject('controller', 'session', 'session:current');
}
});
This doesn't work.
The session controller does exist. That's the content of the file app/controllers/session.js
export default Ember.Controller.extend({
isLoggedIn: false,
});
The error message I get is
TypeError: Attempting to register an unknown factory: `session:current`
It appears in the browser.
I googled that message, but I found nothing about dependency injection in Ember CLI.
Any idea?
In ember-cli you can use ember generate service <name of service> and ember generate initializer <name of initializer> to build the stubs to achieve this, which is far better than fiddling about with app.js.
You create a service basically like this:
// app/services/notifications.js
import Ember from 'ember';
export default Ember.Object.extend({
initNotifications: function() {
// setup comes here
}.on('init'),
// Implementation snipped, not relevant to the answer.
});
And the initializer, which injects the service into the component(s) of your application which need it:
// app/initializers/notifications-service.js
import Notifications from '../services/notifications';
export default {
name: 'notification-service',
after: 'auth-service',
initialize: function( container, app ) {
app.register( 'notifications:main', Notifications, { singleton: true } );
app.inject( 'component:system-notifications', 'notificationService', 'service:notifications' );
app.inject( 'service:auth', 'notificationService', 'service:notifications' );
}
};
With that, it becomes available as notificationService on the components specified.
Documentation on the subject of dependency injection in Ember can be found at http://emberjs.com/guides/understanding-ember/dependency-injection-and-service-lookup/

How to use a custom authorizer and custom authenticator for ember simple-auth in ember cli

I don't understand how I'm supposed to include my custom authenticator and custom authorizor with ember cli.
Where to put it and what to include and how to do it. The cli example for simple-auth provided unfortunately does not cover custom authorizer and authenticator.
The build is successfully, but when running it in the browser, I get the error
TypeError: SimpleAuth.Authenticators is undefined
I'm aware that I'm doing something wrong, but could you please guide me or point me to the right documentation on how to do this, I can't find anything :(
My initializer looks like this:
import Ember from 'ember';
import CustomAuthenticator from "../models/customauthenticator";
export default {
name : 'authentication',
before : 'simple-auth',
initialize : function(container) {
container.register('authenticator:custom', CustomAuthenticator);
//container.register('authorizer:custom', CustomAuthorizer);
}
};
My authenticator looks like this
import Ember from "ember";
import App from '../app';
import SimpleAuth from "simple-auth/authenticators/base";
App.CustomAuthenticator = SimpleAuth.Authenticators.Base.extend({
tokenEndpoint: '/api/RestUser.php/users/core/access/',
restore: function(data) {
[...]
},
authenticate: function(credentials) {
[...]
},
invalidate: function() {
[...]
}
});
What am I missing? Thanks in advance!
Change that to:
...
import Base from "simple-auth/authenticators/base";
export default Base.extend({
...

BaseURL in Ember CLI application with IE9 support

For my Ember CLI application I want to use a baseURL, as described here. It works very well for the History API, but for the old Hash API it won't work as expected.
My configuration:
module.exports = function(environment) {
var ENV = {
environment: environment,
baseURL: '/base/',
locationType: 'auto',
...
};
...
return ENV;
}
In IE9 i got localhost:4200/#/base/login instead of localhost:4200/base#/login. Going manually to this page results in a blank (white) page.
I found you have to set the router rootUrl as well as the environment baseUrl.
//router.js
import Ember from 'ember';
import config from './config/environment';
let Router = Ember.Router.extend({
location: config.locationType,
rootURL: config.baseURL
});
export default Router;
It's a known issue apparently: http://github.com/stefanpenner/ember-cli/issues/417

EmberCLI app errors when using fixtures

I usually use Rails for my Ember apps. However this time we opted to decouple the API from the Ember app, and as such I'm trying EmberCLI. So far it's lovely to setup and use. However when using attempting to use fixtures it doesn't load the data.
As listed in this post I am using reopenClass when declaring the fixtures.
If I do not override the model, it does not error but the Ember inspector also shows no data was loaded. If I override my file with:
// routes/campaigns/index.js
export default Ember.Route.extend({
model: function() {
return this.store.find('campaign');
}
});
And visit the /campaigns path then I get the error I get the error Error while loading route: undefined.
From what I can find this seems to happen when Ember cannot find the data.
My router and model with obvious items like export default excluded:
// app/router.js
Router.map(function() {
this.resource('campaigns', function() {
});
});
// models/campaign.js
var Campaign = DS.Model.extend({
name: DS.attr('string')
});
Campaign.reopenClass({
FIXTURES: [
{ "id": 1, "name": "Campaign #1" },
{ "id": 2, "name": "Campaign #2" }
]
});
I have tested the same setup in a Rails app I just made, and it works perfectly. I'd love any insight people could give, as EmberCLI seems lightweight and worth the effort.
Edit: Adding my app.js file to answer question about whether I included DS.FixtureAdapter:
// Import statements
Ember.MODEL_FACTORY_INJECTIONS = true;
var App = Ember.Application.extend({
modulePrefix: 'nala', // TODO: loaded via config
Resolver: Resolver
});
loadInitializers(App, 'nala');
App.ApplicationAdapter = DS.FixtureAdapter({});
export default App;
You need to set up your application adapter located at the filepath adapters/application.js as follows:
export default DS.FixtureAdapter.extend({});
See the first paragraph under ember-cli Naming Conventions. N.B. you won't need to import DS or Ember if you're using ember-cli and have them listed in your .jshintrc file.