├── .editorconfig ├── .eslintignore ├── .eslintrc ├── .gitignore ├── .yo-rc.json ├── LICENSE ├── README.md ├── client ├── .editorconfig ├── .gitignore ├── README.md ├── angular-cli.json ├── e2e │ ├── app.e2e-spec.ts │ ├── app.po.ts │ └── tsconfig.json ├── karma.conf.js ├── package.json ├── protractor.conf.js ├── src │ ├── app │ │ ├── app.component.css │ │ ├── app.component.html │ │ ├── app.component.spec.ts │ │ ├── app.component.ts │ │ ├── app.module.ts │ │ ├── index.ts │ │ ├── pages │ │ │ ├── about │ │ │ │ ├── about.component.css │ │ │ │ ├── about.component.html │ │ │ │ ├── about.component.spec.ts │ │ │ │ └── about.component.ts │ │ │ ├── home │ │ │ │ ├── home.component.css │ │ │ │ ├── home.component.html │ │ │ │ ├── home.component.spec.ts │ │ │ │ └── home.component.ts │ │ │ ├── login │ │ │ │ ├── login.component.css │ │ │ │ ├── login.component.html │ │ │ │ ├── login.component.spec.ts │ │ │ │ └── login.component.ts │ │ │ └── reset-password │ │ │ │ ├── reset-password.component.css │ │ │ │ ├── reset-password.component.html │ │ │ │ ├── reset-password.component.spec.ts │ │ │ │ └── reset-password.component.ts │ │ ├── services │ │ │ ├── auth.guard.ts │ │ │ ├── auth.service.ts │ │ │ └── index.ts │ │ └── shared │ │ │ └── navgation │ │ │ ├── navgation.component.css │ │ │ ├── navgation.component.html │ │ │ ├── navgation.component.spec.ts │ │ │ └── navgation.component.ts │ ├── assets │ │ └── .gitkeep │ ├── environments │ │ ├── environment.prod.ts │ │ └── environment.ts │ ├── favicon.ico │ ├── index.html │ ├── main.ts │ ├── polyfills.ts │ ├── styles.css │ ├── test.ts │ ├── tsconfig.json │ └── typings.d.ts ├── tslint.json └── yarn.lock ├── common ├── mailgun.js └── models │ ├── app-user.js │ └── app-user.json ├── package.json ├── server ├── boot │ ├── authentication.js │ ├── my-boot-script.js │ └── root.js ├── component-config.json ├── config.json ├── datasources.json ├── middleware.development.json ├── middleware.json ├── model-config.json └── server.js └── test └── AppUser.js /.editorconfig: -------------------------------------------------------------------------------- 1 | # EditorConfig helps developers define and maintain consistent 2 | # coding styles between different editors and IDEs 3 | # http://editorconfig.org 4 | 5 | root = true 6 | 7 | [*] 8 | indent_style = space 9 | indent_size = 2 10 | end_of_line = lf 11 | charset = utf-8 12 | trim_trailing_whitespace = true 13 | insert_final_newline = true 14 | -------------------------------------------------------------------------------- /.eslintignore: -------------------------------------------------------------------------------- 1 | /client/ -------------------------------------------------------------------------------- /.eslintrc: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "loopback" 3 | } -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.csv 2 | *.dat 3 | *.iml 4 | *.log 5 | *.out 6 | *.pid 7 | *.seed 8 | *.sublime-* 9 | *.swo 10 | *.swp 11 | *.tgz 12 | *.xml 13 | .DS_Store 14 | .idea 15 | .project 16 | .strong-pm 17 | coverage 18 | node_modules 19 | npm-debug.log 20 | client/src/app/sdk 21 | server/config.local.json -------------------------------------------------------------------------------- /.yo-rc.json: -------------------------------------------------------------------------------- 1 | { 2 | "generator-loopback": {} 3 | } -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2016 Recurship 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # loopback-angular2-auth-demo 2 | This is a simple practice project build using [LoopBack.io](http://loopback.io) and [Angular2](https://angular.io/). 3 | 4 | - The main codebase is generated by [LoopBack](http://loopback.io). 5 | - The frontend (angular2) codebase (i.e., under `/client` folder) is generated by [`angular-cli`](https://github.com/angular/angular-cli). 6 | 7 | ### If you are looking to start an Angular2 + Loopback project, then use the `init` 8 | ### Tags to branch off this repository and start your own project. 9 | 10 | - [x] It currently supports authentication using the extended Loopback User model. 11 | - [x] It has bootstrap css configured and a basic 2 page protected routes. 12 | - [x] It has super test + mocha + chai configured for server testing 13 | (client testing handled by angular-cli) 14 | - [ ] Create a new model + add a relation 15 | - [ ] Use the new model/service in Angular2 16 | - [ ] Configure Mailgun for sending emails (verify emails on user signup + reset) 17 | - [ ] User sign up and reset 18 | 19 | ### How can I support developers? 20 | 21 | - Star our GitHub repo ⭐ 22 | - Create pull requests, submit bugs, suggest new features or documentation updates 🔧 23 | - Follow us on [Twitter](https://twitter.com/recurship) 🐾 24 | - Like our page on [Facebook](http://facebook.com/recurship) 👍 25 | 26 | ### Can I hire you guys? 27 | 28 | Yes! Visit our [homepage](http://recurship.com) or simply send a note to mashhoodr@recurship.com. We will be happy to work with you! 29 | 30 | ### Setup 31 | 32 | - Download / clone the repo: 33 | ``` 34 | $ git clone https://github.com/recurship/loopback-angular2-auth-demo.git 35 | ``` 36 | - open your terminal and run the following commands. 37 | ``` 38 | # if you want to use slc commands globally 39 | $ npm install -g strongloop 40 | 41 | # if you want to use ng commands globally 42 | $ npm install -g angular-cli 43 | 44 | # install project dependencies 45 | $ npm install && cd client && npm install && cd .. 46 | 47 | # to generate the Loopback Models and Services 48 | $ npm run generate 49 | ``` 50 | - Create a `config.local.json` file for extra configuration: 51 | ``` 52 | { 53 | "mailgun": { 54 | "apiKey": "", 55 | "domain": "" 56 | } 57 | } 58 | ``` 59 | 60 | ### Run 61 | ``` 62 | # start the server from /project root folder 63 | $ node . 64 | 65 | # start serving the angular from /project/client folder 66 | $ cd client 67 | $ ng serve 68 | ``` 69 | **Note:** ^ Make sure you serve both client and server simultaneously (in seperate terminal tabs). 70 | 71 | ### License 72 | 73 | MIT in [LICENSE](/LICENSE) file. 74 | -------------------------------------------------------------------------------- /client/.editorconfig: -------------------------------------------------------------------------------- 1 | # Editor configuration, see http://editorconfig.org 2 | root = true 3 | 4 | [*] 5 | charset = utf-8 6 | indent_style = space 7 | indent_size = 2 8 | insert_final_newline = true 9 | trim_trailing_whitespace = true 10 | 11 | [*.md] 12 | max_line_length = off 13 | trim_trailing_whitespace = false 14 | -------------------------------------------------------------------------------- /client/.gitignore: -------------------------------------------------------------------------------- 1 | # See http://help.github.com/ignore-files/ for more about ignoring files. 2 | 3 | # compiled output 4 | /dist 5 | /tmp 6 | 7 | # dependencies 8 | /node_modules 9 | /bower_components 10 | 11 | # IDEs and editors 12 | /.idea 13 | /.vscode 14 | .project 15 | .classpath 16 | .c9/ 17 | *.launch 18 | .settings/ 19 | 20 | # misc 21 | /.sass-cache 22 | /connect.lock 23 | /coverage/* 24 | /libpeerconnection.log 25 | npm-debug.log 26 | testem.log 27 | /typings 28 | 29 | # e2e 30 | /e2e/*.js 31 | /e2e/*.map 32 | 33 | #System Files 34 | .DS_Store 35 | Thumbs.db 36 | -------------------------------------------------------------------------------- /client/README.md: -------------------------------------------------------------------------------- 1 | # Client 2 | 3 | This project was generated with [angular-cli](https://github.com/angular/angular-cli) version 1.0.0-beta.21. 4 | 5 | ## Development server 6 | Run `ng serve` for a dev server. Navigate to `http://localhost:4200/`. The app will automatically reload if you change any of the source files. 7 | 8 | ## Code scaffolding 9 | 10 | Run `ng generate component component-name` to generate a new component. You can also use `ng generate directive/pipe/service/class`. 11 | 12 | ## Build 13 | 14 | Run `ng build` to build the project. The build artifacts will be stored in the `dist/` directory. Use the `-prod` flag for a production build. 15 | 16 | ## Running unit tests 17 | 18 | Run `ng test` to execute the unit tests via [Karma](https://karma-runner.github.io). 19 | 20 | ## Running end-to-end tests 21 | 22 | Run `ng e2e` to execute the end-to-end tests via [Protractor](http://www.protractortest.org/). 23 | Before running the tests make sure you are serving the app via `ng serve`. 24 | 25 | ## Deploying to Github Pages 26 | 27 | Run `ng github-pages:deploy` to deploy to Github Pages. 28 | 29 | ## Further help 30 | 31 | To get more help on the `angular-cli` use `ng --help` or go check out the [Angular-CLI README](https://github.com/angular/angular-cli/blob/master/README.md). 32 | -------------------------------------------------------------------------------- /client/angular-cli.json: -------------------------------------------------------------------------------- 1 | { 2 | "project": { 3 | "version": "1.0.0-beta.21", 4 | "name": "client" 5 | }, 6 | "apps": [ 7 | { 8 | "root": "src", 9 | "outDir": "dist", 10 | "assets": [ 11 | "assets", 12 | "favicon.ico" 13 | ], 14 | "index": "index.html", 15 | "main": "main.ts", 16 | "test": "test.ts", 17 | "tsconfig": "tsconfig.json", 18 | "prefix": "app", 19 | "mobile": false, 20 | "styles": [ 21 | "styles.css", 22 | "../node_modules/bootstrap/dist/css/bootstrap.min.css" 23 | ], 24 | "scripts": [], 25 | "environments": { 26 | "source": "environments/environment.ts", 27 | "dev": "environments/environment.ts", 28 | "prod": "environments/environment.prod.ts" 29 | } 30 | } 31 | ], 32 | "addons": [], 33 | "packages": [], 34 | "e2e": { 35 | "protractor": { 36 | "config": "./protractor.conf.js" 37 | } 38 | }, 39 | "test": { 40 | "karma": { 41 | "config": "./karma.conf.js" 42 | } 43 | }, 44 | "defaults": { 45 | "styleExt": "css", 46 | "prefixInterfaces": false, 47 | "inline": { 48 | "style": false, 49 | "template": false 50 | }, 51 | "spec": { 52 | "class": false, 53 | "component": true, 54 | "directive": true, 55 | "module": false, 56 | "pipe": true, 57 | "service": true 58 | } 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /client/e2e/app.e2e-spec.ts: -------------------------------------------------------------------------------- 1 | import { ClientPage } from './app.po'; 2 | 3 | describe('client App', function() { 4 | let page: ClientPage; 5 | 6 | beforeEach(() => { 7 | page = new ClientPage(); 8 | }); 9 | 10 | it('should display message saying app works', () => { 11 | page.navigateTo(); 12 | expect(page.getParagraphText()).toEqual('app works!'); 13 | }); 14 | }); 15 | -------------------------------------------------------------------------------- /client/e2e/app.po.ts: -------------------------------------------------------------------------------- 1 | import { browser, element, by } from 'protractor'; 2 | 3 | export class ClientPage { 4 | navigateTo() { 5 | return browser.get('/'); 6 | } 7 | 8 | getParagraphText() { 9 | return element(by.css('app-root h1')).getText(); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /client/e2e/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compileOnSave": false, 3 | "compilerOptions": { 4 | "declaration": false, 5 | "emitDecoratorMetadata": true, 6 | "experimentalDecorators": true, 7 | "module": "commonjs", 8 | "moduleResolution": "node", 9 | "outDir": "../dist/out-tsc-e2e", 10 | "sourceMap": true, 11 | "target": "es5", 12 | "typeRoots": [ 13 | "../node_modules/@types" 14 | ] 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /client/karma.conf.js: -------------------------------------------------------------------------------- 1 | // Karma configuration file, see link for more information 2 | // https://karma-runner.github.io/0.13/config/configuration-file.html 3 | 4 | module.exports = function (config) { 5 | config.set({ 6 | basePath: '', 7 | frameworks: ['jasmine', 'angular-cli'], 8 | plugins: [ 9 | require('karma-jasmine'), 10 | require('karma-chrome-launcher'), 11 | require('karma-remap-istanbul'), 12 | require('angular-cli/plugins/karma') 13 | ], 14 | files: [ 15 | { pattern: './src/test.ts', watched: false } 16 | ], 17 | preprocessors: { 18 | './src/test.ts': ['angular-cli'] 19 | }, 20 | mime: { 21 | 'text/x-typescript': ['ts','tsx'] 22 | }, 23 | remapIstanbulReporter: { 24 | reports: { 25 | html: 'coverage', 26 | lcovonly: './coverage/coverage.lcov' 27 | } 28 | }, 29 | angularCli: { 30 | config: './angular-cli.json', 31 | environment: 'dev' 32 | }, 33 | reporters: config.angularCli && config.angularCli.codeCoverage 34 | ? ['progress', 'karma-remap-istanbul'] 35 | : ['progress'], 36 | port: 9876, 37 | colors: true, 38 | logLevel: config.LOG_INFO, 39 | autoWatch: true, 40 | browsers: ['Chrome'], 41 | singleRun: false 42 | }); 43 | }; 44 | -------------------------------------------------------------------------------- /client/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "client", 3 | "version": "0.0.0", 4 | "license": "MIT", 5 | "angular-cli": {}, 6 | "scripts": { 7 | "start": "ng serve", 8 | "lint": "tslint \"src/**/*.ts\"", 9 | "test": "ng test", 10 | "pree2e": "webdriver-manager update", 11 | "e2e": "protractor" 12 | }, 13 | "private": true, 14 | "dependencies": { 15 | "@angular/common": "2.2.1", 16 | "@angular/compiler": "2.2.1", 17 | "@angular/core": "2.2.1", 18 | "@angular/forms": "2.2.1", 19 | "@angular/http": "2.2.1", 20 | "@angular/platform-browser": "2.2.1", 21 | "@angular/platform-browser-dynamic": "2.2.1", 22 | "@angular/router": "3.2.1", 23 | "bootstrap": "^3.3.7", 24 | "core-js": "^2.4.1", 25 | "rxjs": "5.0.0-beta.12", 26 | "ts-helpers": "^1.1.1", 27 | "zone.js": "^0.6.23" 28 | }, 29 | "devDependencies": { 30 | "@angular/compiler-cli": "2.2.1", 31 | "@types/jasmine": "2.5.38", 32 | "@types/node": "^6.0.42", 33 | "angular-cli": "1.0.0-beta.21", 34 | "codelyzer": "~1.0.0-beta.3", 35 | "jasmine-core": "2.5.2", 36 | "jasmine-spec-reporter": "2.5.0", 37 | "karma": "1.2.0", 38 | "karma-chrome-launcher": "^2.0.0", 39 | "karma-cli": "^1.0.1", 40 | "karma-jasmine": "^1.0.2", 41 | "karma-remap-istanbul": "^0.2.1", 42 | "protractor": "4.0.9", 43 | "ts-node": "1.2.1", 44 | "tslint": "3.13.0", 45 | "typescript": "~2.0.3", 46 | "webdriver-manager": "10.2.5" 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /client/protractor.conf.js: -------------------------------------------------------------------------------- 1 | // Protractor configuration file, see link for more information 2 | // https://github.com/angular/protractor/blob/master/docs/referenceConf.js 3 | 4 | /*global jasmine */ 5 | var SpecReporter = require('jasmine-spec-reporter'); 6 | 7 | exports.config = { 8 | allScriptsTimeout: 11000, 9 | specs: [ 10 | './e2e/**/*.e2e-spec.ts' 11 | ], 12 | capabilities: { 13 | 'browserName': 'chrome' 14 | }, 15 | directConnect: true, 16 | baseUrl: 'http://localhost:4200/', 17 | framework: 'jasmine', 18 | jasmineNodeOpts: { 19 | showColors: true, 20 | defaultTimeoutInterval: 30000, 21 | print: function() {} 22 | }, 23 | useAllAngular2AppRoots: true, 24 | beforeLaunch: function() { 25 | require('ts-node').register({ 26 | project: 'e2e' 27 | }); 28 | }, 29 | onPrepare: function() { 30 | jasmine.getEnv().addReporter(new SpecReporter()); 31 | } 32 | }; 33 | -------------------------------------------------------------------------------- /client/src/app/app.component.css: -------------------------------------------------------------------------------- 1 | .wrapper { 2 | padding: 20px; 3 | } -------------------------------------------------------------------------------- /client/src/app/app.component.html: -------------------------------------------------------------------------------- 1 |
2 | 3 | 4 |
-------------------------------------------------------------------------------- /client/src/app/app.component.spec.ts: -------------------------------------------------------------------------------- 1 | /* tslint:disable:no-unused-variable */ 2 | 3 | import { TestBed, async } from '@angular/core/testing'; 4 | import { AppComponent } from './app.component'; 5 | 6 | describe('AppComponent', () => { 7 | beforeEach(() => { 8 | TestBed.configureTestingModule({ 9 | declarations: [ 10 | AppComponent 11 | ], 12 | }); 13 | }); 14 | 15 | it('should create the app', async(() => { 16 | let fixture = TestBed.createComponent(AppComponent); 17 | let app = fixture.debugElement.componentInstance; 18 | expect(app).toBeTruthy(); 19 | })); 20 | 21 | it(`should have as title 'app works!'`, async(() => { 22 | let fixture = TestBed.createComponent(AppComponent); 23 | let app = fixture.debugElement.componentInstance; 24 | expect(app.title).toEqual('app works!'); 25 | })); 26 | 27 | it('should render title in a h1 tag', async(() => { 28 | let fixture = TestBed.createComponent(AppComponent); 29 | fixture.detectChanges(); 30 | let compiled = fixture.debugElement.nativeElement; 31 | expect(compiled.querySelector('h1').textContent).toContain('app works!'); 32 | })); 33 | }); 34 | -------------------------------------------------------------------------------- /client/src/app/app.component.ts: -------------------------------------------------------------------------------- 1 | import { Component } from '@angular/core'; 2 | 3 | @Component({ 4 | selector: 'app-root', 5 | templateUrl: './app.component.html', 6 | styleUrls: ['./app.component.css'] 7 | }) 8 | export class AppComponent { 9 | title = 'app works!'; 10 | } 11 | -------------------------------------------------------------------------------- /client/src/app/app.module.ts: -------------------------------------------------------------------------------- 1 | import { BrowserModule } from '@angular/platform-browser'; 2 | import { NgModule } from '@angular/core'; 3 | import { FormsModule } from '@angular/forms'; 4 | import { HttpModule } from '@angular/http'; 5 | import {RouterModule} from '@angular/router'; 6 | 7 | import { SDKModule } from './sdk'; 8 | import { AuthGuard, AuthService } from './services'; 9 | 10 | import { AppComponent } from './app.component'; 11 | import { NavgationComponent } from './shared/navgation/navgation.component'; 12 | import { HomeComponent } from './pages/home/home.component'; 13 | import { AboutComponent } from './pages/about/about.component'; 14 | import { LoginComponent } from './pages/login/login.component'; 15 | import { ResetPasswordComponent } from './pages/reset-password/reset-password.component'; 16 | 17 | @NgModule({ 18 | declarations: [ 19 | AppComponent, 20 | NavgationComponent, 21 | HomeComponent, 22 | AboutComponent, 23 | LoginComponent, 24 | ResetPasswordComponent 25 | ], 26 | imports: [ 27 | BrowserModule, 28 | FormsModule, 29 | HttpModule, 30 | SDKModule.forRoot(), 31 | RouterModule.forRoot([ 32 | { path: 'login', component: LoginComponent }, 33 | { path: 'reset', component: ResetPasswordComponent }, 34 | { path: '', component: HomeComponent, canActivate: [AuthGuard] }, 35 | { path: 'about', component: AboutComponent, canActivate: [AuthGuard] }, 36 | { path: '**', redirectTo: '/' } 37 | ]) 38 | ], 39 | providers: [ 40 | AuthGuard, 41 | AuthService 42 | ], 43 | bootstrap: [AppComponent] 44 | }) 45 | export class AppModule { } 46 | -------------------------------------------------------------------------------- /client/src/app/index.ts: -------------------------------------------------------------------------------- 1 | export * from './app.component'; 2 | export * from './app.module'; 3 | -------------------------------------------------------------------------------- /client/src/app/pages/about/about.component.css: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/recurship/loopback-angular2-auth-demo/b2279348d74c43202ab6b28e430af7e25787faf4/client/src/app/pages/about/about.component.css -------------------------------------------------------------------------------- /client/src/app/pages/about/about.component.html: -------------------------------------------------------------------------------- 1 |

