preventing access to certain routes based on some condition - angularjs - 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.

Related

Firebase seems to not resolve current user until after views rendered. Any way around this?

I am converting an app that used Parse as the backbone user database to Firebase. Parse always seemed to re-authenticate the user before any views were rendered or controllers executed. I.e. if you open a page in the site (even a deep linked page like www.mysite.com/admin/my_account_details),
Parse.User.current()
will return the current user - the Parse toolkit has re-authenticated (or cached) the current user's data. So controller code could depend on Parse.User.current() being a valid user object at all times, if the user was logged in, even when the page is opened deep into the site, say, via a bookmark.
Firebase seems not to work this way. In my .run() method I have something to the effect of:
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// do something with current user
}
});
but this code gets executed AFTER controller code, which depends on the current user's info. In other words,
firebase.auth().currentUser
is returning no user, even though after firebase finishes loading, there will be a current user.
Am I correct in this diagnosis? And is there any way to ensure that firebase re-connects the current user before any controller code is executed?

AngularJS: controller not connected to view when dynamically routed

So, I guess this question is more academic than anything. I've been working all afternoon on a MEAN stack application's reset password functionality, and the general method I chose to employ is as follows:
In the login view, the user enters their username and clicks the forgot password button.
This submits a post request to the server's /forgot route, along with the { username: username } object.
The server looks for the user in the database, and if found, it creates a long string of random characters (e.g. '823uhr8824hriij3993') and saves the string as the user's remember token (valid for an hour, and the expiration is also saved).
An email is sent out to the user with a link to reset the password, corresponding to Angular route '/reset/:token' (continuing the example, '/reset/823uhr8824hriij3993').
If the user submits an updated password from that url before the token expires, the server checks the params for the appropriate remember token and their password is successfully changed.
I am using ng-Route, and my reset password route is configured as:
.when('/reset/:token', {
templateUrl: 'partials/account/reset-password.html',
controller: 'resetPasswordCtrl'
})
Unless I am missing something blatant (which is entirely possible), when the user hits the '/reset/823uhr8824hriij3993' route and Angular renders the reset-password.html view, it should be connected to the resetPasswordCtrl, should it not?
I spent a couple hours today trying to troubleshoot the username, password, and password confirmation validations that were not working, many of which are coded in the resetPasswordCtrl, figuring there must have been some typo somewhere causing a disconnect. But in fact the controller wasn't actually connected to the view until I put ng-controller="resetPasswordCtrl" in the topmost div tag.
All the other routes in this application are static and are set up via the $routeProvider just as above, and this is the first time I've run into this issue, so I suppose it must arise because of the dynamic /:token portion of the route. Anyway, my immediate problem is solved, but if someone wouldn't mind taking a moment to explain why it was a problem in the first place, I would really appreciate it... for future reference!
as I can see the problem is your reset password page come directly from server so the angular itself and routing you wrote do not work there because all the works handle by a server itself so if you want to use that functionality you should create a separate html file like('reset.html') with all tags and everything you need to load your app and controller then point it to servers response page
In that case when server going to serve reset page it's came up with actual page

How to make a login page outside the single page application skeleton

I have an angularJS single page application. It is an admin dashboard. However I do not want anyone to access the dashboard unless he is logged in.
Problem that I am facing is when I create a login template, it is usually part of the admin dashboard, since it is a single page application. However I want the login page to look completely different from the single page application index default view. Same for registration page.
What are ways to make a page different completely from the skeleton of the single page application with angular ?
I am sorry if the question is broad but I am new to angular. I do not care about any code written I just would like to understand a good technique for a sort of thing.
Feel free to send me any articles or documentations that explains similar technique
If I am understanding your question correctly, what you need to do is the following.
Use ui-router to control the navigation (or routing) in your application. Note that ui-router will become native in AngularJS 2, right now you will need to use NPM or Bower to include it in your project.
Then use the events it provides to determine if the user needs to logon before accessing the given route. If logon is required you can redirect to the logon page, the redirect back upon successful authentication.

angularjs technique for login then redirecting to dashboard page

I'am doing my first AngularJS project with ASP.NET Web API backend. What I am trying to do is, whenever a user visits www.mydomain.com, a login page (index.html) will displayed. After successfull login, he will be redirected to the dashboard.html (this is the shell page, partial views go here). My project structure is shown below-
I am confused about some issues:
Is this the best/common practices what i am trying to do in above?
As because dashboard.html is the main page, should i place app.js on dashboard.html?
If i put app.js on dashboard.html, will index.html (login page) have another app.js (i.e. loginApp.js)?
How should I manage the login state i.e. IsUserLoggedId, UserId etc in angular part?
This question may be silly. I googled, but did not find any example/article addressing such issue.
Would you please help?
Thank you in advance.
I am not sure how ASP.NET deals with it, but to my knowledge ASP.NET is just a server side framework whereas AngularJS is client side framework.
These two framework solve different problem, but has some overlapping features.
If you start using angularjs, then most of the time you will deal with the term "Single Page Application (SPA)".
There are different approaches in how you can handle the url redirection after login. I will just show you two example. There are many more how you can handle the user authentication and session.
First Approach:
In SPA, most of the time browser will change the url route and state directly in the page itself without making the entire page request from the server.
With that said, your dashboard.html will most likely be come a static template file which will be loaded from the browser directly. (i.e. the server does not dynamically parse the dashboard.html but only serve as a static file). Upon the user login, the angularjs will fire a asynchronous HTTP request into the ASP.NET authentication end point. A successful login may return a token to the browser, and the client will use it to manage the user session. At the same time, the Angular will have to change the route to /dashboard/. Notice that that the entire flow happens transparent to the user, it does not fire a full page HTTP request.
Second Approach:
Alternatively, if you choose to redirect from the server, you will have to send a HTTP Redirect 302. and since HTTP redirect will eventually call make a full HTTP request to /dashboard/, and it will then have to reload and bootstrap the angular app.js from the browser again. In this case, the user will have to wait for the dashboard page to be processed by the server upon login
Issues:
Is this the best/common practices what i am trying to do in above? there are many approaches, I think it is best to find the one that works for you. If you have a RESTful API, then you might want to have a look at the SPA approach in more detail.
As because dashboard.html is the main page, should i place app.js on dashboard.html? in SPA, you don't need to load app.js twice. but if you use the second approach, you have to reload the app.js again.
If i put app.js on dashboard.html, will index.html (login page) have another app.js (i.e. loginApp.js)? depends on your approach as stated above
How should I manage the login state i.e. IsUserLoggedId, UserId etc in angular part? Authentication Strategy, UNIX style authorization
There are more official guide that can help AngularJS Developer Guide.
Hope this helps you to integrate with the ASP.NET authentication mechanism.
you should have multiple shell pages. this link can help you...
refer to Multiple Shell Pages part.

Dynamic route without redirect

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

Resources