Skip to content

Instantly share code, notes, and snippets.

@wilk
Last active May 10, 2016 09:13
Show Gist options
  • Save wilk/3d4a4364782a5f1485de to your computer and use it in GitHub Desktop.
Save wilk/3d4a4364782a5f1485de to your computer and use it in GitHub Desktop.
Angular session
'use strict';
angular
.module('myApp', ['ngCookies', 'ngRoute'])
.service('Auth', ['$cookieStore', function ($cookieStore) {
var me = this;
me.authenticate = function (token) {
if (token) $cookieStore.put('token', token);
return $cookieStore.get('token');
};
me.data = function (data) {
if (data) $cookieStore.put('data', data);
return $cookieStore.get('data');
};
}])
.config(['$routeProvider', function ($routeProvider) {
$routeProvider
.when('/', {
controller: 'MainCtrl',
templateUrl: 'views/main.html'
})
.when('/login', {
controller: 'LoginCtrl',
templateUrl: 'views/login.html'
})
.otherwise({
templateUrl: 'views/404.html'
});
}])
.controller('MainCtrl', ['$scope', 'Auth', function ($scope, Auth) {
$scope.data = Auth.data();
}])
.controller('LoginCtrl', ['$scope', '$http', '$location', 'Auth', function ($scope, $http, $location, Auth) {
$scope.login = function (username, password) {
$http.post('/login', {username: username, password: password})
.$promise.then(function (res) {
Auth.authenticate(res.token);
Auth.data(res.data);
$location.path('/').replace();
}, function (err) {
$scope.error = err;
});
};
}])
.run(['$rootScope', '$location', 'Auth', function ($rootScope, $location, Auth) {
$rootScope.$on('$routeChangeStart', function (event) {
if ($location.path() !== '/login') {
var token = Auth.authenticate();
if (token && token.length > 0) {
event.preventDefault();
$location.path('/login').replace();
}
}
});
}])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment