2017-02-05 20 views
2

我尝试创建一个登录系统,但我希望会话可以从PHP代码中获取。如果会话登录是falsenull它将重定向到登录页面。 这里我跑AngularJS代码:如何从PHP获取会话到AngularJS进行重定向

app.run(["$rootScope", 'adminService', '$location', function($rootScope, adminService, $location) { 
    $rootScope.$on("$routeChangeStart", function() { 
     $location.path('/login'); 
    }); 
}]); 

路由代码:

app.config(function($routeProvider){ 
    $routeProvider.when('/', { 
     templateUrl: 'welcome.html' 
    }).when('/administrator', { 
     templateUrl: './part/administrator.html', 
     controller: 'adminPageControl' 
    }).when('/administrator/:id_admin', { 
     templateUrl: './part/addit-administrator.html', 
    }).when('/alternatif', { 
     templateUrl: './part/alternatif.html', 
     controller: 'alternatifPageControl' 
    }).when('/alternatif/:id_alternatif', { 
     templateUrl: './part/addit-alternatif.html' 
    }).when('/skala', { 
     templateUrl: './part/skala.html', 
     controller: 'skalaPageControl' 
    }).when('/skala/:id_skala', { 
     templateUrl: './part/addit-skala.html' 
    }).when('/kriteria', { 
     templateUrl: './part/kriteria.html', 
     controller: 'kriteriaPageControl' 
    }).when('/kriteria/:id_kriteria', { 
     templateUrl: './part/addit-kriteria.html' 
    }).when('/klasifikasi', { 
     templateUrl: './part/klasifikasi.html', 
     controller: 'klasifikasiPageControl' 
    }).when('/klasifikasi/:id_klasifikasi', { 
     templateUrl: './part/addit-klasifikasi.html' 
    }).when('/analisis', { 
     templateUrl: './part/topsis.php', 
     controller: 'analisisPageControl' 
    }).when('/login', { 
     templateUrl: './login.html' 
    }).when('/logout', { 
     template: 'logout' 
    }).otherwise({ 
     redirectTo: '/' 
    }); 
}); 

PHP函数会话代码:

function logincheck(){ 
    return $_SESSION['authid']; 
} 

logincheck(); 
+1

你应该建立在你的后端的唯一的会话标识,而不直接解析PHP会话状态到您的客户端。请记住,AngularJS是为SPA设计的。因此,使您的客户端通过使用API​​与后端进行通信。例如一个RESTful API。一旦用户通过客户端登录,返回一个唯一的会话令牌给客户端。在任何安全的数据HTTP请求上放置并验证该令牌。看看oAuth处理,它也一样。 – lin

+0

如何制作令牌? –

+0

例如'$ token = md5('what-ever-you-want');' – lin

回答

0

对方回答是正确的。通过使用API​​与后端进行通信是一种很好的做法,因为AngularJS是为SPA设计的。但是,如果你坚持使用会话,没关系。您可以创建一个路由器诸如/api/logincheck

PHP:

public function index() 
{ 
    $res = ['login'=>false]; 
    if(isset($_SESSION['authid'])) 
    { 
     $res['login'] = true; 
    } 
    echo json_encode($res); 
} 

JS:

$http.get('http://XX/api/checklogin').success(function(res){ 
    if(res.login) 
    { 
     #handle it 
    } 
}); 
+0

booom,我明白了........ –

0

你应该建立在你的后端的唯一的会话令牌不必解析PHP -Session直接进入你的客户端。请记住,AngularJS是为SPA设计的。因此,使您的客户端通过使用API​​与后端进行通信。例如一个RESTful API。一旦用户通过客户端登录,返回一个唯一的会话令牌给客户端。在每个安全数据HTTP请求上放置并验证该令牌。看看oAuth处理,其相同。

您可以创建一个简单的令牌:$token = md5('what-ever-you-want');并将其实施到您的API逻辑中。在这里您可以找到关于handling security interfaces的更多信息。

enter image description here