Skip to content

Commit

Permalink
Merge pull request #273 from mycookbook/develop
Browse files Browse the repository at this point in the history
Develop
  • Loading branch information
fokosun authored Aug 21, 2023
2 parents c34d6c2 + 6297a70 commit faf3376
Show file tree
Hide file tree
Showing 19 changed files with 1,718 additions and 736 deletions.
5 changes: 4 additions & 1 deletion .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -48,4 +48,7 @@ PINTEREST_REDIRECT_URI=

INSTAGRAM_CLIENT_ID=
INSTAGRAM_CLIENT_SECRET=
INSTAGRAM_REDIRECT_URI=
INSTAGRAM_REDIRECT_URI=

MAILGUN_DOMAIN=
MAILGUN_SECRET=
4 changes: 4 additions & 0 deletions app/Exceptions/Handler.php
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,10 @@ public function render($request, Throwable $throwable)
], $throwable->getContext()), $throwable->getCode());
}

if ($throwable instanceof TikTokException) {
return response()->json( ['error' => $throwable->getMessage()]);
}

return parent::render($request, $throwable);
}
}
14 changes: 14 additions & 0 deletions app/Exceptions/TikTokException.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<?php

namespace App\Exceptions;

use Exception;

class TikTokException extends Exception
{
public function __construct(string $message = "", array $context = [])
{
$message = $message . json_encode($context);
parent::__construct($message, 400);
}
}
4 changes: 2 additions & 2 deletions app/Http/Controllers/AuthController.php
Original file line number Diff line number Diff line change
Expand Up @@ -220,7 +220,7 @@ public function tikTokHandleCallback(Request $request, Client $client, UserServi
TikTokUserIsAuthenticated::dispatch(new TikTokUserDto(
$user->getKey(),
$userInfo['data']['user']['open_id'],
$code,
$decoded['data']['access_token'],
$userInfo['data']['user']['is_verified'],
$userInfo['data']['user']['profile_deep_link'],
$userInfo['data']['user']['bio_description'],
Expand All @@ -246,7 +246,7 @@ public function tikTokHandleCallback(Request $request, Client $client, UserServi
'error' => $e->getMessage(),
]);

return redirect('https://web.cookbookshq.com/#/errors/?m=Tiktok is having a hard time processing this request, please try again.');
return redirect("https://web.cookbookshq.com/#/errors/?m=We are experiencing some technical difficulty logging you in with TikTok, please try again.");
}
}

Expand Down
8 changes: 4 additions & 4 deletions app/Http/Controllers/Controller.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,19 +16,19 @@ class Controller extends BaseController

use AuthorizesRequests, DispatchesJobs, ValidatesRequests;

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

public function noContentResponse(): Response
{
return response()->noContent();
}

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

public function unauthorizedResponse(): \Illuminate\Http\JsonResponse
Expand Down
28 changes: 28 additions & 0 deletions app/Http/Controllers/UserController.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,12 @@
use App\Services\TikTok\Videos;
use App\Services\UserService;
use Carbon\Carbon;
use Ichtrojan\Otp\Otp;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;
use Tymon\JWTAuth\Facades\JWTAuth;

/**
Expand Down Expand Up @@ -276,4 +278,30 @@ public function listVideos(HttpRequestRunner $requestRunner)

return $this->unauthorizedResponse();
}

public function generateOtp(Request $request, Otp $otp)
{
$identifier = (string) $request->get('identifier');

$token = $otp->generate(
$identifier,
config('services.otp.digits'),
config('services.otp.validity')
);

try {
Mail::to($identifier)->send(new \App\Mail\OtpWasGenerated($token->token));
} catch (\Exception $exception) {
Log::debug('Error sending email', ['e' => $exception]);
return $this->errorResponse(['message' => 'There was an error processing this request. Please try again.']);
}
}

public function validateOtp(Request $request, Otp $otp): object
{
$identifier = (string) $request->get('identifier');
$token = (string) $request->get('token');

return $otp->validate($identifier, $token);
}
}
88 changes: 53 additions & 35 deletions app/Listeners/GetTikTokUserVideos.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@

namespace App\Listeners;

//use GuzzleHttp\Client;
use App\Exceptions\TikTokException;
use GuzzleHttp\Client;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;

class GetTikTokUserVideos
Expand All @@ -12,39 +14,55 @@ class GetTikTokUserVideos
*/
public function handle(object $event): void
{
// $client = new Client();
$code = DB::table('tiktok_users')->where(['user_id' => $event->getUser()->getkey()])->first();

dd([
'form_params' => [
'client_key' => config('services.tiktok.client_id'),
'client_secret' => config('services.tiktok.client_secret'),
'code' => $code,
'grant_type' => 'authorization_code',
'redirect_uri' => 'https://web.cookbookshq.com/callback/tiktok'
],
]);

// try {
// $response = $client->request('POST',
// 'https://open.tiktokapis.com/v2/oauth/token/',
// [
// 'form_params' => [
// 'client_key' => config('services.tiktok.client_id'),
// 'client_secret' => config('services.tiktok.client_secret'),
// 'code' => $code,
// 'grant_type' => 'authorization_code',
// 'redirect_uri' => 'https://web.cookbookshq.com/callback/tiktok'
// ],
// ]
// );
//
// dd(json_decode($response->getBody()->getContents(), true));
// } catch (\Exception $exception) {
// dd([
// 'e' => $exception,
// 'code' => $code
// ]);
// }
$client = new Client();
$tikTokUser = $event->tikTokUserDto;
$context = [];
$claims = [
'cover_image_url',
'id',
'title',
'video_description',
'duration',
'height',
'width',
'title',
'embed_html',
'embed_link'
];
$endpoint = 'https://open.tiktokapis.com/v2/video/list/?fields=';

try {
$response = $client->request('POST',
$endpoint . implode( ',', $claims),
[
'headers' => [
'Authorization' => 'Bearer ' . $tikTokUser->getCode(),
'Content-Type' => 'application/json'
]
]
);

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

$db = DB::table('tiktok_users');

$tiktok_user = $db->where(['user_id' => $event->tikTokUserDto->getUserId()])->first();
$data = [
'videos' => json_encode($decoded['data']['videos']),
'created_at' => Carbon::now(),
'updated_at' => Carbon::now()
];

if ($tiktok_user === null) {
$data['user_id'] = $event->tikTokUserDto->getUserId();
$db->insert($data);
} else {
$db->update($data);
}

} catch(\Exception $exception) {
dd($exception->getMessage());
// throw new TikTokException($exception->getMessage(), $context);
}
}
}
2 changes: 2 additions & 0 deletions app/Listeners/UpdateOrCreateTikTokUser.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ public function handle(TikTokUserIsAuthenticated $event): void
"updated_at" => Carbon::now()
];

unset($attributes['code']);

$data = array_merge($attributes, $timestamps);

$tiktok_user = DB::table('tiktok_users')->where(["user_id" => $user_id])->first();
Expand Down
48 changes: 48 additions & 0 deletions app/Mail/OtpWasGenerated.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
<?php

declare(strict_types=1);

namespace App\Mail;

use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Mail\Mailables\Address;
use Illuminate\Mail\Mailables\Content;
use Illuminate\Mail\Mailables\Envelope;
use Illuminate\Queue\SerializesModels;

class OtpWasGenerated extends Mailable
{
use Queueable, SerializesModels;

protected string $token;

/**
* Create a new message instance.
*/
public function __construct(string $token)
{
$this->token = $token;
}

public function envelope(): Envelope
{
return new Envelope(
from: new Address('[email protected]', 'CookbooksHQ'),
subject: 'Your OTP',
);
}

/**
* Get the message content definition.
*/
public function content(): Content
{
return new Content(
view: 'emails.send-otp',
with: [
'token' => $this->token
]
);
}
}
11 changes: 11 additions & 0 deletions app/Models/User.php
Original file line number Diff line number Diff line change
Expand Up @@ -297,4 +297,15 @@ public function getTikTokUser()
{
return DB::table('tiktok_users')->where(['user_id' => $this->getKey()])->first();
}

public function getTiktokVideosAttribute(): Collection
{
$tikTokUser = DB::table('tiktok_users')->where(['user_id' => $this->getKey()])->first();

if ($tikTokUser === null) {
return collect();
}

return collect(json_decode($tikTokUser->videos, true));
}
}
2 changes: 1 addition & 1 deletion app/Services/UserService.php
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ public function show($q)
return response(
[
'data' => [
'user' => $this->findWhere($q)->get(),
'user' => $this->findWhere($q)->get()->append(['tiktok_videos']),
],
], Response::HTTP_OK
);
Expand Down
33 changes: 19 additions & 14 deletions bootstrap/cache/services.php
Original file line number Diff line number Diff line change
Expand Up @@ -37,14 +37,15 @@
33 => 'SocialiteProviders\\Manager\\ServiceProvider',
34 => 'Spatie\\LaravelIgnition\\IgnitionServiceProvider',
35 => 'Tymon\\JWTAuth\\Providers\\LaravelServiceProvider',
36 => 'App\\Providers\\AppServiceProvider',
37 => 'App\\Providers\\AuthServiceProvider',
38 => 'App\\Providers\\EventServiceProvider',
39 => 'App\\Providers\\RouteServiceProvider',
40 => 'Laravel\\Socialite\\SocialiteServiceProvider',
41 => 'SocialiteProviders\\Manager\\ServiceProvider',
42 => 'Thedevsaddam\\LaravelSchema\\LaravelSchemaServiceProvider',
43 => 'Sentry\\Laravel\\ServiceProvider',
36 => 'Ichtrojan\\Otp\\OtpServiceProvider',
37 => 'App\\Providers\\AppServiceProvider',
38 => 'App\\Providers\\AuthServiceProvider',
39 => 'App\\Providers\\EventServiceProvider',
40 => 'App\\Providers\\RouteServiceProvider',
41 => 'Laravel\\Socialite\\SocialiteServiceProvider',
42 => 'SocialiteProviders\\Manager\\ServiceProvider',
43 => 'Thedevsaddam\\LaravelSchema\\LaravelSchemaServiceProvider',
44 => 'Sentry\\Laravel\\ServiceProvider',
),
'eager' =>
array (
Expand All @@ -68,12 +69,13 @@
17 => 'Sentry\\Laravel\\Tracing\\ServiceProvider',
18 => 'Spatie\\LaravelIgnition\\IgnitionServiceProvider',
19 => 'Tymon\\JWTAuth\\Providers\\LaravelServiceProvider',
20 => 'App\\Providers\\AppServiceProvider',
21 => 'App\\Providers\\AuthServiceProvider',
22 => 'App\\Providers\\EventServiceProvider',
23 => 'App\\Providers\\RouteServiceProvider',
24 => 'Thedevsaddam\\LaravelSchema\\LaravelSchemaServiceProvider',
25 => 'Sentry\\Laravel\\ServiceProvider',
20 => 'Ichtrojan\\Otp\\OtpServiceProvider',
21 => 'App\\Providers\\AppServiceProvider',
22 => 'App\\Providers\\AuthServiceProvider',
23 => 'App\\Providers\\EventServiceProvider',
24 => 'App\\Providers\\RouteServiceProvider',
25 => 'Thedevsaddam\\LaravelSchema\\LaravelSchemaServiceProvider',
26 => 'Sentry\\Laravel\\ServiceProvider',
),
'deferred' =>
array (
Expand All @@ -97,6 +99,7 @@
'Illuminate\\Auth\\Console\\ClearResetsCommand' => 'Illuminate\\Foundation\\Providers\\ConsoleSupportServiceProvider',
'Illuminate\\Foundation\\Console\\ConfigCacheCommand' => 'Illuminate\\Foundation\\Providers\\ConsoleSupportServiceProvider',
'Illuminate\\Foundation\\Console\\ConfigClearCommand' => 'Illuminate\\Foundation\\Providers\\ConsoleSupportServiceProvider',
'Illuminate\\Foundation\\Console\\ConfigShowCommand' => 'Illuminate\\Foundation\\Providers\\ConsoleSupportServiceProvider',
'Illuminate\\Database\\Console\\DbCommand' => 'Illuminate\\Foundation\\Providers\\ConsoleSupportServiceProvider',
'Illuminate\\Database\\Console\\MonitorCommand' => 'Illuminate\\Foundation\\Providers\\ConsoleSupportServiceProvider',
'Illuminate\\Database\\Console\\PruneCommand' => 'Illuminate\\Foundation\\Providers\\ConsoleSupportServiceProvider',
Expand Down Expand Up @@ -138,6 +141,7 @@
'Illuminate\\Console\\Scheduling\\ScheduleClearCacheCommand' => 'Illuminate\\Foundation\\Providers\\ConsoleSupportServiceProvider',
'Illuminate\\Console\\Scheduling\\ScheduleTestCommand' => 'Illuminate\\Foundation\\Providers\\ConsoleSupportServiceProvider',
'Illuminate\\Console\\Scheduling\\ScheduleWorkCommand' => 'Illuminate\\Foundation\\Providers\\ConsoleSupportServiceProvider',
'Illuminate\\Console\\Scheduling\\ScheduleInterruptCommand' => 'Illuminate\\Foundation\\Providers\\ConsoleSupportServiceProvider',
'Illuminate\\Database\\Console\\ShowModelCommand' => 'Illuminate\\Foundation\\Providers\\ConsoleSupportServiceProvider',
'Illuminate\\Foundation\\Console\\StorageLinkCommand' => 'Illuminate\\Foundation\\Providers\\ConsoleSupportServiceProvider',
'Illuminate\\Foundation\\Console\\UpCommand' => 'Illuminate\\Foundation\\Providers\\ConsoleSupportServiceProvider',
Expand Down Expand Up @@ -211,6 +215,7 @@
'translation.loader' => 'Illuminate\\Translation\\TranslationServiceProvider',
'validator' => 'Illuminate\\Validation\\ValidationServiceProvider',
'validation.presence' => 'Illuminate\\Validation\\ValidationServiceProvider',
'Illuminate\\Contracts\\Validation\\UncompromisedVerifier' => 'Illuminate\\Validation\\ValidationServiceProvider',
'Laravel\\Sail\\Console\\InstallCommand' => 'Laravel\\Sail\\SailServiceProvider',
'Laravel\\Sail\\Console\\PublishCommand' => 'Laravel\\Sail\\SailServiceProvider',
'Laravel\\Socialite\\Contracts\\Factory' => 'SocialiteProviders\\Manager\\ServiceProvider',
Expand Down
7 changes: 5 additions & 2 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
"guzzlehttp/guzzle": "7.4.5",
"symfony/console": "^6.0.3",
"doctrine/dbal": "^3.0",
"symfony/http-kernel": "^6.0",
"symfony/http-kernel": "^6.3",
"ext-exif": "*",
"laravel/tinker": "^2.5",
"ext-json": "*",
Expand All @@ -31,7 +31,10 @@
"thedevsaddam/laravel-schema": "^2.0",
"sentry/sentry-laravel": "^3.1",
"ipinfo/ipinfolaravel": "^2.4",
"spatie/laravel-ignition": "^2.1"
"spatie/laravel-ignition": "^2.1",
"ichtrojan/laravel-otp": "^1.4",
"symfony/mailgun-mailer": "^6.3",
"symfony/http-client": "^6.3"
},
"require-dev": {
"mockery/mockery": "^1.4.2",
Expand Down
Loading

0 comments on commit faf3376

Please sign in to comment.