{"id":16223640,"url":"https://github.com/lykmapipo/ngaa","last_synced_at":"2025-03-19T12:30:31.069Z","repository":{"id":27581179,"uuid":"31063810","full_name":"lykmapipo/ngAA","owner":"lykmapipo","description":"DRY authentication and authorization for angular and ui-router","archived":false,"fork":false,"pushed_at":"2017-11-01T05:20:20.000Z","size":149,"stargazers_count":42,"open_issues_count":14,"forks_count":13,"subscribers_count":6,"default_branch":"master","last_synced_at":"2025-02-27T12:06:32.399Z","etag":null,"topics":["angular","angularjs","authentication","authorization","ui-router"],"latest_commit_sha":null,"homepage":null,"language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/lykmapipo.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2015-02-20T12:24:36.000Z","updated_at":"2025-01-20T20:53:59.000Z","dependencies_parsed_at":"2022-08-31T00:01:05.862Z","dependency_job_id":null,"html_url":"https://github.com/lykmapipo/ngAA","commit_stats":null,"previous_names":[],"tags_count":16,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/lykmapipo%2FngAA","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/lykmapipo%2FngAA/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/lykmapipo%2FngAA/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/lykmapipo%2FngAA/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/lykmapipo","download_url":"https://codeload.github.com/lykmapipo/ngAA/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":243989419,"owners_count":20379648,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["angular","angularjs","authentication","authorization","ui-router"],"created_at":"2024-10-10T12:19:32.358Z","updated_at":"2025-03-19T12:30:30.433Z","avatar_url":"https://github.com/lykmapipo.png","language":"JavaScript","readme":"ngAA\n=======\n[![Build Status](https://travis-ci.org/lykmapipo/ngAA.svg?branch=master)](https://travis-ci.org/lykmapipo/ngAA)\n\nDRY authentication and authorization for angular and ui-router.\nIt uses [json web tokens](http://jwt.io/) and http authorization header for it authentication workflow and restrict state access by [permits](#permits).\n\n*Note: ngAA works only with [ui-router](https://github.com/angular-ui/ui-router)*\n\n[Demo](#demo)\n\n## Guide\n\n* [Install](#install)\n* [Usage](#usage)\n* [Authentication](#authentication)\n* [Permits](#permits)\n    * [`withOnly`](#withonly) \n    * [`withAll`](#withall) \n    * [`withAny`](#withany) \n* [$auth API](#auth-api)\n  * [`$auth.signout`](#authsignout)\n  * [`$auth.isAuthenticated`](#authisauthenticated)\n  * [`$auth.isAuthenticatedSync`](#authisauthenticated)\n  * [`$auth.getClaim`](#authgetclaim)\n  * [`$auth.getProfile`](#authgetprofile)\n  * [`$auth.hasPermission`](#authhaspermission)\n  * [`$auth.hasPermissions`](#authhaspermissions)\n  * [`$auth.hasAnyPermission`](#authhasanypermission)\n* [Directives](#directives)\n    * [`signout`](#signout) \n    * [`show-if-has-permit`](#show-if-has-permit) \n    * [`show-if-has-permits`](https://github.com/lykmapipo#show-if-has-permits) \n    * [`show-if-has-any-permit`](#show-if-has-any-permit) \n* [Configurations](#configuration)\n    * [`afterSigninRedirectTo`](#aftersigninredirectto) \n    * [`afterSignoutRedirectTo`](#aftersignoutredirectto) \n    * [`signinUrl`](#signinurl) \n    * [`signinState`](#signinstate) \n    * [`signinRoute`](#signinroute) \n    * [`signinTemplateUrl`](#signintemplateurl) \n    * [`tokenPrefix`](#tokenprefix) \n    * [`tokenName`](#tokenname) \n    * [`profileKey`](#profilekey) \n    * [`storage`](#storage) \n    * [`authHeader`](#authheader)\n* [Testing](#testing)\n* [Development](#development)\n* [Contribute](#contribute)\n\n\n## Installation\n\n### Bower Installation\n```sh\n$ bower install --save ng-aa\n```\n\n### npm Installation\n```sh\n$ npm install --save ng-aa\n```\n\n## Usage\n- Include `ngAA` into your app index.html or `require('ng-aa')` it in your application\n\n```html\n\u003c!doctype html\u003e\n\u003chtml ng-app=\"yourApp\"\u003e\n\u003chead\u003e\n    ...\n\u003c/head\u003e\n\u003cbody\u003e\n    ...\n\n    \u003c!-- build:js(.) scripts/vendor.js --\u003e\n    \u003c!-- bower:js --\u003e\n    \u003cscript src=\"bower_components/angular/angular.js\"\u003e\u003c/script\u003e\n    \u003cscript src=\"bower_components/angular-ui-router/release/angular-ui-router.js\"\u003e\u003c/script\u003e\n    \u003cscript src=\"bower_components/angular-jwt/dist/angular-jwt.js\"\u003e\u003c/script\u003e\n    \u003cscript src=\"bower_components/ngstorage/ngStorage.js\"\u003e\u003c/script\u003e\n    \u003cscript src=\"bower_components/ng-aa/dist/ng-aa.js\"\u003e\u003c/script\u003e\n    \u003c!-- endbower --\u003e\n    \u003c!-- endbuild --\u003e\n\n    \u003c!-- build:js({.tmp,app}) scripts/yourApp.js --\u003e\n    \u003cscript src=\"scripts/app.js\"\u003e\u003c/script\u003e\n    \u003c!-- endbuild --\u003e\n\u003c/body\u003e\n\u003c/html\u003e\n```\n- Define your `signin` template to be used by `ngAA` at `views/signin.html`\n\u003cbr/\u003e**Note!** `user` in signin is no longer restricted to `email` and `password` you can use any structure applicable to your `API` or backend. \n\n```html\n\u003cform ng-submit=\"signin()\" role=\"form\" autocomplete=\"off\"\u003e\n    \u003clegend\u003eLogin\u003c/legend\u003e\n\n    \u003cdiv class=\"form-group\"\u003e\n        \u003clabel for=\"email\"\u003eEmail\u003c/label\u003e\n        \u003cinput ng-model=\"user.email\" type=\"email\" class=\"form-control\" id=\"email\" placeholder=\"Email\" required\u003e\n    \u003c/div\u003e\n\n    \u003cdiv class=\"form-group\"\u003e\n        \u003clabel for=\"password\"\u003ePassword\u003c/label\u003e\n        \u003cinput ng-model=\"user.password\" type=\"password\" class=\"form-control\" id=\"password\" placeholder=\"Password\"\u003e\n    \u003c/div\u003e\n\n    \u003cbutton type=\"submit\" class=\"btn btn-primary\"\u003eSubmit\u003c/button\u003e\n\u003c/form\u003e\n```\n\n- Require `ngAA` module into your angular application or module and define your redirect states \n```js\nangular\n.module('yourApp',[\n'ngAA'\n])\n.config(function($stateProvider, $urlRouterProvider, $authProvider) {\n        //configure after user signin redirect state\n        $authProvider.afterSigninRedirectTo = 'contact';\n        //configure after user signout redirect state\n        $authProvider.afterSignoutRedirectTo = 'main';\n});\n```\n\n- Define your application states and include `permits` or `authenticated` definitions to restrict access.\n```js\n$stateProvider\n    .state('main', {\n        url: '/',\n        templateUrl: 'views/main.html',\n        controller: 'MainCtrl',\n        data:{\n            authenticated:true //check for authenticity only\n        }\n    })\n    .state('about', {\n        url: '/about',\n        templateUrl: 'views/about.html',\n        controller: 'AboutCtrl',\n        data: {\n            permits: { //check for authenticity and permissions\n                withOnly: 'Post:delete'\n            }\n        }\n    })\n    .state('contact', {\n        url: '/contact',\n        templateUrl: 'views/contact.html',\n        controller: 'ContactCtrl',\n        data: {\n            permits: { //check for authenticity and permissions\n                withAll: ['Post:create','Post:edit']\n            }\n        },\n        resolve: {\n            profile: function($q, $auth) {\n                return $auth.getProfile();\n            }\n        }\n    });\n```\n\n- Implements your backend signin end point\n`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\n```js\n{\n    email:'user email',\n    password:'password'\n}\n\n// or your custom structure\n{\n    username:'',\n    password:''\n}\n```\nIn return it expect the following response format\n```js\n{\n    token:'your jwt valid token',\n    user:{\n        ....,\n        permissions:[...]\n    }\n}\n```\n\n## Authentication\n`ngAA` can restrict state transition to only authenticated user using `authenticated:true` state data. To ensure authenticity on state define it as below:\n\n```js\n'use strict';\nangular\n    .module('ngAPP', [\n        'ui.router',\n        'ngAA'\n    ])\n    .config(function($stateProvider, $urlRouterProvider, $authProvider) {\n        $stateProvider\n            .state('about', {\n                url: '/about',\n                templateUrl: 'views/about.html',\n                controller: 'AboutCtrl',\n                data: {\n                    authenticated:true\n                }\n            });\n            ...\n    });\n```\n\n## Permits\n`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:\n\n### withOnly \nWhich 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:\n```js\n'use strict';\nangular\n    .module('ngAPP', [\n        'ui.router',\n        'ngAA'\n    ])\n    .config(function($stateProvider, $urlRouterProvider, $authProvider) {\n        $stateProvider\n            .state('about', {\n                url: '/about',\n                templateUrl: 'views/about.html',\n                controller: 'AboutCtrl',\n                data: {\n                    permits: {\n                        withOnly: 'Post:delete'\n                    }\n                }\n            });\n            ...\n    });\n```\n\n\n### withAll \nWhich 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:\n```js\n'use strict';\nangular\n    .module('ngAPP', [\n        'ui.router',\n        'ngAA'\n    ])\n    .config(function($stateProvider, $urlRouterProvider, $authProvider) {\n        $stateProvider\n            .state('about', {\n                url: '/about',\n                templateUrl: 'views/about.html',\n                controller: 'AboutCtrl',\n                data: {\n                    permits: {\n                        withAll: ['Post:delete','Post:create']\n                    }\n                }\n            });\n            ...\n    });\n```\n\n\n### withAny\nWhich 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:\n```js\n'use strict';\nangular\n    .module('ngAPP', [\n        'ui.router',\n        'ngAA'\n    ])\n    .config(function($stateProvider, $urlRouterProvider, $authProvider) {\n        $stateProvider\n            .state('about', {\n                url: '/about',\n                templateUrl: 'views/about.html',\n                controller: 'AboutCtrl',\n                data: {\n                    permits: {\n                        withAny: ['Post:delete','Comment:delete']\n                    }\n                }\n            });\n            ...\n    });\n```\n\n\n## $auth API\n`ngAA $auth` service expose the following API to be used.\n\n### $auth.signout\nUsed to signout current signin user.\n```js\n$auth\n    .signout()\n    .then(function() {\n        //your codes\n        ...\n    })\n    .catch(function(error) {\n        //catch errors\n        ...\n    });\n```\n### $auth.isAuthenticated\nUsed to check if user is authenticated.\n```js\n$auth\n    .isAuthenticated()\n    .then(function(isAuthenticated) {\n        //your codes\n        ...\n    })\n    .catch(function(error) {\n        //catch errors\n        ...\n    });\n```\n\n### $auth.isAuthenticatedSync\nThis is the synchronous version of `isAuthenticated`.\n```js\n$rootScope.isAuthenticated = $auth.isAuthenticatedSync();\n```\n\n### $auth.getClaim\nUsed to get current user `claim` from the token.\n```js\n$auth\n    .getClaim()\n    .then(function(claim) {\n        //your codes\n        ...\n    })\n    .catch(function(error) {\n        //catch errors\n        ...\n    });   \n```\n\n### $auth.getProfile\nUsed to get current user profile. Its highly recommended to use `getProfile` in your state resolve properties to get the current user profile.\n```js\n$stateProvider\n    .state('contact', {\n        url: '/contact',\n        templateUrl: 'views/contact.html',\n        controller: 'ContactCtrl',\n        data: {\n            permits: {\n                withOnly: 'Post:create'\n            }\n        },\n        resolve: {\n            profile: function($q, $auth) {\n                return $auth.getProfile();\n            }\n        }\n    });   \n```\n\n### $auth.hasPermission\nUsed to check if user has a given permission.\n```js\n$auth\n    .hasPermission('Post:create')\n    .then(function(hasPermission) {\n        //your codes\n        ...\n    })\n    .catch(function(error) {\n        //catch errors\n        ...\n    }); \n```\n\n### $auth.hasPermissions\nUsed to check if user has all permissions\n```js\n$auth\n    .hasPermissions(['Post:create','Post:edit'])\n    .then(function(hasPermission) {\n        //your codes\n        ...\n    })\n    .catch(function(error) {\n        //catch errors\n        ...\n    }); \n```\n    \n### $auth.hasAnyPermission\nUsed to check if user has any of the permissions\n```js\n$auth\n    .hasAnyPermission(['Post:create','Post:edit'])\n    .then(function(hasPermission) {\n        //your codes\n        ...\n    })\n    .catch(function(error) {\n        //catch errors\n        ...\n    }); \n```\n\n## Directives\n\n### signout\n`ngAA` provide a `signout` directive which can be used in templates to signout the current sign-in user\n```html\n\u003cli ng-show=\"isAuthenticated\"\u003e\n    \u003ca data-signout\u003eSignout\u003c/a\u003e\n\u003c/li\u003e\n```\n\n### show-if-has-permit\n`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.\n```html\n\u003cli show-if-has-any-permit=\"Post:delete\"\u003e\n    ...\n\u003c/li\u003e\n```\n\n### show-if-has-permits\n`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.\n```html\n\u003cli show-if-has-permits=\"Post:view, Comment:create\"\u003e\n    ...\n\u003c/li\u003e\n```\n\n### show-if-has-any-permit\n`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.\n```html\n\u003cli show-if-has-any-permit=\"Post:view, Comment:create\"\u003e\n    ...\n\u003c/li\u003e\n```\n\n## Configuration\nOut 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\n\n### afterSigninRedirectTo\nSpecify which state to redirect user after signin successfully. Default to `home`. You can override this default on your module config as: \n```js\nangular\n.module('yourApp',[\n'ngAA'\n])\n.config(function($stateProvider, $urlRouterProvider, $authProvider) {\n        $authProvider.afterSigninRedirectTo = 'dashboard';\n});\n```\n\n### afterSignoutRedirectTo\nSpecify to which state to redirect user after signout. Defaults to `signin`. \nYou can override this default on your module config as: \n```js\nangular\n.module('yourApp',[\n'ngAA'\n])\n.config(function($stateProvider, $urlRouterProvider, $authProvider) {\n        $authProvider.afterSignoutRedirectTo = 'site';\n});\n```\n\n### signinUrl\nSpecify 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: \n```js\nangular\n.module('yourApp',[\n'ngAA'\n])\n.config(function($stateProvider, $urlRouterProvider, $authProvider) {\n        $authProvider.signinUrl = '/auth/signin';\n});\n```\n### signinState\nSpecify signin state to be used when `ngAA` when configuring it `ngAAAuthCtrl`. Default to `signin`. You can override this default on your module config as: \n```js\nangular\n.module('yourApp',[\n'ngAA'\n])\n.config(function($stateProvider, $urlRouterProvider, $authProvider) {\n        $authProvider.signinState = 'auth.signin';\n});\n```\n\n### signinRoute \nSpecify a signin route to be used with `ngAAAuthCtrl` internally. Default to `/signin`. You can override this default on your module config as: \n```js\nangular\n.module('yourApp',[\n'ngAA'\n])\n.config(function($stateProvider, $urlRouterProvider, $authProvider) {\n        $authProvider.signinRoute = '/auth/signin';\n});\n```\n\n### signinTemplateUrl\nThis 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: \n```js\nangular\n.module('yourApp',[\n'ngAA'\n])\n.config(function($stateProvider, $urlRouterProvider, $authProvider) {\n        $authProvider.signinTemplateUrl = 'views/auth/signin.html';\n});\n```\n\n### tokenPrefix \nA 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: \n```js\nangular\n.module('yourApp',[\n'ngAA'\n])\n.config(function($stateProvider, $urlRouterProvider, $authProvider) {\n        $authProvider.tokenPrefix = 'yourApp';\n});\n```\n\n### tokenName\nSpecify 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: \n```js\nangular\n.module('yourApp',[\n'ngAA'\n])\n.config(function($stateProvider, $urlRouterProvider, $authProvider) {\n        $authProvider.tokenName = 'token';\n});\n```\n\n### profileKey\nSpecify 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: \n```js\nangular\n.module('yourApp',[\n'ngAA'\n])\n.config(function($stateProvider, $urlRouterProvider, $authProvider) {\n        $authProvider.profileKey = 'profile';\n});\n```\n\n### storage\nSpecify 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: \n```js\nangular\n.module('yourApp',[\n'ngAA'\n])\n.config(function($stateProvider, $urlRouterProvider, $authProvider) {\n        $authProvider.storage = 'sessionStorage';\n});\n```\n\n### authHeader\nHttp `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: \n```js\nangular\n.module('yourApp',[\n'ngAA'\n])\n.config(function($stateProvider, $urlRouterProvider, $authProvider) {\n        $authProvider.authHeader = 'your authorization header name';\n});\n```\n\n## Testing\n* Clone this repository\n* Install all development dependencies\n```sh\n$ npm install \u0026\u0026 bower install\n```\n* Then run test\n```sh\n$ npm test\n```\n\n## Demo\n`ngAA` repository has a `example` witch can lauched by\n```sh\n$ grunt serve\n```\nthen supply any `email` and `password`\n\n## Development\n`ngAA` has set of useful `grunt` tasks to help you with development. By running\n```sh\n$ grunt\n```\n`ngAA` will be able watch your development environment for file changes and apply `jshint` and `karma` to the project.\n\n## Contribute\nFork this repo and push in your ideas. Do not forget to add a bit of test(s) of what value you adding.\n\n## Licence\n\nCopyright (c) 2015 lykmapipo\n\nPermission 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:\n\nThe above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n\nTHE 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.","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Flykmapipo%2Fngaa","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Flykmapipo%2Fngaa","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Flykmapipo%2Fngaa/lists"}