create-prisma-php-app 4.3.7 → 4.3.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,7 @@
1
- import { createProxyMiddleware } from "http-proxy-middleware";
1
+ import {
2
+ createProxyMiddleware,
3
+ responseInterceptor,
4
+ } from "http-proxy-middleware";
2
5
  import { writeFileSync, existsSync, mkdirSync } from "fs";
3
6
  import browserSync, { BrowserSyncInstance } from "browser-sync";
4
7
  import prismaPhpConfigJson from "../prisma-php.json";
@@ -121,10 +124,85 @@ bs.init(
121
124
  res.setHeader("Expires", "0");
122
125
  next();
123
126
  },
127
+
128
+ (req, _, next) => {
129
+ const time = new Date().toLocaleTimeString();
130
+ console.log(
131
+ `${chalk.gray(time)} ${chalk.cyan("[Proxy]")} ${chalk.bold(req.method)} ${req.url}`,
132
+ );
133
+ next();
134
+ },
135
+
124
136
  createProxyMiddleware({
125
137
  target: prismaPhpConfigJson.bsTarget,
126
138
  changeOrigin: true,
127
139
  pathRewrite: {},
140
+ selfHandleResponse: true,
141
+
142
+ on: {
143
+ proxyReq: (proxyReq, req, _res) => {
144
+ proxyReq.setHeader("Accept-Encoding", "");
145
+
146
+ const sendsJson =
147
+ req.headers["content-type"]?.includes("application/json");
148
+ const asksJson =
149
+ req.headers["accept"]?.includes("application/json");
150
+
151
+ if (!sendsJson && !asksJson) return;
152
+
153
+ const originalWrite = proxyReq.write;
154
+ proxyReq.write = function (data, ...args) {
155
+ if (data) {
156
+ try {
157
+ const body = data.toString();
158
+ const json = JSON.parse(body);
159
+ console.log(
160
+ chalk.blue("→ API Request:"),
161
+ JSON.stringify(json, null, 2),
162
+ );
163
+ } catch {
164
+ if (data.toString().trim() !== "") {
165
+ console.log(chalk.blue("→ API Request:"), data.toString());
166
+ }
167
+ }
168
+ }
169
+ // @ts-ignore
170
+ return originalWrite.call(proxyReq, data, ...args);
171
+ };
172
+ },
173
+
174
+ proxyRes: responseInterceptor(
175
+ async (responseBuffer, proxyRes, _req, _res) => {
176
+ const contentType = proxyRes.headers["content-type"] || "";
177
+
178
+ if (!contentType.includes("application/json")) {
179
+ return responseBuffer;
180
+ }
181
+
182
+ try {
183
+ const body = responseBuffer.toString("utf8");
184
+ console.log(
185
+ chalk.green("← API Response:"),
186
+ JSON.stringify(JSON.parse(body), null, 2),
187
+ );
188
+ console.log(
189
+ chalk.gray("----------------------------------------"),
190
+ );
191
+ } catch (e) {
192
+ console.log(
193
+ chalk.red("← API Response (Parse Error):"),
194
+ responseBuffer.toString(),
195
+ );
196
+ }
197
+
198
+ return responseBuffer;
199
+ },
200
+ ),
201
+
202
+ error: (err) => {
203
+ console.error(chalk.red("Proxy Error:"), err);
204
+ },
205
+ },
128
206
  }),
129
207
  ],
130
208
  notify: false,
@@ -175,7 +175,7 @@ class Auth
175
175
  if (empty($token->{Auth::PAYLOAD_NAME})) return null;
176
176
  if (isset($token->exp) && time() >= $token->exp) return null;
177
177
 
178
- return $token;
178
+ return $token->{Auth::PAYLOAD_NAME};
179
179
  } catch (Exception) {
180
180
  return null;
181
181
  }
@@ -198,15 +198,20 @@ class Auth
198
198
  */
199
199
  public function refreshToken(string $jwt, ?string $tokenValidity = null): string
