Building a Phonegap app with Laravel and Angular - Part 2

Published by at 18th September 2016 10:18 pm

In this lesson, the initial scope of the app will be extremely simple. We will implement functionality that:

  • Allows users to log in and out
  • Displays the home page

That's fairly simple, and easily achievable within a fairly short timeframe. We'll also write automated tests for our app. By the end of this lesson, we'll have built a first pass for our app using Angular.js.

NOTE: As at time of writing, Angular 2 has just come out. I'm using Angular 1 here, and the two are not compatible, so make sure you're using Angular 1.

Creating our app

Start by creating a new folder, separate from the backend, for the app. Then, in there, run the following command:

$ npm init -y

Then let's install our dependencies:

$ npm install --save-dev gulp karma karma-browserify karma-phantomjs-launcher browserify angular angular-route angular-mocks angular-animate angular-messages angular-sanitize angular-material angular-resource vinyl-buffer vinyl-source-stream gulp-sass karma-coverage karma-jasmine jasmine-core gulp-webserver

We're going to use Angular Material for our user interface as it includes support out of the box for swiping left and right. You'll notice it mentioned as one of the dependencies above.

We'll also use Karma for running our tests. Save the following as karma.conf.js:

1module.exports = function(config) {
2 config.set({
3 basePath: '',
4 frameworks: ['browserify', 'jasmine'],
5 files: [
6 'node_modules/angular/angular.min.js',
7 'node_modules/angular-mocks/angular-mocks.js',
8 'node_modules/angular-material/angular-material-mocks.js',
9 'js/*.js',
10 'test/*.js'
11 ],
12 exclude: [
13 ],
14 preprocessors: {
15 'js/*.js': ['browserify', 'coverage'],
16 'tests/js': ['browserify']
17 },
18 browserify: {
19 debug: true
20 },
21 reporters: ['progress', 'coverage'],
22 port: 9876,
23 colors: true,
24 logLevel: config.LOG_DEBUG,
25 autoWatch: true,
26 browsers: ['PhantomJS'],
27 singleRun: true,
28 coverageReporter: {
29 dir : 'coverage/',
30 reporters: [
31 { type: 'html', subdir: 'report-html' },
32 { type: 'cobertura', subdir: 'report-cobertura' }
33 ]
34 }
35 });
36};

This is our Karma configuration. Karma can run the same test in multiple browsers. Here we're going to use PhantomJS, but it's trivial to amend the browsers section to add more. You just need to make sure you install the appropriate launchers for those browsers.

We'll use Gulp to build the app. Here's the gulpfile.js:

1var gulp = require('gulp');
2var source = require('vinyl-source-stream');
3var buffer = require('vinyl-buffer');
4var browserify = require('browserify');
5var sass = require('gulp-sass');
6var server = require('gulp-webserver');
7
8var paths = {
9 scripts: ['js/*.js'],
10 styles: ['sass/*.scss']
11};
12
13gulp.task('sass', function() {
14 gulp.src('sass/style.scss')
15 .pipe(sass().on('error', sass.logError))
16 .pipe(gulp.dest('www/css'));
17});;
18
19gulp.task('js', function () {
20 return browserify({ entries: ['js/main.js'], debug: true })
21 .bundle()
22 .pipe(source('bundle.js'))
23 .pipe(buffer())
24 .pipe(gulp.dest('www/js/'));
25});
26
27gulp.task('server', function () {
28 gulp.src('www/')
29 .pipe(server({
30 livereload: true,
31 open: true,
32 port: 5000
33 }));
34});
35
36
37gulp.task('watch', function () {
38 gulp.watch(paths.scripts, ['js']);
39 gulp.watch(paths.styles, ['sass']);
40});
41
42gulp.task('default', ['sass','js','server', 'watch']);

Note that we're going to be using Browserify to handle our dependencies. If you haven't used it before, it lets you use the require() syntax from Node.js to include other JavaScript files, including ones available via NPM such as jQuery or Angular, allowing you to compile them all into a single file.

We should be able to test and run the app using NPM, so add these scripts to package.json:

1 "scripts": {
2 "test": "karma start",
3 "run": "gulp"
4 },

We also need an HTML file. Save this as www/index.html:

1<!DOCTYPE html>
2<html lang="en">
3 <head>
4 <meta charset="utf-8">
5 <meta http-equiv="X-UA-Compatible" content="IE=edge">
6 <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=0">
7 <title>My New Animal Friend</title>
8 <link href="/css/style.css" rel="stylesheet" type="text/css">
9 </head>
10 <body>
11 <div>
12 <div ng-app="mynewanimalfriend" ng-cloak>
13 <div ng-view></div>
14 </div>
15 </div>
16 </body>
17 <script language="javascript" type="text/javascript" src="/js/bundle.js"></script>
18</html>

Note the use of the Angular directives. ng-app denotes the name of the app namespace, ng-cloak hides the application until it's fully loaded, and ng-view denotes the area containing our content.

You should also create the files js/main.js, sass/style.scss, and the test folder.

Creating our first routes

Our first task is to create the routes we need. Our default route will be /, representing the home page. However, users will need to be logged in to see this. Otherwise, they should be redirected to the login route, which will be /login, appropriately enough. We'll also have a /logout route, which should be self-explanatory.

Before we implement these routes, we need to write a test for them. We'll start with our login route, and we'll test that for this route, the controller will be LoginCtrl and the template will be templates/login.html. The significance of these will become apparent later. Save this as test/routes.spec.js:

1'use strict';
2
3describe('Routes', function () {
4
5 beforeEach(angular.mock.module('mynewanimalfriend'));
6 it('should map login route to login controller', function () {
7 inject(function ($route) {
8 expect($route.routes['/login'].controller).toBe('LoginCtrl');
9 expect($route.routes['/login'].templateUrl).toEqual('templates/login.html');
10 });
11 });
12});

Note the beforeEach() hook. This is used to set up the application.

We can run this test with npm test as that calls Karma directly. Note that we're using Jasmine to write our tests.

