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

Added: API de autenticacao e cadastro usuário #8

Open
wants to merge 9 commits 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
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,10 @@ composer install
```
php artisan migrate:install
```
### Swagger
```
http://localhost:8002/
```
## Para contribuir
Ao concluir o seu desenvolvimento suba sua branch para o repositório
e abra uma PR para develop, assim que sua PR for aprovada estará liberado para merge,
Expand Down
3 changes: 2 additions & 1 deletion backend/.gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
/public/hot
/public/storage
/storage/*.key
/vendor
vendor
.env
.env.backup
.phpunit.result.cache
Expand All @@ -13,3 +13,4 @@ npm-debug.log
yarn-error.log
/.idea
/.vscode
../.idea/*.*
2 changes: 1 addition & 1 deletion backend/app/Console/Kernel.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ protected function schedule(Schedule $schedule)
*/
protected function commands()
{
$this->load(__DIR__.'/Commands');
$this->load(__DIR__ . '/Commands');

require base_path('routes/console.php');
}
Expand Down
50 changes: 50 additions & 0 deletions backend/app/DTO/UserDTO.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
<?php

namespace App\DTO;

use Illuminate\Support\Facades\Hash;
use App\Models\User;
use DateTime;

class UserDTO
{
public string $name = '';
public string $email = '';
public string $password = '';
public int $userId = 0;
public string $token = '';
private string $unHashedPass = '';
private Hash $hash;
public function __construct(
string $name,
string $email,
string $password
) {
$this->hash = new Hash();
$this->name = $name;
$this->email = $email;
$this->password = $this->hash->make($password);
$this->unHashedPass = $password;
}

public function checkPass(string $pass): bool
{
return $this->hash->check($this->unHashedPass, $pass);
}

public function userAuthenticated(User $userData): array
{
$dateTime = new DateTime("now");
$this->name = data_get($userData, "name", "");
$this->userId = data_get($userData, "id", "");
$hashedCode = $this->hash->make($dateTime->getTimestamp() + $this->userId);
$personalToken = $userData->createToken($hashedCode)->accessToken;
$this->token = $personalToken->token;

return [
"name" => $this->name,
"email" => $this->email,
"token" => $this->token
];
}
}
10 changes: 9 additions & 1 deletion backend/app/Http/Controllers/Controller.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,15 @@
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Routing\Controller as BaseController;

/**
* @OA\Info(
* version="1.0",
* title="Open Ticket"
* )
*/
class Controller extends BaseController
{
use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
use AuthorizesRequests;
use DispatchesJobs;
use ValidatesRequests;
}
1 change: 1 addition & 0 deletions backend/app/Http/Controllers/Events/EventsController.php
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
<?php

namespace App\Http\Controllers\Events;

use App\Http\Controllers\Controller;
Expand Down
117 changes: 117 additions & 0 deletions backend/app/Http/Controllers/Users/UserController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
<?php

namespace App\Http\Controllers\Users;

use _HumbugBox1bcd60ea4a04\Symfony\Component\Config\Definition\Exception\Exception;
use App\Trait\ValidatorUserFormTrait;
use Symfony\Component\HttpFoundation\Request;
use App\Services\UserService;

class UserController
{
use ValidatorUserFormTrait;

/**
* @OA\Get(
* path="/api/users/auth",
* summary="Autentica o usuário",
* @OA\Parameter(
* description="Seu Email",
* in="query",
* name="email",
* required=true,
* example="[email protected]",
* @OA\Schema(
* type="string"
* )
* ),
* @OA\Parameter(
* description="Sua senha",
* in="query",
* name="password",
* required=true,
* example="123456",
* @OA\Schema(
* type="string"
* )
* ),
* @OA\Response(
* response=200,
* description="Usuário autenticado com sucesso!"
* ),
* @OA\Response(
* response="404",
* description="Usuário ou senha inválidos!"
* )
* )
*/
public function auth(Request $request): array
{
$userService = new UserService($request->toArray());
return $userService->authenticateUser();
}

/**
* @OA\Post(
* path="/api/users/sign-on",
* summary="Cadastro de usuário",
* @OA\Parameter(
* description="Seu Nome",
* in="query",
* name="name",
* required=true,
* example="Fulano de tal",
* @OA\Schema(
* type="string"
* )
* ),
* @OA\Parameter(
* description="Seu email",
* in="query",
* name="email",
* required=true,
* example="[email protected]",
* @OA\Schema(
* type="string"
* )
* ),
* @OA\Parameter(
* description="Sua senha",
* in="query",
* name="password",
* required=true,
* example="123456",
* @OA\Schema(
* type="string"
* )
* ),
* @OA\Response(
* response=200,
* description="Usuário acadastrado com sucesso!"
* ),
* @OA\Response(
* response="400",
* description="Houve um problema ao criar o usuário."
* )
* )
*/
public function signOn(Request $request)
{
$validate = $this->validatorUserForm($request->toArray());

if ($validate->fails()) {
return $validate->errors();
}

$userService = new UserService($request->toArray());
$saved = $userService->signOn();

if (!$saved) {
abort("400");
}

return [
"success" => "Usuário cadastrado com sucesso!"
];
}
}
4 changes: 3 additions & 1 deletion backend/app/Models/User.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,9 @@