2 | about works! 3 |

4 | -------------------------------------------------------------------------------- /client/src/app/pages/about/about.component.spec.ts: -------------------------------------------------------------------------------- 1 | /* tslint:disable:no-unused-variable */ 2 | import { async, ComponentFixture, TestBed } from '@angular/core/testing'; 3 | import { By } from '@angular/platform-browser'; 4 | import { DebugElement } from '@angular/core'; 5 | 6 | import { AboutComponent } from './about.component'; 7 | 8 | describe('AboutComponent', () => { 9 | let component: AboutComponent; 10 | let fixture: ComponentFixture; 11 | 12 | beforeEach(async(() => { 13 | TestBed.configureTestingModule({ 14 | declarations: [ AboutComponent ] 15 | }) 16 | .compileComponents(); 17 | })); 18 | 19 | beforeEach(() => { 20 | fixture = TestBed.createComponent(AboutComponent); 21 | component = fixture.componentInstance; 22 | fixture.detectChanges(); 23 | }); 24 | 25 | it('should create', () => { 26 | expect(component).toBeTruthy(); 27 | }); 28 | }); 29 | -------------------------------------------------------------------------------- /client/src/app/pages/about/about.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | 3 | @Component({ 4 | selector: 'app-about', 5 | templateUrl: './about.component.html', 6 | styleUrls: ['./about.component.css'] 7 | }) 8 | export class AboutComponent implements OnInit { 9 | 10 | constructor() { } 11 | 12 | ngOnInit() { 13 | } 14 | 15 | } 16 | -------------------------------------------------------------------------------- /client/src/app/pages/home/home.component.css: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/recurship/loopback-angular2-auth-demo/b2279348d74c43202ab6b28e430af7e25787faf4/client/src/app/pages/home/home.component.css -------------------------------------------------------------------------------- /client/src/app/pages/home/home.component.html: -------------------------------------------------------------------------------- 1 |

