I have an angularjs app and would like the homepage to depend on the logged in status of the user.
Im looking for something like the following to happen:
When I goto mypage.com use 'resolve' to perform an HTTP GET with a server to check if logged in.
If the user is not logged in resolve the promise from 1) and show some generic splash screen. For example, templateUrl: splash.html
If the user is logged in then fetch additional data from the server. Once the data has been returned then resolve the promise from 1) and show a page specific for this user. For example, templateUrl: loggedin.html
In either case, the URL should not change. ie: I do no want to redirect to another route. The URL should always be mypage.com.
How can I have a dynamic page like this without using any redirects?
Have a look # https://github.com/angular-app/angular-app, its the best example app I've found so far for dealing with the user authorization rabbit hole.
For a quick start with getting your head around how user auth works in angular-app, have a look at these 3 files:
https://github.com/angular-app/angular-app/blob/master/client/src/app/app.js
https://github.com/angular-app/angular-app/blob/master/client/src/common/security/security.js
https://github.com/angular-app/angular-app/blob/master/client/src/common/security/authorization.js
Related
I am using MEAN Stack, and jade for html templating for developing a project. Since I am using jade all the .when() of the $routeProvider goes through the server and then rendered. Things are absolutely fine until recently I added $httpProvider.interceptor for authenticating each request. Basically, I started using JWT token based authentication and before requesting anything to the server, in my interceptor I am attaching 'Authorization' header. And the first middleware for protected apis I am verifying the token present in the 'Authorization' header. If present then proceed, else send authorization error.
Now, as mentioned in the title of the question. I have a few URLs containing hypen(-) between two words just to increase the readability.
eg: .when('/firstPart/secondPart1-secondPart2/thrirdPart', {
templateUrl: '/path/to/file'
})
this url is working fine if user going through the normal flow of getting to this url. The problem arises when the user comes to this page and hits the browser's refresh button, as he gets an error 'Authorization header not set'
I did a few research on what and why this is happening, I found the answer in
AngularJS not intercepting direct requests from Address Bar. According, to this answer and few other I understood that on refreshing browser makes a direct request to the server and doesn't go through angular routes, and thus, interceptor that is attaching the Authorization header to each request header is not getting called.
As, suggested by the same link, the workaround is that if auth verification fails make a call to '/', I donnot wish to do that as the user has just refreshed the page and he has to ideally get back the same page as he was in before he pressed refreshed. I am stuck here on how to do this.
Also, there is another mind–boggling this is if, I remove the 'hyphen'(-), and make it one word i.e., .when('/firstPart/secondPart1SecondPart2/thrirdPart', {
templateUrl: '/path/to/file'
})
everything works as expected even when the user hits the refresh button. It is first going through the angular router and interceptor attaches the Authorization header and then goes to make a get request for that template.
Wondering, is there any problem in using hyphen in URLs? However, I do not wish to remove the hyphens as I have already used it in many places and also I feel its good to have - between two words that needs to be displayed together in the URL than making them camel cased.
S, finally I have two questions :
1. How to load the same page as the user was in before he hit refresh, instead of redirecting him to '/' or login url.
2. The problem explained above, occurs only for hyphenated(-) URLs, what is the problem having '-' in the URL.
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.
My use case is very simple and i'm sure many apps share the same one. I need to verify user and need a simple url to retrieve user token from URL, make api call to my backend service and route the user according to the result from the API.
I don't need to render any page but just make API call and parse the response. I see two options to accomplish: Resolve or OnEnter. I also think there might be another simple way.
Here are the steps:
user getting email with link to /verify?token={token}
in app.js I have a state 'verify' and URL '/verify=token'
call API and get "true" or "false"
if false, redirect user to homepage, if true redirect the user the user profile page.
What is the best and simple way to accomplish what I like to do?
Thanks.
btw - I'm using ui-router.
In your case, I think you should use Resolve of ui-router to make sure state won't load until all data were resolved.
To make user feel good, you should show a loading indicator and register event $stateChangeSuccess to hide it once done
I have an application running on angular and I already have an http intercept setup. My issue is that my api returns some 404 errors that I would want to redirect to a 404 page and some that I wouldn't. For example when navigating to a new page, if the content of that page returns a 404 I want to direct to a 404 page instead of loading an empty template. However on a page where a user is checking out (paying for a purchased item) I check to see if they have a credit card token stored on file. If they do we can offer them the choice to use it. If they don't have one on file the api returns a 404 and we ask them to enter one.
My issue is that because of these two cases, it's not as simple at calling $state.go('404') anytime a 404 is thrown. I'm weighing a few options. One, have the api return a special message if it should redirect to a 404. This seems less than ideal, not really the responsibility of the api and we have multiple clients on a shared api. I could try to detect the current state/page in the http intercept and create a list of states that should redirect. I could $rootScope.$broadcast('no-template-data') or something similar from each controller that needs this and redirect from an global app.run function.
Has anyone else faced this challenge with single page applications?
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.