Skip to content

Commit

Permalink
jwt
Browse files Browse the repository at this point in the history
  • Loading branch information
wouerner committed Jan 26, 2024
1 parent 1fe20b3 commit bf873eb
Show file tree
Hide file tree
Showing 19 changed files with 1,866 additions and 322 deletions.
1 change: 1 addition & 0 deletions Insomnia.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"_type":"export","__export_format":4,"__export_date":"2024-01-26T01:56:25.263Z","__export_source":"insomnia.desktop.app:v2023.1.0","resources":[{"_id":"req_cb32a09b103642c19e0ba59783f39d2f","parentId":"fld_5556a0aad10b471084824aa64768421a","modified":1706210936781,"created":1706191448588,"url":"{{server}}{{api_prefix}}/login","name":"Login","description":"","method":"POST","body":{"mimeType":"application/json","text":"{\n\t\"email\": \"w@w.com\",\n\t\"password\": \"12345678\"\n\t\n}"},"parameters":[],"headers":[{"name":"Content-Type","value":"application/json"}],"authentication":{},"metaSortKey":-1698660890765.375,"isPrivate":false,"settingStoreCookies":true,"settingSendCookies":true,"settingDisableRenderRequestBody":false,"settingEncodeUrl":true,"settingRebuildPath":true,"settingFollowRedirects":"global","_type":"request"},{"_id":"fld_5556a0aad10b471084824aa64768421a","parentId":"wrk_c1999f3cd1f046af8c64d7240a118999","modified":1706195537674,"created":1706195537674,"name":"Auth","description":"","environment":{},"environmentPropertyOrder":null,"metaSortKey":-1706195537674,"_type":"request_group"},{"_id":"wrk_c1999f3cd1f046af8c64d7240a118999","parentId":null,"modified":1702324683970,"created":1702324683970,"name":"Test","description":"","scope":"collection","_type":"workspace"},{"_id":"req_5033c8a57f14469dbeabeb8f314f0a7e","parentId":"fld_2791c5c524f947fcb43bbba2ddf000c6","modified":1706212537744,"created":1702406241508,"url":"{{server}}{{api_prefix}}/users","name":"User","description":"","method":"GET","body":{},"parameters":[],"headers":[],"authentication":{"type":"bearer","token":"{{token}}"},"metaSortKey":-1699393650461.5,"isPrivate":false,"settingStoreCookies":true,"settingSendCookies":true,"settingDisableRenderRequestBody":false,"settingEncodeUrl":true,"settingRebuildPath":true,"settingFollowRedirects":"global","_type":"request"},{"_id":"fld_2791c5c524f947fcb43bbba2ddf000c6","parentId":"fld_b3490ec52f084ab288d3fb190ae5931b","modified":1706210276762,"created":1706210276762,"name":"Protected","description":"","environment":{},"environmentPropertyOrder":null,"metaSortKey":-1706210276762,"_type":"request_group"},{"_id":"fld_b3490ec52f084ab288d3fb190ae5931b","parentId":"wrk_c1999f3cd1f046af8c64d7240a118999","modified":1702406510291,"created":1702406510291,"name":"User","description":"","environment":{},"environmentPropertyOrder":null,"metaSortKey":-1702406510291,"_type":"request_group"},{"_id":"req_53022f13aacb42c78003f588e73e3b50","parentId":"fld_2791c5c524f947fcb43bbba2ddf000c6","modified":1706213480116,"created":1702409687651,"url":"{{server}}{{api_prefix}}/user/fc3b9383-34ff-40ad-bd5e-9ec542f303f0","name":"Update","description":"","method":"PUT","body":{"mimeType":"application/json","text":"{\n\t\"name\": \"dev2\",\n\t\"email\": \"w@w.com\",\n\t\"password\": \"12345678\",\n\t\"birth_date\": \"1989/11/27\",\n\t\"document\" : \"111111\",\n\t\"cellphone\" : \"619999999\"\n}"},"parameters":[],"headers":[{"name":"Content-Type","value":"application/json"}],"authentication":{"type":"bearer","token":"{{token}}"},"metaSortKey":-1699393650436.5,"isPrivate":false,"settingStoreCookies":true,"settingSendCookies":true,"settingDisableRenderRequestBody":false,"settingEncodeUrl":true,"settingRebuildPath":true,"settingFollowRedirects":"global","_type":"request"},{"_id":"req_20e501f047aa4adcb866848f0081118c","parentId":"fld_2791c5c524f947fcb43bbba2ddf000c6","modified":1706213877932,"created":1702409691621,"url":"{{server}}{{api_prefix}}/user/{{ _.uuid_user }}","name":"User","description":"","method":"DELETE","body":{},"parameters":[],"headers":[],"authentication":{"type":"bearer","token":"{{ _.token }}"},"metaSortKey":-1699393650386.5,"isPrivate":false,"settingStoreCookies":true,"settingSendCookies":true,"settingDisableRenderRequestBody":false,"settingEncodeUrl":true,"settingRebuildPath":true,"settingFollowRedirects":"global","_type":"request"},{"_id":"req_9dabd6fca0f84ba2bbe843ce430964bb","parentId":"fld_b3490ec52f084ab288d3fb190ae5931b","modified":1706211345387,"created":1706195551971,"url":"{{server}}{{ _.api_prefix }}/register","name":"User","description":"","method":"POST","body":{"mimeType":"application/json","text":"{\n\t\"name\": \"dev\",\n\t\"email\": \"w@w.com\",\n\t\"password\": \"12345678\",\n\t\"birth_date\": \"1989/11/27\",\n\t\"document\" : \"111111\",\n\t\"cellphone\" : \"619999999\"\n}\n"},"parameters":[],"headers":[{"name":"Content-Type","value":"application/json"}],"authentication":{},"metaSortKey":-1703290470030,"isPrivate":false,"settingStoreCookies":true,"settingSendCookies":true,"settingDisableRenderRequestBody":false,"settingEncodeUrl":true,"settingRebuildPath":true,"settingFollowRedirects":"global","_type":"request"},{"_id":"req_46bb133b1a35469da9a7ab59f0b5f615","parentId":"fld_3ee24478d87d4b46892b1cdee5da0973","modified":1706211203452,"created":1702406249471,"url":"{{server}}{{ _.api_prefix }}/squads","name":"Squad","description":"","method":"GET","body":{},"parameters":[],"headers":[],"authentication":{},"metaSortKey":-1701347676459.5,"isPrivate":false,"settingStoreCookies":true,"settingSendCookies":true,"settingDisableRenderRequestBody":false,"settingEncodeUrl":true,"settingRebuildPath":true,"settingFollowRedirects":"global","_type":"request"},{"_id":"fld_3ee24478d87d4b46892b1cdee5da0973","parentId":"wrk_c1999f3cd1f046af8c64d7240a118999","modified":1706210506716,"created":1702406487903,"name":"Squad - Protected","description":"","environment":{},"environmentPropertyOrder":null,"metaSortKey":-1702406487903,"_type":"request_group"},{"_id":"req_1fb9576453b241dea81ef8ca717c978c","parentId":"fld_3ee24478d87d4b46892b1cdee5da0973","modified":1706211199997,"created":1702409700280,"url":"{{server}}{{api_prefix}}/squad","name":"Squad","description":"","method":"POST","body":{},"parameters":[],"headers":[],"authentication":{},"metaSortKey":-1700859169978.75,"isPrivate":false,"settingStoreCookies":true,"settingSendCookies":true,"settingDisableRenderRequestBody":false,"settingEncodeUrl":true,"settingRebuildPath":true,"settingFollowRedirects":"global","_type":"request"},{"_id":"req_7b375a3e9171419183d3b11cd505689f","parentId":"fld_3ee24478d87d4b46892b1cdee5da0973","modified":1706211191650,"created":1702409704601,"url":"{{server}}{{api_prefix}}/squad","name":"Squad","description":"","method":"PUT","body":{},"parameters":[],"headers":[],"authentication":{},"metaSortKey":-1700614916738.375,"isPrivate":false,"settingStoreCookies":true,"settingSendCookies":true,"settingDisableRenderRequestBody":false,"settingEncodeUrl":true,"settingRebuildPath":true,"settingFollowRedirects":"global","_type":"request"},{"_id":"req_557cdc94898c45f9925303e5ac0c2458","parentId":"fld_3ee24478d87d4b46892b1cdee5da0973","modified":1706211224236,"created":1702409708886,"url":"{{server}}{{api_prefix}}/squad","name":"Squad","description":"","method":"DELETE","body":{},"parameters":[],"headers":[],"authentication":{},"metaSortKey":-1700492790118.1875,"isPrivate":false,"settingStoreCookies":true,"settingSendCookies":true,"settingDisableRenderRequestBody":false,"settingEncodeUrl":true,"settingRebuildPath":true,"settingFollowRedirects":"global","_type":"request"},{"_id":"req_fe82c9fe6f2648bb9d63cd274872f715","parentId":"fld_68cbe8428fb84ecdaf057c2611ef0173","modified":1706211155580,"created":1702406978192,"url":"{{server}}{{api_prefix}}/product","name":"Create","description":"","method":"POST","body":{"mimeType":"application/json","text":"{\n\t\"name\": \"Henrique\"\n}"},"parameters":[],"headers":[{"name":"Content-Type","value":"application/json"}],"authentication":{},"metaSortKey":-1702406978192,"isPrivate":false,"settingStoreCookies":true,"settingSendCookies":true,"settingDisableRenderRequestBody":false,"settingEncodeUrl":true,"settingRebuildPath":true,"settingFollowRedirects":"global","_type":"request"},{"_id":"fld_68cbe8428fb84ecdaf057c2611ef0173","parentId":"wrk_c1999f3cd1f046af8c64d7240a118999","modified":1706210517708,"created":1702406450563,"name":"Products - Protected","description":"","environment":{},"environmentPropertyOrder":null,"metaSortKey":-1702406450563,"_type":"request_group"},{"_id":"req_a139e921f0894b37bebf292e51655acc","parentId":"fld_68cbe8428fb84ecdaf057c2611ef0173","modified":1706211160524,"created":1702324689421,"url":"{{server}}{{api_prefix}}/products","name":"Index","description":"","method":"GET","body":{},"parameters":[],"headers":[],"authentication":{},"metaSortKey":-1702152372901.625,"isPrivate":false,"settingStoreCookies":true,"settingSendCookies":true,"settingDisableRenderRequestBody":false,"settingEncodeUrl":true,"settingRebuildPath":true,"settingFollowRedirects":"global","_type":"request"},{"_id":"req_21a1377b4e674dab918ee8e5ab33fe04","parentId":"fld_68cbe8428fb84ecdaf057c2611ef0173","modified":1706211165093,"created":1702408098329,"url":"{{server}}{{api_prefix}}/product","name":"Update","description":"","method":"PUT","body":{},"parameters":[],"headers":[],"authentication":{},"metaSortKey":-1701643162320.875,"isPrivate":false,"settingStoreCookies":true,"settingSendCookies":true,"settingDisableRenderRequestBody":false,"settingEncodeUrl":true,"settingRebuildPath":true,"settingFollowRedirects":"global","_type":"request"},{"_id":"req_f385cc00b9de4da1b4a8c60d094030f4","parentId":"fld_68cbe8428fb84ecdaf057c2611ef0173","modified":1706211171931,"created":1702408082754,"url":"{{server}}{{api_prefix}}/product","name":"Delete","description":"","method":"DELETE","body":{},"parameters":[],"headers":[],"authentication":{},"metaSortKey":-1701643162270.875,"isPrivate":false,"settingStoreCookies":true,"settingSendCookies":true,"settingDisableRenderRequestBody":false,"settingEncodeUrl":true,"settingRebuildPath":true,"settingFollowRedirects":"global","_type":"request"},{"_id":"env_768327098579b77a6e586f60e7bfed27e6003a18","parentId":"wrk_c1999f3cd1f046af8c64d7240a118999","modified":1706215785312,"created":1702324683972,"name":"Base Environment","data":{"server":"http://127.0.0.1:9501","api_prefix":"/api","token":"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1dWlkIjoiMzRmODU4NjYtOWY5OS00ZjM0LTk3M2QtMDcyYjUzYmExZTkwIiwiZW1haWwiOiJ3QHcuY29tIiwiaWF0IjoxNzA2MjE1NzY4fQ.dE92ck_It4qSYnY1Kv_LIUbbv7RKbCdGCSTOQ8KGE8M","uuid_user":"34f85866-9f99-4f34-973d-072b53ba1e90"},"dataPropertyOrder":{"&":["server","api_prefix","token","uuid_user"]},"color":null,"isPrivate":false,"metaSortKey":1702324683972,"_type":"environment"},{"_id":"jar_768327098579b77a6e586f60e7bfed27e6003a18","parentId":"wrk_c1999f3cd1f046af8c64d7240a118999","modified":1702324683973,"created":1702324683973,"name":"Default Jar","cookies":[],"_type":"cookie_jar"},{"_id":"spc_e6cfbc2ed7984bd59775f3c401796236","parentId":"wrk_c1999f3cd1f046af8c64d7240a118999","modified":1702324683971,"created":1702324683971,"fileName":"Test","contents":"","contentType":"yaml","_type":"api_spec"},{"_id":"env_fbfc8d4bf7424e879f9dbbf65f3e38a4","parentId":"env_768327098579b77a6e586f60e7bfed27e6003a18","modified":1706210837799,"created":1706210788737,"name":"dev","data":{"server":"http://127.0.0.1:9501"},"dataPropertyOrder":{"&":["server"]},"color":null,"isPrivate":false,"metaSortKey":1706210788737,"_type":"environment"},{"_id":"env_da10b8664912477595f019892b047e35","parentId":"env_768327098579b77a6e586f60e7bfed27e6003a18","modified":1706215927331,"created":1706215919997,"name":"homolog","data":{},"dataPropertyOrder":null,"color":null,"isPrivate":false,"metaSortKey":1706215919997,"_type":"environment"}]}
51 changes: 51 additions & 0 deletions app/Controller/AuthController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
<?php

