Coder Social home page Coder Social logo

ngaa's Introduction

ngAA

Build Status

DRY authentication and authorization for angular and ui-router. It uses json web tokens and http authorization header for it authentication workflow and restrict state access by permits.

Note: ngAA works only with ui-router

Demo

Guide

Installation

Bower Installation

$ bower install --save ng-aa

npm Installation

$ npm install --save ng-aa

Usage

  • Include ngAA into your app index.html or require('ng-aa') it in your application
<!doctype html>
<html ng-app="yourApp">
<head>
    ...
</head>
<body>
    ...

    <!-- build:js(.) scripts/vendor.js -->
    <!-- bower:js -->
    <script src="bower_components/angular/angular.js"></script>
    <script src="bower_components/angular-ui-router/release/angular-ui-router.js"></script>
    <script src="bower_components/angular-jwt/dist/angular-jwt.js"></script>
    <script src="bower_components/ngstorage/ngStorage.js"></script>
    <script src="bower_components/ng-aa/dist/ng-aa.js"></script>
    <!-- endbower -->
    <!-- endbuild -->

    <!-- build:js({.tmp,app}) scripts/yourApp.js -->
    <script src="scripts/app.js"></script>
    <!-- endbuild -->
</body>
</html>
  • Define your signin template to be used by ngAA at views/signin.html
    Note! user in signin is no longer restricted to email and password you can use any structure applicable to your API or backend.
<form ng-submit="signin()" role="form" autocomplete="off">
    <legend>Login</legend>

    <div class="form-group">
        <label for="email">Email</label>
        <input ng-model="user.email" type="email" class="form-control" id="email" placeholder="Email" required>
    </div>

    <div class="form-group">
        <label for="password">Password</label>
        <input ng-model="user.password" type="password" class="form-control" id="password" placeholder="Password">
    </div>

    <button type="submit" class="btn btn-primary">Submit</button>
</form>
  • Require ngAA module into your angular application or module and define your redirect states
angular
.module('yourApp',[
'ngAA'
])
.config(function($stateProvider, $urlRouterProvider, $authProvider) {
        //configure after user signin redirect state
        $authProvider.afterSigninRedirectTo = 'contact';
        //configure after user signout redirect state
        $authProvider.afterSignoutRedirectTo = 'main';
});
  • Define your application states and include permits or authenticated definitions to restrict access.
$stateProvider
    .state('main', {
        url: '/',
        templateUrl: 'views/main.html',
        controller: 'MainCtrl',
        data:{
            authenticated:true //check for authenticity only
        }
    })
    .state('about', {
        url: '/about',
        templateUrl: 'views/about.html',
        controller: 'AboutCtrl',
        data: {
            permits: { //check for authenticity and permissions
                withOnly: 'Post:delete'
            }
        }
    })
    .state('contact', {
        url: '/contact',
        templateUrl: 'views/contact.html',
        controller: 'ContactCtrl',
        data: {
            permits: { //check for authenticity and permissions
                withAll: ['Post:create','Post:edit']
            }
        },
        resolve: {
            profile: function($q, $auth) {
                return $auth.getProfile();
            }
        }
    });
  • Implements your backend signin end point ngAA expect you to implement your backend end point using your language of choice. It will send user credentials for signin in the following format
{
    email:'user email',
    password:'password'
}

// or your custom structure
{
    username:'',
    password:''
}

In return it expect the following response format

{
    token:'your jwt valid token',
    user:{
        ....,
        permissions:[...]
    }
}

Authentication

ngAA can restrict state transition to only authenticated user using authenticated:true state data. To ensure authenticity on state define it as below:

'use strict';
angular
    .module('ngAPP', [
        'ui.router',
        'ngAA'
    ])
    .config(function($stateProvider, $urlRouterProvider, $authProvider) {
        $stateProvider
            .state('about', {
                url: '/about',
                templateUrl: 'views/about.html',
                controller: 'AboutCtrl',
                data: {
                    authenticated:true
                }
            });
            ...
    });

Permits