1$ npm test
2
3> mynewanimalfriend-app@1.0.0 test /home/matthew/Projects/mynewanimalfriend-app
4> karma start
5
612 09 2016 22:22:34.168:DEBUG [config]: autoWatch set to false, because of singleRun
712 09 2016 22:22:34.172:DEBUG [plugin]: Loading karma-* from /home/matthew/Projects/mynewanimalfriend-app/node_modules
812 09 2016 22:22:34.176:DEBUG [plugin]: Loading plugin /home/matthew/Projects/mynewanimalfriend-app/node_modules/karma-browserify.
912 09 2016 22:22:34.314:DEBUG [plugin]: Loading plugin /home/matthew/Projects/mynewanimalfriend-app/node_modules/karma-coverage.
1012 09 2016 22:22:34.484:DEBUG [plugin]: Loading plugin /home/matthew/Projects/mynewanimalfriend-app/node_modules/karma-jasmine.
1112 09 2016 22:22:34.485:DEBUG [plugin]: Loading plugin /home/matthew/Projects/mynewanimalfriend-app/node_modules/karma-phantomjs-launcher.
1212 09 2016 22:22:34.535:DEBUG [framework.browserify]: created browserify bundle: /tmp/f8c46bd8d72c5b8578e64552192273be.browserify
1312 09 2016 22:22:34.553:DEBUG [framework.browserify]: add bundle to config.files at position 3
1412 09 2016 22:22:34.559:DEBUG [web-server]: Instantiating middleware
1512 09 2016 22:22:34.569:DEBUG [reporter]: Trying to load reporter: coverage
1612 09 2016 22:22:34.570:DEBUG [reporter]: Trying to load color-version of reporter: coverage (coverage_color)
1712 09 2016 22:22:34.571:DEBUG [reporter]: Couldn't load color-version.
1812 09 2016 22:22:34.596:DEBUG [framework.browserify]: updating js/main.js in bundle
1912 09 2016 22:22:34.597:DEBUG [framework.browserify]: building bundle
2012 09 2016 22:22:35.302:DEBUG [framework.browserify]: bundling
2112 09 2016 22:22:35.328:DEBUG [preprocessor.coverage]: Processing "/home/matthew/Projects/mynewanimalfriend-app/js/main.js".
2212 09 2016 22:22:35.345:INFO [framework.browserify]: bundle built
2312 09 2016 22:22:35.352:INFO [karma]: Karma v1.3.0 server started at http://localhost:9876/
2412 09 2016 22:22:35.352:INFO [launcher]: Launching browser PhantomJS with unlimited concurrency
2512 09 2016 22:22:35.361:INFO [launcher]: Starting browser PhantomJS
2612 09 2016 22:22:35.361:DEBUG [temp-dir]: Creating temp dir at /tmp/karma-17657666
2712 09 2016 22:22:35.364:DEBUG [launcher]: /home/matthew/Projects/mynewanimalfriend-app/node_modules/phantomjs-prebuilt/lib/phantom/bin/phantomjs /tmp/karma-17657666/capture.js
2812 09 2016 22:22:35.466:DEBUG [web-server]: serving: /home/matthew/Projects/mynewanimalfriend-app/node_modules/karma/static/client.html
2912 09 2016 22:22:35.478:DEBUG [web-server]: serving: /home/matthew/Projects/mynewanimalfriend-app/node_modules/karma/static/karma.js
3012 09 2016 22:22:35.541:DEBUG [karma]: A browser has connected on socket /#dQYjOD4F_HJwPXiYAAAA
3112 09 2016 22:22:35.564:DEBUG [web-server]: upgrade /socket.io/?EIO=3&transport=websocket&sid=dQYjOD4F_HJwPXiYAAAA
3212 09 2016 22:22:35.629:INFO [PhantomJS 2.1.1 (Linux 0.0.0)]: Connected on socket /#dQYjOD4F_HJwPXiYAAAA with id 17657666
3312 09 2016 22:22:35.630:DEBUG [launcher]: PhantomJS (id 17657666) captured in 0.277 secs
3412 09 2016 22:22:35.642:DEBUG [phantomjs.launcher]:
35
3612 09 2016 22:22:35.643:DEBUG [middleware:karma]: custom files null null
3712 09 2016 22:22:35.644:DEBUG [middleware:karma]: Serving static request /context.html
3812 09 2016 22:22:35.646:DEBUG [web-server]: serving: /home/matthew/Projects/mynewanimalfriend-app/node_modules/karma/static/context.html
3912 09 2016 22:22:35.650:DEBUG [middleware:source-files]: Requesting /base/node_modules/jasmine-core/lib/jasmine-core/jasmine.js?b1682a1eb50e00abf147fc1fb28e31006d499aae /
4012 09 2016 22:22:35.650:DEBUG [middleware:source-files]: Fetching /home/matthew/Projects/mynewanimalfriend-app/node_modules/jasmine-core/lib/jasmine-core/jasmine.js
4112 09 2016 22:22:35.652:DEBUG [web-server]: serving (cached): /home/matthew/Projects/mynewanimalfriend-app/node_modules/jasmine-core/lib/jasmine-core/jasmine.js
4212 09 2016 22:22:35.654:DEBUG [middleware:source-files]: Requesting /base/node_modules/angular-material/angular-material-mocks.js?9f31553e4bbbad4d6b52638351e3a274352311c2 /
4312 09 2016 22:22:35.654:DEBUG [middleware:source-files]: Fetching /home/matthew/Projects/mynewanimalfriend-app/node_modules/angular-material/angular-material-mocks.js
4412 09 2016 22:22:35.654:DEBUG [middleware:source-files]: Requesting /base/node_modules/karma-jasmine/lib/boot.js?945a38bf4e45ad2770eb94868231905a04a0bd3e /
4512 09 2016 22:22:35.655:DEBUG [middleware:source-files]: Fetching /home/matthew/Projects/mynewanimalfriend-app/node_modules/karma-jasmine/lib/boot.js
4612 09 2016 22:22:35.655:DEBUG [middleware:source-files]: Requesting /base/node_modules/karma-jasmine/lib/adapter.js?7975a273517f1eb29d7bd018790fd4c7b9a485d5 /
4712 09 2016 22:22:35.655:DEBUG [middleware:source-files]: Fetching /home/matthew/Projects/mynewanimalfriend-app/node_modules/karma-jasmine/lib/adapter.js
4812 09 2016 22:22:35.656:DEBUG [middleware:source-files]: Requesting /base/node_modules/angular/angular.min.js?78069f9f3a9ca9652cb04c13ccb0670d747666b8 /
4912 09 2016 22:22:35.656:DEBUG [middleware:source-files]: Fetching /home/matthew/Projects/mynewanimalfriend-app/node_modules/angular/angular.min.js
5012 09 2016 22:22:35.656:DEBUG [middleware:source-files]: Requesting /base/node_modules/angular-mocks/angular-mocks.js?cc56136dc551d94abe8195cf8475eb27a3aa3c4b /
5112 09 2016 22:22:35.657:DEBUG [middleware:source-files]: Fetching /home/matthew/Projects/mynewanimalfriend-app/node_modules/angular-mocks/angular-mocks.js
5212 09 2016 22:22:35.657:DEBUG [web-server]: serving (cached): /home/matthew/Projects/mynewanimalfriend-app/node_modules/angular-material/angular-material-mocks.js
5312 09 2016 22:22:35.658:DEBUG [web-server]: serving (cached): /home/matthew/Projects/mynewanimalfriend-app/node_modules/karma-jasmine/lib/boot.js
5412 09 2016 22:22:35.658:DEBUG [web-server]: serving (cached): /home/matthew/Projects/mynewanimalfriend-app/node_modules/karma-jasmine/lib/adapter.js
5512 09 2016 22:22:35.659:DEBUG [web-server]: serving (cached): /home/matthew/Projects/mynewanimalfriend-app/node_modules/angular/angular.min.js
5612 09 2016 22:22:35.659:DEBUG [web-server]: serving (cached): /home/matthew/Projects/mynewanimalfriend-app/node_modules/angular-mocks/angular-mocks.js
5712 09 2016 22:22:35.660:DEBUG [web-server]: serving: /home/matthew/Projects/mynewanimalfriend-app/node_modules/karma/static/context.js
5812 09 2016 22:22:35.661:DEBUG [middleware:source-files]: Requesting /absolute/tmp/f8c46bd8d72c5b8578e64552192273be.browserify?8ffde4eef27d38e92cc62da4e8dd0ffa5a3a4a4c /
5912 09 2016 22:22:35.661:DEBUG [middleware:source-files]: Fetching /tmp/f8c46bd8d72c5b8578e64552192273be.browserify
6012 09 2016 22:22:35.662:DEBUG [middleware:source-files]: Requesting /base/js/main.js?41c850cecc07c24d7cd0421e914bd2420671e573 /
6112 09 2016 22:22:35.662:DEBUG [middleware:source-files]: Fetching /home/matthew/Projects/mynewanimalfriend-app/js/main.js
6212 09 2016 22:22:35.662:DEBUG [middleware:source-files]: Requesting /base/test/routes.spec.js?92b15bb7c24bc6ead636994fb1c737b91727d887 /
6312 09 2016 22:22:35.662:DEBUG [middleware:source-files]: Fetching /home/matthew/Projects/mynewanimalfriend-app/test/routes.spec.js
6412 09 2016 22:22:35.663:DEBUG [web-server]: serving (cached): /tmp/f8c46bd8d72c5b8578e64552192273be.browserify
6512 09 2016 22:22:35.664:DEBUG [web-server]: serving (cached): /home/matthew/Projects/mynewanimalfriend-app/js/main.js
6612 09 2016 22:22:35.664:DEBUG [web-server]: serving (cached): /home/matthew/Projects/mynewanimalfriend-app/test/routes.spec.js
67PhantomJS 2.1.1 (Linux 0.0.0) Routes should map login route to login controller FAILED
68 Error: [$injector:modulerr] http://errors.angularjs.org/1.5.8/$injector/modulerr?p0=mynewanimalfriend&p1=%5B%24injector%3Anomod%5D%20http%3A%2F%2Ferrors.angularjs.org%2F1.5.8%2F%24injector%2Fnomod%3Fp0%3Dmynewanimalfriend%0Ahttp%3A%2F%2Flocalhost%3A9876%2Fbase%2Fnode_modules%2Fangular%2Fangular.min.js%3F78069f9f3a9ca9652cb04c13ccb0670d747666b8%3A25%3A111%0Ab%40http%3A%2F%2Flocalhost%3A9876%2Fbase%2Fnode_modules%2Fangular%2Fangular.min.js%3F78069f9f3a9ca9652cb04c13ccb0670d747666b8%3A24%3A143%0Ahttp%3A%2F%2Flocalhost%3A9876%2Fbase%2Fnode_modules%2Fangular%2Fangular.min.js%3F78069f9f3a9ca9652cb04c13ccb0670d747666b8%3A24%3A489%0Ahttp%3A%2F%2Flocalhost%3A9876%2Fbase%2Fnode_modules%2Fangular%2Fangular.min.js%3F78069f9f3a9ca9652cb04c13ccb0670d747666b8%3A39%3A473%0Aq%40http%3A%2F%2Flocalhost%3A9876%2Fbase%2Fnode_modules%2Fangular%2Fangular.min.js%3F78069f9f3a9ca9652cb04c13ccb0670d747666b8%3A7%3A359%0Ag%40http%3A%2F%2Flocalhost%3A9876%2Fbase%2Fnode_modules%2Fangular%2Fangular.min.js%3F78069f9f3a9ca9652cb04c13ccb0670d747666b8%3A39%3A320%0Acb%40http%3A%2F%2Flocalhost%3A9876%2Fbase%2Fnode_modules%2Fangular%2Fangular.min.js%3F78069f9f3a9ca9652cb04c13ccb0670d747666b8%3A43%3A337%0AworkFn%40http%3A%2F%2Flocalhost%3A9876%2Fbase%2Fnode_modules%2Fangular-mocks%2Fangular-mocks.js%3Fcc56136dc551d94abe8195cf8475eb27a3aa3c4b%3A3074%3A60%0Ainject%40http%3A%2F%2Flocalhost%3A9876%2Fbase%2Fnode_modules%2Fangular-mocks%2Fangular-mocks.js%3Fcc56136dc551d94abe8195cf8475eb27a3aa3c4b%3A3054%3A46%0Ahttp%3A%2F%2Flocalhost%3A9876%2Fbase%2Ftest%2Froutes.spec.js%3F92b15bb7c24bc6ead636994fb1c737b91727d887%3A5%3A11%0AattemptSync%40http%3A%2F%2Flocalhost%3A9876%2Fbase%2Fnode_modules%2Fjasmine-core%2Flib%2Fjasmine-core%2Fjasmine.js%3Fb1682a1eb50e00abf147fc1fb28e31006d499aae%3A1942%3A28%0Arun%40http%3A%2F%2Flocalhost%3A9876%2Fbase%2Fnode_modules%2Fjasmine-core%2Flib%2Fjasmine-core%2Fjasmine.js%3Fb1682a1eb50e00abf147fc1fb28e31006d499aae%3A1930%3A20%0Aexecute%40http%3A%2F%2Flocalhost%3A9876%2Fbase%2Fnode_modules%2Fjasmine-core%2Flib%2Fjasmine-core%2Fjasmine.js%3Fb1682a1eb50e00abf147fc1fb28e31006d499aae%3A1915%3A13%0AqueueRunnerFactory%40http%3A%2F%2Flocalhost%3A9876%2Fbase%2Fnode_modules%2Fjasmine-core%2Flib%2Fjasmine-core%2Fjasmine.js%3Fb1682a1eb50e00abf147fc1fb28e31006d499aae%3A710%3A42%0Aexecute%40http%3A%2F%2Flocalhost%3A9876%2Fbase%2Fnode_modules%2Fjasmine-core%2Flib%2Fjasmine-core%2Fjasmine.js%3Fb1682a1eb50e00abf147fc1fb28e31006d499aae%3A367%3A28%0Afn%40http%3A%2F%2Flocalhost%3A9876%2Fbase%2Fnode_modules%2Fjasmine-core%2Flib%2Fjasmine-core%2Fjasmine.js%3Fb1682a1eb50e00abf147fc1fb28e31006d499aae%3A2568%3A44%0AattemptAsync%40http%3A%2F%2Flocalhost%3A9876%2Fbase%2Fnode_modules%2Fjasmine-core%2Flib%2Fjasmine-core%2Fjasmine.js%3Fb1682a1eb50e00abf147fc1fb28e31006d499aae%3A1972%3A28%0Arun%40http%3A%2F%2Flocalhost%3A9876%2Fbase%2Fnode_modules%2Fjasmine-core%2Flib%2Fjasmine-core%2Fjasmine.js%3Fb1682a1eb50e00abf147fc1fb28e31006d499aae%3A1927%3A21%0Aexecute%40http%3A%2F%2Flocalhost%3A9876%2Fbase%2Fnode_modules%2Fjasmine-core%2Flib%2Fjasmine-core%2Fjasmine.js%3Fb1682a1eb50e00abf147fc1fb28e31006d499aae%3A1915%3A13%0AqueueRunnerFactory%40http%3A%2F%2Flocalhost%3A9876%2Fbase%2Fnode_modules%2Fjasmine-core%2Flib%2Fjasmine-core%2Fjasmine.js%3Fb1682a1eb50e00abf147fc1fb28e31006d499aae%3A710%3A42%0Afn%40http%3A%2F%2Flocalhost%3A9876%2Fbase%2Fnode_modules%2Fjasmine-core%2Flib%2Fjasmine-core%2Fjasmine.js%3Fb1682a1eb50e00abf147fc1fb28e31006d499aae%3A2553%3A31%0AattemptAsync%40http%3A%2F%2Flocalhost%3A9876%2Fbase%2Fnode_modules%2Fjasmine-core%2Flib%2Fjasmine-core%2Fjasmine.js%3Fb1682a1eb50e00abf147fc1fb28e31006d499aae%3A1972%3A28%0Arun%40http%3A%2F%2Flocalhost%3A9876%2Fbase%2Fnode_modules%2Fjasmine-core%2Flib%2Fjasmine-core%2Fjasmine.js%3Fb1682a1eb50e00abf147fc1fb28e31006d499aae%3A1927%3A21%0Aexecute%40http%3A%2F%2Flocalhost%3A9876%2Fbase%2Fnode_modules%2Fjasmine-core%2Flib%2Fjasmine-core%2Fjasmine.js%3Fb1682a1eb50e00abf147fc1fb28e31006d499aae%3A1915%3A13%0AqueueRunnerFactory%40http%3A%2F%2Flocalhost%3A9876%2Fbase%2Fnode_modules%2Fjasmine-core%2Flib%2Fjasmine-core%2Fjasmine.js%3Fb1682a1eb50e00abf147fc1fb28e31006d499aae%3A710%3A42%0Aexecute%40http%3A%2F%2Flocalhost%3A9876%2Fbase%2Fnode_modules%2Fjasmine-core%2Flib%2Fjasmine-core%2Fjasmine.js%3Fb1682a1eb50e00abf147fc1fb28e31006d499aae%3A2415%3A25%0Aexecute%40http%3A%2F%2Flocalhost%3A9876%2Fbase%2Fnode_modules%2Fjasmine-core%2Flib%2Fjasmine-core%2Fjasmine.js%3Fb1682a1eb50e00abf147fc1fb28e31006d499aae%3A772%3A24%0Ahttp%3A%2F%2Flocalhost%3A9876%2Fbase%2Fnode_modules%2Fkarma-jasmine%2Flib%2Fadapter.js%3F7975a273517f1eb29d7bd018790fd4c7b9a485d5%3A320%3A23%0Aloaded%40http%3A%2F%2Flocalhost%3A9876%2Fcontext.js%3A151%3A17%0Aglobal%20code%40http%3A%2F%2Flocalhost%3A9876%2Fcontext.html%3A50%3A28 in node_modules/angular/angular.min.js (line 40)
69 node_modules/angular/angular.min.js:40:260
70 q@node_modules/angular/angular.min.js:7:359
71 g@node_modules/angular/angular.min.js:39:320
72 cb@node_modules/angular/angular.min.js:43:337
73 workFn@node_modules/angular-mocks/angular-mocks.js:3074:60
74 inject@node_modules/angular-mocks/angular-mocks.js:3054:46
75 test/routes.spec.js:5:11
76 loaded@http://localhost:9876/context.js:151:17
77PhantomJS 2.1.1 (Linux 0.0.0): Executed 1 of 1 (1 FAILED) ERROR (0.044 secs / 0.006 secs)
7812 09 2016 22:22:35.778:DEBUG [karma]: Run complete, exiting.
7912 09 2016 22:22:35.778:DEBUG [launcher]: Disconnecting all browsers
8012 09 2016 22:22:35.778:DEBUG [framework.browserify]: cleaning up
8112 09 2016 22:22:35.782:DEBUG [coverage]: Writing coverage to /home/matthew/Projects/mynewanimalfriend-app/coverage/report-html
8212 09 2016 22:22:35.876:DEBUG [coverage]: Writing coverage to /home/matthew/Projects/mynewanimalfriend-app/coverage/report-cobertura
8312 09 2016 22:22:35.880:DEBUG [launcher]: Process PhantomJS exited with code 0
8412 09 2016 22:22:35.881:DEBUG [temp-dir]: Cleaning temp dir /tmp/karma-17657666
8512 09 2016 22:22:35.884:DEBUG [launcher]: Finished all browsers
86npm ERR! Test failed. See above for more details.

Now that we have a failing test, we can set about making it pass. Save this at js/main.js:

1'use strict';
2
3require('angular');
4require('angular-route');
5require('angular-animate');
6require('angular-material');
7
8angular.module('mynewanimalfriend', [
9 'ngRoute',
10 'ngAnimate',
11 'ngMaterial'
12])
13
14.config(function ($routeProvider) {
15 $routeProvider
16 .when('/login', {
17 templateUrl: 'templates/login.html',
18 controller: 'LoginCtrl'
19 });
20});

As mentioned earlier, because we're using Browserify, we can use the require() syntax to import our dependencies. Note we also give our module a name and specify the dependencies. Finally, note that we use $routeProvider to set up our first route, and we map the template URL and controller to match our test.

Let's run the test again:

1$ npm test
2
3> mynewanimalfriend-app@1.0.0 test /home/matthew/Projects/mynewanimalfriend-app
4> karma start
5
612 09 2016 22:35:51.231:DEBUG [config]: autoWatch set to false, because of singleRun
712 09 2016 22:35:51.235:DEBUG [plugin]: Loading karma-* from /home/matthew/Projects/mynewanimalfriend-app/node_modules
812 09 2016 22:35:51.237:DEBUG [plugin]: Loading plugin /home/matthew/Projects/mynewanimalfriend-app/node_modules/karma-browserify.
912 09 2016 22:35:51.354:DEBUG [plugin]: Loading plugin /home/matthew/Projects/mynewanimalfriend-app/node_modules/karma-coverage.
1012 09 2016 22:35:51.496:DEBUG [plugin]: Loading plugin /home/matthew/Projects/mynewanimalfriend-app/node_modules/karma-jasmine.
1112 09 2016 22:35:51.497:DEBUG [plugin]: Loading plugin /home/matthew/Projects/mynewanimalfriend-app/node_modules/karma-phantomjs-launcher.
1212 09 2016 22:35:51.547:DEBUG [framework.browserify]: created browserify bundle: /tmp/02002698e6d413a542186462d3a0a6ce.browserify
1312 09 2016 22:35:51.559:DEBUG [framework.browserify]: add bundle to config.files at position 3
1412 09 2016 22:35:51.564:DEBUG [web-server]: Instantiating middleware
1512 09 2016 22:35:51.581:DEBUG [reporter]: Trying to load reporter: coverage
1612 09 2016 22:35:51.582:DEBUG [reporter]: Trying to load color-version of reporter: coverage (coverage_color)
1712 09 2016 22:35:51.582:DEBUG [reporter]: Couldn't load color-version.
1812 09 2016 22:35:51.602:DEBUG [framework.browserify]: updating js/main.js in bundle
1912 09 2016 22:35:51.603:DEBUG [framework.browserify]: building bundle
2012 09 2016 22:35:52.306:DEBUG [framework.browserify]: bundling
2112 09 2016 22:35:54.095:DEBUG [preprocessor.coverage]: Processing "/home/matthew/Projects/mynewanimalfriend-app/js/main.js".
2212 09 2016 22:35:54.170:INFO [framework.browserify]: bundle built
2312 09 2016 22:35:54.189:INFO [karma]: Karma v1.3.0 server started at http://localhost:9876/
2412 09 2016 22:35:54.189:INFO [launcher]: Launching browser PhantomJS with unlimited concurrency
2512 09 2016 22:35:54.197:INFO [launcher]: Starting browser PhantomJS
2612 09 2016 22:35:54.198:DEBUG [temp-dir]: Creating temp dir at /tmp/karma-91342786
2712 09 2016 22:35:54.201:DEBUG [launcher]: /home/matthew/Projects/mynewanimalfriend-app/node_modules/phantomjs-prebuilt/lib/phantom/bin/phantomjs /tmp/karma-91342786/capture.js
2812 09 2016 22:35:54.300:DEBUG [web-server]: serving: /home/matthew/Projects/mynewanimalfriend-app/node_modules/karma/static/client.html
2912 09 2016 22:35:54.308:DEBUG [web-server]: serving: /home/matthew/Projects/mynewanimalfriend-app/node_modules/karma/static/karma.js
3012 09 2016 22:35:54.366:DEBUG [karma]: A browser has connected on socket /#FpcuZAJUT-u6Dl4sAAAA
3112 09 2016 22:35:54.386:DEBUG [web-server]: upgrade /socket.io/?EIO=3&transport=websocket&sid=FpcuZAJUT-u6Dl4sAAAA
3212 09 2016 22:35:54.442:INFO [PhantomJS 2.1.1 (Linux 0.0.0)]: Connected on socket /#FpcuZAJUT-u6Dl4sAAAA with id 91342786
3312 09 2016 22:35:54.442:DEBUG [launcher]: PhantomJS (id 91342786) captured in 0.253 secs
3412 09 2016 22:35:54.447:DEBUG [phantomjs.launcher]:
35
3612 09 2016 22:35:54.448:DEBUG [middleware:karma]: custom files null null
3712 09 2016 22:35:54.448:DEBUG [middleware:karma]: Serving static request /context.html
3812 09 2016 22:35:54.449:DEBUG [web-server]: serving: /home/matthew/Projects/mynewanimalfriend-app/node_modules/karma/static/context.html
3912 09 2016 22:35:54.451:DEBUG [middleware:source-files]: Requesting /base/node_modules/jasmine-core/lib/jasmine-core/jasmine.js?b1682a1eb50e00abf147fc1fb28e31006d499aae /
4012 09 2016 22:35:54.451:DEBUG [middleware:source-files]: Fetching /home/matthew/Projects/mynewanimalfriend-app/node_modules/jasmine-core/lib/jasmine-core/jasmine.js
4112 09 2016 22:35:54.452:DEBUG [web-server]: serving (cached): /home/matthew/Projects/mynewanimalfriend-app/node_modules/jasmine-core/lib/jasmine-core/jasmine.js
4212 09 2016 22:35:54.453:DEBUG [middleware:source-files]: Requesting /base/node_modules/angular-material/angular-material-mocks.js?9f31553e4bbbad4d6b52638351e3a274352311c2 /
4312 09 2016 22:35:54.453:DEBUG [middleware:source-files]: Fetching /home/matthew/Projects/mynewanimalfriend-app/node_modules/angular-material/angular-material-mocks.js
4412 09 2016 22:35:54.453:DEBUG [middleware:source-files]: Requesting /base/node_modules/karma-jasmine/lib/boot.js?945a38bf4e45ad2770eb94868231905a04a0bd3e /
4512 09 2016 22:35:54.454:DEBUG [middleware:source-files]: Fetching /home/matthew/Projects/mynewanimalfriend-app/node_modules/karma-jasmine/lib/boot.js
4612 09 2016 22:35:54.454:DEBUG [middleware:source-files]: Requesting /base/node_modules/karma-jasmine/lib/adapter.js?7975a273517f1eb29d7bd018790fd4c7b9a485d5 /
4712 09 2016 22:35:54.454:DEBUG [middleware:source-files]: Fetching /home/matthew/Projects/mynewanimalfriend-app/node_modules/karma-jasmine/lib/adapter.js
4812 09 2016 22:35:54.454:DEBUG [middleware:source-files]: Requesting /base/node_modules/angular-mocks/angular-mocks.js?cc56136dc551d94abe8195cf8475eb27a3aa3c4b /
4912 09 2016 22:35:54.454:DEBUG [middleware:source-files]: Fetching /home/matthew/Projects/mynewanimalfriend-app/node_modules/angular-mocks/angular-mocks.js
5012 09 2016 22:35:54.455:DEBUG [middleware:source-files]: Requesting /base/node_modules/angular/angular.min.js?78069f9f3a9ca9652cb04c13ccb0670d747666b8 /
5112 09 2016 22:35:54.455:DEBUG [middleware:source-files]: Fetching /home/matthew/Projects/mynewanimalfriend-app/node_modules/angular/angular.min.js
5212 09 2016 22:35:54.455:DEBUG [web-server]: serving (cached): /home/matthew/Projects/mynewanimalfriend-app/node_modules/angular-material/angular-material-mocks.js
5312 09 2016 22:35:54.455:DEBUG [web-server]: serving (cached): /home/matthew/Projects/mynewanimalfriend-app/node_modules/karma-jasmine/lib/boot.js
5412 09 2016 22:35:54.455:DEBUG [web-server]: serving (cached): /home/matthew/Projects/mynewanimalfriend-app/node_modules/karma-jasmine/lib/adapter.js
5512 09 2016 22:35:54.456:DEBUG [web-server]: serving (cached): /home/matthew/Projects/mynewanimalfriend-app/node_modules/angular-mocks/angular-mocks.js
5612 09 2016 22:35:54.457:DEBUG [web-server]: serving (cached): /home/matthew/Projects/mynewanimalfriend-app/node_modules/angular/angular.min.js
5712 09 2016 22:35:54.458:DEBUG [middleware:source-files]: Requesting /absolute/tmp/02002698e6d413a542186462d3a0a6ce.browserify?f4c82dc0618d979f84c89967ea1c412e646a5fe5 /
5812 09 2016 22:35:54.458:DEBUG [middleware:source-files]: Fetching /tmp/02002698e6d413a542186462d3a0a6ce.browserify
5912 09 2016 22:35:54.458:DEBUG [middleware:source-files]: Requesting /base/js/main.js?41c850cecc07c24d7cd0421e914bd2420671e573 /
6012 09 2016 22:35:54.459:DEBUG [middleware:source-files]: Fetching /home/matthew/Projects/mynewanimalfriend-app/js/main.js
6112 09 2016 22:35:54.460:DEBUG [middleware:source-files]: Requesting /base/test/routes.spec.js?92b15bb7c24bc6ead636994fb1c737b91727d887 /
6212 09 2016 22:35:54.461:DEBUG [middleware:source-files]: Fetching /home/matthew/Projects/mynewanimalfriend-app/test/routes.spec.js
6312 09 2016 22:35:54.461:DEBUG [web-server]: serving (cached): /tmp/02002698e6d413a542186462d3a0a6ce.browserify
6412 09 2016 22:35:54.496:DEBUG [web-server]: serving (cached): /home/matthew/Projects/mynewanimalfriend-app/js/main.js
6512 09 2016 22:35:54.497:DEBUG [web-server]: serving (cached): /home/matthew/Projects/mynewanimalfriend-app/test/routes.spec.js
6612 09 2016 22:35:54.497:DEBUG [web-server]: serving: /home/matthew/Projects/mynewanimalfriend-app/node_modules/karma/static/context.js
6712 09 2016 22:35:54.582:DEBUG [phantomjs.launcher]: WARNING: Tried to load angular more than once.
68
69PhantomJS 2.1.1 (Linux 0.0.0) LOG: 'WARNING: Tried to load angular more than once.'
70
71PhantomJS 2.1.1 (Linux 0.0.0): Executed 1 of 1 SUCCESS (0.004 secs / 0.358 secs)
7212 09 2016 22:35:55.003:DEBUG [karma]: Run complete, exiting.
7312 09 2016 22:35:55.003:DEBUG [launcher]: Disconnecting all browsers
7412 09 2016 22:35:55.003:DEBUG [framework.browserify]: cleaning up
7512 09 2016 22:35:55.006:DEBUG [coverage]: Writing coverage to /home/matthew/Projects/mynewanimalfriend-app/coverage/report-html
7612 09 2016 22:35:55.078:DEBUG [coverage]: Writing coverage to /home/matthew/Projects/mynewanimalfriend-app/coverage/report-cobertura
7712 09 2016 22:35:55.082:DEBUG [launcher]: Process PhantomJS exited with code 0
7812 09 2016 22:35:55.082:DEBUG [temp-dir]: Cleaning temp dir /tmp/karma-91342786
7912 09 2016 22:35:55.085:DEBUG [launcher]: Finished all browsers

