Skip to content

Commit

Permalink
sync
Browse files Browse the repository at this point in the history
  • Loading branch information
dermatthes committed Jun 13, 2024
1 parent 7952787 commit 33260f7
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 13 deletions.
26 changes: 22 additions & 4 deletions src/Session.php
Original file line number Diff line number Diff line change
Expand Up @@ -42,12 +42,30 @@ public function set(string $key, mixed $value): void
/**
* Retrieve a value from the session.
*
* @template T
* @param string $key
* @return mixed
* @param class-string<T>|null $cast
* @return T
*/
public function get(string $key): mixed
public function get(string $key, string $cast = null, bool $silentFail=false): mixed
{
return $this->sessionData[$key] ?? null;
$val = $this->sessionData[$key] ?? null;


if ($cast !== null) {
try {

if ($val === null)
throw new \InvalidArgumentException("Value of session key '$key' is null");
return phore_hydrate($val, $cast);
} catch (\Exception $e) {
if ($silentFail)
return null;
throw new \InvalidArgumentException("Cannot cast session value '$key' to $cast: " . $e->getMessage(), 0, $e);
}
}

return $val;
}

/**
Expand Down Expand Up @@ -112,6 +130,6 @@ public function isDestroyed() : bool
{
return $this->isDestroyed;
}

}

16 changes: 8 additions & 8 deletions src/SessionMiddleware.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,9 @@ public function __construct(
private int $ttl = 3600,
private int $expires = 86400,
private string $cookieName = "X-SESS",
private ?string $cookiePath = null
private ?string $cookiePath = "/"
) {

}


Expand Down Expand Up @@ -65,26 +65,26 @@ public function _createSession(string $sessionId, &$sessionDataRef): Session

public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{

if ($this->cookiePath === null) {
if ($this->app->has("router")) {
$this->cookiePath = $this->app->router->getRoutePrefix();
} else {
$this->cookiePath = "/";
}
}

$newSessionId = null;

$loadedSessionId = null;
$sessionDataRef = null;

$sessionObj = null;





$this->app->define(
self::SESSION_DI_NAME,
new DiService(
Expand Down
2 changes: 1 addition & 1 deletion src/Storages/CookieSessionStorage.php
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ public function write(string $sessionId, array $data): void
$nonce = random_bytes(SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);
$encryped = sodium_crypto_secretbox(json_encode($data), $nonce, substr(sodium_crypto_generichash($this->secretKey), 0, 32));

setcookie($this->cookieName, base64_encode($nonce) . "." . base64_encode($encryped));
setcookie($this->cookieName, base64_encode($nonce) . "." . base64_encode($encryped), time() + 3600 * 24, "/");
}

/**
Expand Down

0 comments on commit 33260f7

Please sign in to comment.