Transition back to origin route - javascript

So. I have a very simple problem, that should have a simple solution. I'm just not seeing it.
In my ember app, I have a login route, and a link to this in the header. You click this, and get to a login form. When successfully logged in, I want to go back to the route displayed before the login form.
Something like the following url sequence
/post/209 - user clicks login
/login - user provides credentials, submits, and
/post/209 - is displayed

I haven't tried this out and this may not be the most elegant solution, but could you not simply do window.history.back() and the Router will take care of the rest?

To answer my own question, you can use the didTransition hook on Router, like this
App.Router.reopen({
didTransition: function(infos) {
this._super(infos);
var currentRoute = infos[infos.length - 1];
this.send('routeChanged', {
route: currentRoute.name,
context: currentRoute.context
});
}
});
infos contains an array of the active routes after transitioning. E.g. transition to PostEdit, the active routes will be
infos[0].name = 'application'
infos[1].name = 'post'
infos[2].name = 'post.edit'
In my application i catch the routeChanged event in ApplicationRoute, and keep a stack of the last ones in ApplicationController. The second entry in this stack is used to transition to the previous route.

Login page link should be a GET request with a link to the previous page.
like the following Ex, twitter
https://twitter.com/login?redirect_after_login=%2FitsWillyFerrell%2Ffollowers
Observe the redirect_after_login field is pointing to the username of the persons page I came from, so you have a place to go to once after login.

Related

Best approach/design to web application?

