Skip to content

Instantly share code, notes, and snippets.

@DKepov
Created June 14, 2016 08:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DKepov/f0c2a6bb1fbd78d44e414354e88d1508 to your computer and use it in GitHub Desktop.
Save DKepov/f0c2a6bb1fbd78d44e414354e88d1508 to your computer and use it in GitHub Desktop.
Lumen example
```php
<?php
namespace App\Exceptions;
use Exception;
use Illuminate\Validation\ValidationException;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Laravel\Lumen\Exceptions\Handler as ExceptionHandler;
use App\Http\Helper\Error;
class Handler extends ExceptionHandler
{
/**
* A list of the exception types that should not be reported.
*
* @var array
*/
protected $dontReport = [
AuthorizationException::class,
HttpException::class,
ModelNotFoundException::class,
ValidationException::class,
];
/**
* Report or log an exception.
*
* This is a great spot to send exceptions to Sentry, Bugsnag, etc.
*
* @param \Exception $e
* @return void
*/
public function report(Exception $e)
{
parent::report($e);
}
/**
* Render an exception into an HTTP response.
*
* @param \Illuminate\Http\Request $request
* @param \Exception $e
* @return \Illuminate\Http\Response
*/
public function render($request, Exception $e)
{
if (env('APP_DEBUG', false) === false AND env('APP_ENV', 'production') === 'production')
{
return Error::exceptionError();
}
return parent::render($request, $e);
}
}
```
```php
<?php
namespace App\Http\Controllers\ApiV1;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Input;
use App\Domain\Model\User;
use App\Domain\Model\Token;
class UserController extends Controller
{
public function __construct()
{
//
}
public function auth()
{
$login = Input::get('login', null);
$password = Input::get('password', null);
if ( ! $login || ! $password) {
return $this->sendError(111, 'Not set login or password');
}
$user = User::where('login', '=', $login)->where('password', '=', md5($password))->first();
if ( ! $user) {
return $this->sendError(112, 'Not found user');
}
$token = $user->token;
if ( ! $token) {
$token = Token::create([
'id_user' => $user->user_id,
'token' => md5($user->login.$user->user_id.time()),
'active' => 1,
]);
} else {
$user->token->token = md5($user->login.$user->user_id.time());
$user->token->save();
}
return $this->sendResult([
'token' => $token->token,
'user' => [
'user_id' => $user->user_id,
'login' => $user->login,
'name' => $user->name,
'city' => $user->city,
'points' => $user->statuses->sum('points'),
],
]);
}
public function register()
{
$login = Input::get('login', null);
$password = Input::get('password', null);
$name = Input::get('name', null);
$city = Input::get('city', null);
if ( ! $login || ! $password || ! $name || ! $city) {
return $this->sendError(121, 'Not all of the data set');
}
$user = User::where('login', '=', $login)->first();
if ($user) {
return $this->sendError(122, 'User has already');
}
$user = User::create([
'login' => $login,
'password' => md5($password),
'name' => $name,
'city' => $city,
]);
$token = Token::create([
'id_user' => $user->user_id,
'token' => md5($user->login.$user->user_id.time()),
'active' => 1,
]);
return $this->sendResult([
'token' => $token->token,
'user' => [
'user_id' => $user->user_id,
'login' => $user->login,
'name' => $user->name,
'city' => $user->city,
'points' => 0,
],
]);
}
public function recovery()
{
return $this->sendError(131, 'Undefined method');
}
public function getInfo($id)
{
$id = (integer)$id;
$user_id = app()->user_id;
if ( ! $id) {
return $this->sendError(140, 'Not set ID');
}
if ($id !== $user_id) {
return $this->sendError(141, 'Access closed');
}
$user = User::find($user_id);
return $this->sendResult([
'user' => [
'user_id' => $user->user_id,
'login' => $user->login,
'name' => $user->name,
'city' => $user->city,
'points' => $user->statuses->sum('points'),
],
]);
}
public function updateInfo($id)
{
$password = Input::get('password', null);
$name = Input::get('name', null);
$city = Input::get('city', null);
$id = (integer)$id;
$user_id = app()->user_id;
if ( ! $id) {
return $this->sendError(150, 'Not set ID');
}
if ($id !== $user_id) {
return $this->sendError(151, 'Access closed');
}
if ( ! $password || ! $name || ! $city) {
return $this->sendError(152, 'Not all of the data set');
}
$user = User::find($user_id);
$user->password = md5($password);
$user->name = $name;
$user->city = $city;
$user->save();
return $this->sendResult([
'user' => [
'user_id' => $user->user_id,
'login' => $user->login,
'name' => $user->name,
'city' => $user->city,
'points' => $user->statuses->sum('points'),
],
]);
}
}
```
```php
<?php
namespace App\Http\Controllers;
use Laravel\Lumen\Routing\Controller as BaseController;
class Controller extends BaseController
{
public function sendResult($response)
{
$grand = [
'code' => 0,
'message' => '',
'token' => app()->token,
];
$merge = array_merge($grand, $response);
return response()->json($merge, 200);
}
public function sendError($code, $message)
{
$error = [
'code' => $code,
'message' => $message,
];
return response()->json($error, 400);
}
}
```
```php
<?php
namespace App\Http\Helper;
class Error
{
public static function notSign()
{
return response()->json([
'code' => 403,
'message' => 'No Sign fact',
], 403);
}
public static function noValidSign()
{
return response()->json([
'code' => 403,
'message' => 'No Valid Sign fact',
], 403);
}
public static function notToken()
{
return response()->json([
'code' => 403,
'message' => 'No Token fact',
], 403);
}
public static function noValidToken()
{
return response()->json([
'code' => 403,
'message' => 'No Valid Token fact',
], 403);
}
public static function exceptionError()
{
return response()->json([
'code' => 500,
'message' => 'Server Exception Error',
], 500);
}
}
```
```php
<?php
namespace App\Http\Middleware;
use Closure;
use App\Http\Helper\Error;
class SignMiddleware
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
$signOrigin = 'quest';
$sign = $request->get('sign');
if ( ! $sign) {
return Error::notSign();
}
if ($sign !== $signOrigin) {
return Error::noValidSign();
}
return $next($request);
}
}
```

Минимальный набросок для API

Не приведена к единому виду обработка ошибок

Как работает.

  • Все запросы restful
  • Каждый запрос имеет два параметра передаваемых в get. sign и token
  • sign - переменная которая содержит подпись от запроса, о формировании которой знает только апи и клиент апи.
  • token - переменная идентификации пользователя.
  • Апи всегда отдает ответ - 200, в случае нарушения прав - 403, в случае ошибки сервера - 500, в случае любой другой ошибки - общий ответ 400. Код дублируется как в виде ответа http, так и в теле ответа.
  • Входящие и исходящие данные в json
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment