can I store the next route complete with path variables? - angularjs

I am implementing deep linking in a system using angular. (User follows link in to system, gets login screen, authenticates, then next step is the page they requested with the link (as opposed to the generic fresh-login-start page)).
In the $routeChangeStart event handler I store the next route location in the cookie. After the user authenticates I retrieve the location and send them there.
It works fine for urls without any path variables. For example, if they were trying to get to mydomain.com/viewAllServices then they go to the location post login.
It does not work for urls with path variables. For example, if they were trying to get to mydomain.com/service/123 then post login, they go to mydomain.com/service/:serviceId
I can see the parameters in the next.params and next.pathParams objects in my $routeChangeStart event handler. I can figure out how to replace them programatically, but I wonder if there is a friendlier part of the angular interface that I should be using.
Has anyone else implemented this? Is it necessary to put the values in the url using regex?

Related

Conditional routing in to the Angular application

I have an existing Angular App using ui.router wherein multiple states are being internally called from one another. The initial state is directed using $urlRouterProvider as :
$urlRouterProvider.otherwise('/initial');
Authentications are then made in this initial state and application flow starts.
Now, the user want to directly see a particular screen based on some Id parameters. To explain, now the user directly wants to open http://domain/stateC/12. This link should open from some hyperlink in an excel file.
My question now is how can I check the condition whether which url is entered in to the address bar and based on that if the url is matching pattern likehttp://domain/stateC/12 then I can redirect to state stateC else to state initial. Basically I am looking to make some condition in my app.config module based on the incoming URL to the application.
Any suggestions are appreciated.

routing in angular js application with ui-router

When developing a web application with angular js, a part of time that developers spend is the time for implementing routing.
When using ui-router in a application, there are two "phases" to consider with regards to routing:
user navigates inside application: when click is made on some button, user is transfered to another state by using $state.go("somestate"). Parameters can be send etc. And url is changed accordingly.
user navigates directly via url.
Lets say application has such route:
/mythings/{thingid}/mysubthings/{mysubthingid}
If user navigates to that url directly by pasting it into browser window, application needs to handle it. My question is what's the best practice to do it?
What I'm thinging is: if looking at url example above what needs to be done when user enters that url in browser:
get {thingid} from url (from $stateParams), then get {mysubthingid} also from $stateParams (probably by using resolve (ui-router feature) when defining state), then inject what was resolved to controller and then make a query to api and get data about "subthing" and present view in ui with that data. So that should work with both "types of navigations": when user clicks and is transfered to state, or when user enter url directly into browser. Is this the right path to go?
And I suppose that any url you go to when you click something in application, you should be able to take that url and just paste it into browser and see the same results without being redirected to anywhere else. If application cannot handle every url in such way, maybe application' architecture needs to be reconsidered?
Thanks
In UI-Router, the main component of the routing is the state. The URL is essentially just an address that points to a specific state of the app. I don't think it's necessarily productive to think of the two ways of navigating as separate; they're just two sides of the same coin. There should be no URL that isn't handled by a state. Any URL that doesn't match a state should be caught by the otherwise definition on the $stateProvider and probably redirect to your home page or a 404 page.
In your example, the thing/:thingId/subthing/:subthingId url should map to a predefined state just like any other state. Let's say that state is main.subthing. The process for loading the data, initiating the controller and rendering the UI should be exactly the same whether you get there by calling $state.go('main.subthing', {thing: 123, subthing: 456}) or ui-sref='main.subthing({thing: 123, subthing: 456})' or you paste myapp.com/thing/123/subthing/456 into the browser. They'll all end up at exactly the same place with exactly the same data by calling the exact same logic (most likely loading thing 123 and subthing 456 in resolves and injecting those into a controller).
You're right that if a url can't be handled by the application, that's a sign that something is wrong. Like I said, bad urls should be handled by defining otherwise when setting up states. But pasting a URL into a browser shouldn't require any extra work if your states are defined correctly. URL handling is baked into UI-Router by default.
I partially agree with you. The point where I disagree is when the URL is obtained by a user who is not supposed to access it. Quite often some websites implement authorization code to check if the user who is currently accessing the page is authorized to do so.
Also I think the route could be a bit different. Something like:
{thingid}/{mysubthingid}
This, I think is a cleaner URL and the parameters could be handled in the same way as the one in your example.
I suggest this in order to make it a bit difficult to unauthorized users.
Anyway, it definitely depends on the kind of application you are implementing. If the app's requirement is to be able to access the page by pasting the URL in the browser then I guess your approach is much better.

How to provide a specific link to angularJs routed page

I have an angularJs application, which uses $routeProvider to handle internal routing. The back end uses Rest controllers within a Spring Boot application. The application is based on this: https://spring.io/guides/tutorials/spring-security-and-angular-js/
What I want to do is send an email with an embedded link similar to "http://localhost:8080/link/key1234". The user should be able to click this, and go to specific content as indicated by the key1234 variable.
I have seen a similar item (Refreshing page gives "Page not found") which suggests using .htaccess to handle this, but I do not currently have a .htaccess file.
I also have html5mode on [$locationProvider.html5Mode(true);]
Another suggestion (Spring Boot with AngularJS html5Mode) is to intercept the request and redirect to the home page. Whilst this prevents the application from failing, I need the user to go to a specific page, not the Home page.
I have managed to get quite confused about the interactions of my different components. Can you point me in the right direction to enable a specific link to be provided ?
UPDATE
I think that the .htaccess file is a red herring.
The spring.io tutorial includes the following code:
#RequestMapping(value = "/{[path:[^\\.]*}")
public String redirect() {
return "forward:/";
}
And this segment performs a redirect for some of the pages.
However, my tests (until recently) had been using "http://localhost:8080/public/about" which is not getting picked up by the RequestMapping snippet above.
If I use a single level url (e.g. "http://localhost:8080/test") then my existing code works fine.
It looks like there is a flaw in this regex.
When a request like http://localhost:8080/link/key1234 hits your server, you would need to forward the request to home page. Then, the client should get the response of the home page, while the URL will still be http://localhost:8080/link/key1234. html5mode will then come to play, changing the view at the client side.
I think the best way to do it might be to use urlrewrite filter, which should forward all requests except those starting with, say /api/**, to the home page.

Passport.js, Express.js, and Angular.js routing: how can they coexist?

I apologize this question turned out a bit long, but I have worked on this for some time and really needed to explain all the story.
Background: App based on MEAN stack, trying to authorize Facebook logins using Passport.js.
Following Passport.js guide I implemented something similar to:
// HTML
Add a Facebook login
// send to facebook to do the authentication
app.get('/connect/facebook',isLoggedIn, passport.authorize('facebook',
{ scope : 'email' })
);
// handle the callback after facebook has authorized the user
app.get('/connect/facebook/callback',
passport.authorize('facebook', {
successRedirect : '/profile',
failureRedirect : '/profile'
}));
Notice the target=_self in the html in order to skip Angular routing.
Clearly, authorization works fine. However, redirection does not work, as the routing is handled by Angular. After authorization I never land on /profile (but on the default Angular route).
Therefore, I tried with a custom callback as suggested by Passport.js here, with the hope of passing json data to Angular, and let Angular do the routing. I ended up doing something like:
// In the controller
$http.get("/connect/facebook").success(function(data){
// here I wait for json data from the server and do the routing
});
// I call this route from Angular
app.get('/connect/facebook',isLoggedIn,passport.authorize('facebook',
{ scope : 'email' })
);
// But Facebook lands here!
app.get('/connect/facebook/callback',function(req, res, next) {
passport.authorize('facebook', function(err, user, info) {
res.json({something:smtg});
...
Clearly custom callbacks work for local-login, as Passport.js explains. But here do you see the problem? I call /connect/facebook from Angular, but I should receive some json from /connect/facebook/callback.
I am about to give up Passport, but before this, do you see any solution which would allow landing on /profile after FB authorization, perhaps with a custom message? Many thanks for reading through.
EDIT:
The same question had been reported as an issue on the Passport-Facebook GitHub account. Some additional attempts have been posted there, but not quite the fix yet.
This is a bit more in depth than can be described in one answer, but I'll try to start pointing you in the right direction.
Essentially, Angular.js routes are not really HTML routes at all, but an internal route structure that happens to use the URL for use of the end user. Remember that Angular.js is a client script, and that a full page reload is not desired, as this will reload the entire script. Therefore, /# is used to trick the browser into jumping to a specific bit of code within the already loaded script. (as opposed to the traditional anchor location in the HTML document). Unfortunately (or fortunately), HTML 5 mode allows you to hide the /# part of the url, so instead of seeing http://somesite.com/#/someroute you just see http://somesite.com/someroute. Rest assured, however, that the /# is still there. Angular.js uses the HTML5 pushState (AKA HistoryAPI) to perform the magic replacement.
Given this, if you have called a server route, you are outside the Angular.js script, and any call to load the angular script again will start from the very beginning. You can't actually call your Angular.js route from the server without a full reload. Therefore, you are really doing a double route redirect here. Your server should be calling it's default route for angular, appending /#/someroute to the call. The angular.js page will load, parse off the /#, and redirect to the correct angular route. Keep in mind, however, that if there was any dependency on already loaded objects, those are no longer in memory. Therefore, any route accessed this way should operate as if it is an entry point to your application.
Effectively, you should try using successRedirect : '#/profile', keeping in mind that the profile route in angular should be treated as an app entry point.
Hopefully this gets you started.
If #Claies's way is not working, is it possible you have not get rid of the #= fragment from the facebook callback.
Have a read of this post

preventing access to certain routes based on some condition - angularjs

I am writing a small angular js app with different views. Some views are available to all users but few views are available to only logged in user. I have a small login form on top of my main page [note that there is no separate login screen].
Everything was working fine till here,till then I noticed that even though all the views are not available on my screen initially and will get loaded only once the user logs in. But if the user knows the url of the restricted views , he can bypass the login process.
I have found this stackoverflow question as something very similar to my problem Redirecting to a certain route based on condition. Please see the accepted answer.
But the issue here is that I don't have a separate login screen , so I can't use this code snippet given in the accepted answer
if ( next.templateUrl == "partials/login.html" ) {
// already going to #login, no redirect needed
} else {
// not going to #login, we should redirect now
$location.path( "/login" );
}
How can I achieve the same solution with an integrated login form since I don't have a separate url for my login screen?
I am using ui-router, and that provides a resolve attribute for every route. Whenever a route is accessed, the resolve part is executed first. It returns a promise, and the page does not get loaded until it is resolved. Here you can write some server side calls to validate user, and if invalid, just redirect to any valid page. You can write a resolve to every view and validate the user at every step. I used node/express sessions for storing the logged-in user data.

Resources