-
Notifications
You must be signed in to change notification settings - Fork 97
/
Copy pathauth.client.js
87 lines (78 loc) · 2.5 KB
/
auth.client.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
var myApp = angular.module('myApp', []);
//this is used to parse the profile
function url_base64_decode(str) {
var output = str.replace('-', '+').replace('_', '/');
switch (output.length % 4) {
case 0:
break;
case 2:
output += '==';
break;
case 3:
output += '=';
break;
default:
throw 'Illegal base64url string!';
}
return window.atob(output); //polifyll https://github.com/davidchambers/Base64.js
}
myApp.controller('UserCtrl', function ($scope, $http, $window) {
$scope.user = {username: 'john.doe', password: 'foobar'};
$scope.isAuthenticated = false;
$scope.welcome = '';
$scope.message = '';
$scope.submit = function () {
$http
.post('/authenticate', $scope.user)
.success(function (data, status, headers, config) {
$window.sessionStorage.token = data.token;
$scope.isAuthenticated = true;
var encodedProfile = data.token.split('.')[1];
var profile = JSON.parse(url_base64_decode(encodedProfile));
$scope.welcome = 'Welcome ' + profile.first_name + ' ' + profile.last_name;
})
.error(function (data, status, headers, config) {
// Erase the token if the user fails to log in
delete $window.sessionStorage.token;
$scope.isAuthenticated = false;
// Handle login errors here
$scope.error = 'Error: Invalid user or password';
$scope.welcome = '';
});
};
$scope.logout = function () {
$scope.welcome = '';
$scope.message = '';
$scope.isAuthenticated = false;
delete $window.sessionStorage.token;
};
$scope.callRestricted = function () {
$http({url: '/api/restricted', method: 'GET'})
.success(function (data, status, headers, config) {
$scope.message = $scope.message + ' ' + data.name; // Should log 'foo'
})
.error(function (data, status, headers, config) {
alert(data);
});
};
});
myApp.factory('authInterceptor', function ($rootScope, $q, $window) {
return {
request: function (config) {
config.headers = config.headers || {};
if ($window.sessionStorage.token) {
config.headers.Authorization = 'Bearer ' + $window.sessionStorage.token;
}
return config;
},
responseError: function (rejection) {
if (rejection.status === 401) {
// handle the case where the user is not authenticated
}
return $q.reject(rejection);
}
};
});
myApp.config(function ($httpProvider) {
$httpProvider.interceptors.push('authInterceptor');
});