Architecture For Login System On Mean Stack?
I'm developing a web app on the MEAN stack (MongoDB, Express, AngularJS, and node.js). I'm developing a login system, and will also have some of the Angular routes protected so tha
Solution 1:
I ended up combining my original workflow with Express's auth example, seen here. It is as follows:
- When user initially loads the app, an http call is made to an Express endpoint that checks if a session exists already for the user. If so, the user is stored in
$rootScopeand considered logged in. - Any time the AngularJS route changes, the same endpoint is accessed. Route protection was specified in a way similar to that described here. If the endpoint ever returns that no session exists,
$rootScope.useris unset (if it needs to be), and the user is redirected to the login page. - When the login form is processed, it posts to an Express endpoint. The endpoint retrieves the user from the mongoDB (if it exists), and attempts to hash the password. If it's a match, the user's session is set, stored in the mongo DB, and the endpoint returns the
userobject (used to store in the $rootScope as previously mentioned). - Any time any further endpoints are accessed, the functions are first passed through the
restrictfunction which ensures that a session exists before sending any data to the client. It returns a401if no session exists, which is then handled on the Angular side using this HTTP interceptor to unset$rootScope.userand redirect to the login screen. - When the user clicks "log out" on the Angular side, the session is unset and deleted from the mongo DB,
$rootScope.useris set to null, and the user is redirected back to the front page.
Post a Comment for "Architecture For Login System On Mean Stack?"