Folks,
I've been trying to get ESA to redirect to specific pages after login and logout events without success.
I'm trying to do this by overriding the "sessionAuthenticated" method, but have also tried setting the "routeAfterConfiguration" setting with no luck.
At the moment, login sends me to "/", and logout sends the app to "/undefined".
I'm using simple-auth-token as a JWT authenticator strategy.
The code for my application route looks like this...
import Ember from 'ember';
import ApplicationRouteMixin from 'ember-simple-auth/mixins/application-route-mixin';
export default Ember.Route.extend(ApplicationRouteMixin,{
actions: {
sessionAuthenticated: function() {
console.log('sessionAuthenticated: authentications ok');
window.location.replace('/profile');
},
},
});
My login.js is as follows:
import Ember from 'ember';
const {service} = Ember.inject;
export default Ember.Route.extend({
session: service('session'),
errorMessage: null,
model: function(){
return Ember.Object.create({
identification:'',
password: '',
errorMessage: this.get('errorMessage')
});
},
setupController: function(controller, model) {
controller.set('credentials',model);
},
actions: {
authenticate: function(credentials) {
console.log(credentials);
this.get('session').authenticate('simple-auth-authenticator:jwt', credentials)
.catch((reason) => {
console.log('Login Error');
credentials.set('errorMessage', reason);
});
},
},
});
Does anyone have any idea what I might be doing wrong here?
Cheers,
Andy
OK. Found the problem. These are not actions - they're methods. So I just had to promote the methods out of the actions object and it's all come good.
So the correct routes/application.js looks like this:
import Ember from 'ember';
import ApplicationRouteMixin from 'ember-simple-auth/mixins/application-route-mixin';
export default Ember.Route.extend(ApplicationRouteMixin,{
sessionAuthenticated: function() {
console.log('sessionAuthenticated: authentications ok');
window.location.replace('/profile');
},
});
Related
When I refresh the index page of my ember app, it appears that I can't call the functions inside my index.js file located in app/routes.
I don't really know how I can solve this issue.
The source code of index.js:
import Ember from 'ember';
import ProjectRoute from 'web/project-route';
export default ProjectRoute.extend({
authSrv: Ember.inject.service('authentication'),
_title: 'index.title',
_requireAuth: true,
beforeModel()
{
"use strict";
this._super();
},
model()
{
"use strict";
console.log(this.get('authSrv').username);
return {user_id: this.get('authSrv').user_id,
username: this.get('authSrv').username};
}
});
In the code source above we can see that I try to display the username. When I first log onto this page, it display well, but when I refresh the page, it doesn't display anything.
Any thought about it is welcomed!
So I fixed it with the Ember module RSVP. Basically, the main problem was coming from a promise. I didn't waited to catch the promise.
The index.js look like this know.
import Ember from 'ember';
import ProjectRoute from 'web/project-route';
export default ProjectRoute.extend({
authSrv: Ember.inject.service('authentication'),
_title: 'index.title',
_requireAuth: true,
beforeModel()
{
"use strict";
this._super();
},
model()
{
"use strict";
let promise = new Ember.RSVP.Promise((resolve, reject) =>
{
this.get('authSrv').get('current_auth').promise.then((res) =>
{
resolve({user_id: this.get('authSrv').user_id,
username: this.get('authSrv').username});
});
});
return promise;
}
});
I've done
ember g route auth
ember g route auth/pending
Which then gave me :
app/
routes/
auth/
pending.js
auth.js
and my router has
this.route('auth', function() {
this.route('pending', { path: '/pending/:steamid/:token'});
});
Which everything is fine, when I visit
http://localhost:4200/auth/pending/1/2
The page loads, but how do I access :steamid and :token outside of the model.
I'd like to use it so that I can set values in my session service
Like:
import Ember from 'ember';
export default Ember.Route.extend({
session: Ember.inject.service(),
steamID: this.get(// Params Some How),
token: this.get(// Params some How)
thing(params) {
this.get('session').set('tokenID', token),
this.get('session').set('steamID', steamID)
}
});
^^ Pseudo code to express what I'm trying to accomplish.
While it's not in the website documentation, looking at the source code of the Transition object passed to some Route hooks (e.g. afterModel and beforeModel) it have a params property which contains the dynamic segment params.
So you can, for example:
import Ember from 'ember';
export default Ember.Route.extend({
session: Ember.inject.service(),
thing(params) {
// Do some check and returns the result
},
beforeModel (transition) {
if (!this.thing(transition.params)) {
transition.abort();
this.transitionTo('/login');
}
}
});
You can set them in your service from many different hooks:
import Ember from 'ember';
export default Ember.Route.extend({
session: Ember.inject.service(),
/* Access from beforeModel */
beforeModel(transition) {
this.get('session').setProperties({
tokenID: transition.params.token,
steamID: transition.params.steamid
});
},
/* Access from model */
model(params, transition) {
this.get('session').setProperties({
tokenID: params.token,
steamID: params.steamid
});
}
});
If you ask me model hook is the best choice. Especially if you want your query params to refresh the model every time they change (see guide).
My authenticators/custom.js:
import Ember from 'ember';
import Base from 'simple-auth/authenticators/base';
export default Base.extend({
restore: function(data) {
},
authenticate: function(email, password, authenticateCallback) {
return new Ember.RSVP.Promise((resolve, reject) => {
Ember.$.ajax({
type: 'POST',
url: apiOrigin + '/api/v1/login',
data: {
email: email,
password: password
},
dataType: 'json'
}).then(function(userData){
console.log('login post success', userData)
authenticateCallback(userData)
Ember.run(function() {
resolve(userData.uuid)
})
})['catch'](function(main){
alert('login error ' + JSON.stringify(main))
console.error('\'caught\' error from login post request', arguments);
})
})
},
invalidate: function(data) {
}
});
And login/controller.js:
import Ember from 'ember';
export default Ember.Controller.extend({
session: Ember.inject.service('session'),
application: Ember.inject.controller(),
actions: {
authenticate() {
let { identification, password } = this.getProperties('identification', 'password');
this.get('session').authenticate('authenticator:custom', identification, password, (userData) => {
//TODO set these properties on ember-simple-auth's session object instead of application controller
this.get('application').setProperties(userData)
this.transitionToRoute('associate-device')
}).catch((reason) => {
this.set('errorMessage', reason.error);
})
}
}
});
My associate-device route is an AuthenticatedRoute.. I don't get an error, but instead, the last thing printed to the console is "Preparing to transition from 'login' to 'associate-device'"
Basically, ember simple auth documents here http://ember-simple-auth.com/api/classes/BaseAuthenticator.html#method_authenticate that "A resolving promise will result in the session becoming authenticated. Any data the promise resolves with will be saved in and accessible via the session service's data.authenticated property (see data). A rejecting promise indicates that authentication failed and will result in the session remaining unauthenticated."
However, my session does not seem to be authenticated after I successfully resolve my promise.
$.ajax has no catch method. This exception was hidden because I was copy-pasting away from the documentation for writing custom authenticators. To expose any exceptions occurring in your custom authenticators authenticate method, you should probably console.log them like so:
// app/controllers/login.js
import Ember from 'ember';
export default Ember.Controller.extend({
session: Ember.inject.service('session'),
actions: {
authenticate() {
let { identification, password } = this.getProperties('identification', 'password');
this.get('session').authenticate('authenticator:oauth2', identification, password).catch((reason) => {
// **CHANGE THE BELOW LINE**
console.error('exception in your authenticators authenticate method', reason)
});
}
}
});
I'm trying to implement custom auth with ember-simple-auth and I stuck at the start. I have app/autheticators/digest.js
import Base from 'ember-simple-auth/authenticators/base';
import Ember from 'ember';
export default Base.extend({
restore(data) {
//
},
authenticate(email, password) {
console.log(email, password);
return new Ember.RSVP.Promise(function(resolve, reject) {
Ember.run(function() {
resolve({email: email, password: password});
});
});
},
invalidate(data) {
//
}
});
app/authorizers/digest.js
import Base from 'simple-auth/authorizers/base';
import Ember from 'ember';
export default Base.extend({
header: function() {
return "test-digest";
},
authorize: function(sessionData, block) {
console.log('authorize...');
block('Authorization', this.get('header'));
}
});
Login component:
import Ember from 'ember';
import CryptoJS from 'npm:crypto-js';
export default Ember.Component.extend({
session: Ember.inject.service('session'),
actions: {
login() {
let { email, password } = this.getProperties('email', 'password');
this.get("session").authenticate('autheticator:digest',
email, CryptoJS.SHA256(password).toString()).catch((reason) => {
this.set('errorMessage', reason.error);
});
}
}
});
Authentication called properly (I hope), but "authorize" in authorizer never called. I also tried add some values to ENV:
ENV['simple-auth'] = {
authorizer: 'authorizer:digest',
crossOriginWhitelist: ['http://prod-drunkedguru.rhcloud.com:80/'] // ['*'] I also tried
};
But nothing changed. What I'm doing wrong?
P.S. I'm using EmberJS 1.13.0 with EAS 1.0.
I assume you're using ESA 1.0. In that version the authorizer isn't automatically called anymore but you need to call it manually. There is the DataAdapterMixin that you can use to automatically authorizer Ember Data requests though. See this blog post for guidance on migrating to 1.0: http://log.simplabs.com/post/131698328145/updating-to-ember-simple-auth-10
ember-cli 0.2.7
ember 1.13-beta2
Im trying to setup a component to handle overlays in my webapp. I want to be able to open this overlay from across the application but I'm having trouble figuring out how to do so. Here is what I got.
It seems like ember doesn't recognise the service though. Any help greatly appreciated!
The service
import Ember from 'ember';
export default Ember.Service.extend(Ember.Evented, {
publish: function() {
return this.trigger.apply(this, arguments);
},
subscribe: function() {
this.on.apply(this, arguments);
},
unsubscribe: function() {
this.off.apply(this, arguments);
}
});
The navigation component
import Ember from 'ember';
export default Ember.Component.extend({
tagName: 'nav',
classNames: ['l-navigation'],
events: Ember.inject.service('event-bus'),
actions: {
openDashboard: function() {
this.get('events').publish('dashboard:open');
}
}
});
And then the 'overlay' component
import Ember from 'ember';
export default Ember.Component.extend({
tagName: 'section',
classNames: ['l-dashboard'],
events: Ember.inject.service('event-bus'),
init: function() {
this.get('events').subscribe('dashboard:open', this, 'openDashboard');
},
openDashboard: function() {
alert('opening dashboard');
}
});
EDIT - By popular demand :-)
Here is the jsbin for the issue. http://emberjs.jsbin.com/cesotamuza/1/