I answered a similar question: AngularJS Authentication + RESTful API
I wrote an AngularJS module for UserApp that does pretty much what you want. You can:
- Modify the module and add functions to your own API or
- Use the module with UserApp (cloud user management API)
https://github.com/userapp-io/userapp-angular
It supports secure / public routes, redirection on login / logout, heartbeat for checking status, saving session token in cookie, events, etc.
If you use UserApp, you will not need to write any server-side code for user-defined materials (more than token validation). Take a course on Codecademy to try it.
Here are some examples of how this works:
Error handling login form:
<form ua-login ua-error="error-msg"> <input name="login" placeholder="Username"><br> <input name="password" placeholder="Password" type="password"><br> <button type="submit">Log in</button> <p id="error-msg"></p> </form>
Error registration form:
<form ua-signup ua-error="error-msg"> <input name="first_name" placeholder="Your name"><br> <input name="login" ua-is-email placeholder="Email"><br> <input name="password" placeholder="Password" type="password"><br> <button type="submit">Create account</button> <p id="error-msg"></p> </form>
How to specify routes that should be publicly accessible, and which route is a form of login:
$routeProvider.when('/login', {templateUrl: 'partials/login.html', public: true, login: true}); $routeProvider.when('/signup', {templateUrl: 'partials/signup.html', public: true});
The .otherwise() route should be set where you want your users to be redirected after logging in. Example:
$routeProvider.otherwise({redirectTo: '/home'});
Sign Out:
<a href="#" ua-logout>Log Out</a>
(Logs out and redirects the login route)
Access to user properties:
Access to user properties is carried out using the user service, for example: user.current.email
Or in the template: <span>{{ user.email }}</span>
Hide items that should only be displayed at login:
<div ng-show="user.authorized">Welcome {{ user.first_name }}!</div>
Show item based on permissions:
<div ua-has-permission="admin">You are an admin</div>
To authenticate your internal services, simply use user.token() to get the session token and send it using an AJAX request. In the background, use the UserApp API (if you are using UserApp) to check if the token is valid.
If you need any help just let me know :)
Timothy E. Johansson
source share