Skip to content

Commit

Permalink
Merge pull request #11 from huntmori/6-profile-create-implement
Browse files Browse the repository at this point in the history
6 profile create implement
  • Loading branch information
huntmori authored Jan 9, 2024
2 parents 9d03535 + e886ce5 commit 0bf31b9
Show file tree
Hide file tree
Showing 14 changed files with 222 additions and 46 deletions.
1 change: 1 addition & 0 deletions app/middleware.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

declare(strict_types=1);

use App\Application\Middleware\JwtMiddleware;
use App\Application\Middleware\SessionMiddleware;
use Slim\App;

Expand Down
6 changes: 6 additions & 0 deletions app/repositories.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

declare(strict_types=1);

use App\Application\Middleware\JwtHandler;
use App\Application\Middleware\JwtMiddleware;
use App\Domain\Profile\Repository\ProfileRepository;
use App\Domain\Profile\Repository\ProfileRepositoryImplement;
use App\Domain\Profile\service\ProfileService;
Expand Down Expand Up @@ -31,4 +33,8 @@
$containerBuilder->addDefinitions([
ProfileRepository::class => autowire(ProfileRepositoryImplement::class)
]);
$containerBuilder->addDefinitions([
JwtMiddleware::class => autowire(JwtMiddleware::class),
JwtHandler::class => autowire(JwtHandler::class)
]);
};
21 changes: 15 additions & 6 deletions app/routes.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
declare(strict_types=1);

use App\Application\Common\MemberPasswordEncrypt;
use App\Application\Middleware\JwtMiddleware;
use App\Domain\Profile\controller\ProfileController;
use App\Domain\User\actions\UserCreateAction;
use App\Domain\User\controller\UserController;
use Psr\Http\Message\ResponseInterface as Response;
Expand All @@ -12,9 +14,11 @@

