angular-spa-auth

GitHub issues GitHub license NPM Version Bower NPM Downloads Build Status Coverage Status

NPM

Frontend module that provides ability to easily handle most of the logic related to the authentication process and route change for the AngularJS SPA

Table of Contents

Features

Installation

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']);

Bower

Install via Bower

bower install --save angular-spa-auth

npm

Install via npm

npm install --save angular-spa-auth

Dependencies

Examples

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

Documentation

Config

First of all you have to pass config object to the AuthService#run method

Example
'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> List urls that are available for unauthorized users
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

Verbose

For development perspective you can enable console.info message using verbose parameter

Default value: false

Example
AuthService.run({
    ...
    verbose: true,
    ...
})

Public Urls

Public urls is a list of urls that available for all unauthorized users.

Default value: ['/login', '/home']

Example
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

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'
}
Example
AuthService.run({
    ...
    endpoints: {
        isAuthenticated: '/api/is-authenticated',
        currentUser: '/api/user/current',
        logout: '/auth/logout',
        login: '/auth/login'
    },
    ...
})

isAuthenticated endpoint

Mandatory Method
false GET

This endpoint should return only true or false in a response which means that user is already authenticated or not.

currentUser endpoint

Mandatory Method
true GET

Should return user information/user representation in JSON format if authenticated or 404 status code

login endpoint

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

logout endpoint

Mandatory Method
true GET

Should provide ability on the backend side to invalidate user session

UI Routes

In some cases these ui routes will be used for user redirection

Routes:

Default value:

{
    login: '/login',
    home: '/home'
}
Example
AuthService.run({
    ...
    uiRoutes: {
        login: '/login',
        home: '/dashboard'
    },
    ...
})

login route

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

home 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

target route

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

Handlers

We are providing handlers as additional possibility to customize authentication process. Instead of using endpoints configuration you can use your own implementation

getHomePage handler

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.

Example
AuthService.run({
    ...
    handlers: {
        getHomePage: function(user) {
            return user.admin ? '/dashboard' : '/profile'
        }
    },
    ...
})

getUser handler

You should provide implementation of how to get authenticated user from backed or other source.

Output

Type Description
Promise Promise with user
Example
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;
            })
        }
    },
    ...
})
Example
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)
            });
        }
    },
    ...
})

login handler

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
Example
AuthService.run({
    ...
    handlers: {
        login: function(credentials) {
            return $http.post('/api/login', credentials);
        }
    },
    ...
})
Example
AuthService.run({
    ...
    handlers: {
        login: function(credentials) {
            return $auth.authenticate('strava')
        }
    },
    ...
})

Note: $auth service is provided by satellizer module

logout handler

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
Example
AuthService.run({
    ...
    handlers: {
        logout: function() {
            return $http.post('/api/logout');
        }
    },
    ...
})
Example
AuthService.run({
    ...
    handlers: {
        logout: function() {
            return Firebase.logout()
        }
    },
    ...
})

success handler

You can provide your reaction on login success using this handler

Example
AuthService.run({
    ...
    handlers: {
        success: function(data) {
            toastr.success('Successfully authenticated', {timeOut: 1500});
        }
    },
    ...
})

error handler

Override this handler to provide your reaction on login error using this handler

Example
AuthService.run({
    ...
    handlers: {
        error: function(data) {
            toastr.error('Unable to authenticate.');
        }
    },
    ...
})

AuthService

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 method

This method is a start point of the angular-spa-auth module. It should be used inside the .run method of your app

Example

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

login method

To login using user credentials you need to pass them to the AuthService#login method

Example
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

logout method

Simply call AuthService#logout method without any parameters

Example
AuthService.logout()

getCurrentUser method

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

Example
var user = AuthService.getCurrentUser()
doSomething(user);
Example
AuthService.getCurrentUser().then(function(user) {
    doSomething(user);
})

refreshCurrentUser method

Load fresh version of current user model from backend. Returns promise.

Example
var promise = AuthService.refreshCurrentUser().then(function(user) {
    // your logic here
})

isAuthenticated method

Returns true if user already authenticated and false if not

Example
if(AuthService.isAuthenticated()) {
    // do something
}

isPublic method

Checks if provided url is in a list of public urls

Example
if(AuthService.isPublic('/private')) {
    // do something
} else {
    // redirect somewhere
}

saveTarget method

Saves current route as a target route. Will be used in case of successful login. Can be cleaned using #clearTarget()

Example
AuthService.saveTarget()

clearTarget method

Clears target route

Example
AuthService.clearTarget()

openTarget method

Redirects user to the saved target route

Example
AuthService.openTarget()

openLogin method

Redirects user to the login page

Example
AuthService.openLogin()

openHome method

Redirects user to the home page

Example
AuthService.openHome()

License

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.