Our first test has passed. Let's add tests for the other routes:

1'use strict';
2
3describe('Routes', function () {
4
5 beforeEach(angular.mock.module('mynewanimalfriend'));
6 it('should map default route to home controller', function () {
7 inject(function ($route) {
8 expect($route.routes['/'].controller).toBe('HomeCtrl');
9 expect($route.routes['/'].templateUrl).toEqual('templates/home.html');
10 });
11 });
12
13 it('should map login route to login controller', function () {
14 inject(function ($route) {
15 expect($route.routes['/login'].controller).toBe('LoginCtrl');
16 expect($route.routes['/login'].templateUrl).toEqual('templates/login.html');
17 });
18 });
19
20 it('should map logout route to logout controller', function () {
21 inject(function ($route) {
22 expect($route.routes['/logout'].controller).toBe('LogoutCtrl');
23 expect($route.routes['/logout'].templateUrl).toEqual('templates/login.html');
24 });
25 });
26});

Note that the logout route uses the login template. This is because all it will do is redirect the user to the login form.

For the sake of brevity I won't display the test output, but two of these tests should now fail. We can easily set up the new routes in js/main.js:

1'use strict';
2
3require('angular');
4require('angular-route');
5require('angular-animate');
6require('angular-material');
7
8angular.module('mynewanimalfriend', [
9 'ngRoute',
10 'ngAnimate',
11 'ngMaterial'
12])
13
14.config(function ($routeProvider) {
15 $routeProvider
16 .when('/login', {
17 templateUrl: 'templates/login.html',
18 controller: 'LoginCtrl'
19 })
20 .when('/', {
21 templateUrl: 'templates/home.html',
22 controller: 'HomeCtrl'
23 })
24 .when('/logout', {
25 templateUrl: 'templates/login.html',
26 controller: 'LogoutCtrl'
27 });
28});