return function (App $app) {
$app->options('/{routes:.+}', function ($request, $response, $args) {
echo 'options'.PHP_EOL;
return $response;
});
$app->add(function ($request, $handler) {
echo 'cors middleware' .PHP_EOL;
$response = $handler->handle($request);
return $response
->withHeader('Access-Control-Allow-Origin', '*')
Expand All @@ -27,16 +31,21 @@
return $response;
});


$app->group('/api/user', function(RouteCollectorProxy $group) use ($app) {
$app->group('/api/user', function (RouteCollectorProxy $group) use ($app) {
$group->post('', UserController::class.':createUser');
$group->get('/id:{id}', UserController::class.':getUser');

$group->post('/login', UserController::class.':userLogin');
});

$app->group("/api/profile", function(RouteCollectorProxy $group) use ($app) {
//$group->put("", $callable);
$app->get(
'/api/user/id:{id}',
UserController::class.':getUser'
)->add(JwtMiddleware::class);

$app->group("/api/profile", function (RouteCollectorProxy $group) {
$group->put(
"",
ProfileController::class . ':createUserProfile'
)->add(JwtMiddleware::class);
});
/*
$app->get("/test", function(Request $request, Response $response) use ($app) {
Expand Down
31 changes: 24 additions & 7 deletions src/Application/Middleware/JwtMiddleware.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
use App\Application\Actions\ActionError;
use App\Application\Actions\ActionPayload;
use App\Application\Actions\AppResponsePayload;
use App\Application\Common\MemberPasswordEncrypt;
use App\Application\Settings\SettingsInterface;
use DI\Container;
use Psr\Http\Message\ServerRequestInterface;
Expand All @@ -22,14 +23,21 @@ class JwtMiddleware implements MiddlewareInterface
private string $HEADER_KEY_NAME = "Authorization";
protected LoggerInterface $logger;

private JwtHandler $jwtHandler;
private MemberPasswordEncrypt $encrypt;

public function __construct(
SettingsInterface $settings,
Container $container,
LoggerInterface $logger
LoggerInterface $logger,
MemberPasswordEncrypt $encrypt,
JwtHandler $jwtHandler
)
{
$this->logger = $logger;
$this->secretKey = $settings->get('config')['ENCRYPT_KEY'];
$this->jwtHandler = $jwtHandler;
$this->encrypt = $encrypt;
}


Expand All @@ -44,17 +52,20 @@ public function extractToken(ServerRequestInterface $request) : ?string
public function validateTokenReturnUserIdx(string $token) : bool
{
// 암호화 디코드
$tokenDecoded = JwtHandler::decryptToken($this->secretKey, $token);
$decryptToken = $this->encrypt->decrypt($token);
$tokenDecoded = $this->jwtHandler->decryptToken($decryptToken);
//$tokenDecoded = $token;
var_dump($tokenDecoded);
// claims 디코드
$claims = JwtHandler::decodeJwt($tokenDecoded, $this->secretKey);

$claims = $this->jwtHandler->decodeJwt($tokenDecoded);
var_dump($claims);
// 유효기간 확인
$expiredAt = $claims['exp'];
$now = strtotime("now");
if ($expiredAt < $now) {
return false;
}
$userId = $claims['user_id'];
$userId = $claims['userId'];
// 세션 확인
//session_start();
//$tokens = $_SESSION[$userId];
Expand All @@ -68,13 +79,19 @@ public function validateTokenReturnUserIdx(string $token) : bool

public function validateToken(string $token) : bool
{
return is_numeric($this->validateTokenReturnUserIdx($token));
return $this->validateTokenReturnUserIdx($token);
}

public function __invoke(Request $request, RequestHandlerInterface $handler): Response
{
$this->logger->info("jwt-invoke");
return $this->process($request, $handler);
}
public function process(Request $request, RequestHandlerInterface $handler): Response
{
$this->logger->info("jwt-process");
$token = $this->extractToken($request); // JWT 토큰 추출 메서드 구현

echo $token.PHP_EOL;
$this->logger->info(
"TOKEN PROCESS {$request->getUri()} : ".PHP_EOL
."TOKEN : ".$token
Expand Down
18 changes: 18 additions & 0 deletions src/Domain/Common/models/AuthorizationRequestTrait.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<?php

namespace App\Domain\Common\models;
use Psr\Http\Message\ServerRequestInterface as Request;

trait AuthorizationRequestTrait
{
static string $tokenHeaderKey = "Authorization";

public function extractToken(Request $request) : ?string {
echo self::$tokenHeaderKey.PHP_EOL;
echo $request->getHeader(self::$tokenHeaderKey)[0].PHP_EOL;
if($request->hasHeader(self::$tokenHeaderKey)) {
return $request->getHeader(self::$tokenHeaderKey)[0];
}
return null;
}
}
6 changes: 5 additions & 1 deletion src/Domain/Common/models/BaseDto.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,12 @@ public function __construct($params = null)
}

if (is_object($params)) {
$KEY_NAMES = array_keys(get_object_vars($params));
$arrayParameter = (array)($params);
echo 'array Parameter :';
var_dump($arrayParameter);
echo PHP_EOL . PHP_EOL;
$KEY_NAMES = array_keys($arrayParameter);
var_dump($KEY_NAMES);
}
$allowKeys = $this->getAllowKeyNames();
foreach($KEY_NAMES as $key) {
Expand Down
16 changes: 16 additions & 0 deletions src/Domain/Common/repository/BaseRepository.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,4 +29,20 @@ public function disposePdo(PDO $pdo): void
{
// $this->connectionPool->dispose($pdo);
}

public function selectOne(string $sql, array $paramMap, string $returnType) {
$pdo = $this->getPdo();
$stmt = $pdo->prepare($sql);

$keys = array_keys($paramMap);
for ($i=0; $i<count($keys); $i++) {
$key = $keys[$i];
$stmt->bindValue($key, $paramMap[$key]);
}

$stmt->execute();
$result = $stmt->fetchObject($returnType);
$this->disposePdo($pdo);
return $result;
}
}
5 changes: 5 additions & 0 deletions src/Domain/Profile/Repository/ProfileRepository.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,9 @@ interface ProfileRepository
{

public function createUserProfile(int $userIdx, Profile $profile);

public function getUserProfileByProfileIdx(int $profileIdx);
public function getUserProfileByUserUid(string $uid);

public function getUserProfileByProfileUid(string $uid);
}
48 changes: 40 additions & 8 deletions src/Domain/Profile/Repository/ProfileRepositoryImplement.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,23 +24,23 @@ public function createUserProfile(int $userIdx, Profile $profile) : int
$pdo = $this->getPdo();
$stmt = $pdo->prepare("
INSERT INTO profile
SET user_idx = :useIdx,
uuid = UPPER(UUID()),
SET uid = UPPER(UUID()),
user_uid = :userUid,
profile_nickname = :nickName,
is_primary = :isPrimary,
deleted = :deleted,
activate = :activate,
activated = :activated,
banned = :banned,
created_at = :createdAt,
updated_at = :updatedAt
");

$stmt->bindValue("useIdx", $profile->getUserIdx());
$stmt->bindValue("userUid", $profile->getUserUid());
$stmt->bindValue("nickName", $profile->getProfileNickName());
$stmt->bindValue("isPrimary", $profile->getIsPrimary());
$stmt->bindValue("deleted", $profile->getDeleted());
$stmt->bindValue("activate", $profile->getActivated());
$stmt->bindValue("banned", $profile->getBanned());
$stmt->bindValue("isPrimary", $profile->getIsPrimary() ? 1:0);
$stmt->bindValue("deleted", $profile->getDeleted() ? 1:0);
$stmt->bindValue("activated", $profile->getActivated() ? 1:0);
$stmt->bindValue("banned", $profile->getBanned() ? 1 : 0);
$stmt->bindValue("createdAt", $profile->getCreatedAt());
$stmt->bindValue("updatedAt", $profile->getUpdatedAt());

Expand All @@ -53,4 +53,36 @@ public function createUserProfile(int $userIdx, Profile $profile) : int
$this->disposePdo($pdo);
return $lastId;
}

public function getUserProfileByProfileIdx(int $profileIdx)
{
return $this->selectOne(
" SELECT prf.idx as idx,
prf.uid as uid,
prf.user_uid as userUid,
prf.profile_nickname as profileNickName,
prf.is_primary as isPrimary,
prf.deleted as deleted,
prf.activated as activated,
prf.banned as banned,
prf.created_at as createdAt,
prf.updated_at as updatedAt
FROM profile prf
WHERE prf.idx = :profileIdx
LIMIT 1 ",
[ 'profileIdx'=>$profileIdx ],
Profile::class
);
}

public function getUserProfileByUserUid(string $uid)
{
// TODO: Implement getUserProfileByUserUid() method.
return null;
}

public function getUserProfileByProfileUid(string $uid)
{
return null;
}
}
5 changes: 3 additions & 2 deletions src/Domain/Profile/controller/ProfileController.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,8 @@ public function getUserProfile($userIdx) : array

public function createUserProfile(Request $request, Response $response, array $args) : Response
{
$body = new ProfileCreateRequest($request->getBody());
return $this->respondWithData($response);
$requestDto = new ProfileCreateRequest($request);
$profile = $this->profileService->createUserProfileByRequestDto($requestDto);
return $this->respondWithData($response, $profile->toArray(), 200);
}
}
37 changes: 27 additions & 10 deletions src/Domain/Profile/entities/Profile.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@
class Profile
{
private ?int $idx;
private ?int $userIdx;
private ?string $uuid;
private ?string $userUid;
private ?string $uid;
private ?string $profileNickName;
private ?bool $isPrimary;
private ?bool $deleted;
Expand All @@ -15,6 +15,21 @@ class Profile
private ?string $createdAt;
private ?string $updatedAt;

public function toArray() : array {
return ([
'idx'=> $this->idx,
'uid'=> $this->uid,
'userUid' => $this->userUid,
'profileNickName' => $this->profileNickName,
'isPrimary' => $this->isPrimary,
'deleted' => $this->deleted,
'activated' => $this->activated,
'banned' => $this->banned,
'createdAt' => $this->createdAt,
'updatedAt' => $this->updatedAt
]);
}

public function getIdx(): ?int
{
return $this->idx;
Expand All @@ -25,24 +40,24 @@ public function setIdx(?int $idx): void
$this->idx = $idx;
}

public function getUserIdx(): ?int
public function getUserUid(): ?string
{
return $this->userIdx;
return $this->userUid;
}

public function setUserIdx(?int $userIdx): void
public function setUserUid(?string $userUid): void
{
$this->userIdx = $userIdx;
$this->userUid = $userUid;
}

public function getUuid(): ?string
public function getUid(): ?string
{
return $this->uuid;
return $this->uid;
}

public function setUuid(?string $uuid): void
public function setUid(?string $uid): void
{
$this->uuid = $uuid;
$this->uid = $uid;
}

public function getProfileNickName(): ?string
Expand Down Expand Up @@ -115,4 +130,6 @@ public function setUpdatedAt(?string $updatedAt): void
$this->updatedAt = $updatedAt;
}



}
Loading

0 comments on commit 0bf31b9

Please sign in to comment.