2 | home works! 3 |

4 | -------------------------------------------------------------------------------- /client/src/app/pages/home/home.component.spec.ts: -------------------------------------------------------------------------------- 1 | /* tslint:disable:no-unused-variable */ 2 | import { async, ComponentFixture, TestBed } from '@angular/core/testing'; 3 | import { By } from '@angular/platform-browser'; 4 | import { DebugElement } from '@angular/core'; 5 | 6 | import { HomeComponent } from './home.component'; 7 | 8 | describe('HomeComponent', () => { 9 | let component: HomeComponent; 10 | let fixture: ComponentFixture; 11 | 12 | beforeEach(async(() => { 13 | TestBed.configureTestingModule({ 14 | declarations: [ HomeComponent ] 15 | }) 16 | .compileComponents(); 17 | })); 18 | 19 | beforeEach(() => { 20 | fixture = TestBed.createComponent(HomeComponent); 21 | component = fixture.componentInstance; 22 | fixture.detectChanges(); 23 | }); 24 | 25 | it('should create', () => { 26 | expect(component).toBeTruthy(); 27 | }); 28 | }); 29 | -------------------------------------------------------------------------------- /client/src/app/pages/home/home.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | 3 | @Component({ 4 | selector: 'app-home', 5 | templateUrl: './home.component.html', 6 | styleUrls: ['./home.component.css'] 7 | }) 8 | export class HomeComponent implements OnInit { 9 | 10 | constructor() { } 11 | 12 | ngOnInit() { 13 | } 14 | 15 | } 16 | -------------------------------------------------------------------------------- /client/src/app/pages/login/login.component.css: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/recurship/loopback-angular2-auth-demo/b2279348d74c43202ab6b28e430af7e25787faf4/client/src/app/pages/login/login.component.css -------------------------------------------------------------------------------- /client/src/app/pages/login/login.component.html: -------------------------------------------------------------------------------- 1 |
2 |
3 |
4 |