That's looking good so far. But what if someone navigates to a URL that doesn't exist? Our router should handle that. Add this to the test:

1 it('should redirect other or empty routes to the home controller', function () {
2 inject(function ($route) {
3 expect($route.routes[null].redirectTo).toEqual('/')
4 });
5 });

Once again, the test should fail. Fixing it is fairly straightforward - we'll use the otherwise() method to define a fallback route:

1'use strict';
2
3require('angular');
4require('angular-route');
5require('angular-animate');
6require('angular-material');
7
8angular.module('mynewanimalfriend', [
9 'ngRoute',
10 'ngAnimate',
11 'ngMaterial'
12])
13
14.config(function ($routeProvider) {
15 $routeProvider
16 .when('/login', {
17 templateUrl: 'templates/login.html',
18 controller: 'LoginCtrl'
19 })
20 .when('/', {
21 templateUrl: 'templates/home.html',
22 controller: 'HomeCtrl'
23 })
24 .when('/logout', {
25 templateUrl: 'templates/login.html',
26 controller: 'LogoutCtrl'
27 })
28 .otherwise({
29 redirectTo: '/'
30 });
31});

Now our routes are in place, we need to implement the three controllers we will need. However, as two of these controllers deal with authentication, we'll first create some services to handle that, and they'll need to be tested. Save this as test/services.spec.js:

