Basically, I want to learn a good practice for this implementation in my angularjs web application. I want to be able to display some greeting and logout button for logged users, even after the refresh the whole page until they logout or close the browser. And to show a "Sign in/Sign up" button if the user is not authenticated yet. I need to use the same logic with some "private" states of my application, for example: if user is not logged and he accesses this url account/options
then he's forced to log in in order to proceed.
Example: Not logged user
Logged user, no matter if page was refreshed after login
Limitation: API
The api I was provided with only responds with this
So I think I should build somehow a method like Auth.isLogged()
that triggers with the application initialization (through the Auth
service maybe?) and then use the condition to include some views, and also in router for the "private views".
But the problem here is that I'm just learning angularjs, and I never developed a login system before, so I don't know how can I create that method in which the application checks for a valid session.
Actually API is creating a cookie at api.aog.com.uy
domain, which I think it's useless because I can't access that cookie under my web app domain...
The code:
'use strict';
angular
.module('webapp', [
'ngCookies',
'ngResource',
'ui.router',
])
.run(
[ '$rootScope', '$state', '$stateParams',
function ($rootScope, $state, $stateParams) {
$rootScope.$state = $state;
$rootScope.$stateParams = $stateParams;
}
]
)
.config(['$stateProvider', function ($stateProvider) {
/*
MAYBE I SHOULD INITIALIZE Auth.isLogged() HERE?
*/
$stateProvider
.state('inicio', {
url: '/',
templateUrl: 'views/main.html',
controller: 'MainCtrl',
})
.state('panel', {
url: '/panel',
title: 'Panel de usuario -',
templateUrl: 'views/panel.html',
controller: 'PanelCtrl'
})
.state('login', {
url: '/login',
title: 'Iniciar sesión -',
templateUrl: 'views/login.html',
controller: 'LoginCtrl'
});
}]);
'use strict';
angular.module('webapp')
.service('Auth', function($http) {
return {
isLogged: function(cookieORsomethingElse){
//some magic
if (sessionAlive) {
return true;
} else {
destroyOldCookieIfPresent();
return false;
}
},
login: function(credencial) {
return $http.post('http://api.aog.com.uy/login/login', credencial);
},
logout: function() {
},
registro: function() {
}
};
});
'use strict';
angular.module('webapp')
.controller('LoginCtrl', function ($scope, Auth, $rootScope, $state) {
$scope.credencial = {servidor: 'alpha'};
$scope.login = function() {
Auth.login({
user_id: $scope.credencial.username,
password: $scope.credencial.password,
server: $scope.credencial.servidor
}).success(function(data, status) {
console.log(data, status);
$state.go('panel');
}).error(function() {
console.log('error: you suck');
});
};
});
Live demo in case you want to check headers. This is the example i'm trying to follow. Thanks in advance! I'll really appreciate any kind of help :)