Login

5 | 6 | 7 |
8 | Login 9 | Reset password 10 | Signup 11 |
12 | 13 |
14 |

Reset Password

15 | 16 |
17 | Reset password 18 | Login 19 | Signup 20 |
21 | 22 |
23 |

Login

24 | 25 | 26 | 27 | 28 | 32 |
33 | Signup 35 | Reset password 36 | Login 37 |
38 |
39 |
40 | -------------------------------------------------------------------------------- /client/src/app/pages/login/login.component.spec.ts: -------------------------------------------------------------------------------- 1 | /* tslint:disable:no-unused-variable */ 2 | import { async, ComponentFixture, TestBed } from '@angular/core/testing'; 3 | import { By } from '@angular/platform-browser'; 4 | import { DebugElement } from '@angular/core'; 5 | 6 | import { LoginComponent } from './login.component'; 7 | 8 | describe('LoginComponent', () => { 9 | let component: LoginComponent; 10 | let fixture: ComponentFixture; 11 | 12 | beforeEach(async(() => { 13 | TestBed.configureTestingModule({ 14 | declarations: [ LoginComponent ] 15 | }) 16 | .compileComponents(); 17 | })); 18 | 19 | beforeEach(() => { 20 | fixture = TestBed.createComponent(LoginComponent); 21 | component = fixture.componentInstance; 22 | fixture.detectChanges(); 23 | }); 24 | 25 | it('should create', () => { 26 | expect(component).toBeTruthy(); 27 | }); 28 | }); 29 | -------------------------------------------------------------------------------- /client/src/app/pages/login/login.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | import { Router } from '@angular/router'; 3 | 4 | import { SDKToken, AppUserApi } from '../../sdk'; 5 | import { AuthService } from '../../services/auth.service'; 6 | @Component({ 7 | selector: 'app-login', 8 | templateUrl: './login.component.html', 9 | styleUrls: ['./login.component.css'] 10 | }) 11 | export class LoginComponent implements OnInit { 12 | 13 | private state: string = 'login'; 14 | 15 | constructor( 16 | private userApi: AppUserApi, 17 | private authService: AuthService, 18 | private router: Router) { 19 | } 20 | 21 | ngOnInit() {} 22 | 23 | setState(state: string) { 24 | this.state = state; 25 | } 26 | 27 | login(email, password) { 28 | this.userApi.login({ email: email.value, password: password.value }) 29 | .subscribe((token: SDKToken) => { 30 | this.authService.setUser(token); 31 | this.router.navigate(['/']); 32 | }, err => { 33 | alert(err && err.message ? err.message : 'Login failed!'); 34 | password.value = ''; 35 | }); 36 | } 37 | 38 | signup(username, email, password, passwordConfirm, type) { 39 | if(password.value !== passwordConfirm.value) { 40 | return alert('Passwords must match!'); 41 | } 42 | 43 | this.userApi.create({ 44 | username: username.value, 45 | email: email.value, 46 | password: password.value, 47 | type: type.value 48 | }).subscribe((res) => { 49 | console.log('created.', res); 50 | if(res.id) { 51 | this.login(email, password); 52 | } 53 | }); 54 | } 55 | 56 | resetPassword(email) { 57 | this.userApi.resetPassword({ 58 | email: email.value 59 | }).subscribe((res) => { 60 | console.log('Restted!', res); 61 | }) 62 | } 63 | 64 | } 65 | -------------------------------------------------------------------------------- /client/src/app/pages/reset-password/reset-password.component.css: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/recurship/loopback-angular2-auth-demo/b2279348d74c43202ab6b28e430af7e25787faf4/client/src/app/pages/reset-password/reset-password.component.css -------------------------------------------------------------------------------- /client/src/app/pages/reset-password/reset-password.component.html: -------------------------------------------------------------------------------- 1 |
2 |
3 |
4 |

Reset Password

