Unverified Commit 78a91df2 authored by Viral Solani's avatar Viral Solani Committed by GitHub

Merge pull request #159 from indranshastri/develop

Change done for api validation and exception handling 
parents cc0e7808 a99a8018
...@@ -55,6 +55,35 @@ class Handler extends ExceptionHandler ...@@ -55,6 +55,35 @@ class Handler extends ExceptionHandler
* Redirect if token mismatch error * Redirect if token mismatch error
* Usually because user stayed on the same screen too long and their session expired * Usually because user stayed on the same screen too long and their session expired
*/ */
if ($exception instanceof \Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException) {
switch (get_class($exception->getPrevious())) {
case \App\Exceptions\Handler::class:
return response()->json([
'status' => 'error',
'error' => 'Token has not been provided',
'data' => json_decode("{}"),
], $exception->getStatusCode());
case \Tymon\JWTAuth\Exceptions\TokenExpiredException::class:
return response()->json([
'status' => 'error',
'error' => 'Token has expired',
'data' => json_decode("{}"),
], $exception->getStatusCode());
case \Tymon\JWTAuth\Exceptions\TokenInvalidException::class:
case \Tymon\JWTAuth\Exceptions\TokenBlacklistedException::class:
return response()->json([
'status' => 'error',
'error' => 'Token is invalid',
'data' => json_decode("{}"),
], $exception->getStatusCode());
default:
break;
}
}
/*
* Redirect if token mismatch error
* Usually because user stayed on the same screen too long and their session expired
*/
if ($exception instanceof TokenMismatchException) { if ($exception instanceof TokenMismatchException) {
return redirect()->route('frontend.auth.login'); return redirect()->route('frontend.auth.login');
} }
...@@ -63,6 +92,17 @@ class Handler extends ExceptionHandler ...@@ -63,6 +92,17 @@ class Handler extends ExceptionHandler
* All instances of GeneralException redirect back with a flash message to show a bootstrap alert-error * All instances of GeneralException redirect back with a flash message to show a bootstrap alert-error
*/ */
if ($exception instanceof GeneralException) { if ($exception instanceof GeneralException) {
//Note:Below code is required when we use an extra class as api request then we need to pass accept:application/json in the header also
//if the header has accept application/json then $request->wantsJson() returns true
// if ($request->ajax() || $request->wantsJson()){
// $json = [
// 'success' => false,
// 'error' => [
// 'message' => $exception->getMessage(),
// ],
// ];
// return response()->json($json, 400);
// }
return redirect()->back()->withInput()->withFlashDanger($exception->getMessage()); return redirect()->back()->withInput()->withFlashDanger($exception->getMessage());
} }
...@@ -105,6 +145,7 @@ class Handler extends ExceptionHandler ...@@ -105,6 +145,7 @@ class Handler extends ExceptionHandler
*/ */
protected function unauthenticated($request, AuthenticationException $exception) protected function unauthenticated($request, AuthenticationException $exception)
{ {
if ($request->expectsJson()) { if ($request->expectsJson()) {
return response()->json(['error' => 'Unauthenticated.'], 401); return response()->json(['error' => 'Unauthenticated.'], 401);
} }
......
...@@ -178,6 +178,20 @@ class APIController extends Controller ...@@ -178,6 +178,20 @@ class APIController extends Controller
return $this->setStatusCode(204)->respond(null); return $this->setStatusCode(204)->respond(null);
} }
/**Note this function is same as the below function but instead of responding with error below function returns error json
* Throw Validation.
*
* @param string $message
*
* @return mix
*/
// public function throwValidation($message)
// {
// return $this->setStatusCode(422)
// ->respondWithError($message);
// }
/** /**
* Throw Validation. * Throw Validation.
* *
...@@ -185,9 +199,8 @@ class APIController extends Controller ...@@ -185,9 +199,8 @@ class APIController extends Controller
* *
* @return mix * @return mix
*/ */
public function throwValidation($message) public function throwValidation($validation)
{ {
return $this->setStatusCode(422) return ["error"=>$validation->errors()];
->respondWithError($message);
} }
} }
...@@ -6,7 +6,9 @@ use App\Http\Resources\BlogTagsResource; ...@@ -6,7 +6,9 @@ use App\Http\Resources\BlogTagsResource;
use App\Models\BlogTags\BlogTag; use App\Models\BlogTags\BlogTag;
use App\Repositories\Backend\BlogTags\BlogTagsRepository; use App\Repositories\Backend\BlogTags\BlogTagsRepository;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use App\Http\Requests\Backend\BlogTags\StoreApiBlogTagsRequest;
use Validator; use Validator;
use Exception;
class BlogTagsController extends APIController class BlogTagsController extends APIController
{ {
...@@ -67,6 +69,22 @@ class BlogTagsController extends APIController ...@@ -67,6 +69,22 @@ class BlogTagsController extends APIController
return new BlogTagsResource(BlogTag::orderBy('created_at', 'desc')->first()); return new BlogTagsResource(BlogTag::orderBy('created_at', 'desc')->first());
} }
/** NOTE This function is same as about but uses StoreApiBlogTagsRequest for validation of the api
* Creates the Resource for BlogTag.
*
* @param Request $request
*
* @return \Illuminate\Http\Response
*
*
*/
// public function store(StoreApiBlogTagsRequest $request)
// {
// $this->repository->create($request->all());
// return new BlogTagsResource(BlogTag::orderBy('created_at', 'desc')->first());
// }
/** /**
* @param BlogTag $blog_tag * @param BlogTag $blog_tag
* @param UpdateBlogTagRequest $request * @param UpdateBlogTagRequest $request
...@@ -78,7 +96,7 @@ class BlogTagsController extends APIController ...@@ -78,7 +96,7 @@ class BlogTagsController extends APIController
$validation = $this->validatingRequest($request, $blog_tag->id); $validation = $this->validatingRequest($request, $blog_tag->id);
if ($validation->fails()) { if ($validation->fails()) {
return $this->throwValidation($validation->messages()->first()); return $this->throwValidation($validation);
} }
$this->repository->update($blog_tag, $request->all()); $this->repository->update($blog_tag, $request->all());
......
<?php
namespace App\Http\Controllers\Api\V1;
use App\Events\Backend\Access\User\UserCreated;
use App\Events\Backend\Access\User\UserUpdated;
use App\Http\Resources\UserResource;
use App\Models\Access\User\User;
use App\Repositories\Backend\Access\User\UserRepository;
use Illuminate\Http\Request;
use Validator;
class DeactivatedUsersController extends APIController
{
protected $repository;
/**
* __construct.
*
* @param $repository
*/
public function __construct(UserRepository $repository)
{
$this->repository = $repository;
}
/**
* Return the deactivated users.
*
* @param Request $request
*
* @return \Illuminate\Http\JsonResponse
*/
public function index(Request $request)
{
$limit = $request->get('paginate') ? $request->get('paginate') : 25;
return UserResource::collection(
$this->repository->getForDataTable(0, false)->paginate($limit)
);
}
}
<?php
namespace App\Http\Controllers\Api\V1;
use App\Events\Backend\Access\User\UserCreated;
use App\Events\Backend\Access\User\UserUpdated;
use App\Http\Resources\UserResource;
use App\Models\Access\User\User;
use App\Repositories\Backend\Access\User\UserRepository;
use Illuminate\Http\Request;
use Validator;
class DeletedUsersController extends APIController
{
protected $repository;
/**
* __construct.
*
* @param $repository
*/
public function __construct(UserRepository $repository)
{
$this->repository = $repository;
}
/**
* Return the deleted users.
*
* @param Request $request
*
* @return \Illuminate\Http\JsonResponse
*/
public function index(Request $request)
{
$limit = $request->get('paginate') ? $request->get('paginate') : 25;
return UserResource::collection(
$this->repository->getForDataTable(0, true)->paginate($limit)
);
}
}
...@@ -22,26 +22,29 @@ class RolesController extends APIController ...@@ -22,26 +22,29 @@ class RolesController extends APIController
$this->repository = $repository; $this->repository = $repository;
} }
/** /**
* Return the users. * Return the roles.
* *
* @return \Illuminate\Http\Response * @param Request $request
*
* @return \Illuminate\Http\JsonResponse
*/ */
public function index(Request $request) public function index(Request $request)
{ {
$limit = $request->get('paginate') ? $request->get('paginate') : 25; $limit = $request->get('paginate') ? $request->get('paginate') : 25;
return RoleResource::collection( return RoleResource::collection(
$this->repository->getPaginated($limit) $this->repository->getForDataTable()->paginate($limit)
); );
} }
/** /**
* Return the specified resource. * Return the specified resource.
* *
* @param User $user * @param Role $role
* *
* @return \Illuminate\Http\Response * @return \Illuminate\Http\JsonResponse
*/ */
public function show(Role $role) public function show(Role $role)
{ {
...@@ -49,7 +52,7 @@ class RolesController extends APIController ...@@ -49,7 +52,7 @@ class RolesController extends APIController
} }
/** /**
* Creates the Resourse for Role. * Creates the Resource for Role.
* *
* @param Request $request * @param Request $request
* *
...@@ -57,7 +60,7 @@ class RolesController extends APIController ...@@ -57,7 +60,7 @@ class RolesController extends APIController
*/ */
public function store(Request $request) public function store(Request $request)
{ {
$validation = $this->validatingRequest($request); $validation = $this->validateRole($request);
if ($validation->fails()) { if ($validation->fails()) {
return $this->throwValidation($validation->messages()->first()); return $this->throwValidation($validation->messages()->first());
} }
...@@ -68,14 +71,16 @@ class RolesController extends APIController ...@@ -68,14 +71,16 @@ class RolesController extends APIController
} }
/** /**
* Update User.
*
* @param Request $request
* @param Role $role * @param Role $role
* @param UpdateRoleRequest $request
* *
* @return mixed * @return \Illuminate\Http\JsonResponse
*/ */
public function update(Request $request, Role $role) public function update(Request $request, Role $role)
{ {
$validation = $this->validatingRequest($request); $validation = $this->validateRole($request);
if ($validation->fails()) { if ($validation->fails()) {
return $this->throwValidation($validation->messages()->first()); return $this->throwValidation($validation->messages()->first());
...@@ -88,7 +93,30 @@ class RolesController extends APIController ...@@ -88,7 +93,30 @@ class RolesController extends APIController
return new RoleResource($role); return new RoleResource($role);
} }
public function validatingRequest(Request $request) /**
* @param Role $role
* @param Request $request
*
* @return \Illuminate\Http\JsonResponse
*/
public function destroy(Role $role, Request $request)
{
$this->repository->delete($role);
return $this->respond([
'message' => trans('alerts.backend.roles.deleted'),
]);
}
/**
* validateUser User.
*
* @param $request
*
* @return Validator object
*/
public function validateRole(Request $request)
{ {
$permissions = ''; $permissions = '';
...@@ -103,17 +131,4 @@ class RolesController extends APIController ...@@ -103,17 +131,4 @@ class RolesController extends APIController
return $validation; return $validation;
} }
/**
* @param Role $role
* @param DeleteRoleRequest $request
*
* @return mixed
*/
public function destroy(Role $role, Request $request)
{
$this->repository->delete($role);
return ['message'=>'success'];
}
} }
...@@ -76,7 +76,7 @@ class UsersController extends APIController ...@@ -76,7 +76,7 @@ class UsersController extends APIController
* @param Request $request * @param Request $request
* @param User $user * @param User $user
* *
* @return \Illuminate\Http\JsonResponse * @return Validator object
*/ */
public function update(Request $request, User $user) public function update(Request $request, User $user)
{ {
...@@ -108,38 +108,6 @@ class UsersController extends APIController ...@@ -108,38 +108,6 @@ class UsersController extends APIController
]); ]);
} }
/**
* Return the deactivate users.
*
* @param Request
*
* @return \Illuminate\Http\JsonResponse
*/
public function deactivatedUserList(Request $request)
{
$limit = $request->get('paginate') ? $request->get('paginate') : 25;
return UserResource::collection(
$this->repository->getForDataTable(0, false)->paginate($limit)
);
}
/**
* Return the deleted users.
*
* @param User $user
*
* @return \Illuminate\Http\JsonResponse
*/
public function deleteUserList(Request $request)
{
$limit = $request->get('paginate') ? $request->get('paginate') : 25;
return UserResource::collection(
$this->repository->getForDataTable(0, true)->paginate($limit)
);
}
/** /**
* validateUser User. * validateUser User.
* *
......
<?php
namespace App\Http\Requests\Backend\BlogTags;
use App\Http\Requests\Request;
/**
* Class StoreBlogTagsRequest.
*/
class StoreApiBlogTagsRequest extends Request
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'name' => 'required|max:191',
];
}
/**
* Get the custom validation messages.
*
* @return array
*/
public function messages()
{
return [
'name.required' => 'Blog Tag name is a required field.111111',
'name.max' => 'Blog Tag may not be greater than 191 characters.',
];
}
}
...@@ -27,17 +27,14 @@ Route::group(['namespace' => 'Api\V1', 'prefix' => 'v1', 'as' => 'v1.'], functio ...@@ -27,17 +27,14 @@ Route::group(['namespace' => 'Api\V1', 'prefix' => 'v1', 'as' => 'v1.'], functio
Route::post('password/email', 'ForgotPasswordController@sendResetLinkEmail'); Route::post('password/email', 'ForgotPasswordController@sendResetLinkEmail');
// Route::post('password/reset', 'ResetPasswordController@reset')->name('password.reset'); // Route::post('password/reset', 'ResetPasswordController@reset')->name('password.reset');
}); });
Route::resource('users', 'UsersController', ['except' => ['edit', 'udpate']]);
// Users // Users
Route::group(['prefix' => 'users'], function () { Route::resource('users', 'UsersController', ['except' => ['create','edit']]);
Route::get('deactiveUsers', 'UsersController@deactivatedUserList'); Route::get('deactivatedUsers', 'DeactivatedUsersController@index');
Route::get('deleteUsers', 'UsersController@deleteUserList'); Route::get('deletedUsers', 'DeletedUsersController@index');
});
// Roles // Roles
Route::resource('roles', 'RolesController'); Route::resource('roles', 'RolesController' , ['except' => ['create', 'edit']]);
// Permission // Permission
Route::resource('permission', 'PermissionController'); Route::resource('permission', 'PermissionController');
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment