<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;

use App\User;



class UserController extends Controller
{

    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function login(Request $request) {
        $name = $request->input("name");
        $password = $request->input("password");

        if($name && $password) {
            $user = User::where("name", $name)->where("password", md5($password))->first();
            if($user) {
                $token = md5($user->name . mt_rand());
                //$request->session()->put($token, $user);
                Cache::put($token, $user, 60 * 24);
                return response()->json([
                    "status" => 0,
                    "token" => $token,
                    "role" => $user->role
                ]);
            } else {
                return response()->json([
                    "status" => -2,
                    "message" => "用户不存在或密码错误"
                ]);
            }
        } else {
            return response()->json([
                "status" => -1,
                "message" => "信息不能为空"
            ]);
        }
    }

    /**
     * @param Request $request
     */
    public function logout(Request $request) {
        $token = $request->header("Authorization");
        if($token) {
            $token = trim($token);
            $token = str_replace("Bearer ", "", $token);
            if ($request->session()->has($token)) {
                $request->session()->forget($token);
                return response()->json([
                    "status" => 0,
                    "message" => "登出成功"
                ]);
            }
        }
    }
}
