Skip to content

Commit

Permalink
Merge pull request #284 from mycookbook/develop
Browse files Browse the repository at this point in the history
Develop
  • Loading branch information
fokosun authored Sep 10, 2023
2 parents 2983824 + d6e0d37 commit 27cdb6b
Show file tree
Hide file tree
Showing 34 changed files with 544 additions and 390 deletions.
2 changes: 2 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -52,3 +52,5 @@ INSTAGRAM_REDIRECT_URI=

MAILGUN_DOMAIN=
MAILGUN_SECRET=

GH_PAT=
2 changes: 1 addition & 1 deletion .github/workflows/feature-test.yml
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
name: Feature test
name: Run Feature tests

on:
push:
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/static-analysis.yml
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
name: Static analysis
name: Run Static analysis

on:
push:
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/unit-test.yml
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
name: Unit test
name: Run Unit tests

on:
push:
Expand Down
3 changes: 3 additions & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -42,5 +42,8 @@ WORKDIR /var/www

USER $user

RUN echo "xdebug.mode=debug" >> /usr/local/etc/php/conf.d/php.ini
RUN echo "xdebug.client_host=host.docker.internal" >> /usr/local/etc/php/conf.d/php.ini
RUN echo "xdebug.idekey=PHPSTORM" >> /usr/local/etc/php/conf.d/php.ini
RUN echo "memory_limit=1024M" >> /usr/local/etc/php/conf.d/php.ini
RUN echo "allow_url_fopen=on" >> /usr/local/etc/php/conf.d/php.ini
8 changes: 7 additions & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ db_migrate: ## run db migrations
db_schemefy: ## Display the db schema in table format
@php artisan schema:show

setup: composer generate_key
setup: composer generate_key jwt_key db_connection

copy_env: #todo: figure out a way to not override env vars if file_exists already
@cp .env.example .env
Expand All @@ -38,6 +38,12 @@ composer: ## Install project dependencies
generate_key: ## Generate APP_KEY and set in .env
@docker-compose exec app php artisan key:generate

jwt_key: ## Generate JWT_SECRET and set in .env
@docker-compose exec app php artisan jwt:secret

db_connection: ## Generate DB Connection details and set in .env
@docker-compose exec app php artisan db:connection

login: ## Creates a new user/token or generate new token for given user
@php artisan auth:token

Expand Down
33 changes: 33 additions & 0 deletions readme.md → README.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,3 +61,36 @@ Examples:

![Alt text](docs/images/help.png?raw=true "help")

## Setup PHPStorm + + Docker + Xdebug + postman
- Open settings by pressing `(cmd + ,)` button
- Under PHP, add a new CLI interpreter

![add-new-cli-interpreter1.png](docs%2Fimages%2Fadd-new-cli-interpreter1.png)

- Select From Docker, Vagrant ... option
- Select Docker Compose, set the configuration file to ./docker-compose.yml and the service select app
![add-new-cli-interpreter2.png](docs%2Fimages%2Fadd-new-cli-interpreter2.png)

- Now your PHP interpreter settings hosuld look like this
![xdebug-php.png](docs%2Fimages%2Fxdebug-php.png)

- Next, you want to set up the test framework, click the plus sign and select PHPUnit by remote interpreter
![test-framework1.png](docs%2Fimages%2Ftest-framework1.png)

- Select the interpreter you just created from the dropdown list
![test-framework2.png](docs%2Fimages%2Ftest-framework2.png)

- Now you can start debugging, set a break point in any controller class and run the test associated with it in debug mode

### Listening for requests from postman
- First step is to set up a server
![server.png](docs%2Fimages%2Fserver.png)
- On postman add this parameter. When postman detects this in a request, it creates a cookie with the value of XDEBUG_SESSION_START. This has an expiry time of 30 minutes so you dont have to include it in your requests all the time.

```angular2html
XDEBUG_SESSION_START=PHPSTORM
```
- Finally, tell postman to listen for PHP Debug Connections
![php-debug-connections.png](docs%2Fimages%2Fphp-debug-connections.png)

- Set a break point in the code called by the endpoint you are consuming on postman, hit send to start debugging
75 changes: 75 additions & 0 deletions app/Console/Commands/DatabaseConnectionDetails.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Str;

