CakePHP - Use jQuery to check if user is logged in thru Auth
How can I find out if a user is logged in CakePHP thru the Auth component using jQuery. If a user is logged in allow the action to execute if not display an alert asking the user to log in.
<script>
$(document).ready(function(){
$(".voteup").click(function() {
// var isLoggedIn = ... code needed
if(isLoggedIn){
var Id = $(this).children("p").text();
$(this).children("#article_thumbsUp").load("/comments/voteup/"+Id);
}else{
alert('You must be logged in to vote on a comment');
}
});
});
</script>
开发者_StackOverflow中文版
Assuming you have a CommentsController
with an action check_login()
public function check_login() {
// $this->Auth->user() returns NULL or User info for logged in user
if ($this->Auth->user()) {
// your user is logged in echo success
...
} else {
// you user is NOT logged in echo failure
...
}
}
You should not use javascript for this, it's not safe at all. You should check this server-side, in the controller, as shown in the answer by Charles Sprayberry.
Then in javascript you always do the Ajax request (use $.get
with a callback), and check the response to display the alert or update the UI.
I was able to fix my problem with the following suggestion. So thanks guys for your help...
commments_controller.php
public function checklogin() {
$this->autoRender = false;
if ($this->Auth->user()) {
$loggedIn = 1;
} else {
$loggedIn = 0;
}
return $loggedIn;
}
jQuery Code
<script>
$(document).ready(function(){
var isLoggedIn = 0;
$.ajax({
type: "POST",
url: "/comments/checklogin",
success: function(msg){
isLoggedIn = msg;
}
});
$(".voteup").click(function() {
if(isLoggedIn == 1){
var Id = $(this).children("p").text();
$(this).children("#article_thumbsUp").load("/comments/voteup/"+Id);
}else{
alert('You must be logged in to vote');
}
});
});
</script>
It works nicely... I am not sure if it is the best one but it works
精彩评论