class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable;
use HasApiTokens;
use HasFactory;
use Notifiable;

/**
* The attributes that are mass assignable.
Expand Down
7 changes: 6 additions & 1 deletion backend/app/Providers/BroadcastServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,16 @@
use Illuminate\Support\Facades\Broadcast;
use Illuminate\Support\ServiceProvider;

/**
* This will suppress all the PMD warnings in
* this class.
*
* @SuppressWarnings(PHPMD)
*/
class BroadcastServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
Expand Down
6 changes: 6 additions & 0 deletions backend/app/Providers/RouteServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,12 @@
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\Facades\Route;

/**
* This will suppress all the PMD warnings in
* this class.
*
* @SuppressWarnings(PHPMD)
*/
class RouteServiceProvider extends ServiceProvider
{
/**
Expand Down
41 changes: 41 additions & 0 deletions backend/app/Services/UserService.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
<?php

namespace App\Services;

use App\DTO\UserDTO;
use App\Models\User;

class UserService
{
private UserDTO $userDTO;

public function __construct(array $data)
{
$this->userDTO = new UserDTO(
data_get($data, "name", ""),
data_get($data, "email", ""),
data_get($data, "password", "")
);
}

public function signOn(): bool
{
$user = new User();

$user->name = $this->userDTO->name;
$user->email = $this->userDTO->email;
$user->password = $this->userDTO->password;

return $user->save();
}

public function authenticateUser(): array
{
$user = User::where('email', $this->userDTO->email)->first();
if (!$this->userDTO->checkPass(data_get($user, "password", ""))) {
abort("404");
}

return $this->userDTO->userAuthenticated($user);
}
}
21 changes: 21 additions & 0 deletions backend/app/Trait/ValidatorUserFormTrait.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<?php

namespace App\Trait;

trait ValidatorUserFormTrait
{
public function validatorUserForm($data)
{
return validator($data, [
'name' => 'required|min:5',
'email' => 'required|min:6',
'password' => 'required',
], [
"name.required" => "Nome é obrigatório.",
"name.min" => "Nome deve conter pelo menos 5 caracteres.",
"password.required" => "Senha é obrigatória.",
"email.required" => "Email é obrigagotório.",
"email.min" => "Email deve conter pelo menos 6 caracteres."
]);
}
}
19 changes: 16 additions & 3 deletions backend/composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
"license": "MIT",
"require": {
"php": "^8.0.2",
"darkaonline/l5-swagger": "^8.4",
"guzzlehttp/guzzle": "^7.2",
"laravel/framework": "^9.19",
"laravel/sanctum": "^2.14.1",
Expand All @@ -16,8 +17,15 @@
"laravel/sail": "^1.0.1",
"mockery/mockery": "^1.4.4",
"nunomaduro/collision": "^6.1",
"php-parallel-lint/php-parallel-lint": "^1.3",
"phpmd/phpmd": "^2.13",
"phpro/grumphp-shim": "^1.15",
"phpstan/phpstan": "^1.9",
"phpunit/phpunit": "^9.5.10",
"spatie/laravel-ignition": "^1.0"
"povils/phpmnd": "^3.0",
"sebastian/phpcpd": "^6.0",
"spatie/laravel-ignition": "^1.0",
"squizlabs/php_codesniffer": "^3.7"
},
"autoload": {
"psr-4": {
Expand All @@ -44,7 +52,8 @@
],
"post-create-project-cmd": [
"@php artisan key:generate --ansi"
]
],
"code-qa": "./vendor/bin/grumphp run"
},
"extra": {
"laravel": {
Expand All @@ -54,7 +63,11 @@
"config": {
"optimize-autoloader": true,
"preferred-install": "dist",
"sort-packages": true
"sort-packages": true,
"allow-plugins": {
"phpro/grumphp-shim": true,
"phpro/grumphp": true
}
},
"minimum-stability": "dev",
"prefer-stable": true
Expand Down
Loading