Skip to content

Commit

Permalink
FWW-16: Removed passport and created auth with jwt with the client model
Browse files Browse the repository at this point in the history
  • Loading branch information
DanielKadevjo committed Jun 8, 2018
1 parent c912050 commit 71a9589
Show file tree
Hide file tree
Showing 10 changed files with 207 additions and 107 deletions.
21 changes: 21 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,2 +1,23 @@
# fibonacci-web
Vendor fibonacci


To use the middlewares you will have to register them in app/Http/Kernel.php under the $routeMiddleware property:

protected $routeMiddleware = [
...
'jwt.auth' => 'Tymon\JWTAuth\Middleware\GetUserFromToken',
'jwt.refresh' => 'Tymon\JWTAuth\Middleware\RefreshToken',
];


Add the following code to the render method within app/Exceptions/Handler.php

if ($exception instanceof Tymon\JWTAuth\Exceptions\TokenExpiredException) {
return response()->json(['error'=>'token_expired'], $exception->getStatusCode());
} else if ($exception instanceof Tymon\JWTAuth\Exceptions\TokenInvalidException) {
return response()->json(['token_invalid'], $exception->getStatusCode());
} else if($exception instanceof \Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException ){
return response()->json(['error'=>'token_not_found'], $exception->getStatusCode());
}
}
6 changes: 4 additions & 2 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,9 @@
"illuminate/support": "4.*|5.*",
"laravel/passport": "~4.0",
"spatie/laravel-analytics": "^3.3",
"spatie/url": "^1.3"
"spatie/url": "^1.3",
"tcg/voyager": "^1.1",
"tymon/jwt-auth": "1.0.0-rc.2"
},
"autoload": {
"psr-4": {
Expand Down Expand Up @@ -35,4 +37,4 @@
}
],
"minimum-stability": "dev"
}
}
32 changes: 21 additions & 11 deletions src/Commands/InstallCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,32 +10,42 @@
class InstallCommand extends Command
{
protected $name = 'fibonacci:install';

public function handle(Filesystem $filesystem)
{
{

//automatic install of voyager 1.*
$this->info("Installing Voyager");
$this->call('voyager:install');

//configurating JWT
$this->info("Installing Jwt");
$this->call('vendor:publish',[ '--provider'=>'Tymon\JWTAuth\Providers\LaravelServiceProvider']);
$this->call('jwt:secret');

$this->info('Migrating the database tables into your application');
$this->call('migrate', array('--path' => 'vendor/kadevjo/fibonacci/src/Database/Migrations'));

$this->info('Publishing config files');
$this->call('vendor:publish', ['--provider' => FibonacciServiceProvider::class]);

$this->info('Creating menu items');
$newMenu = CreateMenu::buildMenu();

$this->info('Adding fibonacci routes to routes/web.php');
$routes_contents = $filesystem->get(base_path('routes/web.php'));

if (false === strpos($routes_contents, 'Fibonacci::webRoutes()')) {
$filesystem->append(
base_path('routes/web.php'),
"\n\nRoute::group(['prefix' => 'admin'], function () {\n Fibonacci::webRoutes();\n});\n"
);
}
$this->info('Adding Fibonacci API routes to routes/api.php');

$this->info('Adding Fibonacci API routes to routes/api.php');

$routes_contents = $filesystem->get(base_path('routes/api.php'));

if (false === strpos($routes_contents, 'Fibonacci::apiRoutes()')) {
$filesystem->append(
base_path('routes/api.php'),
Expand All @@ -44,4 +54,4 @@ public function handle(Filesystem $filesystem)
}

}
}
}
59 changes: 29 additions & 30 deletions src/Controllers/APIController.php
Original file line number Diff line number Diff line change
Expand Up @@ -49,27 +49,27 @@ public function __construct(Request $request){
$this->middleware('auth:api')->only( $this->makeSecure($slug) );
}
}

// Browse
public function index(Request $request){

$slug = $this->getSlug($request);

if( !$this->checkAPI($slug,'browse') ) return response()->json(array('error'=>'Action not allowed') );

$modelClass = $this->getModel($slug);

if($request->has('filter'))
{
$filters = json_decode($request->input('filter'));

$query = $modelClass::query();

foreach ($filters as $filter)
{
call_user_func_array( array($query, $filter->method), $filter->parameters );
}

$response = $query->get();
}
else
Expand All @@ -84,14 +84,14 @@ public function index(Request $request){
public function show(Request $request, $id){
$slug = $this->getSlug($request);
if( !$this->checkAPI($slug,'read') ) return response()->json( array('error'=>'Action not allowed') );

$modelClass = $this->getModel($slug);
$model = $modelClass::find($id);
return $model??response()->json(array('error'=>'WHOOPS! Nothing here, please try again'));
return $model??response()->json(array('error'=>'WHOOPS! Nothing here, please try again'));
}

// Udate
public function update(Request $request, $id){
public function update(Request $request, $id){
$slug = $this->getSlug($request); // table name
if( !$this->checkAPI($slug,'edit') ) return response()->json( array('error'=>'Action not allowed') );

Expand All @@ -104,27 +104,27 @@ public function update(Request $request, $id){
if( $request->hasFile($key) ){
$requestData[$key] = $this->upload($key, $value, $slug);
// Delete old image in storage
$oldImage = $update->where('id', $id)->first();
$oldImage = $update->where('id', $id)->first();
if (Storage::disk(config('voyager.storage.disk'))->exists($oldImage->{$key})) {
Storage::disk(config('voyager.storage.disk'))->delete($oldImage->{$key});
}
}
}

$restrict = config('voyager.restrict');
foreach ($requestData as $key => $value) {
if($restrict && in_array($key, $restrict))
unset($requestData[$key]);
}

if( $update->forceFill($requestData)->save() ){
return response()->json( array('state'=>'success') );
}else{
return response()->json( array('state'=>'error') );
}
}
}
// Insert

// Insert
public function store(Request $request){
$slug = $this->getSlug($request);
if( !$this->checkAPI($slug,'add') ) return response()->json( array('error'=>'Action not allowed') );
Expand All @@ -136,8 +136,8 @@ public function store(Request $request){
// Check for images to upload
foreach ($requestData as $key => $value) {
if( $request->hasFile($key) ){
$requestData[$key] = $this->upload($key, $value, $slug);
}
$requestData[$key] = $this->upload($key, $value, $slug);
}
}

$restrict = config('voyager.restrict');
Expand All @@ -149,12 +149,12 @@ public function store(Request $request){
return response()->json( array('state'=>'success') );
}else{
return response()->json( array('state'=>'error') );
}
}
}

private function upload($name,$image,$slug){
$file = $image;
$dataType = DataType::where('name','=',$slug)->first();
$dataType = DataType::where('name','=',$slug)->first();
$folder = $dataType ? $dataType->slug : $slug;
$path = $folder.'/'.date('FY').'/';

Expand All @@ -163,8 +163,8 @@ private function upload($name,$image,$slug){
while (Storage::disk(config('voyager.storage.disk'))->exists($path.$filename.'.'.$file->getClientOriginalExtension())) {
$filename = Str::random(20);
}
$fullPath = $path.$filename.'.'.$file->getClientOriginalExtension();
$fullPath = $path.$filename.'.'.$file->getClientOriginalExtension();

$resize_width = 1800;
$resize_height = null;
$image = Image::make($file)->resize(
Expand All @@ -182,17 +182,17 @@ function (Constraint $constraint) {

// Delete
public function destroy(Request $request, $id){
$slug = $this->getSlug($request);
$slug = $this->getSlug($request);
if( !$this->checkAPI($slug,'delete') ) return response()->json( array('error'=>'Action not allowed') );

$modelClass = $this->getModel($slug);
$remove = $modelClass::find($id);

if( $remove->delete() ){
return response()->json( array('state'=>'success') );
}else{
return response()->json( array('state'=>'error') );
}
}
}


Expand All @@ -214,21 +214,21 @@ private function checkAPI($table,$action){
if(!$api) return false;

$options = json_decode($api->config);
return $options->{$action}->enable;
return $options->{$action}->enable;
}
// Create array to auth:api
private function makeSecure($table){
$secure = array();
$api = ApiConfig::where('table_name','=',$table)->first();
if($api){
if($api){
$options = json_decode($api->config);

if( $options->browse->secure ) array_push($secure, 'index');
if( $options->read->secure ) array_push($secure, 'show');
if( $options->edit->secure ) array_push($secure, 'update');
if( $options->add->secure ) array_push($secure, 'store');
if( $options->delete->secure ) array_push($secure, 'destroy');
}
}
return $secure;
}

Expand Down Expand Up @@ -295,6 +295,5 @@ public function deleteBreadImages($data, $rows)
if ($rows->count() > 0) {
event(new BreadImagesDeleted($data, $rows));
}
}

}
}
}
86 changes: 86 additions & 0 deletions src/Controllers/Auth/JwtApiController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
<?php

namespace Kadevjo\Fibonacci\Controllers\Auth;

use Illuminate\Support\Facades\Auth;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;

class JwtApiController extends BaseController
{
/**
* Create a new AuthController instance.
*
* @return void
*/
protected $guard = 'api';

public function __construct()
{
//$this->middleware('auth:api', ['except' => ['login']]);
}

/**
* Get a JWT via given credentials.
*
* @return \Illuminate\Http\JsonResponse
*/
public function login()
{
$credentials = request(['email', 'password']);
if ($token = auth('api')->attempt($credentials)) {
$user = \Kadevjo\Fibonacci\Models\Client::where('email',$credentials['email'])->first();
return response()->json(['user'=>$user,'token'=>$token]);
}
return response()->json(['error' => 'Unauthorized'], 401);
}

/**
* Get the authenticated User.
*
* @return \Illuminate\Http\JsonResponse
*/
public function me()
{
return response()->json(\JWTAuth::parseToken()->authenticate());
}

/**
* Log the user out (Invalidate the token).
*
* @return \Illuminate\Http\JsonResponse
*/
public function logout()
{
auth('api')->logout();
return response()->json(['message' => 'Successfully logged out']);
}

/**
* Refresh a token.
*
* @return \Illuminate\Http\JsonResponse
*/
public function refresh()
{
$user = \JWTAuth::parseToken()->authenticate();
return response()->json(['user'=>$user,'token'=>auth('api')->refresh()]);
}

/**
* Get the token array structure.
*
* @param string $token
*
* @return \Illuminate\Http\JsonResponse
*/
protected function respondWithToken($token)
{
return response()->json([
'access_token' => $token,
'token_type' => 'bearer',
'expires_in' => auth('api')->factory()->getTTL() * 60
]);
}
}
Loading

0 comments on commit 71a9589

Please sign in to comment.