declare(strict_types=1);

namespace App\Controller;

use App\Request\UserRegisterRequest;
use App\Request\LoginRequest;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\RequestMapping;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Contract\ResponseInterface;

/* use App\Interfaces\LoginRepositoryInterface; */

use App\Repositories\LoginRepository;

class AuthController extends AbstractController
{
private $loginRepository;
/* protected $response; */

public function __construct(
LoginRepository $loginRepository,
/* LoginRepositoryInterface $loginRepository, */
/* ResponseInterface $response */
) {
$this->loginRepository = $loginRepository;
/* $this->response = $response; */
}

public function login(LoginRequest $request)
{
return $this->loginRepository->login($request);
}

public function register(UserRegisterRequest $request)
{
$result = $this->loginRepository->register($request);

if ($result) {
return $this->response->json([
'message' => 'Usuário cadastrado com sucesso.'
])->withStatus(201);
} else {
return $this->response->json([
'error' => 'Não foi possível realizar o cadastro.'
])->withStatus(500);
}
}
}
14 changes: 12 additions & 2 deletions app/Controller/IndexController.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,19 +9,29 @@
* @contact group@hyperf.io
* @license https://github.com/hyperf/hyperf/blob/master/LICENSE
*/

namespace App\Controller;

use Hyperf\Swagger\Annotation as SA;

#[SA\HyperfServer(name: 'http')]
class IndexController extends AbstractController
{
#[SA\Get(path: '/index', summary: 'GET example', tags: ['/Index'])]
#[SA\Response(
response: 200,
description: 'Description of the returned value',
content: new SA\JsonContent(
example: '{"code":200, "data":[]}'
)
)]
public function index()
{
$user = $this->request->input('user', 'Hyperf');
$method = $this->request->getMethod();

return [
'method' => $method,
'message' => "Hello {$user}.",
'message' => "Hello bro, {$user}.",
];
}
}
113 changes: 74 additions & 39 deletions app/Controller/UserController.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,35 +12,29 @@

namespace App\Controller;

use App\Model\User;
use Hyperf\HttpServer\Contract\RequestInterface;
use Psr\Http\Message\ResponseInterface as Psr7ResponseInterface;

class UserController extends AbstractController
{
public function index()
{
$user = $this->request->input('user', 'Hyperf');
$method = $this->request->getMethod();

return [
[
"id" => 1,
"name" => "Product 1",
"linkedin" => "https://picsum.photos/200/300",
"description" => "Product 1 description",
"image" => "https://picsum.photos/200/300",
],
[
"id" => 2,
"name" => "Product 2",
"linkedin" => "https://picsum.photos/200/300",
"description" => "Product 1 description",
"image" => "https://picsum.photos/200/300",
],
];
return User::select(
'uuid',
'name',
'email',
'created_at',
'updated_at'
)->get();
}

/**
*
* @Todo
*/
public function create()
{
$user = $this->request->all();

return [
"id" => 1,
"linkedin" => "https://picsum.photos/200/300",
Expand All @@ -50,29 +44,70 @@ public function create()
];
}

public function update()
public function update(RequestInterface $request, $id)
{
$user = $this->request->all();
if ($user->uuid !== $id) {
return $this->response->json([
'error' => 'Você não tem permissão para autalizar este usuário.',
], 403);
}

return [
"id" => 1,
"linkedin" => "https://picsum.photos/200/300",
"description" => "Product 1 description",
"image" => "https://picsum.photos/200/300",
"token" => "token"
];
$email = $this->request->input('email');
$name = $this->request->input('name');
$password = $this->request->input('password');
$birthDate = $this->request->input('birth_date');
$document = $this->request->input('document');
$cellphone = $this->request->input('cellphone');

$user = User::query()->where('uuid', $id)->first();

if (empty($user)) {
return $this->response->json([
'error' => 'Usuário não encontrado.',
], 404);
}

$user->name = $name;
$user->password = password_hash($password, PASSWORD_BCRYPT); // Hash da senha
$user->birth_date = $birthDate;
$user->document = $document;
$user->cellphone = $cellphone;
$user->save();

return $this->response->json([
'message' => 'Usuário atualizado com sucesso!',
'user' => $user,
]);
}

public function del()
public function del($id): Psr7ResponseInterface
{
$user = $this->request->all();
$user = $this->container->get('user');

return [
"id" => 1,
"linkedin" => "https://picsum.photos/200/300",
"description" => "Product 1 description",
"image" => "https://picsum.photos/200/300",
"token" => "token"
];
if ($user->uuid !== $id) {
return $this->response->json([
'error' => 'Você não tem permissão para deletar este usuário.',
], 403);
}

if (!$id) {
return $this->response->json([
'error' => 'O email é necessário para deletar o usuário.',
], 400);
}

$user = User::query()->where('uuid', $id)->first();

if (!$user) {
return $this->response->json([
'error' => 'Usuário não encontrado.',
], 404);
}

$user->delete();

return $this->response->json([
'message' => 'Usuário deletado com sucesso!',
]);
}
}
45 changes: 45 additions & 0 deletions app/Middleware/AuthMiddleware.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
<?php

namespace App\Middleware;

use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\HttpServer\Contract\ResponseInterface;
use Hyperf\Di\Container;
use Hyperf\Utils\Context;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use Hyperf\Config\Annotation\Value;

class AuthMiddleware
{
#[Value(key: "jwt_secret_key")]
protected $jwtSecretKey;

public function __construct(RequestInterface $request, ResponseInterface $response, Container $container)
{
$this->request = $request;
$this->response = $response;
/* $this->jwtSecretKey = env('JWT_SECRET_KEY'); */
$this->container = $container;
}

public function process($request, $handler)
{
$token = $this->request->getHeader('Authorization');

if (empty($token)) {
return $this->response->json(['error' => 'Token de autenticação ausente'], 401);
}

try {
$token = explode(' ', $token[0]);

$decoded = JWT::decode($token[1], new Key($this->jwtSecretKey, 'HS256'));
$this->container->set('user', $decoded);
} catch (\Exception $e) {
return $this->response->json(['error' => 'Token de autenticação inválido', 'message'=> $e->getMessage()], 401);
}

return $handler->handle($request);
}
}
40 changes: 40 additions & 0 deletions app/Model/User.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
<?php

declare(strict_types=1);

namespace App\Model;

use Hyperf\DbConnection\Model\Model;

/**
* @property int $id
* @property string $uuid
* @property string $name
* @property string $email
* @property string $birth_date
* @property string $document
* @property string $cellphone
* @property string $password
* @property string $remember_token
* @property \Carbon\Carbon $created_at
* @property \Carbon\Carbon $updated_at
*/
class User extends Model
{
/**
* The table associated with the model.
*/
protected ?string $table = 'users';

/**
* The attributes that are mass assignable.
*/
protected array $fillable = [];

protected array $guarded = [];

/**
* The attributes that should be cast to native types.
*/
protected array $casts = ['id' => 'integer', 'created_at' => 'datetime', 'updated_at' => 'datetime'];
}
Loading

0 comments on commit bf873eb

Please sign in to comment.