1'use strict';
2
3describe('Services', function () {
4
5 beforeEach(function(){
6 jasmine.addMatchers({
7 toEqualData: function(util, customEqualityTesters) {
8 return {
9 compare: function(actual, expected) {
10 return {
11 pass: angular.equals(actual, expected)
12 };
13 }
14 };
15 }
16 });
17 });
18
19 beforeEach(angular.mock.module('mynewanimalfriend.services'));
20
21 describe('Token service', function () {
22 var mockBackend, Token;
23
24 beforeEach(inject(function (_Token_, _$httpBackend_) {
25 Token = _Token_;
26 mockBackend = _$httpBackend_;
27 }));
28
29 it('can create a new token', function () {
30 mockBackend.expectPOST('http://localhost:8000/api/authenticate', '{"email":"bob@example.com","password":"password"}').respond({token: 'mytoken'});
31 var token = new Token({
32 email: 'bob@example.com',
33 password: 'password'
34 });
35 token.$save(function (response) {
36 expect(response).toEqualData({token: 'mytoken'});
37 });
38 mockBackend.flush();
39 });
40 });
41});

In this test we use the $httpBackend facility from ngMock to mock out our API endpoints. We already have a REST API capable of generating a token, and we set this test up to behave similarly. We specify that it should expect to receive a certain POST request, and should respond with the token mytoken. Run the test to make sure it fails, then save this as js/services.js:

1'use strict';
2
3require('angular');
4require("angular-resource");
5
6angular.module('mynewanimalfriend.services', ['ngResource'])
7
8.factory('Token', function ($resource) {
9 return $resource('http://localhost:8000/api/authenticate/');
10});

A little explanation is called for. In Angular, the $resource dependency represents an HTTP resource. By default it supports making HTTP requests to the denoted endpoint via GET, POST and DELETE, and it's trivial to add support for PUT or PATCH methods. Using $resource, you can easily interface with a RESTful web service, and it's one of my favourite things about Angular.

We also need to load services.js in our main.js file:

1'use strict';
2
3require('angular');
4require('angular-route');
5require('angular-animate');
6require('angular-material');
7require('./services');
8
9angular.module('mynewanimalfriend', [
10 'ngRoute',
11 'ngAnimate',
12 'ngMaterial',
13 'mynewanimalfriend.services'
14])
15
16.config(function ($routeProvider) {
17 $routeProvider
18 .when('/login', {
19 templateUrl: 'templates/login.html',
20 controller: 'LoginCtrl'
21 })
22 .when('/', {
23 templateUrl: 'templates/home.html',
24 controller: 'HomeCtrl'
25 })
26 .when('/logout', {
27 templateUrl: 'templates/login.html',
28 controller: 'LogoutCtrl'
29 })
30 .otherwise({
31 redirectTo: '/'
32 });
33});

Now, running the tests should show that they pass.

With that in place, we will also create an authentication service that lets the app determine if the user is logged in. Add this to test/services.spec.js:

1 describe('Auth service', function () {
2 var Auth;
3
4 beforeEach(inject(function (_Auth_) {
5 Auth = _Auth_;
6 }));
7
8 it('can set user', function () {
9 Auth.setUser('mytoken');
10 var token = localStorage.getItem('authHeader');
11 expect(token).toEqual('Bearer mytoken');
12 });
13
14 it('can return login status', function () {
15 localStorage.setItem('authHeader', 'Bearer mytoken');
16 expect(Auth.isLoggedIn()).toBeTruthy();
17 });
18
19 it('can log the user out', function () {
20 localStorage.setItem('authHeader', 'Bearer mytoken');
21 Auth.logUserOut();
22 expect(Auth.isLoggedIn()).toBeFalsy();
23 expect(localStorage.getItem('authHeader')).toBeFalsy();
24 });
25 });

This service is expected to do three things:

  • Set the current user's details in local storage
  • Return whether the user is logged in
  • Log the user out

Make sure the test fails, then amend js/services.js as follows:

1'use strict';
2
3require('angular');
4require("angular-resource");
5
6angular.module('mynewanimalfriend.services', ['ngResource'])
7
8.factory('Auth', function(){
9 return{
10 setUser : function (aUser) {
11 localStorage.setItem('authHeader', 'Bearer ' + aUser);
12 },
13 isLoggedIn: function () {
14 var user = localStorage.getItem('authHeader');
15 return(user)? user : false;
16 },
17 logUserOut: function () {
18 localStorage.removeItem('authHeader');
19 }
20 }
21})
22
23.factory('Token', function ($resource) {
24 return $resource('http://localhost:8000/api/authenticate/');
25});