5 | 6 | 7 |
8 | Reset and login 9 |
10 |
11 |
-------------------------------------------------------------------------------- /client/src/app/pages/reset-password/reset-password.component.spec.ts: -------------------------------------------------------------------------------- 1 | /* tslint:disable:no-unused-variable */ 2 | import { async, ComponentFixture, TestBed } from '@angular/core/testing'; 3 | import { By } from '@angular/platform-browser'; 4 | import { DebugElement } from '@angular/core'; 5 | 6 | import { ResetPasswordComponent } from './reset-password.component'; 7 | 8 | describe('ResetPasswordComponent', () => { 9 | let component: ResetPasswordComponent; 10 | let fixture: ComponentFixture; 11 | 12 | beforeEach(async(() => { 13 | TestBed.configureTestingModule({ 14 | declarations: [ ResetPasswordComponent ] 15 | }) 16 | .compileComponents(); 17 | })); 18 | 19 | beforeEach(() => { 20 | fixture = TestBed.createComponent(ResetPasswordComponent); 21 | component = fixture.componentInstance; 22 | fixture.detectChanges(); 23 | }); 24 | 25 | it('should create', () => { 26 | expect(component).toBeTruthy(); 27 | }); 28 | }); 29 | -------------------------------------------------------------------------------- /client/src/app/pages/reset-password/reset-password.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | import { ActivatedRoute } from '@angular/router'; 3 | import {Http} from '@angular/http'; 4 | 5 | import { LoopBackConfig } from '../../sdk'; 6 | @Component({ 7 | selector: 'app-reset-password', 8 | templateUrl: './reset-password.component.html', 9 | styleUrls: ['./reset-password.component.css'] 10 | }) 11 | export class ResetPasswordComponent implements OnInit { 12 | 13 | accessToken: string = ''; 14 | 15 | constructor(private http: Http, private route: ActivatedRoute) { 16 | this.accessToken = this.route.snapshot.queryParams['token']; 17 | // TODO validate the token using API 18 | if(!this.accessToken) { 19 | alert('No token found.'); 20 | } 21 | } 22 | 23 | ngOnInit() { 24 | } 25 | 26 | resetPassword(password, newPassword) { 27 | // TODO extend the AppUser service and put this there. 28 | this.http.post( 29 | `${LoopBackConfig.getPath()}/${LoopBackConfig.getApiVersion()}/ApiUsers/reset-password?accessToken=${this.accessToken}`, 30 | { 31 | password: password.value 32 | }) 33 | .subscribe((res) => { 34 | console.log('Rest complete', res); 35 | }); 36 | } 37 | 38 | } 39 | -------------------------------------------------------------------------------- /client/src/app/services/auth.guard.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from "@angular/core"; 2 | import { CanActivate, Router, ActivatedRouteSnapshot, RouterStateSnapshot } from "@angular/router"; 3 | import { AuthService } from "./auth.service"; 4 | 5 | @Injectable() 6 | export class AuthGuard implements CanActivate { 7 | constructor(private router: Router, private auth: AuthService) {} 8 | 9 | canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot) { 10 | let path: string = next.url[0] ? next.url[0].path : ""; 11 | if (((path === "login") || (path === "register")) && this.isAuthenticated()) { 12 | this.router.navigate(["/"]); 13 | return false; 14 | } else if (((path === "login") || (path === "register")) && (!this.isAuthenticated()) ) { 15 | return true; 16 | } else if (((path !== "login") || (path !== "register")) && (!this.isAuthenticated()) ){ 17 | this.router.navigate(["/login"]); 18 | return true; 19 | }else{ 20 | return true; 21 | } 22 | } 23 | 24 | isAuthenticated(): boolean { 25 | return this.auth.getAccessTokenId(); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /client/src/app/services/auth.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { SDKToken } from '../sdk'; 3 | import { LoopBackAuth } from '../sdk'; 4 | 5 | declare var Object: any; 6 | @Injectable() 7 | export class AuthService extends LoopBackAuth { 8 | private sessiontoken: SDKToken = new SDKToken(); 9 | private remembeMe : boolean = true; 10 | constructor() { 11 | super(); 12 | this.loadFromSession(); 13 | } 14 | 15 | clear(): void{ 16 | super.clear(); 17 | this.clearFromSession(); 18 | } 19 | 20 | saveToSession(): void { 21 | this.remembeMe = false; 22 | this.persist('id', super.getAccessTokenId()); 23 | this.persist('userId', super.getCurrentUserId); 24 | this.persist('user', super.getCurrentUserData()); 25 | } 26 | 27 | loadFromSession(): void{ 28 | this.sessiontoken.id = sessionStorage.getItem('id'); 29 | this.sessiontoken.userId = sessionStorage.getItem('userId'); 30 | this.sessiontoken.user = sessionStorage.getItem('user'); 31 | if(this.sessiontoken.id && this.sessiontoken.user && this.sessiontoken.userId){ 32 | super.setUser(this.sessiontoken); 33 | } 34 | } 35 | 36 | clearFromSession(): void{ 37 | Object.keys(this.sessiontoken).forEach(prop => sessionStorage.removeItem(prop)); 38 | this.sessiontoken = new SDKToken(); 39 | } 40 | 41 | persist(prop: string, value: any): void { 42 | if(this.remembeMe) { 43 | super.persist(prop, value); 44 | } else { 45 | sessionStorage.setItem(prop, JSON.stringify(value)); 46 | } 47 | } 48 | } -------------------------------------------------------------------------------- /client/src/app/services/index.ts: -------------------------------------------------------------------------------- 1 | export * from './auth.service'; 2 | export * from './auth.guard'; -------------------------------------------------------------------------------- /client/src/app/shared/navgation/navgation.component.css: -------------------------------------------------------------------------------- 1 | ul { 2 | margin-bottom: 20px; 3 | } -------------------------------------------------------------------------------- /client/src/app/shared/navgation/navgation.component.html: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /client/src/app/shared/navgation/navgation.component.spec.ts: -------------------------------------------------------------------------------- 1 | /* tslint:disable:no-unused-variable */ 2 | import { async, ComponentFixture, TestBed } from '@angular/core/testing'; 3 | import { By } from '@angular/platform-browser'; 4 | import { DebugElement } from '@angular/core'; 5 | 6 | import { NavgationComponent } from './navgation.component'; 7 | 8 | describe('NavgationComponent', () => { 9 | let component: NavgationComponent; 10 | let fixture: ComponentFixture; 11 | 12 | beforeEach(async(() => { 13 | TestBed.configureTestingModule({ 14 | declarations: [ NavgationComponent ] 15 | }) 16 | .compileComponents(); 17 | })); 18 | 19 | beforeEach(() => { 20 | fixture = TestBed.createComponent(NavgationComponent); 21 | component = fixture.componentInstance; 22 | fixture.detectChanges(); 23 | }); 24 | 25 | it('should create', () => { 26 | expect(component).toBeTruthy(); 27 | }); 28 | }); 29 | -------------------------------------------------------------------------------- /client/src/app/shared/navgation/navgation.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | import { Router } from '@angular/router'; 3 | 4 | import { AppUserApi } from '../../sdk'; 5 | 6 | @Component({ 7 | selector: 'app-navgation', 8 | templateUrl: './navgation.component.html', 9 | styleUrls: ['./navgation.component.css'] 10 | }) 11 | export class NavgationComponent implements OnInit { 12 | 13 | isLogin: boolean = false; 14 | 15 | constructor( 16 | private router: Router, 17 | private userApi: AppUserApi) { 18 | 19 | this.router.events.subscribe((route) => { 20 | this.isLogin = route.url.match('/login') !== null || 21 | route.url.match('/reset') !== null; 22 | }); 23 | } 24 | 25 | ngOnInit() {} 26 | 27 | logout() { 28 | this.userApi.logout().subscribe((response) => { 29 | this.router.navigate(['/login']); 30 | }); 31 | } 32 | 33 | } 34 | -------------------------------------------------------------------------------- /client/src/assets/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/recurship/loopback-angular2-auth-demo/b2279348d74c43202ab6b28e430af7e25787faf4/client/src/assets/.gitkeep -------------------------------------------------------------------------------- /client/src/environments/environment.prod.ts: -------------------------------------------------------------------------------- 1 | export const environment = { 2 | production: true 3 | }; 4 | -------------------------------------------------------------------------------- /client/src/environments/environment.ts: -------------------------------------------------------------------------------- 1 | // The file contents for the current environment will overwrite these during build. 2 | // The build system defaults to the dev environment which uses `environment.ts`, but if you do 3 | // `ng build --env=prod` then `environment.prod.ts` will be used instead. 4 | // The list of which env maps to which file can be found in `angular-cli.json`. 5 | 6 | export const environment = { 7 | production: false 8 | }; 9 | -------------------------------------------------------------------------------- /client/src/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/recurship/loopback-angular2-auth-demo/b2279348d74c43202ab6b28e430af7e25787faf4/client/src/favicon.ico -------------------------------------------------------------------------------- /client/src/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Client 6 | 7 | 8 | 9 | 10 | 11 | 12 | Loading... 13 | 14 | 15 | -------------------------------------------------------------------------------- /client/src/main.ts: -------------------------------------------------------------------------------- 1 | import './polyfills.ts'; 2 | 3 | import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; 4 | import { enableProdMode } from '@angular/core'; 5 | import { environment } from './environments/environment'; 6 | import { AppModule } from './app/'; 7 | 8 | if (environment.production) { 9 | enableProdMode(); 10 | } 11 | 12 | platformBrowserDynamic().bootstrapModule(AppModule); 13 | -------------------------------------------------------------------------------- /client/src/polyfills.ts: -------------------------------------------------------------------------------- 1 | // This file includes polyfills needed by Angular 2 and is loaded before 2 | // the app. You can add your own extra polyfills to this file. 3 | import 'core-js/es6/symbol'; 4 | import 'core-js/es6/object'; 5 | import 'core-js/es6/function'; 6 | import 'core-js/es6/parse-int'; 7 | import 'core-js/es6/parse-float'; 8 | import 'core-js/es6/number'; 9 | import 'core-js/es6/math'; 10 | import 'core-js/es6/string'; 11 | import 'core-js/es6/date'; 12 | import 'core-js/es6/array'; 13 | import 'core-js/es6/regexp'; 14 | import 'core-js/es6/map'; 15 | import 'core-js/es6/set'; 16 | import 'core-js/es6/reflect'; 17 | 18 | import 'core-js/es7/reflect'; 19 | import 'zone.js/dist/zone'; 20 | -------------------------------------------------------------------------------- /client/src/styles.css: -------------------------------------------------------------------------------- 1 | /* You can add global styles to this file, and also import other style files */ 2 | -------------------------------------------------------------------------------- /client/src/test.ts: -------------------------------------------------------------------------------- 1 | import './polyfills.ts'; 2 | 3 | import 'zone.js/dist/long-stack-trace-zone'; 4 | import 'zone.js/dist/proxy.js'; 5 | import 'zone.js/dist/sync-test'; 6 | import 'zone.js/dist/jasmine-patch'; 7 | import 'zone.js/dist/async-test'; 8 | import 'zone.js/dist/fake-async-test'; 9 | import { getTestBed } from '@angular/core/testing'; 10 | import { 11 | BrowserDynamicTestingModule, 12 | platformBrowserDynamicTesting 13 | } from '@angular/platform-browser-dynamic/testing'; 14 | 15 | // Unfortunately there's no typing for the `__karma__` variable. Just declare it as any. 16 | declare var __karma__: any; 17 | declare var require: any; 18 | 19 | // Prevent Karma from running prematurely. 20 | __karma__.loaded = function () {}; 21 | 22 | // First, initialize the Angular testing environment. 23 | getTestBed().initTestEnvironment( 24 | BrowserDynamicTestingModule, 25 | platformBrowserDynamicTesting() 26 | ); 27 | // Then we find all the tests. 28 | let context = require.context('./', true, /\.spec\.ts/); 29 | // And load the modules. 30 | context.keys().map(context); 31 | // Finally, start Karma to run the tests. 32 | __karma__.start(); 33 | -------------------------------------------------------------------------------- /client/src/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "baseUrl": "", 4 | "declaration": false, 5 | "emitDecoratorMetadata": true, 6 | "experimentalDecorators": true, 7 | "lib": ["es6", "dom"], 8 | "mapRoot": "./", 9 | "module": "es6", 10 | "moduleResolution": "node", 11 | "outDir": "../dist/out-tsc", 12 | "sourceMap": true, 13 | "target": "es5", 14 | "typeRoots": [ 15 | "../node_modules/@types" 16 | ] 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /client/src/typings.d.ts: -------------------------------------------------------------------------------- 1 | // Typings reference file, you can add your own global typings here 2 | // https://www.typescriptlang.org/docs/handbook/writing-declaration-files.html 3 | -------------------------------------------------------------------------------- /client/tslint.json: -------------------------------------------------------------------------------- 1 | { 2 | "rulesDirectory": [ 3 | "node_modules/codelyzer" 4 | ], 5 | "rules": { 6 | "class-name": true, 7 | "comment-format": [ 8 | true, 9 | "check-space" 10 | ], 11 | "curly": true, 12 | "eofline": true, 13 | "forin": true, 14 | "indent": [ 15 | true, 16 | "spaces" 17 | ], 18 | "label-position": true, 19 | "label-undefined": true, 20 | "max-line-length": [ 21 | true, 22 | 140 23 | ], 24 | "member-access": false, 25 | "member-ordering": [ 26 | true, 27 | "static-before-instance", 28 | "variables-before-functions" 29 | ], 30 | "no-arg": true, 31 | "no-bitwise": true, 32 | "no-console": [ 33 | true, 34 | "debug", 35 | "info", 36 | "time", 37 | "timeEnd", 38 | "trace" 39 | ], 40 | "no-construct": true, 41 | "no-debugger": true, 42 | "no-duplicate-key": true, 43 | "no-duplicate-variable": true, 44 | "no-empty": false, 45 | "no-eval": true, 46 | "no-inferrable-types": true, 47 | "no-shadowed-variable": true, 48 | "no-string-literal": false, 49 | "no-switch-case-fall-through": true, 50 | "no-trailing-whitespace": true, 51 | "no-unused-expression": true, 52 | "no-unused-variable": true, 53 | "no-unreachable": true, 54 | "no-use-before-declare": true, 55 | "no-var-keyword": true, 56 | "object-literal-sort-keys": false, 57 | "one-line": [ 58 | true, 59 | "check-open-brace", 60 | "check-catch", 61 | "check-else", 62 | "check-whitespace" 63 | ], 64 | "quotemark": [ 65 | true, 66 | "single" 67 | ], 68 | "radix": true, 69 | "semicolon": [ 70 | "always" 71 | ], 72 | "triple-equals": [ 73 | true, 74 | "allow-null-check" 75 | ], 76 | "typedef-whitespace": [ 77 | true, 78 | { 79 | "call-signature": "nospace", 80 | "index-signature": "nospace", 81 | "parameter": "nospace", 82 | "property-declaration": "nospace", 83 | "variable-declaration": "nospace" 84 | } 85 | ], 86 | "variable-name": false, 87 | "whitespace": [ 88 | true, 89 | "check-branch", 90 | "check-decl", 91 | "check-operator", 92 | "check-separator", 93 | "check-type" 94 | ], 95 | 96 | "directive-selector-prefix": [true, "app"], 97 | "component-selector-prefix": [true, "app"], 98 | "directive-selector-name": [true, "camelCase"], 99 | "component-selector-name": [true, "kebab-case"], 100 | "directive-selector-type": [true, "attribute"], 101 | "component-selector-type": [true, "element"], 102 | "use-input-property-decorator": true, 103 | "use-output-property-decorator": true, 104 | "use-host-property-decorator": true, 105 | "no-input-rename": true, 106 | "no-output-rename": true, 107 | "use-life-cycle-interface": true, 108 | "use-pipe-transform-interface": true, 109 | "component-class-suffix": true, 110 | "directive-class-suffix": true, 111 | "templates-use-public": true, 112 | "invoke-injectable": true 113 | } 114 | } 115 | -------------------------------------------------------------------------------- /common/mailgun.js: -------------------------------------------------------------------------------- 1 | 2 | var app = require('../server/server'); 3 | 4 | if(!app.get('mailgun').apiKey || !app.get('mailgun').domain) { 5 | throw new Error('Please configure Mailgun variables in server/config.local.json'); 6 | } 7 | 8 | var mailgun = require('mailgun-js')({ 9 | apiKey: app.get('mailgun').apiKey, 10 | domain: app.get('mailgun').domain 11 | }); 12 | 13 | module.exports = mailgun; -------------------------------------------------------------------------------- /common/models/app-user.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | var app = require('../../server/server'); 4 | var mailGun = require('../mailgun'); 5 | var handlers = {}; 6 | var User; 7 | 8 | handlers.sendResetMail = (userInstance) => { 9 | console.log(userInstance); 10 | var data = { 11 | from: 'Admin ', 12 | to: userInstance.email, 13 | subject: 'Reset Password', 14 | text: ` 15 | Please reset your password at 16 | http://${app.get('host')}:${app.get('port')}/reset?token=${userInstance.accessToken.id}` 17 | }; 18 | 19 | mailGun.messages().send(data,(err, body) => { 20 | if(err) console.log('Unable to send create email', err); 21 | console.log('Reset done', body, data); 22 | }); 23 | } 24 | 25 | app.post('/api/ApiUsers/reset-password', function(req, res, next) { 26 | if (!req.query.accessToken) return res.sendStatus(401); 27 | app.models.AccessToken.findById(req.query.accessToken, (err, token) => { 28 | User.findById(token.userId, function(err, user) { 29 | if (err) return res.sendStatus(404); 30 | user.updateAttribute('password', req.body.password, function(err, user) { 31 | if (err) return res.sendStatus(404); 32 | res.send(200); 33 | }); 34 | }); 35 | }); 36 | }); 37 | 38 | 39 | module.exports = function(AppUser) { 40 | User = AppUser; 41 | AppUser.validatesInclusionOf('type', {in: ['free', 'paid']}); 42 | AppUser.validatesUniquenessOf('email', {message: 'Email is already present.'}); 43 | AppUser.validatesUniquenessOf('username', {message: 'Username is already taken.'}); 44 | AppUser.on('resetPasswordRequest', handlers.sendResetMail); 45 | }; 46 | 47 | -------------------------------------------------------------------------------- /common/models/app-user.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "AppUser", 3 | "plural": "AppUsers", 4 | "base": "User", 5 | "idInjection": true, 6 | "options": { 7 | "validateUpsert": true 8 | }, 9 | "properties": { 10 | "type": { 11 | "type": "string", 12 | "required": true, 13 | "default": "free" 14 | }, 15 | "username": { 16 | "type": "string", 17 | "required": true 18 | }, 19 | "email": { 20 | "type": "string", 21 | "required": true 22 | } 23 | }, 24 | "validations": [], 25 | "relations": {}, 26 | "acls": [], 27 | "methods": {} 28 | } 29 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "loopback-auth-demo", 3 | "version": "1.0.0", 4 | "main": "server/server.js", 5 | "scripts": { 6 | "lint": "eslint .", 7 | "start": "node .", 8 | "posttest": "npm run lint && nsp check", 9 | "test": "mocha", 10 | "remove-sdk": "rm -rf client/src/app/sdk", 11 | "generate": "npm run remove-sdk;./node_modules/.bin/lb-sdk server/server client/src/app/sdk -i disabled" 12 | }, 13 | "dependencies": { 14 | "@mean-expert/loopback-sdk-builder": "^2.1.0-beta.17", 15 | "compression": "^1.0.3", 16 | "cors": "^2.5.2", 17 | "helmet": "^1.3.0", 18 | "loopback": "^2.22.0", 19 | "loopback-boot": "^2.6.5", 20 | "loopback-component-explorer": "^2.4.0", 21 | "loopback-connector-mysql": "^2.4.0", 22 | "loopback-datasource-juggler": "^2.39.0", 23 | "mailgun-js": "^0.7.14", 24 | "serve-favicon": "^2.0.1", 25 | "strong-error-handler": "^1.0.1" 26 | }, 27 | "devDependencies": { 28 | "chai": "^3.5.0", 29 | "chai-http": "^3.0.0", 30 | "eslint": "^2.13.1", 31 | "eslint-config-loopback": "^4.0.0", 32 | "mocha": "^3.2.0", 33 | "nsp": "^2.1.0", 34 | "supertest": "^2.0.1" 35 | }, 36 | "repository": { 37 | "type": "", 38 | "url": "" 39 | }, 40 | "license": "UNLICENSED", 41 | "description": "loopback-auth-demo" 42 | } 43 | -------------------------------------------------------------------------------- /server/boot/authentication.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | module.exports = function enableAuthentication(server) { 4 | // enable authentication 5 | server.enableAuth(); 6 | }; 7 | -------------------------------------------------------------------------------- /server/boot/my-boot-script.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | // Any objects you want to have on initialization please add here. 4 | module.exports = function(app) { 5 | var AppUser = app.models.AppUser; 6 | AppUser.destroyAll(function() { 7 | AppUser.create( 8 | { 9 | username: 'test', 10 | type: 'free', 11 | email: 'test@user.com', 12 | password: '123456', 13 | }, function(err, userInstance) { 14 | if (err) console.log('===>', err); 15 | console.log(userInstance); 16 | }); 17 | }); 18 | }; 19 | 20 | -------------------------------------------------------------------------------- /server/boot/root.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | module.exports = function(server) { 4 | // Install a `/` route that returns server status 5 | var router = server.loopback.Router(); 6 | router.get('/', server.loopback.status()); 7 | server.use(router); 8 | }; 9 | -------------------------------------------------------------------------------- /server/component-config.json: -------------------------------------------------------------------------------- 1 | { 2 | "loopback-component-explorer": { 3 | "mountPath": "/explorer" 4 | } 5 | } 6 | -------------------------------------------------------------------------------- /server/config.json: -------------------------------------------------------------------------------- 1 | { 2 | "restApiRoot": "/api", 3 | "host": "0.0.0.0", 4 | "port": 3000, 5 | "remoting": { 6 | "context": false, 7 | "rest": { 8 | "normalizeHttpPath": false, 9 | "xml": false 10 | }, 11 | "json": { 12 | "strict": false, 13 | "limit": "100kb" 14 | }, 15 | "urlencoded": { 16 | "extended": true, 17 | "limit": "100kb" 18 | }, 19 | "cors": false, 20 | "handleErrors": false 21 | }, 22 | "legacyExplorer": false 23 | } 24 | -------------------------------------------------------------------------------- /server/datasources.json: -------------------------------------------------------------------------------- 1 | { 2 | "db": { 3 | "host": "localhost", 4 | "port": 3306, 5 | "database": "loopback-auth-demo", 6 | "username": "root", 7 | "password": "test", 8 | "name": "db", 9 | "connector": "mysql", 10 | "debug": false 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /server/middleware.development.json: -------------------------------------------------------------------------------- 1 | { 2 | "final:after": { 3 | "strong-error-handler": { 4 | "params": { 5 | "debug": true, 6 | "log": true 7 | } 8 | } 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /server/middleware.json: -------------------------------------------------------------------------------- 1 | { 2 | "initial:before": { 3 | "loopback#favicon": {} 4 | }, 5 | "initial": { 6 | "compression": {}, 7 | "cors": { 8 | "params": { 9 | "origin": true, 10 | "credentials": true, 11 | "maxAge": 86400 12 | } 13 | }, 14 | "helmet#xssFilter": {}, 15 | "helmet#frameguard": { 16 | "params": [ 17 | "deny" 18 | ] 19 | }, 20 | "helmet#hsts": { 21 | "params": { 22 | "maxAge": 0, 23 | "includeSubdomains": true 24 | } 25 | }, 26 | "helmet#hidePoweredBy": {}, 27 | "helmet#ieNoOpen": {}, 28 | "helmet#noSniff": {}, 29 | "helmet#noCache": { 30 | "enabled": false 31 | } 32 | }, 33 | "session": {}, 34 | "auth": {}, 35 | "parse": { 36 | "body-parser#json": {}, 37 | "body-parser#urlencoded": {"params": { "extended": true }} 38 | }, 39 | "routes": { 40 | "loopback#rest": { 41 | "paths": [ 42 | "${restApiRoot}" 43 | ] 44 | } 45 | }, 46 | "files": {}, 47 | "final": { 48 | "loopback#urlNotFound": {} 49 | }, 50 | "final:after": { 51 | "strong-error-handler": {} 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /server/model-config.json: -------------------------------------------------------------------------------- 1 | { 2 | "_meta": { 3 | "sources": [ 4 | "loopback/common/models", 5 | "loopback/server/models", 6 | "../common/models", 7 | "./models" 8 | ], 9 | "mixins": [ 10 | "loopback/common/mixins", 11 | "loopback/server/mixins", 12 | "../common/mixins", 13 | "./mixins" 14 | ] 15 | }, 16 | "User": { 17 | "dataSource": "db", 18 | "public": false 19 | }, 20 | "AccessToken": { 21 | "dataSource": "db", 22 | "public": false 23 | }, 24 | "ACL": { 25 | "dataSource": "db", 26 | "public": false 27 | }, 28 | "RoleMapping": { 29 | "dataSource": "db", 30 | "public": false 31 | }, 32 | "Role": { 33 | "dataSource": "db", 34 | "public": false 35 | }, 36 | "AppUser": { 37 | "dataSource": "db", 38 | "public": true, 39 | "options": { 40 | "emailVerificationRequired": false 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /server/server.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | var loopback = require('loopback'); 4 | var boot = require('loopback-boot'); 5 | 6 | var app = module.exports = loopback(); 7 | 8 | app.start = function() { 9 | // start the web server 10 | return app.listen(function() { 11 | app.emit('started'); 12 | var baseUrl = app.get('url').replace(/\/$/, ''); 13 | console.log('Web server listening at: %s', baseUrl); 14 | if (app.get('loopback-component-explorer')) { 15 | var explorerPath = app.get('loopback-component-explorer').mountPath; 16 | console.log('Browse your REST API at %s%s', baseUrl, explorerPath); 17 | } 18 | }); 19 | }; 20 | 21 | // Bootstrap the application, configure models, datasources and middleware. 22 | // Sub-apps like REST API are mounted via boot scripts. 23 | boot(app, __dirname, function(err) { 24 | if (err) throw err; 25 | 26 | // start the server if `$ node server.js` 27 | if (require.main === module) { 28 | var dataSource = app.dataSources.db; 29 | dataSource.autoupdate(null, function(err) { 30 | if (err) console.log(err); 31 | }); 32 | app.start(); 33 | } 34 | }); 35 | -------------------------------------------------------------------------------- /test/AppUser.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | describe('/AppUser', function() { 4 | var server = require('../server/server'); 5 | var request = require('supertest')(server); 6 | var chai = require('chai'); 7 | var chaiHttp = require('chai-http'); 8 | var should = chai.should(); 9 | chai.use(chaiHttp); 10 | 11 | var AppUser; 12 | 13 | before(function(done) { 14 | AppUser = server.models.AppUser; 15 | AppUser.destroyAll(function() { 16 | AppUser.create( 17 | { 18 | username: 'testuser', 19 | type: 'free', 20 | email: 'testuser@user.com', 21 | password: '123456', 22 | }, function(err, userInstance) { 23 | if (err) console.log('===>', err); 24 | done(); 25 | }); 26 | }); 27 | }); 28 | 29 | it('logins AppUsers successfully using email', function(done) { 30 | chai.request(server) 31 | .post('/api/AppUsers/login') 32 | .send({email: 'testuser@user.com', password: '123456'}) 33 | .end(function(err, res) { 34 | res.should.have.status(200); 35 | res.body.should.have.property('id'); 36 | res.body.should.have.property('ttl'); 37 | res.body.should.have.property('userId'); 38 | done(); 39 | }); 40 | }); 41 | 42 | it('logins AppUsers successfully using username', function(done) { 43 | chai.request(server) 44 | .post('/api/AppUsers/login') 45 | .send({username: 'testuser', password: '123456'}) 46 | .end(function(err, res) { 47 | res.should.have.status(200); 48 | res.body.should.have.property('id'); 49 | res.body.should.have.property('ttl'); 50 | res.body.should.have.property('userId'); 51 | done(); 52 | }); 53 | }); 54 | 55 | it('throws logins AppUsers errors', function(done) { 56 | chai.request(server) 57 | .post('/api/AppUsers/login') 58 | .send({email: 'testuser@user.com', password: '12345'}) 59 | .end(function(err, res) { 60 | res.should.have.status(401); 61 | res.body.should.have.property('error'); 62 | done(); 63 | }); 64 | }); 65 | 66 | }); 67 | --------------------------------------------------------------------------------