Skip to content

Commit

Permalink
refactoring
Browse files Browse the repository at this point in the history
  • Loading branch information
fokosun committed Sep 9, 2023
1 parent 3ddbe29 commit 5fca8c2
Show file tree
Hide file tree
Showing 8 changed files with 81 additions and 84 deletions.
2 changes: 1 addition & 1 deletion app/Console/Commands/LoginCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ public function handle(UserService $userService, AuthService $authService)
'password' => 'testing123'
]));

$this->info($token->getContent());
$this->info($token);

$this->line('====================================');
$this->info("Here you go! Use this token to access protected resources.!");
Expand Down
31 changes: 19 additions & 12 deletions app/Http/Controllers/AuthController.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use Symfony\Component\HttpFoundation\Response as ResponseAlias;
use Tymon\JWTAuth\Exceptions\JWTException;

/**
Expand All @@ -36,21 +37,27 @@ public function __construct(AuthService $service)
$this->service = $service;
}

/**
* @param SignInRequest $request
* @return \Illuminate\Http\JsonResponse
*/
public function login(SignInRequest $request): \Illuminate\Http\JsonResponse
{
return $this->service->login($request);
if (!$token = $this->service->login($request)) {
return response()->json(
[
'Not found or Invalid Credentials.',
], ResponseAlias::HTTP_NOT_FOUND
);
}

return $this->successResponse(['token' => $token]);
}

/**
* @return \Illuminate\Http\JsonResponse|\Illuminate\Http\Response
* @return \Illuminate\Http\JsonResponse|Response
*/
public function logout()
{
return $this->service->logout();
return $this->service->logout() ?
$this->noContentResponse() :
$this->errorResponse(['Not found or Invalid Credentials.']);
}

