gpt4 book ai didi

php - Laravel 赞成/反对系统 - AJAX 安全

转载 作者:行者123 更新时间:2023-12-01 04:11:23 25 4
gpt4 key购买 nike

我如何在 Laravel 中创建一个安全的赞成/反对系统,比如 reddits,甚至是无法用假 ajax 请求加载的堆栈溢出系统。 (抱歉,如果我不知道术语)。

我有 3 张 table :

**User**
id

**Post**
id

**Vote**
id
user_id
post_id
vote (int)

我的总体想法是,当单击“赞成票”或“反对票”按钮时,使用 JQuery 来使用具有 post_id 和投票的 POST 数据来触发 AJAX,1 表示赞成票,-1 表示反对票)。这将由 VotesController@vote 路由选择。 vote 方法将检查用户是否经过身份验证,检查是否有来自同一用户和同一帖子的投票,如果投票存在:更改它(反对票),否则它将添加它(赞成票)。

这是我的伪代码

function vote()
{
//Checks if user is logged in
if(Auth::check()){

//checks if ajax request
if (Request::ajax())
{
//get my data
$post = Input::post('post');
$vote = Input::post('vote');
$user = Auth::user()->id;

//checks if user voted
$vote = querythatisnotyetcoded

//if row exists
if($vote->count() > 0){
//change row AKA DOWNVOTE
Vote->vote = $vote // however you change values
}
else{
//add new row AKA UPVOTE
Vote::create([
'user_id' => $user,
'post_id' => $post,
'vote' => $vote
]);
}
}
else{
return "No Ajax Request";
}
}
else{
return "Not logged in";
}
}

请告诉我该逻辑是否安全。

*编辑:不知道为什么我的代码是半棕色的(已修复!)

最佳答案

像这样的事情应该可以解决问题。

function vote()
{
if (Auth::check()) {

if (Request::ajax())
{
$post = Input::post('post');
$vote = Input::post('vote');
$user = Auth::user()->id;

// Grab the vote if it already exists.
$entry = Vote::where('user_id', $user)->where('post_id', $post)->first();

if ($entry->count())
{
$entry->vote = $vote;
$entry->save();
}
else
{
$entry = new Vote;
$entry->user_id = $user;
$entry->post_id = $post;
$entry->save();
}
}
else
{
return "Not an AJAX request.";
}
}
else
{
return "User not logged in.";
}
}

关于php - Laravel 赞成/反对系统 - AJAX 安全,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19991698/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com