使用路由参数和隐藏的输入值来信任用户

问题描述 投票:0回答:1

我正在使用laravel创建学校管理系统软件,该项目恰好是我的第一个大型项目,将在商业上使用。而且没有人监督这项工作(因此,您在这里看到我真的需要建议)。因此,我的问题是何时信任用户输入以及何时在另一个表中使用模型之前检查模型是否存在。例如,在将“ student_id”插入“出勤”表之前,先检查“ users”表中是否存在“ student_id”。这个问题也适用于我想在其他表中持久保存模型的所有其他情况。作为说明,我提出了一部分代码来吸引学生参加。

HTML

<form method="POST" action="{{route('daily.attendance')}}">
    @csrf
    <input type="hidden" name="section_id" value="{{$section_id}}">
    <input type="hidden" name="semester_id" value="{{$semester_id}}">
@foreach ($sections as $section)

 @foreach ($section->users as $student)      
            <input type="checkbox" name = "present[]" value = "{{$student->id}}" class = "present">
            <input type="hidden" name = "students[]" value = "{{$student->id}}"> 
 @endforeach

 @endforeach
<button type="submit" class="btn btn-primary" >{{ __('take attendance') }}</button>      
</form>

php

public static function takeStudentDailyAttendance($request){

        $presentStudents = ( isset($request->present) ) ? $request->present : [] ;
        $dataForPresent = collect( $request->except(['present' , 'students']) )->merge(['status' => 1 , 'takenBy_id' => Auth::user()->id])->toArray();
        $dataForAbsent = collect( $request->except(['present' , 'students']) )->merge(['status' => 0 , 'takenBy_id' => Auth::user()->id])->toArray();

        DB::transaction(function () use ($request , $dataForPresent , $dataForAbsent , $presentStudents) {

            foreach($request->students as $student_id){
                if( in_array($student_id , $presentStudents) ){

                    $dataForPresent['student_id'] = $student_id; 
                    StudentDailyAttendance::create($dataForPresent);

                }else{
                    $dataForAbsent['student_id'] = $student_id;
                    StudentDailyAttendance::create($dataForAbsent);
                } 
            }
        });
    }

因此,即使我为$ section_id和$ semester_id使用隐藏的输入,我也知道用户(admin)可以使用其浏览器控制台更改这些值,然后发送表单。想象管理员有意或无意地(显示for的路由是这样的"daily/student/section/{section_id}')将$ section_id或$ semester_id更改为与sections表和Semesters表中的任何模型都不对应的值。还是她(管理员)参加了一个甚至根本不存在的科目或学期,而且由于数据库完整性的完整性有问题,所以这不好,所以问题是我应该信任管理员还是应该检查在插入“出勤”表之前,在其对应的表中存在$ section_id和$ semester_id(这样做也将增加脚本结束的时间)。同样查看php代码,student_id值也可以从html进行篡改,并且您看到代码循环遍历标记为存在和标记为不存在的学生数组,我是否还应该检查$ student_id是否在“用户”表中参加会议(这样做也会增加脚本结束的时间),或者我也应该信任管理员吗?

php html laravel laravel-routing laravel-5.8
1个回答
0
投票

规则总是说,在谈论数据完整性时,永远不要特别信任用户。我建议尝试使用laravel的有效方法:https://laravel.com/docs/6.x/validation#rule-exists

但是,如果您最关心的是性能,我会在第一次请求出席页面时将用户ID和sectionIds缓存在Redis哈希中一段时间​​,然后检查是否有例如student_id在缓存的user_id中如果您想看看Laravel的缓存:https://laravel.com/docs/5.7/cache#retrieving-items-from-the-cache

© www.soinside.com 2019 - 2024. All rights reserved.