I have been taking a Node.js course on Udemy and would like to apply some of the knowledge I have gained to create a simple web application. I would like to have a user register, which leads him to an admin panel, this part I already have.
This user (requester) can then refer users (invitees) to this website using a unique link. For example he would click a button to generate a unique hyperlink (my idea for this link was to be the http://websiteurl/userid of the requester who is sending the link).
The requester can then send this link through email to their friends to invite them to the website, once they click the link they are taken to a sign up form and when they fill in the form they are linked (added to an array under the original user).
How would I go about setting up this "session", as in make sure that the form that the invitees fill out is linked to the original requester? How can those forms be generated dynamically on the requester's hyperlink?
I'm not looking for the exact code to do this, but rather validation if my idea for the url is a good approach or if there are other approaches I should consider.
Thanks in advance!
Well, this would require you changing the schema for your database. A user will need to have a property like:
{
referred: []
}
The referred array should contain ids or some sort of reference to a user's referred users.
On the "/:userid" route, the form should submit to the route where a new user is created and have a parameter with the user ID. In this case, I am using query parameters.
So if a person were to visit /foo, they would get a form that would post to a URL like /new?userid=foo.
In that route, you can do something like this (assuming Express):
app.post("/new", (req, res) => {
const userID = req.query.userid;
const newUser = // create user normally
if(userID) {
// `userID` referred this user
const referrer = getUser(userID);
referrer.referred.push(newUser);
save(referrer);
}
});
The getUser function should returning the current user, and you should modify the referred property with the new user. This code was merely an outline and you should update the user in your database.
In a nutshell, a form should post to /new?userid=foo, and when creating a new user, if this parameter is present, you can update the database entry for the user id in the parameter with the id of the new user.

Redirect to index page if user is not authenticated

I'm using ember-cli-simple-auth with ember-cli-simple-auth-token:
"ember-cli-simple-auth": "^0.8.0",
"ember-cli-simple-auth-token": "^0.7.3"
And i already made all configurations with my server to receive the token if the credentials matches with some user in my database.
My doubt now is how can i force redirect if a user tries to access one page if is not log in?
I'm using the following:
export default Ember.Route.extend(AuthenticatedRouteMixin, {});
And this is causing a blank page if the user is not authenticated.. but the redirect doesn't happen.. Am i missing some config here?
You need to change authenticationRoute:
// config/environment.js
ENV['ember-simple-auth'] = {
authenticationRoute: 'index' // or '/' or 'application'
};

Ember Client Side Authentication, route authentication

I have been googling about this a lot but haven't been able to find satisfactory answer or solution you can say.
I have this Ember app, http://jsbin.com/aHiVIwU/28#.
My use case is pretty simple. I want to show the user whole app only after user gets authenticated. I am not using Ember Data as you can see, so the authentication will be through $.ajax as well.
If I am not wrong, I would have a template for login page like this,
<script type="text/x-handlebars" id="login">
<h1>Login</h1>
{{view Ember.TextField valueBinding="username"}}
{{view Ember.TextField type="password" valueBinding="password"}}
<button {{action 'login' class="btn"}}>Login</button>
</script>
Then I would map the resource,
App.Router.map(function() {
this.resource( 'login');
});
And then there would be a corresponding controller right?
App.LoginController = Ember.ObjectController.extend({
});
But the point where I am getting stuck is, how will I show only the login template first and then the whole app after the user gets authenticated? I would appreciate some explanation & help on this.
I can't say it any better than how Alex talked about it in his pull request with router facelift in ember. Look about a quarter of the way down, for 'How do I redirect to a login form for an authenticated route and retry the original transition later?':
https://gist.github.com/machty/5647589
Essentially at the root route of the resource where a user needs to be authenticated you will save the current transition, transition to the login route, then after they've authenticated, restart the previous transition.
He included a very simplistic example, where he's created a mixin that could be attached to all the routes requiring authentication and you wouldn't have to duplicate code etc.
http://jsbin.com/axarop/54/edit
App.NeedsAuthMixin = Ember.Mixin.create({
beforeModel: function(transition) {
// We're using beforeModel here to
// make sure the user is authenticated.
var loginController = this.controllerFor('login');
if (!loginController.get('hasLoggedIn')) {
alert('you must log in!');
loginController.set('afterLoginTransition', transition);
this.transitionTo('login');
}
}
});
App.ArticlesRoute = Ember.Route.extend(App.NeedsAuthMixin);
App.LoginRoute = Ember.Route.extend({
events: {
login: function () {
this.controller.set('hasLoggedIn', true);
var savedTransition = this.controller.get('afterLoginTransition');
if (savedTransition) {
this.controller.set('afterLoginTransition', null);
savedTransition.retry();
}
}
}
});
Take a look at the Client-side Authentication screen casts on http://www.embercasts.com/. They are from the same guy that made the examples that kingpin2k referenced, but provides a full, working solution.

url forwarding updating a div instead of global redirect

I have to redirect the flow of my website to login page when user clicks any link in the page once the session is expired (either by time out or manually loggout out from another window)
I added the following piece of code in my main.gsp(included in every gsp)
<script>
$.ajaxSetup({
statusCode: {
401: function(){
// Redirect the to the login page.
location.href = "/gra/login/auth";
}
}
});
</script>
This used to work fine before, but we did some changes to out application in this phase (oracle migration, new UI and also spring security plugin)
Now it doesnt forward the entire page to login page, but content is only refreshed in the target container which is updated by the link click (the logout page comes in that div only)
This is how it used to work without the above code.
How do I make this a global page forward?
Update: I just checked it in firebug and found that clicking a link after session timeout
is generating a 302 (moved temporarily) code number in response and not 401 ?
This is an excellent task for using grails Filters (Documentation).
The code below will intercept all controllers and all actions and belore they are invoked and check the session is valid. If it fails, it redirects to the login page.
You should change the condition in the if statement to check your session appropriately.
class SecurityFilters {
def filters = {
sessionCheck(controller: '*', action: '*') {
before = {
if (!session && !actionName.equals('login')) {
redirect(uri: '/gra/login/auth')
return false
}
}
}
}
}

Facebook auth.sessionChange event and page changes

I am creating a Facebook Canvas application, and I am following more or less the demo app.
As in the demo, I can get the user data from the signed_request which is POSTed to my site on the first page load. Moreover, as suggested in the demo, I use the following snippet to reload the page on user changes:
var Config;
function facebookInit(config) {
Config = config;
FB.init({...});
FB.Event.subscribe('auth.sessionChange', handleSessionChange);
...
}
function handleSessionChange(response) {
if ((Config.userIdOnServer && !response.session) ||
Config.userIdOnServer != response.session.uid) {
goHome();
}
}
function goHome() {
top.location = 'http://apps.facebook.com/' + Config.canvasName + '/';
}
Here Config is an object which is populated with info from the server.
The problem appears when the user navigates the application using a link. If I use AJAX, the page is not actually reloaded and everything works fine. But if I use a standard link, the user comes to another page of my application with a standard GET request. In this case, I do not know how to get the info about the user, so Config.userIdOnServer is undefined and a page reload is triggered.
Of course I can avoid this by removing the call to handleSessionChange, or by making a one-page app with only AJAX links, but I feel I am missing something basic about the Facebook flow.
My fault, I had problems in retrieving the cookie with the user identity for subsequent requests.

Categories