ngAA restrict state transition to only allowed user using permits state data. If there is no permits state data, ngAA wont protect the state. You should define your permits using one the following:

withOnly

Which tells ngAA to allow user with only provided permission to access the state. To tell ngAA to permit user with only one permission in your state definition, you do as bellow:

'use strict';
angular
    .module('ngAPP', [
        'ui.router',
        'ngAA'
    ])
    .config(function($stateProvider, $urlRouterProvider, $authProvider) {
        $stateProvider
            .state('about', {
                url: '/about',
                templateUrl: 'views/about.html',
                controller: 'AboutCtrl',
                data: {
                    permits: {
                        withOnly: 'Post:delete'
                    }
                }
            });
            ...
    });

withAll

Which tells ngAA to allow user with all given permissions to access the state. To tell ngAA to permit user with all given permissions in your state definition, you do as bellow:

'use strict';
angular
    .module('ngAPP', [
        'ui.router',
        'ngAA'
    ])
    .config(function($stateProvider, $urlRouterProvider, $authProvider) {
        $stateProvider
            .state('about', {
                url: '/about',
                templateUrl: 'views/about.html',
                controller: 'AboutCtrl',
                data: {
                    permits: {
                        withAll: ['Post:delete','Post:create']
                    }
                }
            });
            ...
    });

withAny

Which tells ngAA to allow user with any of the given permissions to access the state. To tell ngAA to permit user with any of the given permissions in your state definition, you do as bellow:

'use strict';
angular
    .module('ngAPP', [
        'ui.router',
        'ngAA'
    ])
    .config(function($stateProvider, $urlRouterProvider, $authProvider) {
        $stateProvider
            .state('about', {
                url: '/about',
                templateUrl: 'views/about.html',
                controller: 'AboutCtrl',
                data: {
                    permits: {
                        withAny: ['Post:delete','Comment:delete']
                    }
                }
            });
            ...
    });

$auth API

ngAA $auth service expose the following API to be used.

$auth.signout

Used to signout current signin user.

$auth
    .signout()
    .then(function() {
        //your codes
        ...
    })
    .catch(function(error) {
        //catch errors
        ...
    });

$auth.isAuthenticated

Used to check if user is authenticated.

$auth
    .isAuthenticated()
    .then(function(isAuthenticated) {
        //your codes
        ...
    })
    .catch(function(error) {
        //catch errors
        ...
    });

$auth.isAuthenticatedSync

This is the synchronous version of isAuthenticated.

$rootScope.isAuthenticated = $auth.isAuthenticatedSync();

$auth.getClaim

Used to get current user claim from the token.

$auth
    .getClaim()
    .then(function(claim) {
        //your codes
        ...
    })
    .catch(function(error) {
        //catch errors
        ...
    });   

$auth.getProfile

Used to get current user profile. Its highly recommended to use getProfile in your state resolve properties to get the current user profile.

$stateProvider
    .state('contact', {
        url: '/contact',
        templateUrl: 'views/contact.html',
        controller: 'ContactCtrl',
        data: {
            permits: {
                withOnly: 'Post:create'
            }
        },
        resolve: {
            profile: function($q, $auth) {
                return $auth.getProfile();
            }
        }
    });   

$auth.hasPermission

Used to check if user has a given permission.

$auth
    .hasPermission('Post:create')
    .then(function(hasPermission) {
        //your codes
        ...
    })
    .catch(function(error) {
        //catch errors
        ...
    }); 

$auth.hasPermissions

Used to check if user has all permissions

$auth
    .hasPermissions(['Post:create','Post:edit'])
    .then(function(hasPermission) {
        //your codes
        ...
    })
    .catch(function(error) {
        //catch errors
        ...
    }); 

$auth.hasAnyPermission

Used to check if user has any of the permissions

$auth
    .hasAnyPermission(['Post:create','Post:edit'])
    .then(function(hasPermission) {
        //your codes
        ...
    })
    .catch(function(error) {
        //catch errors
        ...
    }); 

Directives

signout

ngAA provide a signout directive which can be used in templates to signout the current sign-in user