When the user is set, we store the authentication details we need in local storage. We can then use that to determine if they are logged in. When they log out, we simply clear local storage,

That should be enough to make these tests pass. Now we can move on to our controllers. We'll do the login controller first. Save this as test/controllers.spec.js:

1'use strict';
2
3describe('Controllers', function () {
4
5 beforeEach(function(){
6 jasmine.addMatchers({
7 toEqualData: function(util, customEqualityTesters) {
8 return {
9 compare: function(actual, expected) {
10 return {
11 pass: angular.equals(actual, expected)
12 };
13 }
14 };
15 }
16 });
17 });
18
19 beforeEach(angular.mock.module('mynewanimalfriend.controllers'));
20
21 describe('Login Controller', function () {
22 var mockBackend, scope;
23
24 beforeEach(inject(function ($rootScope, $controller, _$httpBackend_) {
25 mockBackend = _$httpBackend_;
26 scope = $rootScope.$new();
27 $controller('LoginCtrl', {
28 $scope: scope
29 });
30 }));
31
32 // Test controller scope is defined
33 it('should define the scope', function () {
34 expect(scope).toBeDefined();
35 });
36
37 // Test doLogin is defined
38 it('should define the login method', function () {
39 expect(scope.doLogin).toBeDefined();
40 });
41
42 // Test doLogin works
43 it('should allow the user to log in', function () {
44 // Mock the backend
45 mockBackend.expectPOST('http://localhost:8000/api/authenticate', '{"email":"user@example.com","password":"password"}').respond({token: 123});
46
47 // Define login data
48 scope.credentials = {
49 email: 'user@example.com',
50 password: 'password'
51 };
52
53 // Submit the request
54 scope.doLogin();
55
56 // Flush the backend
57 mockBackend.flush();
58
59 // Check login complete
60 expect(localStorage.getItem('authHeader')).toEqual('Bearer 123');
61 });
62 });
63});

We check that the scope and the doLogin() method are defined. We then mock the backend's /api/authenticate route to respond with a dummy token when our credentials are provided. Then, we set the credentials in the variable $scope.credentials, call doLogin(), flush the backend, and check the authentication header has been set.

Once you've verified these tests fail, we can start making them pass. Save this as js/controllers.js:

1'use strict';
2
3require('angular');
4require('angular-route');
5require('./services');
6
7angular.module('mynewanimalfriend.controllers', [
8 'mynewanimalfriend.services',
9 "ngMaterial"
10])
11
12.controller('LoginCtrl', function ($scope, $location, Token, Auth) {
13 $scope.doLogin = function () {
14 var token = new Token($scope.credentials);
15 token.$save(function (response) {
16 if (response.token) {
17 // Set up auth service
18 Auth.setUser(response.token);
19
20 // Redirect
21 $location.path('/');
22 }
23 }, function (err) {
24 alert('Unable to log in - please check your details are correct');
25 });
26 };
27});

The LoginCtrl controller accepts the scope, location, and our two services. When doLogin() is called, it picks up the values in $scope.credentials, which we will set in our template later. It then makes a POST request to our endpoint including those credentials. Our API backend should return the new token in the response, and the token is stored using the Auth service. Otherwise, it raises an error.

Check the test now passes before moving onto the logout functionality. Add this to test/controllers.spec.js:

1 describe('Logout Controller', function () {
2 var scope;
3
4 beforeEach(inject(function ($rootScope, $controller, Auth) {
5 Auth.setUser('Blah');
6 scope = $rootScope.$new();
7 $controller('LogoutCtrl', {
8 $scope: scope
9 });
10 }));
11
12 // Test controller scope is defined
13 it('should define the scope', function () {
14 expect(scope).toBeDefined();
15 });
16
17 // Test session cleared
18 it('should clear the session', function () {
19 expect(localStorage.getItem('authHeader')).toEqual(null);
20 });
21 });

We want to ensure that when the user navigates to the route managed by the LogoutCtrl controller, the session is cleared, so we set up an existing session, call the controller, check it's defined, and then check that local storage is empty.

Once you've verified that the test fails, amend the controllers as follows:

1'use strict';
2
3require('angular');
4require('angular-route');
5require('./services');
6
7angular.module('mynewanimalfriend.controllers', [
8 'mynewanimalfriend.services',
9 "ngMaterial"
10])
11
12.controller('LoginCtrl', function ($scope, $location, Token, Auth) {
13 $scope.doLogin = function () {
14 var token = new Token($scope.credentials);
15 token.$save(function (response) {
16 if (response.token) {
17 // Set up auth service
18 Auth.setUser(response.token);
19
20 // Redirect
21 $location.path('/');
22 }
23 }, function (err) {
24 alert('Unable to log in - please check your details are correct');
25 });
26 };
27})
28
29.controller('LogoutCtrl', function ($scope, $location, Auth) {
30 // Log user out
31 Auth.logUserOut();
32
33 // Redirect to login page
34 $location.path('/login');
35});

Our LogoutCtrl controller is very simple - it just logs the user out and redirects them back to the login form. Our final controller is for the home page:

1 describe('Home Controller', function () {
2 var scope;
3
4 beforeEach(inject(function ($rootScope, $controller) {
5 scope = $rootScope.$new();
6 $controller('HomeCtrl', {
7 $scope: scope
8 });
9 }));
10
11 // Test controller scope is defined
12 it('should define the scope', function () {
13 expect(scope).toBeDefined();
14 });
15 });

For now our home controller does nothing except define the scope, so it's easy to implement:

1'use strict';
2
3require('angular');
4require('angular-route');
5require('./services');
6
7angular.module('mynewanimalfriend.controllers', [
8 'mynewanimalfriend.services',
9 "ngMaterial"
10])
11
12.controller('LoginCtrl', function ($scope, $location, Token, Auth) {
13 $scope.doLogin = function () {
14 var token = new Token($scope.credentials);
15 token.$save(function (response) {
16 if (response.token) {
17 // Set up auth service
18 Auth.setUser(response.token);
19
20 // Redirect
21 $location.path('/');
22 }
23 }, function (err) {
24 alert('Unable to log in - please check your details are correct');
25 });
26 };
27})
28
29.controller('LogoutCtrl', function ($scope, $location, Auth) {
30 // Log user out
31 Auth.logUserOut();
32
33 // Redirect to login page
34 $location.path('/login');
35})
36
37.controller('HomeCtrl', function ($scope) {
38});

Verify that the tests pass, and our controllers are done for now. However, we still have some work to do to hook the various elements up. First, of all, our main.js unnecessarily loads our services - since we only use those services in our controllers, we don't need them there. We also need to be able to keep users out of routes other than login when not logged in. Here's what you main.js should look like:

1'use strict';
2
3require('angular');
4require('angular-route');
5require('angular-animate');
6require('angular-material');
7require('./controllers');
8
9angular.module('mynewanimalfriend', [
10 'ngRoute',
11 'ngAnimate',
12 'ngMaterial',
13 'mynewanimalfriend.controllers'
14])
15
16.run(['$rootScope', '$location', 'Auth', function ($rootScope, $location, Auth) {
17 $rootScope.$on('$routeChangeStart', function (event) {
18
19 if (!Auth.isLoggedIn()) {
20 if ($location.path() !== '/login') {
21 $location.path('/login');
22 }
23 }
24 });
25}])
26
27.config(['$httpProvider', function($httpProvider) {
28 $httpProvider.interceptors.push('sessionInjector');
29 $httpProvider.interceptors.push('authInterceptor');
30}])
31
32.config(function ($routeProvider) {
33 $routeProvider
34 .when('/login', {
35 templateUrl: 'templates/login.html',
36 controller: 'LoginCtrl'
37 })
38 .when('/', {
39 templateUrl: 'templates/home.html',
40 controller: 'HomeCtrl'
41 })
42 .when('/logout', {
43 templateUrl: 'templates/login.html',
44 controller: 'LogoutCtrl'
45 })
46 .otherwise({
47 redirectTo: '/'
48 });
49});

