strongloop/loopback-angular — pull request #12 by bajtos (2014-02-03 15:26:03+00:00)
Title: Add User.getCurrent, persist accessTokenId in window.localStorage

The first commit is an unrelated cleanup, the second commit is the meat of this PR.

An example of usage can be found in loopback-example-access control.

1. In the Angular app config, we can install `$http` interceptor to handle 401 responses by redirecting to `/login` view:

```js
// Intercept 401 responses and redirect to login screen
$httpProvider.interceptors.push(function($q, $location, $rootScope) {
return {
responseError: function(rejection) {
if (rejection.status == 401) {
// save the current location so that login can redirect back
$rootScope.nextAfterLogin = $location.path();
$location.path('/login');
}
return $q.reject(rejection);
}
};
});
```

2. The `login` action should redirect to the location saved by the code above:

```js
$scope.loginResult = User.login($scope.credentials,
function() {
var next = $rootScope.nextAfterLogin || '/';
$rootScope.nextAfterLogin = null;
$location.path(next);
},
function(res) {
$scope.loginError = res.data.error;
}
);
```

3. The get data of the current user, the application has to call `User.getCurrent(success, error)`. The application does not need to keep track of the current user id, as it is already tracked by LoopBack. It also does not need to check whether there is a user logged in or not - LoopBack will handle the latter case by returning a stub 401 response.

```js
$scope.currentUser =
$rootScope.currentUser = User.getCurrent(function() {
// success
}, function(response) {
console.log('User.getCurrent() err', arguments);
});
```

This patch implements most of #9, the only missing part is "(do not) remember me".

/to @Schoonology please review
/cc @ritch @seanbrookes