<li ng-show="isAuthenticated">
    <a data-signout>Signout</a>
</li>

show-if-has-permit

ngAA provide a show-if-has-permit directive which can be used in templates to show or hide HTML elements when current signed in user has a given permission.

<li show-if-has-any-permit="Post:delete">
    ...
</li>

show-if-has-permits

ngAA provide a show-if-has-permits directive which can be used in templates to show or hide HTML elements when current signed in user has all of the provided permissions.

<li show-if-has-permits="Post:view, Comment:create">
    ...
</li>

show-if-has-any-permit

ngAA provide a show-if-has-any-permit directive which can be used in templates to show or hide HTML elements when current signed in user has any of the provided permissions.

<li show-if-has-any-permit="Post:view, Comment:create">
    ...
</li>

Configuration

Out of the box ngAA will work if you follow its convection. But it is also an optionated and allows you to override its configuration through its $authProvider. Below is the detailed configuration options that you may override

afterSigninRedirectTo

Specify which state to redirect user after signin successfully. Default to home. You can override this default on your module config as:

angular
.module('yourApp',[
'ngAA'
])
.config(function($stateProvider, $urlRouterProvider, $authProvider) {
        $authProvider.afterSigninRedirectTo = 'dashboard';
});

afterSignoutRedirectTo

Specify to which state to redirect user after signout. Defaults to signin. You can override this default on your module config as:

angular
.module('yourApp',[
'ngAA'
])
.config(function($stateProvider, $urlRouterProvider, $authProvider) {
        $authProvider.afterSignoutRedirectTo = 'site';
});

signinUrl

Specify your backend end-point to be used by ngAA to signin your user. Default to /signin. You can override this default on your module config as:

angular
.module('yourApp',[
'ngAA'
])
.config(function($stateProvider, $urlRouterProvider, $authProvider) {
        $authProvider.signinUrl = '/auth/signin';
});

signinState

Specify signin state to be used when ngAA when configuring it ngAAAuthCtrl. Default to signin. You can override this default on your module config as:

angular
.module('yourApp',[
'ngAA'
])
.config(function($stateProvider, $urlRouterProvider, $authProvider) {
        $authProvider.signinState = 'auth.signin';
});

signinRoute

Specify a signin route to be used with ngAAAuthCtrl internally. Default to /signin. You can override this default on your module config as:

angular
.module('yourApp',[
'ngAA'
])
.config(function($stateProvider, $urlRouterProvider, $authProvider) {
        $authProvider.signinRoute = '/auth/signin';
});

signinTemplateUrl

This is a required configuration which specify where you have put your user signin template. Default to views/signin.html. You can override this default on your module config as:

angular
.module('yourApp',[
'ngAA'
])
.config(function($stateProvider, $urlRouterProvider, $authProvider) {
        $authProvider.signinTemplateUrl = 'views/auth/signin.html';
});

tokenPrefix

A prefix to be used to prefix token and user profile in storage. Default to ngAA. Its highly advisable to use another prefix mostly your application name. You can override this default on your module config as:

angular
.module('yourApp',[
'ngAA'
])
.config(function($stateProvider, $urlRouterProvider, $authProvider) {
        $authProvider.tokenPrefix = 'yourApp';
});

tokenName

Specify which key to use to retrieve token from the json response from the backend server. Default to token. You can override this default on your module config as:

angular
.module('yourApp',[
'ngAA'
])
.config(function($stateProvider, $urlRouterProvider, $authProvider) {
        $authProvider.tokenName = 'token';
});

profileKey

Specify which key to use to retrieve user profile from the json response from the backend server. Default to user. You can override this default on your module config as:

angular
.module('yourApp',[
'ngAA'
])
.config(function($stateProvider, $urlRouterProvider, $authProvider) {
        $authProvider.profileKey = 'profile';
});

storage

Specify which storage you want to use to store user token and profile. There are only two option here, either localStorage or sessionStorage and default to localStorage. You can override this default on your module config as:

angular
.module('yourApp',[
'ngAA'
])
.config(function($stateProvider, $urlRouterProvider, $authProvider) {
        $authProvider.storage = 'sessionStorage';
});

authHeader

Http Authorization header to be set-ed into request header before sent to the backend. Its the one that will carry authenticity token and your can check it in your backend logic. Default to Authorization. You can override this default on your module config as:

angular
.module('yourApp',[
'ngAA'
])
.config(function($stateProvider, $urlRouterProvider, $authProvider) {
        $authProvider.authHeader = 'your authorization header name';
});

Testing

  • Clone this repository
  • Install all development dependencies
$ npm install && bower install
  • Then run test
$ npm test

Demo

ngAA repository has a example witch can lauched by

$ grunt serve

then supply any email and password

Development

ngAA has set of useful grunt tasks to help you with development. By running

$ grunt

ngAA will be able watch your development environment for file changes and apply jshint and karma to the project.

Contribute

Fork this repo and push in your ideas. Do not forget to add a bit of test(s) of what value you adding.

Licence

Copyright (c) 2015 lykmapipo

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.

ngaa's People

Contributors

lykmapipo avatar patricknazar avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

ngaa's Issues

Permits directives

Should be able to deduce in templates if current user

  • hasPermit
  • hasAllPermits
  • hasAnyPermit

Add ability to be able to authenticate user from other source than http

Should be able to authenticate user in more than backend server. This is useful if application are created to leverage device storage like localstorage , indexdb and others.

Motivations:
It should be able to used in developing desktop application which are developed in electron and nw.

Refresh tokens

It would be nice to be able to support 'refresh tokens' so that a user can remain logged in for an extended/infinite period of time.

Grab all permissions and generate permit keys

Should be able to iterate over all permission assigned to user and generate permit keys in the $rootScope to allow:

  • View to check if current user has a given permits
  • Evaluate at any point if user permitted to do given actions

Permit keys may follow format isPermittedTo[permission] where permission if picked from the current assigned permissions to the user.

So if user has permission View report then isPermittedToViewReport will be available in $rootScope as a permit key for view reports.

It may then used in views as:

<div ng-show="isPermittedToViewReport"></div>

Or anywhere in codes as:

   if(isPermittedToViewReport){
     //codes
    ...
  }

How to redirect if already logged in

Hi there ,
My configuration is
$authProvider.signinUrl = 'laravel-frontend/public/api/frontauthenticate';
$authProvider.signinState = 'login';
$authProvider.signinRoute = '/login';
$authProvider.signinTemplateUrl = 'app/shared/views/login.html';
$authProvider.afterSigninRedirectTo = 'dashboard';
$authProvider.afterSignoutRedirectTo = 'login';
so after login it goes to dashboard but then when I write '/login' then it opens login page.

How can I redirect it to dashboard if it is already looged in .

Thanks

signinUrl with internet url error Access-Control-Allow-Origin

Hi

When I use $authProvider.signinUrl with external url (non-localhost) like this:

$authProvider.signinUrl = 'http://example.com/public/api/authenticate';

Show me this error in console:

XMLHttpRequest cannot load http://example.com/public/api/authenticate. 
Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access.

multi login issue

The ability of multi login needs to be implemented.
"Previous localstorage data when replaced by the new one, the previous login should be killed or fallback to login page"

Separate responsibilities of the module

It will be good to have ngAA separated into modules that have their own responsibility

  • authentication
  • authorization
  • profile
  • etc

This will give ngAA ability to grow and cover other user management scenarios

Get updated user information

How can I deal with the situation where a user's info/profile/permissions have changed? It seems that the user json object is only received upon login.

can't override signinTemplateUrl

I want to use my own signin template,
in my main module's config function:
$authProvider.signinTemplateUrl = 'ui/login.html';
but it doesn't work.

I found that the signinState is always registered before the overriding of signinTemplateUrl.
so it always requesting the default signinTemplateUrl when starting the signinState.

The only thing i can do right now is editing ngAA.js to change the default signinTemplateUrl value of ngAAConfig. Do anyone have some better idea?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.