npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

angular-spa-auth

v1.0.1

Published

Provides ability to easily handle most of the logic related to the authentication process and page load for the AngularJS SPA

Downloads

70

Readme

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

  • 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 will all the modules that are based on ngRoute
  • Authneticated user model is always available in $rootScope.currentUser which 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

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.