I'm using Ember simple auth in my app and it's working great, but I've run into a scenario that I'm having trouble getting around.
The library lets you specify the route to redirect to after a successful authentication by overriding routeAfterAuthentication: 'index'. This is working fine, however, I'm finding myself in a situation where I want to have two different types of redirects. When a user first logs in, I want them to go to /dashboard, but when they first sign up and authenticate, I want them to go /settings.
I was hoping to be able to do something like this after successfully creating an account, but it's still trying to use the routeAfterAuthentication option for the transition:
var _this = this;
this.set('identification', _this.get('email'));
this.set('password', password);
this.send('authenticate', function() {
_this.transitionToRoute('settings');
}, function() {});
Is there a way to specify which route to transition to after authenticating on one-off basis? Maybe there's a better way to log someone after they create an account without needing to go through the authenticate() method?
You can simply override the sessionAuthenticated method in the application route and implement your own logic. Beware though that the default implementation will not always transition to routeAfterAuthentication-- if there's a previously intercepted transition stored in the session, sessionAuthenticated will retry that instead.
Related
We have an Ember UI that we're porting to a Single Sign-on provider. This is behind a server-side feature flag such that, when the flag is on, the user is redirected to the SSO provider login portal and, when the flag is off, the user may still login through an Ember route.
I have this functioning with a call to a server endpoint in the Ember Route beforeModel() call. However, since this is an asynchronous call, the page continues rendering before the request returns, the results processed and the browser redirected. Thus, the user can briefly see the old login form before being redirected to the SSO portal. I would prefer that the user only see a blank browser window before the SSO portal is shown.
Is there a way to get the Route beforeModel() method to block on the results of a server call? I tried putting an explicit call to the super.beforeModel() only after the ajax callback has been processed, but Ember doesn't seem to wait for that to finish before proceeding with the rendering.
return Em.Route.extend(/** #lends application.LoginRoute# */{
beforeModel: function() {
var route = this;
return Ember.$.ajax(
'/ws/ssoEnabled',
{'success': function(json) {
Em.Logger.info("[LOGIN ROUTE] SSO Redirect information:", json);
if (json.isSsoEnabled === true) {
Em.Logger.info("[LOGIN ROUTE] Redirecting to", json.ssoRedirectUrl);
window.location.replace(json.ssoRedirectUrl);
return;
}
route._super.beforeModel();
},
'error': function(reason) {
Em.Logger.error("SSO detection failed", reason);
});
},
(Roughly that's what it does; there's some global syntactic sugar helper methods that abstract the Ember.$.ajax call.)
Does the model loading block rendering until loading? I hesitate to experiment because the login pages do not have a model defined, so it would take a bit more new code.
The application is structured somewhat oddly. The Login pages are actually a separate app on Ember v2.4, so I can hook anywhere in the application code without worrying about breaking the actual app. I have tried also hooking into the Application and only calling the Ember.Application.create() method from inside the server call promise resolution. However, it seems that loading the login page components (via RequireJS) at all triggers their render.
do the redirect in the application routes beforeModel hook.
A services init hook is not the right place.
Better call a custom method on your service from the application routes beforeModel hook.
Maybe have a look how ember-simple-auths mixins work.
Ember’s beforeModel hook has been able to block UI rendering since the Ember 1.x era, so it is possible to do what you want.
However, if you are doing jQuery Ajax calls, you’ll need to make sure you are returning a spec-compliant Promise in the hook. jQuery historically did NOT return that type of promise (though that depends on your version of jQuery and the way you call ajax iirc). Worth checking as the behavior you’re describing fits with a non-promise being returned
I use ember-simple-auth to manage authentication in my ember app.
The addon provides a session library which apparently stores the response from API server when I login using token authentication. The response contains typical oAuth2 response like access token, refresh token, expiry time etc. The library provides a boolean variable which tells if the user is authenticated or not currently.
I use an instance initializer which uses this boolean variable to fetch and store current user details. The code looks like this:
// app/instance-initializers/current-user.js
import Session from "ember-simple-auth/services/session";
export default {
name: "current-user",
before: "ember-simple-auth",
initialize: function(container) {
Session.reopen({
setCurrentUser: function() {
if (this.get('isAuthenticated')) {
container.lookup("service:store").find('user', 'me').then((user) => {
this.set('currentUser', user);
});
}
}.observes('isAuthenticated')
});
}
};
This works fine when I login and navigate across different routes in the app. The problem comes when I reload some page. The current user details somehow get erased and this setCurrentUser is also called but it gets called after all the hooks in the current route are called. So in hooks like model, beforeModel, setupController etc. session.currentUser is not set and it is set only after all these hooks are called.
How to avoid this? How to make the current user details available in route hooks on page reload?
New Answer
Completely ignore the below answer for now. Try to change your initializer to only fire after ember-simple-auth, like below:
// app/instance-initializers/current-user.js
import Session from "ember-simple-auth/services/session";
export default {
name: "current-user",
after: "ember-simple-auth",
Have a look at this part of the docs, some more information there regarding the initializer, and the let me know if you are using the following route mixin:
import ApplicationRouteMixin from 'ember-simple-auth/mixins/application-route-mixin';
Previous Answer
I recommend you read through the session stores in the readme and try switch between session stores temporarily to see if that fixes your problem. Otherwise implement your own custom session store with local storage to make sure the persist & restore hooks work like expected.
The object you'll extend in that case looks like this(copied from readme):
// app/session-stores/application.js
import Base from 'ember-simple-auth/session-stores/base';
export default Base.extend({
persist() {
…
},
restore() {
…
}
});
The page to login to our application is a jsp hosted on another machine. I have managed to get requests firing to this machine by modifying authenticated-route-mixin by allowing window.location.replace to be called if the route start with http.
beforeModel(transition) {
if (!this.get('session.isAuthenticated')) {
Ember.assert('The route configured as Configuration.authenticationRoute cannot implement the AuthenticatedRouteMixin mixin as that leads to an infinite transitioning loop!', this.get('routeName') !== Configuration.authenticationRoute);
transition.abort();
this.set('session.attemptedTransition', transition);
debugger;
if (Configuration.authenticationRoute.startsWith('http')) {
window.location.replace(Configuration.authenticationRoute);
} else {
this.transitionTo(Configuration.authenticationRoute);
}
} else {
return this._super(...arguments);
}
}
This is working but when I am redirected back to my application, ember-simple-auth thinks I am no longer logged in and redirects be back to the remote machine, which then sends me back to the application in an infinite loop.
Obviously I need to set something to let ember-simple-auth know that it it is actually logged in. Why is it not doing this automatically? What am I doing wrong?
I am pretty new to oAuth so I could be missing some basic setting here.
Here is the URL.
ENV['ember-simple-auth'] = {
authenticationRoute: 'https://our-server.com/opensso/oauth2/authorize?client_id=test-client-1&response_type=code&redirect_uri=http%3A%2F%2Flocalhost%3A4200%2Fsecure'
};
Instead of modifying the AuthenticatedRouteMixin, I'd recommend handling your app-specific login in an Authenticator-- the key configuration primitive that Ember Simple Auth provides as part of its public API.
To the best of my understanding, on first loading the app, and checking to see if a user is authenticated, Ember Simple Auth will use the restore method, defined as part of the Authenticator API.
You can return a promise from restore that resolves or rejects to indicate whether the user is authenticated. How you check this is an implementation detail of your auth system.
I don't know how you're storing credential(s) on the client (would be great if you could provide more detail), but here's an example flow, using cookies for authentication:
Ember boots, ESA attempts to restore the session.
restore makes a simple AJAX request to a secured, "dummy" resource on your Java server-- and checks if it gets back a 200 or a 401.
We get a 401 back. The user isn't authenticated, so reject in the Promise returned from restore.
Let ESA redirect the user to your authentication route. Ideally, don't override the AuthenticatedRouteMixin-- instead, use the beforeModel hook in the authentication route to send users to your JSP login page.
The user correctly authenticates against the JSP form.
In its response, your Java server sets some kind of encrypted, signed session cookie (this is how it generally works with Rails) as a credential. In addition, it sends a redirect back to your Ember app.
Ember boots again, ESA calls restore again.
restore pings your Java server again, gets a 200 back (thanks to the cookie), and thus resolves its Promise.
ESA learns that the user's authenticated, and redirects to the 'route after authentication'.
Keep in mind that, at its core, ESA can only indicate to the client whether the backend considers it 'authenticated' or not. ESA can never be used to deny access to a resource-- only to show something different on the client, based on the last thing it heard from the backend.
Let me know if any of that was helpful.
I need to modify adaptive.js in ember-simple-auth for my app.
Ultimately I want the restore method to look for two particular cookie security tokens that is shared across our platforms and construct the simple auth localstorage object based on these cookies as a last resort if localStorage authentication data does not already exist in order to determine if the user is already authenticated.
I realise you can create a custom authenticator however the problem with extending Base is that when restore is called on your custom authorizer ember-simple-auth has already looked up localstorage for your auth data. If this isn't available restore never gets called. For this reason I believe I need to extend or modify the simple auth node module to my requirements.
Below is my simple attempt at trying to modify adaptive.js in ember-simple-auth within my app however when restore gets called it's never through the below:
import AdaptiveStore from 'ember-simple-auth/session-stores/adaptive';
AdaptiveStore.reopenClass({
restore(){
alert('do custom stuff here');
}
});
Using reopen worked for me:
import AdaptiveStore from 'ember-simple-auth/session-stores/adaptive';
export default AdaptiveStore.reopen({
restore(){
alert('do custom stuff here');
}
});
I have an app that you can only get in if you are log in. I would like to do a redirection after the user is log but, only if he tried to access a page from the website.
Example :
The user receive this link in his email :
http://mywebsite.com/#/enquiry/1
When he click on it, it will be redirected on the login form because he's not log in. But just after the log in is good he is automatically redirected to this last link.
I already have the redirect from anywhere to the login form if he is not log but I have no idea how to save the URL and go back there again..
I used the redirection like this :
App.MyRoute = Ember.Route.extend({
redirect: function() {
if ( not log in ) {
// TransitionToLogin
}
}
});
Someone know how I can achieve this ?
Thank you !
Quick explanation if you're familiar with ember and routing:
You can do this by using the beforeModel(transition) { ... } hook on the route to see if you are logged in. If you're not logged in, stash the transition variable somewhere, temporarily transition to your login route, then when you've successfully authenticated, .retry() the stored previous transition.
Make sure bullet proof this, as your auth code is pretty "global" on your site. Handle the case where the user goes straight to login, and thus the login route doesn't have a stashed transition available. Also handle weird cases, like if they go to the login page twice, by cleaning up your temp storage for the transition before you call .retry() on it.
An alternative, use Torii:
If you don't want to build this yourself and have to copy this code on all your protected routes, then the Torii authentication library has support for this already, using their protected route mapping function. Once you've got your session and provider set up, you simply use the this.authenticatedRoute('my-protected-route'); route mapping function instead of the normal this.route('my-route'); that you've already been using.
The Torii docs are a little challenging to get through, but once you've figured them out, that library is very useful in getting up and running quickly with multiple authentication mechanisms. It is very little work to start supporting both an email/password and a Facebook login, for example. I recommend checking it out.
Non-Torii code sample:
If you just want to use vanilla Ember, and implement this yourself, I'd provide a code sample for your example, but as ppcano mentioned in comments, this is covered in the documentation. Here's the corresponding text from the docs. It covers everything I mentioned above in the quick explanation.
STORING AND RETRYING A TRANSITION
Aborted transitions can be retried at a later time. A common use case for this is having an authenticated route redirect the user to a login page, and then redirecting them back to the authenticated route once they've logged in.
// app/routes/some-authenticated.js
export default Ember.Route.extend({
beforeModel(transition) {
if (!this.controllerFor('auth').get('userIsLoggedIn')) {
var loginController = this.controllerFor('login');
loginController.set('previousTransition', transition);
this.transitionTo('login');
}
}
});
// app/controllers/login.js
export default Ember.Controller.extend({
actions: {
login() {
// Log the user in, then reattempt previous transition if it exists.
var previousTransition = this.get('previousTransition');
if (previousTransition) {
this.set('previousTransition', null);
previousTransition.retry();
} else {
// Default back to homepage
this.transitionToRoute('index');
}
}
}
});
If you are using ember-simple-auth, then take a look at AuthenticatedRouteMixin, it forces authentication before transitioning to the target route.
It also takes care of redirecting to the previous URL after authentication.
If you are using this mixin and also overriding sessionAuthenticated(), then make sure you have this._super(...arguments); in sessionAuthenticated() to preserve the redirection logic.