Frontend module that provides ability to easily handle most of the logic related to the authentication process and route change for the AngularJS SPA
- Handles for you all the work related to authentication process and route change
- Saves original/target route and redirects user to it after login/authentication check
- Very customizable and flexible
- Works perfect with both: angular-route (ngRoute) and angular-route-segment. Also should work with all the modules that are based on ngRoute
- Authneticated user model is always available in
$rootScope.currentUserwhich means that you can use it in your views as<div ng-show='currentUser.admin'>{{currentUser.firstName}}</div>And you can always get it using service method -AuthService.getCurrentUser()- in any place of your project
Include File
<script type="text/javascript" src=".../angular-spa-auth/dist/angular-spa-auth.min.js"></script>Add angular-spa-auth in your angular app to your module as a requirement.
angular.module('app', ['ngRoute', 'angular-spa-auth']);Install via Bower
bower install --save angular-spa-auth
Install via npm
npm install --save angular-spa-auth
| Name | Route Engine | Source Code | Demo | Description |
|---|---|---|---|---|
| Basic #1 | ngRoute | Source | Demo | User is not logged in on start |
| Basic #2 | ngRoute | Source | Demo | User is logged in on start |
| Extended #1 | ngRoute | ... | ... | ... |
| Extended #2 | angular-route-segment | ... | ... | ... |
| Full Customization | ngRoute | ... | ... | ... |
First of all you have to pass config object to the AuthService#run method
'use strict';
(function () {
angular
.module('app')
.run(['AuthService', '$http', 'toastr',
function (AuthService, $http, toastr) {
AuthService.run({
endpoints: {
isAuthenticated: '/auth/is-authenticated',
currentUser: '/api/user/current',
logout: '/auth/logout',
login: '/auth/login'
},
handlers: {
error: function () {
toastr.error('Unable to authenticate.');
}
}
});
}]);
})();The config object have different field for customizing you authentication process
| Name | Type | Description |
|---|---|---|
| verbose | Boolean |
Activates console.info output if true |
| publicUrls | `Array<String | RegExp>` |
| endpoints | Object |
Gives you ability to setup all the backed endpoints that will own roles in the authentication process |
| uiRoutes | Object |
Helps you automatically redirect user to the specified UI routes such as home and login |
| handlers | Object |
Allows you to provide you implementation for key methods of authentication process |
For development perspective you can enable console.info message using verbose parameter
Default value: false
AuthService.run({
...
verbose: true,
...
})Public urls is a list of urls that available for all unauthorized users.
Default value: ['/login', '/home']
AuthService.run({
...
publicUrls: ['/login', '/home', '/registration', /public/, '/confirmation', '/forgotPassword', /^\/manage\/.*$/],
...
})Please do not add routes that should be visible only for authenticated user to this list
endpoints property is a minimal required configuration for this module.
It's backend endpoints that should be implemented.
Three of them are mandatory and only isAuthenticated is optional
in case if you do not use your custom handlers
These endpoints are needed for basic authentication flow of SPA
Endpoints:
Default value:
{
isAuthenticated: null,
currentUser: null,
logout: '/logout',
login: '/login'
}AuthService.run({
...
endpoints: {
isAuthenticated: '/api/is-authenticated',
currentUser: '/api/user/current',
logout: '/auth/logout',
login: '/auth/login'
},
...
})| Mandatory | Method |
|---|---|
| false | GET |
This endpoint should return only true or false in a response
which means that user is already authenticated or not.
| Mandatory | Method |
|---|---|
| true | GET |
Should return user information/user representation in JSON format
if authenticated or 404 status code
| Mandatory | Method |
|---|---|
| true | POST |
Should provide ability on the backend side to authenticated user using his credentials passed as request payload
This endpoint will be used once you call AuthService#login method
You can override implementation of login handler using custom handlers
| Mandatory | Method |
|---|---|
| true | GET |
Should provide ability on the backend side to invalidate user session
In some cases these ui routes will be used for user redirection
Routes:
Default value:
{
login: '/login',
home: '/home'
}AuthService.run({
...
uiRoutes: {
login: '/login',
home: '/dashboard'
},
...
})login route is a page with login form.
It is used if unauthorized user tries to go the restricted page or
after logout operation the user will be automatically redirected to this route
After the success login user will be automatically redirected to home route
if target route was not caught
For example: If user loads your website in a new tab/reloads page
- user loads root path (e.g. www.domain.com -
targetroute). After the success login he will be redirected to thehomeroute (www.domain.com/#!/home in case of default config) - user loads restricted/private route (e.g. www.domain.com/#!/reports -
targetroute). After the success login he will be redirected to thetargetroute (www.domain.com/#!/reports) - user loads public path (e.g. www.domain.com/#!/registration or www.domain.com/#!/forgotPassword -
targetroute). After the success login he will be redirected to thehomeroute (www.domain.com/#!/home in case of default config)
You do not need to specify target route because it will be saved once user will
try to load private page.
Please see the examples from the previous section
We are providing handlers as additional possibility to customize authentication process. Instead of using endpoints configuration you can use your own implementation
Overriding this handler you should provide logic for getting home page route. It can be based on the user model or on your own logic related to your project.
Input
| Name | Type | Description |
|---|---|---|
| user | Object |
Object representation of JSON received from backend. Can be null |
Output
| Type | Description |
|---|---|
String |
Home page route |
In example you can find easiest use case.
AuthService.run({
...
handlers: {
getHomePage: function(user) {
return user.admin ? '/dashboard' : '/profile'
}
},
...
})You should provide implementation of how to get authenticated user from backed or other source.
Output
| Type | Description |
|---|---|
Promise |
Promise with user |
AuthService.run({
...
handlers: {
getUser: function(user) {
return $http.get('/api/user/current').then(function (response) {
var user = response.data;
// extending user object by two new methods
user.isAdmin = function() {
return this.admin;
}
user.getFullName = function() {
return this.firstName + ' ' + this.lastName;
}
return user;
})
}
},
...
})AuthService.run({
...
handlers: {
getUser: function(user) {
return $q(function (resolve, reject) {
// you can use native window.localStorage or ngStorage module
// but the main idea is that you have to implement logic
// to get user object using any storage type and
// always return Promise
var user = JSON.parse(window.localStorage.get("previouslySavedUser"))
resolve(user)
});
}
},
...
})Overriding this handler you should implement your authentication logic
Input
| Name | Type | Description |
|---|---|---|
| credentials | Object |
Object with username and password or token or any information that will help user to login to the system |
Output
| Type | Description |
|---|---|
Promise |
Promise where success callback means that login operation was successfully completed |
AuthService.run({
...
handlers: {
login: function(credentials) {
return $http.post('/api/login', credentials);
}
},
...
})AuthService.run({
...
handlers: {
login: function(credentials) {
return $auth.authenticate('strava')
}
},
...
})Note: $auth service is provided by satellizer module
Overriding this handler you should implement your logout logic. Instead of standard GET request you can send POST and provide another way
Output
| Type | Description |
|---|---|
Promise |
Promise where success callback means that logout operation was successfully completed |
AuthService.run({
...
handlers: {
logout: function() {
return $http.post('/api/logout');
}
},
...
})AuthService.run({
...
handlers: {
logout: function() {
return Firebase.logout()
}
},
...
})You can provide your reaction on login success using this handler
AuthService.run({
...
handlers: {
success: function(data) {
toastr.success('Successfully authenticated', {timeOut: 1500});
}
},
...
})Override this handler to provide your reaction on login error using this handler
AuthService.run({
...
handlers: {
error: function(data) {
toastr.error('Unable to authenticate.');
}
},
...
})This angular-spa-auth module supplies AuthService which can be injected
in any place of the project allowed by AngularJS
AuthService has a couple of public methods that can be used to complement
your authentication process
Public methods:
- #run(config)
- #login(credentials)
- #logout()
- #getCurrentUser()
- #refreshCurrentUser()
- #isAuthenticated()
- #isPublic(url)
- #saveTarget()
- #clearTarget()
- #openTarget()
- #openLogin()
- #openHome()
This method is a start point of the angular-spa-auth module.
It should be used inside the .run method of your app
app.run.js
angular
.module('app')
.run(['AuthService', function (AuthService) {
var config = {...}
AuthService.run(config);
}]);It has only one mandatory input parameter config. Please see
the configuration section for more details
To login using user credentials you need to pass them to the AuthService#login method
var credentials = {
username: 'admin',
password: 'GOD'
}
AuthService.login(credentials)By default it sends POST request to the login endpoint
Also you can override logic of AuthService#login method using handlers
Simply call AuthService#logout method without any parameters
AuthService.logout()If user already authenticated then it returns user model from $rootScope.currentUser.
If not then tries to load user model from backend and returns promise
var user = AuthService.getCurrentUser()
doSomething(user);AuthService.getCurrentUser().then(function(user) {
doSomething(user);
})Load fresh version of current user model from backend. Returns promise.
var promise = AuthService.refreshCurrentUser().then(function(user) {
// your logic here
})Returns true if user already authenticated and false if not
if(AuthService.isAuthenticated()) {
// do something
}Checks if provided url is in a list of public urls
if(AuthService.isPublic('/private')) {
// do something
} else {
// redirect somewhere
}Saves current route as a target route. Will be used in case of successful login.
Can be cleaned using #clearTarget()
AuthService.saveTarget()Clears target route
AuthService.clearTarget()Redirects user to the saved target route
AuthService.openTarget()Redirects user to the login page
AuthService.openLogin()Redirects user to the home page
AuthService.openHome()The MIT License (MIT)
Copyright (c) 2017 Volodymyr Lavrynovych
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
