<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Str;
use Sentry;
use App\User;
use Dingo\Api\Exception\Handler;
class UserController extends Controller
{
protected $user;
public function __construct(Request $request)
{
$payload = $request->header('X-Auth-Token');
$userModel = Sentry::getUserProvider()->createModel();
$user = $userModel->where('api_token',$payload)->first();
if($payload && $user) {
$this->user = $user;
}
}
/**
* Display a listing of the resource.
*
* @return Response
*/
public function index()
{
if(!$this->user)
return $this->response->errorUnauthorized();
$users = User::all();
if(!$users) {
return $this->response->errorNotFound();
}
return $this->response->array($users->present()->toArray());
// return $this->response->array($users->toArray());
}
/**
* Store a newly created resource in storage.
*
* @param Request $request
* @return Response
*/
public function store(Request $request)
{
Sentry::register(array(
'email' => $request->get('email'),
'password' => $request->get('password'),
'activated' => true,
));
return $this->response->created();
}
/**
* Display the specified resource.
*
* @param int $id
* @return Response
*/
public function show($id)
{
$user = User::find($id);
if(!$user) {
return $this->response->errorNotFound();
}
return $this->response->array($user->toArray());
}
/**
* Update the specified resource in storage.
*
* @param Request $request
* @param int $id
* @return Response
*/
public function update(Request $request, $id)
{
//
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return Response
*/
public function destroy($id)
{
//
}
/**
* Auth in site
*
* @param Request $request
* @return Return access code (200) and token
*/
public function login(Request $request){
try
{
$user = Sentry::authenticate($request->all(), false);
$token = hash('sha256',Str::random(10),false);
$user->api_token = $token;
$user->save();
return $this->response->array(array_except($user->toArray(), ['permissions', 'activated', 'activated_at']));
}
catch(Exception $e)
{
return $this->response->errorUnauthorized();
}
}
}