Laravel Auth用户的IP地址

时间:2018-12-06 08:56:12

标签: php laravel authentication

我正在尝试创建一个投票网站。因此,访问该网站的任何用户都应能够在注册时注册或不注册。我的问题来了-我想通过IP地址对用户进行身份验证。我需要一个如何构造代码和视图的想法,以实现此目的。因为我可以通过IP查找用户并且可以使用Auth::loginUsingId();,但是我正在控制器中进行操作。这是我的代码:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Answer;
use App\Question;
use App\User;
use App\Category;
use DateTime;

class QuestionController extends Controller
{

  public function show()
  {

    $ip = \Request::ip();

    $user = User::where('ip', $ip)->first();

    if($user == NULL)
    {
      $user = new User;
      $user->ip = $ip;
      $user->save();
    }

    Auth::loginUsingId($user->id, true);

    $questions = Question::all();
    $categories = Category::all();

    return view('home')
      ->with('questions', $questions)
      ->with('categories', $categories);
  }

  public function vote(Request $request)
  {

    $user = NULL;
    $ip = $request->ip();

    if(Auth::check()) $user = Auth::user();

    $user = User::where('ip', $ip)->first();
    Auth::loginUsingId($user->id, true);

    if($user->votes_left == 0)
      return response()->json(['success' => false, 'msg' => 'You have no votes left.']);

    if($user == NULL)
    {
      $user = new User;
      $user->ip = $ip;
      $user->save();
    }

    $question = Question::find($request->question_id)->users()->where('user_id', Auth::id())->get();

    if(sizeof($question) >= 1)
      return response()->json(['success' => false, 'msg' => 'You had already answered this question.']);

    $user->votes_left -= 1;
    $user->save();

    $user->questions()->attach($request->question_id);
    $user->answers()->attach($request->answer_id);

    return response()->json(['success' => true]);

  }

  public static function isAnsweredByUser($question)
  {

  }

  public static function timeElapsed($datetime, $full = false) {
    $now = new DateTime;
    $ago = new DateTime($datetime);
    $diff = $now->diff($ago);

    $diff->w = floor($diff->d / 7);
    $diff->d -= $diff->w * 7;

    $string = array(
      'y' => 'year',
      'm' => 'month',
      'w' => 'week',
      'd' => 'day',
      'h' => 'hour',
      'i' => 'minute',
      's' => 'second',
    );
    foreach ($string as $k => &$v) {
      if ($diff->$k) {
        $v = $diff->$k . ' ' . $v . ($diff->$k > 1 ? 's' : '');
      } else {
        unset($string[$k]);
      }
    }

    if (!$full) $string = array_slice($string, 0, 1);
    return $string ? implode(', ', $string) . ' ago' : 'just now';
  }

  public function store(Request $request)
  {
    //
  }
}

0 个答案:

没有答案