Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refatoracao e etc mt cansado pra uma mensagemzinha completa #2

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ TWITCH_OAUTH_SCOPES="user:read:email"


GITHUB_OAUTH_BASE_URI="https://id.twitch.tv/oauth2"
GITHUB_OAUTH_ID=""
GITHUB_OAUTH_ID="6b82a4205e7ce901190b"
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ai namoral qq eu vo fazer com a sua chave? ce alterou o .env.example e nem viu menó toma cuidado com isso pq se vc tiver fazendo oss e uma key dessa passar ce vai tomar mt tapa na cara

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

realmente nem fazia ideia q eu tinha mexido no .example kkkkkkkkkkkkkkk vacilo meu

GITHUB_REDIRECT_URI="http://localhost:8000/auth/oauth/github"
GITHUB_OAUTH_SECRET=""
GITHUB_OAUTH_SCOPES="user:email"
8 changes: 8 additions & 0 deletions app/Contracts/OAuthContract.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<?php

namespace App\Contracts;

interface OAuthContract {
public function auth(string $code): array;
public function getAuthenticatedUser(string $token): array;
}
7 changes: 7 additions & 0 deletions app/Contracts/SocialContract.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
<?php

namespace App\Contracts;

interface SocialContract {
public function findUser(string $username): array;
}
64 changes: 6 additions & 58 deletions app/Http/Controllers/AuthController.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,80 +2,28 @@

namespace App\Http\Controllers;

use App\Models\User;
use App\Services\OAuth\GithubService;
use App\Services\OAuth\TwitchService;
use App\Repositories\AuthRepository;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;
use Ramsey\Uuid\Uuid;

class AuthController extends Controller
{
public function getTwitchProvider(Request $request)
function __construct(AuthRepository $repository)
{
if (!$code = $request->query('code')) {
return redirect('/');
}

$service = new TwitchService();
$response = $service->twitchAuth($code);
$providerUser = $service->getTwitchUser($response['access_token']);

$user = $this->findOrCreate('twitch', $providerUser);
Auth::login($user);

return redirect('/dashboard');
$this->_repository = $repository;
}

public function getGithubProvider(Request $request)
{
public function auth(Request $request, string $provider) {
if (!$code = $request->query('code')) {
return redirect('/');
}

$service = new GithubService();
$response = $service->githubAuth($code);
$providerUser = $service->getGithubUser($response['access_token']);

$user = $this->findOrCreate('github', $providerUser);
Auth::login($user);
$this->_repository->authenticate($provider, $code);
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Me explica exatamente pra quê você meteu um _ ali. Fiquei curioso pra justificativa... Não sei se é só estética ou tem alguma coisa por trás.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

em outras linguagens onde nao da pra usar algumas keywords como public ou private (aka javascript), é normal colocar esse _ pra informar q o atributo em questao é privado ou q nao deve ser acessado por fora, isso aq é mais algo estético e de costume meu msm


return redirect('/dashboard');
}

private function findOrCreate(string $provider, array $providerUser)
{
$payload = [
$provider . '_username' => $providerUser['login'] ?? $providerUser['data'][0]['login'],
"name" => $providerUser['name'] ?? $providerUser['data'][0]['display_name'],
$provider . "_id" => $providerUser['id'] ?? $providerUser['data'][0]['id'],
"email" => $providerUser['email'] ?? $providerUser['data'][0]['email'],
'image' => $providerUser['avatar_url'] ?? $providerUser['data'][0]['profile_image_url']
];


if ($user = User::where($provider . "_id", $payload[$provider . '_id'])->first()) {
return $user;
}

if ($user = User::where('email', $payload['email'])->first()) {
$user->update([
$provider . "_id" => $payload[$provider . '_id'],
$provider . "_username" => $payload[$provider . '_username']
]);

return $user;
}
$imagePath = 'avatars/' . Uuid::uuid4()->toString() . '.png';
Storage::put('public/' . $imagePath, file_get_contents($payload['image']));
$payload['image_path'] = $imagePath;

return User::create($payload);
}

public function getLogout() {
Auth::logout();
$this->_repository->logout();

return redirect('/');
}
Expand Down
31 changes: 7 additions & 24 deletions app/Http/Controllers/MeController.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,44 +2,27 @@

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;
use Ramsey\Uuid\Uuid;
use App\Http\Requests\PostAvatarRequest;
use App\Repositories\MeRepository;

class MeController extends Controller
{
public function __construct()
public function __construct(MeRepository $repository)
{
$this->middleware('auth');
$this->_repository = $repository;
}

public function postProfileAvatar(Request $request)
public function postProfileAvatar(PostAvatarRequest $request)
{
$this->validate($request, [
'image' => 'required|image'
]);

$file = $request->file('image');

$imageName = Uuid::uuid4()->toString() . '.' . $file->getClientOriginalExtension();
$file->storePubliclyAs('public/avatars', $imageName);

Storage::delete('public/' . Auth::user()->image_path);

$imagePath = 'avatars/' . $imageName;

Auth::user()->update([
'image_path' => $imagePath
]);
$this->_repository->postAvatar($request->file('image'));

return response()->json([], 200);
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

O que exatamente é 200? Pra nós, desenvolvedores um pouco mais experientes, sabemos que isso é um HTTP Code etc mas seria legal você usar os Enums ou classes estáticas como a Request pra colocar os HTTP Code como constante e ser mais legível.

}

public function deleteMe()
{
Auth::user()->delete();
Auth::logout();
$this->_repository->delete();

return redirect('/');
}
Expand Down
24 changes: 11 additions & 13 deletions app/Http/Controllers/MessagesController.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,27 +2,25 @@

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Http\Requests\CreateMessageRequest;
use App\Repositories\MessageRepository;
use Exception;

class MessagesController extends Controller
{
public function __construct()
public function __construct(MessageRepository $repository)
{
$this->middleware('auth');
$this->_repository = $repository;
}

public function postMessage(Request $request)
public function postMessage(CreateMessageRequest $request)
{
$fields = $this->validate($request, [
'content' => 'required',
'receiver_username' => 'string|nullable'
]);

$fields['is_private'] = (bool) $request->input('is_private');
$fields['receiver_username'] = strtolower($fields['receiver_username']);

Auth::user()->messages()->create($fields);
try {
$this->_repository->createMessage($request->validated());
} catch (Exception $e) {
return back()->withErrors($e->getMessage());
}

return back();
}
Expand Down
17 changes: 6 additions & 11 deletions app/Http/Controllers/ViewController.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,32 +2,27 @@

namespace App\Http\Controllers;

use App\Models\Message;
use App\Models\User;
use App\Repositories\ViewRepository;

class ViewController extends Controller
{
public function __construct()
public function __construct(ViewRepository $repository)
{
$this->middleware('auth:web', ['except' => 'viewLanding']);
$this->_repository = $repository;
}

public function viewLanding()
{
$users = User::orderByDesc('created_at')->paginate(4);
$registeredUsers = User::count();
$messagesSent = Message::count();
[ $users, $registeredUsers, $messagesSent ] = $this->_repository->getLandingContent();
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Eu achei meio estranho como isso aqui foi implementado, mas no final eu entendi o contexto.

Acho que pra um programador mais leigo seria um pouco difícil de entender, mas foi um bom pensamento.


return view('welcome', compact(['users', 'registeredUsers', 'messagesSent']));
}

public function viewDashboard()
{
$messages = Message::orderByDesc('created_at')
->where('is_private', false)
->orWhere('receiver_username', '=', auth()->user()->github_username)
->orWhere('user_id', auth()->user()->id)
->paginate(15);
[ $messages ] = $this->_repository->getDashboardContent();

return view('dashboard', compact('messages'));
}

Expand Down
31 changes: 31 additions & 0 deletions app/Http/Requests/CreateMessageRequest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class CreateMessageRequest extends FormRequest
{
/**
* 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 [
'content' => 'required',
'receiver_username' => 'string|nullable'
];
}
}
30 changes: 30 additions & 0 deletions app/Http/Requests/PostAvatarRequest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class PostAvatarRequest extends FormRequest
{
/**
* 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 [
'image' => 'required|image'
];
}
}
2 changes: 2 additions & 0 deletions app/Models/User.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,10 @@ class User extends Authenticatable
'password',
'github_id',
'twitch_id',
'discord_id',
'github_username',
'twitch_username',
'discord_username',
'image_path'
];

Expand Down
66 changes: 66 additions & 0 deletions app/Repositories/AuthRepository.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
<?php

namespace App\Repositories;

use App\Models\User;
use App\Services\OAuth\DiscordService;
use Ramsey\Uuid\Uuid;
use Illuminate\Support\Facades\Auth;
use App\Services\OAuth\GithubService;
use App\Services\OAuth\TwitchService;
use Illuminate\Support\Facades\Storage;


class AuthRepository {

public function authenticate($provider, $code) {
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Você não acha interessante TIPAR as funções? Os argumentos e funções já são tipáveis tem uns belos anos dentro do PHP.

Fazendo isso, seu software vai ter mais garantia de que vai funcionar do jeito esperado.

Suggested change
public function authenticate($provider, $code) {
public function authenticate(string $provider, string $code): void
{

$service = $this->getProvider($provider);

$response = $service->auth($code);
$providerUser = $service->getAuthenticatedUser($response['access_token']);

$user = $this->findOrCreate($provider, $providerUser);
Auth::login($user);
}

public function logout() {
Auth::logout();
}

private function getProvider($provider) {
return match ($provider) {
'twitch' => new TwitchService,
'github' => new GithubService,
'discord' => new DiscordService
};
}

private function findOrCreate(string $provider, array $providerUser)
{
$payload = [
$provider . '_username' => $providerUser['login'],
"name" => $providerUser['name'],
$provider . "_id" => $providerUser['id'],
"email" => $providerUser['email'],
'image' => $providerUser['avatar_url']
];

if ($user = User::where($provider . "_id", $payload[$provider . '_id'])->first()) {
return $user;
}

if ($user = User::where('email', $payload['email'])->first()) {
$user->update([
$provider . "_id" => $payload[$provider . '_id'],
$provider . "_username" => $payload[$provider . '_username']
]);

return $user;
}
$imagePath = 'avatars/' . Uuid::uuid4()->toString() . '.png';
Storage::put('public/' . $imagePath, file_get_contents($payload['image']));
$payload['image_path'] = $imagePath;

return User::create($payload);
}
}
Loading