200
200
  {
201
- $decodedToken = $this->verifyToken($jwt);
201
+ $decodedData = $this->verifyToken($jwt);
202
202
 
203
- if (!$decodedToken) {
203
+ if (!$decodedData) {
204
204
  throw new InvalidArgumentException("Invalid token.");
205
205
  }
206
206
 
207
207
  $expirationTime = $this->calculateExpirationTime($tokenValidity ?? $this->defaultTokenValidity);
208
- $decodedToken->exp = $expirationTime;
209
- $newJwt = JWT::encode((array)$decodedToken, $this->secretKey, 'HS256');
208
+
209
+ $payload = [
210
+ self::PAYLOAD_NAME => $decodedData,
211
+ 'exp' => $expirationTime,
212
+ ];
213
+
214
+ $newJwt = JWT::encode($payload, $this->secretKey, 'HS256');
210
215
 
211
216
  if (!headers_sent()) {
212
217
  $this->setCookies($newJwt, $expirationTime);
@@ -7,6 +7,7 @@ namespace Lib\Middleware;
7
7
  use Lib\Auth\Auth;
8
8
  use Lib\Auth\AuthConfig;
9
9
  use PP\Request;
10
+ use Throwable;
10
11
 
11
12
  final class AuthMiddleware
12
13
  {
@@ -24,9 +25,18 @@ final class AuthMiddleware
24
25
  // Check if the user is authenticated and refresh the token if necessary
25
26
  if (AuthConfig::IS_TOKEN_AUTO_REFRESH) {
26
27
  $auth = Auth::getInstance();
27
- if (isset($_COOKIE[Auth::$cookieName])) {
28
- $jwt = $_COOKIE[Auth::$cookieName];
29
- $jwt = $auth->refreshToken($jwt);
28
+
29
+ $jwt = $_COOKIE[Auth::$cookieName] ?? Request::getBearerToken();
30
+
31
+ if ($jwt) {
32
+ try {
33
+ $newJwt = $auth->refreshToken($jwt);
34
+ if (!isset($_COOKIE[Auth::$cookieName])) {
35
+ header('Authorization: Bearer ' . $newJwt);
36
+ header('X-Refreshed-Token: ' . $newJwt);
37
+ }
38
+ } catch (Throwable) {
39
+ }
30
40
  }
31
41
  }
32
42
 
@@ -89,29 +99,35 @@ final class AuthMiddleware
89
99
  protected static function isAuthorized(): bool
90
100
  {
91
101
  $auth = Auth::getInstance();
92
- if (!isset($_COOKIE[Auth::$cookieName])) {
93
- unset($_SESSION[Auth::PAYLOAD_SESSION_KEY]);
102
+ $jwt = $_COOKIE[Auth::$cookieName] ?? Request::getBearerToken();
103
+
104
+ if (!$jwt) {
105
+ if (isset($_SESSION[Auth::PAYLOAD_SESSION_KEY])) {
106
+ unset($_SESSION[Auth::PAYLOAD_SESSION_KEY]);
107
+ }
94
108
  return false;
95
109
  }
96
110
 
97
- $jwt = $_COOKIE[Auth::$cookieName];
98
-
99
111
  if (AuthConfig::IS_TOKEN_AUTO_REFRESH) {
100
- $jwt = $auth->refreshToken($jwt);
101
- $verifyToken = $auth->verifyToken($jwt);
112
+ try {
113
+ $jwt = $auth->refreshToken($jwt);
114
+
115
+ if (!isset($_COOKIE[Auth::$cookieName]) && !headers_sent()) {
116
+ header('Authorization: Bearer ' . $jwt);
117
+ header('X-Refreshed-Token: ' . $jwt);
118
+ }
119
+ } catch (Throwable) {
120
+ return false;
121
+ }
102
122
  }
103
123
 
104
124
  $verifyToken = $auth->verifyToken($jwt);
125
+
105
126
  if ($verifyToken === false) {
106
127
  return false;
107
128
  }
108
129
 
109
- // Access the PAYLOAD_NAME property using the -> operator instead of array syntax
110
- if (isset($verifyToken->{Auth::PAYLOAD_NAME})) {
111
- return true;
112
- }
113
-
114
- return false;
130
+ return isset($verifyToken->{Auth::PAYLOAD_NAME});
115
131
  }
116
132
 
117
133
  protected static function hasRequiredRole(string $requestPathname): string
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "create-prisma-php-app",
3
- "version": "4.3.7",
3
+ "version": "4.3.9",
4
4
  "description": "Prisma-PHP: A Revolutionary Library Bridging PHP with Prisma ORM",
5
5
  "main": "dist/index.js",
6
6
  "type": "module",