Note that we set it up to intercept the HTTP request with the session injector and the auth interceptor. Next we need to create these in js/services.js:

1'use strict';
2
3require('angular');
4require("angular-resource");
5
6angular.module('mynewanimalfriend.services', ['ngResource'])
7
8.factory('Auth', function(){
9 return{
10 setUser : function (aUser) {
11 localStorage.setItem('authHeader', 'Bearer ' + aUser);
12 },
13 isLoggedIn: function () {
14 var user = localStorage.getItem('authHeader');
15 return(user)? user : false;
16 },
17 logUserOut: function () {
18 localStorage.removeItem('authHeader');
19 }
20 }
21})
22
23.factory('Token', function ($resource) {
24 return $resource('http://localhost:8000/api/authenticate/');
25})
26
27.factory('sessionInjector', function (Auth) {
28 var sessionInjector = {
29 request: function (config) {
30 if (Auth.isLoggedIn()) {
31 config.headers.Authorization = Auth.isLoggedIn();
32 }
33 return config;
34 }
35 };
36 return sessionInjector;
37})
38
39.service('authInterceptor', function ($q, Auth, $location) {
40 var service = this;
41
42 service.responseError = function (response) {
43 if (response.status == 400) {
44 Auth.logUserOut();
45 $location.path('/login');
46 }
47 return $q.reject(response);
48 };
49});

I'll walk you through these. sessionInjector adds the authorisation HTTP header to every request to the server if the user is logged in, so that it returns the right user's details. authInterceptor catches any 400 errors, denoting that the user is not authenticated with a current JSON web token, and logs the user out. In this way we can handle the expiry of a user's token.

Now the logic of our app is in place, but that's no use without some content...

Angular templating

We have one very basic HTML template, but that's just a boilerplate for inserting the rest of our content. For the rest of the HTML we'll need to load templates dynamically, and we'll use Angular Material to help us build a nice UI quickly. Run the following commands to create the files:

1$ mkdir www/templates
2$ touch www/templates/login.html
3$ touch www/templates/home.html

We need to import the CSS for Angular Material. Add this to sass/style.scss:

1// Angular Material
2@import "node_modules/angular-material/angular-material.scss";

With that done, we need to configure theming in main.js:

1'use strict';
2
3require('angular');
4require('angular-route');
5require('angular-animate');
6require('angular-material');
7require('./controllers');
8
9angular.module('mynewanimalfriend', [
10 'ngRoute',
11 'ngAnimate',
12 'ngMaterial',
13 'mynewanimalfriend.controllers'
14])
15
16.config(function ($mdThemingProvider) {
17 $mdThemingProvider.theme('default')
18 .primaryPalette('purple')
19 .accentPalette('cyan');
20})
21
22.run(['$rootScope', '$location', 'Auth', function ($rootScope, $location, Auth) {
23 $rootScope.$on('$routeChangeStart', function (event) {
24
25 if (!Auth.isLoggedIn()) {
26 if ($location.path() !== '/login') {
27 $location.path('/login');
28 }
29 }
30 });
31}])
32
33.config(['$httpProvider', function($httpProvider) {
34 $httpProvider.interceptors.push('sessionInjector');
35 $httpProvider.interceptors.push('authInterceptor');
36}])
37
38.config(function ($routeProvider) {
39 $routeProvider
40 .when('/login', {
41 templateUrl: 'templates/login.html',
42 controller: 'LoginCtrl'
43 })
44 .when('/', {
45 templateUrl: 'templates/home.html',
46 controller: 'HomeCtrl'
47 })
48 .when('/logout', {
49 templateUrl: 'templates/login.html',
50 controller: 'LogoutCtrl'
51 })
52 .otherwise({
53 redirectTo: '/'
54 });
55});

You may want to look at the documentation for Angular Material to choose your own theme options. Next, let's create our login template at www/templates/login.html:

1<md-content md-theme="default" layout-gt-sm="row" layout-padding>
2 <div>
3 <md-input-container class="md-block">
4 <label>Email</label>
5 <input ng-model="credentials.email" type="email">
6 </md-input-container>
7
8 <md-input-container class="md-block">
9 <label>Password</label>
10 <input ng-model="credentials.password" type="password">
11 </md-input-container>
12 <md-button class="md-raised md-primary" ng-click="doLogin()">Submit</md-button>
13 </div>
14</md-content>

We're using Angular Material's input and button directives to make our inputs look a bit nicer. Note that the ng-click handler calls the doLogin() method of our controller, and that the ng-model attributes contain the credentials object that gets passed to the API. If you haven't used Angular before, ng-model essentially lets you bind a variable to an element's value so, for instance, when an input is changed, it can be easily accessed via the variable.

Next, we'll implement a placeholder for our home page with a log out button. Save this as www/templates/home.html:

1<md-toolbar>
2 <div class="md-toolbar-tools">
3 <md-button aria-label="Log out" href="#logout">
4 Log out
5 </md-button>
6 </div>
7</md-toolbar>

That should be all we need to demonstrate logging in and out of our app. Let's try it out. First run the Gulp task to show the app in the browser:

$ gulp

Then, in another shell session, switch to the directory with the backend and run the server for that:

$ php artisan serve

You should already have a user account set up and ready to use thanks to the seeder we wrote. The browser should show the login page by default, and if you fill in the login form and click the button you should see the home page. You should then be able to log out again.

Congratulations! We've got authentication working.

Switching to HTML5 routing

You may note that the URLs use hashes - they are in the format http://localhost:5000/#/login. Wouldn't it be better if we didn't use the hash? Fortunately modern browsers support this via the HTML5 pushState API, and Angular has built-in support for this.

To enable it, we first need to declare a base URL in www/index.html. Amend it as follows:

1<!DOCTYPE html>
2<html lang="en">
3 <head>
4 <meta charset="utf-8">
5 <meta http-equiv="X-UA-Compatible" content="IE=edge">
6 <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=0">
7 <title>My New Animal Friend</title>
8 <link href="/css/style.css" rel="stylesheet" type="text/css">
9 <base href="/">
10 </head>
11 <body>
12 <div>
13 <div ng-app="mynewanimalfriend" ng-cloak>
14 <div ng-view></div>
15 </div>
16 </div>
17 </body>
18 <script language="javascript" type="text/javascript" src="/js/bundle.js"></script>
19</html>

Here we've added the <base href="/"> tag to denote our base URL. Next we configure Angular to use HTML5 routing in main.js:

1.config(function($locationProvider) {
2 $locationProvider.html5Mode(true);
3})

And amend the URL in the home template:

1<md-toolbar>
2 <div class="md-toolbar-tools">
3 <md-button aria-label="Log out" href="/logout">
4 Log out
5 </md-button>
6 </div>
7</md-toolbar>

Now, we should be using HTML5 routing throughout.

With that done, we can finish for today. We've got our basic app skeleton and authentication system up and running, and we'll be in a good place to continue developing the rest of the app next time. I've put the source code on Github, and you can find this lesson's work under the lesson-2 tag.

Next time we'll develop the app further, including implementing the pet search functionality.