/**
Expand All @@ -69,7 +76,7 @@ public function loginViaMagicLink(Request $request, LocationService $locationSer
'required' => [
'email' => 'Looks like this is your first time signing in with magiclink! Kindly provide your registered email for verification.',
]
], Response::HTTP_UNPROCESSABLE_ENTITY);
], ResponseAlias::HTTP_UNPROCESSABLE_ENTITY);
}

try {
Expand All @@ -83,7 +90,7 @@ public function loginViaMagicLink(Request $request, LocationService $locationSer
]
]);

return response()->json($locationService->getErrors(), Response::HTTP_UNAUTHORIZED);
return response()->json($locationService->getErrors(), ResponseAlias::HTTP_UNAUTHORIZED);
}

$locationUserEmail = $location->getUser()->email;
Expand All @@ -95,7 +102,7 @@ public function loginViaMagicLink(Request $request, LocationService $locationSer
]
]);

return response()->json($locationService->getErrors(), Response::HTTP_UNAUTHORIZED);
return response()->json($locationService->getErrors(), ResponseAlias::HTTP_UNAUTHORIZED);
} else {
$location->update([
'ip' => $request->ipinfo->ip,
Expand Down Expand Up @@ -124,7 +131,7 @@ public function loginViaMagicLink(Request $request, LocationService $locationSer
} catch (\Throwable $e) {
$m = array_merge($locationService->getErrors(), [$e->getMessage()]);

return response()->json($m, Response::HTTP_UNAUTHORIZED);
return response()->json($m, ResponseAlias::HTTP_UNAUTHORIZED);
}
}

Expand Down Expand Up @@ -263,7 +270,7 @@ public function tikTokHandleCallback(Request $request, Client $client, UserServi
public function validateToken(Request $request)
{
if (!$request->bearerToken() || !Auth::check()) {
throw new JWTException('Expired or Tnvalid token.');
throw new JWTException('Expired or Invalid token.');
}

return response()->json(
Expand Down
4 changes: 2 additions & 2 deletions app/Http/Controllers/Controller.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,9 @@ class Controller extends BaseController

use AuthorizesRequests, DispatchesJobs, ValidatesRequests;

public function successResponse(array $data = []): \Illuminate\Http\JsonResponse
public function successResponse(array $data = [], $code = ResponseAlias::HTTP_OK): \Illuminate\Http\JsonResponse
{
return response()->json($data);
return response()->json($data, $code);
}

public function noContentResponse(): Response
Expand Down
7 changes: 6 additions & 1 deletion app/Http/Controllers/RecipeController.php
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@ public function addClap(Request $request): JsonResponse
);

return ($recipe = $this->service->addClap($request->get('recipe_id'))) ?
/** @phpstan-ignore-next-line */
$this->successResponse(['updated' => true, 'claps' => $recipe->claps]) :
$this->errorResponse(['error' => 'There was an error processing this request. Please try again.']);
}
Expand Down Expand Up @@ -94,7 +95,11 @@ public function store(RecipeStoreRequest $request, JWT $jwtAuth)
{
try {
$jwtAuth->parseToken()->check();
return $this->service->store($request);

return $this->service->store($request) ?
$this->successResponse(['created' => true],ResponseAlias::HTTP_CREATED) :
$this->errorResponse(['created' => false]);

} catch (\Exception $exception) {
Log::debug('An error occurred while creating this recipe', [
'resource' => self::RECIPE_RESOURCE,
Expand Down
31 changes: 10 additions & 21 deletions app/Services/AuthService.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,36 +5,27 @@
namespace App\Services;

use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;

class AuthService
{
/**
* Authenticate the user
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\JsonResponse
*/
public function login(Request $request): \Illuminate\Http\JsonResponse
public function login(Request $request)
{
if (!$token = Auth::attempt($request->only('email', 'password'))) {
return response()->json(
[
'Not found or Invalid Credentials.',
], Response::HTTP_NOT_FOUND
);
return false;
}

return response()->json(['token' => $token], Response::HTTP_OK);
return $token;
}

public function logout(): \Illuminate\Http\JsonResponse|Response
/**
* @return bool
*/
public function logout()
{
try {
Auth::logout();
return response()->noContent();
} catch (\Exception $exception) {
Log::info(
'Not found or Invalid Credentials.',
Expand All @@ -43,11 +34,9 @@ public function logout(): \Illuminate\Http\JsonResponse|Response
]
);

return response()->json(
[
'Not found or Invalid Credentials.'
], Response::HTTP_BAD_REQUEST
);
return false;
}

return true;
}
}
20 changes: 7 additions & 13 deletions app/Services/RecipeService.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,6 @@
use App\Utils\DbHelper;
use App\Utils\IngredientMaker;
use Carbon\Carbon;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Contracts\Routing\ResponseFactory;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Arr;
Expand All @@ -36,7 +32,7 @@ public function __construct()
$this->serviceModel = new Recipe();
}

public function index($user_id = null): Collection
public function index($user_id = null)
{
$recipes = Recipe::paginate(100);

Expand All @@ -59,7 +55,7 @@ public function show($id)

/**
* @param $request
* @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\Routing\ResponseFactory|Response
* @return bool
* @throws ApiException
*/
public function store($request)
Expand Down Expand Up @@ -112,12 +108,10 @@ public function store($request)
'resource_type' => 'recipe'
]);

$draft->save();
return $draft->save();
}

return response([
'created' => $created,
], Response::HTTP_CREATED);
return $created;
} catch (\Exception $e) {
throw new ApiException($e->getMessage());
}
Expand Down Expand Up @@ -251,9 +245,9 @@ private function validatePayload(array $payload)
}
}

//descriptin length
//description length
If ($description = Arr::get($payload, 'description')) {
//todo: ai enabled giberrish detection
//todo: ai enabled gibberish detection
if (Str::wordCount($description) < 100) {
$sources[] = [
'description' =>'Description must not be less than 100 words.'
Expand All @@ -263,7 +257,7 @@ private function validatePayload(array $payload)

//summary length
If ($summary = Arr::get($payload, 'summary')) {
//todo: ai enabled giberrish detection
//todo: ai enabled gibberish detection
if (Str::wordCount($summary) < 50) {
$sources[] = [
'summary' => 'Summary must not be less than 50 words.'
Expand Down
30 changes: 15 additions & 15 deletions tests/Feature/AuthTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@

use App\Models\User;
use Carbon\Carbon;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Log;
use Symfony\Component\HttpFoundation\Response as ResponseAlias;

/**
* Class UserTest
Expand All @@ -24,7 +24,7 @@ public function it_responds_with_an_error_if_the_user_email_is_empty()
'email' => '',
'password' => 'mypassword',
]
)->assertStatus(Response::HTTP_UNPROCESSABLE_ENTITY);
)->assertStatus(ResponseAlias::HTTP_UNPROCESSABLE_ENTITY);

$decoded = json_decode($response->getContent(), true);

Expand All @@ -41,7 +41,7 @@ public function it_responds_with_an_error_if_the_user_email_is_null()
'POST', '/api/v1/auth/login', [
'password' => 'mypassword',
]
)->assertStatus(Response::HTTP_UNPROCESSABLE_ENTITY);
)->assertStatus(ResponseAlias::HTTP_UNPROCESSABLE_ENTITY);

$decoded = json_decode($response->getContent(), true);

Expand All @@ -59,7 +59,7 @@ public function it_responds_with_an_error_if_the_user_password_is_empty()
'email' => '[email protected]',
'password' => '',
]
)->assertStatus(Response::HTTP_UNPROCESSABLE_ENTITY);
)->assertStatus(ResponseAlias::HTTP_UNPROCESSABLE_ENTITY);

$decoded = json_decode($response->getContent(), true);

Expand All @@ -76,7 +76,7 @@ public function it_responds_with_an_error_if_the_user_password_is_null()
'POST', '/api/v1/auth/login', [
'email' => '[email protected]',
]
)->assertStatus(Response::HTTP_UNPROCESSABLE_ENTITY);
)->assertStatus(ResponseAlias::HTTP_UNPROCESSABLE_ENTITY);

$decoded = json_decode($response->getContent(), true);

Expand All @@ -91,7 +91,7 @@ public function it_responds_with_an_error_if_the_request_does_not_contain_email_
{
$response = $this->json(
'POST', '/api/v1/auth/login', []
)->assertStatus(Response::HTTP_UNPROCESSABLE_ENTITY);
)->assertStatus(ResponseAlias::HTTP_UNPROCESSABLE_ENTITY);

$decoded = json_decode($response->getContent(), true);

Expand Down Expand Up @@ -176,7 +176,7 @@ public function it_responds_with_a_404_when_attempting_to_signin_a_user_that_doe
'email' => '[email protected]',
'password' => 'invalidpassword',
]
)->assertStatus(Response::HTTP_NOT_FOUND);
)->assertStatus(ResponseAlias::HTTP_NOT_FOUND);
}

/**
Expand Down Expand Up @@ -220,14 +220,14 @@ public function it_can_logout_an_existing_user()
]
);

$respose = $this->json(
$response = $this->json(
'POST', '/api/v1/auth/login', [
'email' => $email,
'password' => $password,
]
);

$decoded = json_decode($respose->getContent(), true);
$decoded = json_decode($response->getContent(), true);

$this->json(
'GET', '/api/v1/auth/logout', [], [
Expand Down Expand Up @@ -260,7 +260,7 @@ public function logout_responds_with_an_error_if_token_is_invalid()
]
]
)
->assertStatus(Response::HTTP_BAD_REQUEST)
->assertStatus(ResponseAlias::HTTP_BAD_REQUEST)
->assertExactJson([
'Not found or Invalid Credentials.'
]);
Expand All @@ -282,22 +282,22 @@ public function it_can_validate_access_token_success()
]
);

$respose = $this->json(
$response = $this->json(
'POST', '/api/v1/auth/login', [
'email' => $email,
'password' => $password,
]
);

$decoded = json_decode($respose->getContent(), true);
$decoded = json_decode($response->getContent(), true);

$this
->json(
'POST', '/api/v1/auth/validate', [], [
'Authorization' => 'Bearer ' . $decoded['token']
]
)
->assertStatus(Response::HTTP_OK)
->assertStatus(ResponseAlias::HTTP_OK)
->assertExactJson([
'validated' => true
]);
Expand All @@ -314,9 +314,9 @@ public function it_can_validate_access_token_fails()
'Authorization' => 'Bearer invalid-token'
]
)
->assertStatus(Response::HTTP_UNAUTHORIZED)
->assertStatus(ResponseAlias::HTTP_UNAUTHORIZED)
->assertExactJson([
'error' => 'Expired or Tnvalid token.'
'error' => 'Expired or Invalid token.'
]);
}
}
Loading

0 comments on commit 5fca8c2

Please sign in to comment.