class DatabaseConnectionDetails extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'db:connection';

/**
* The console command description.
*
* @var string
*/
protected $description = 'Reads the db connection envs from secrets';

/**
* Execute the console command.
*/
public function handle(): void
{
$connection = [
"DB_HOST" => "ao9moanwus0rjiex.cbetxkdyhwsb.us-east-1.rds.amazonaws.com",
"DB_PORT" => "3306",
"DB_DATABASE" => "athiftsxpmxaj82c",
"DB_USERNAME" => "w7dydvcjsog985xj",
"DB_PASSWORD" => "iliqkyv8vbbtw603"
];

$filepath = $this->envPath();

foreach($connection as $key => $value) {
$fileContents = $this->getFileContents($filepath);

if (Str::contains($fileContents, $key)) {
$this->putFileContents(
$filepath,
preg_replace(
"/{$key}=.*/",
"{$key}={$value}",
$fileContents
)
);
}
}

$this->info("db connection details set successfully.");
}

protected function envPath(): string
{
if (method_exists($this->laravel, 'environmentFilePath')) {
return $this->laravel->environmentFilePath();
}

return $this->laravel->basePath('.env');
}

protected function getFileContents(string $filepath): string
{
return file_get_contents($filepath);
}

protected function putFileContents(string $filepath, string $data): void
{
file_put_contents($filepath, $data);
}
}
9 changes: 6 additions & 3 deletions app/Console/Commands/LoginCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

namespace App\Console\Commands;

use App\Models\User;
use App\Services\AuthService;
use App\Services\UserService;
use Illuminate\Console\Command;
Expand Down Expand Up @@ -39,17 +40,19 @@ public function handle(UserService $userService, AuthService $authService)

$fromCache = Cache::get('testUser');

$email = Str::random(5) . '@console.com';

if (!$fromCache) {
$this->line('User not found in Cache, creating new User ...');
$this->line('==============================================');

$response = $userService->store(new Request([
'name' => 'test user',
'email' => Str::random(5) . '@console.com',
'email' => $email,
'password' => 'testing123'
]));

$user = json_decode($response->getContent(), true)["response"]["data"];
$user = User::where('email', '=', $email)->first();

Cache::put('testUser', $user);
}
Expand All @@ -61,7 +64,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
11 changes: 7 additions & 4 deletions app/Http/Controllers/CommentController.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,8 @@ class CommentController extends Controller
{
public function addComment(Request $request)
{
/** @phpstan-ignore-next-line */
/** @phpstan-ignore-next-line */
if ($user = JWTAuth::parseToken()->user()) {

$payload = $request->only([
'resource-type', 'resource-id', 'comment'
]);
Expand All @@ -44,20 +43,24 @@ public function addComment(Request $request)
}
}
}

return $this->unauthorizedResponse();
}

public function destroyComment(Request $request)
{
/** @phpstan-ignore-next-line */
/** @phpstan-ignore-next-line */
if ($user = JWTAuth::parseToken()->user()) {
$payload = $request->only(['comment-id']);
$comment = Comment::findOrFail($request->only(['comment-id']))->first();

if ($user->isSuper() || $user->ownsComment($payload['comment-id'])) {
return response()->json(['deleted' => $comment->delete()]);
} else {
throw new ApiException('You are not suthorized to perfrom this action.');
throw new ApiException('You are not authorized to perform this action.');
}
}

return $this->unauthorizedResponse();
}
}
9 changes: 5 additions & 4 deletions app/Http/Controllers/Controller.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,16 +9,17 @@
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Http\Response;
use Illuminate\Routing\Controller as BaseController;
use Symfony\Component\HttpFoundation\Response as ResponseAlias;

class Controller extends BaseController
{
const RECIPE_RESOURCE = 'recipe';

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 All @@ -28,13 +29,13 @@ public function noContentResponse(): Response

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

public function unauthorizedResponse(): \Illuminate\Http\JsonResponse
{
return response()->json([
'error' => 'Your login session has expired. Please login.'
], Response::HTTP_UNAUTHORIZED);
], ResponseAlias::HTTP_UNAUTHORIZED);
}
}
Loading

0 comments on commit 27cdb6b

Please sign in to comment.