|
2 | 2 |
|
3 | 3 | namespace ProcessMaker\Http\Resources; |
4 | 4 |
|
5 | | -use Illuminate\Http\Resources\Json\ResourceCollection; |
| 5 | +use Illuminate\Http\Request; |
| 6 | +use Laravel\Passport\PersonalAccessTokenResult; |
| 7 | +use Laravel\Passport\Token; |
6 | 8 |
|
7 | 9 | class UserTokenResource extends ApiResource |
8 | 10 | { |
| 11 | + /** |
| 12 | + * Transform the resource into an array. |
| 13 | + * |
| 14 | + * @param Request $request |
| 15 | + * @return array |
| 16 | + */ |
| 17 | + public function toArray($request) |
| 18 | + { |
| 19 | + // Handle PersonalAccessTokenResult (from token creation) |
| 20 | + if ($this->resource instanceof PersonalAccessTokenResult) { |
| 21 | + $token = $this->resource->getToken(); |
| 22 | + |
| 23 | + return [ |
| 24 | + 'accessToken' => $this->resource->accessToken, |
| 25 | + 'token' => $this->formatTokenModel($token), |
| 26 | + ]; |
| 27 | + } |
| 28 | + |
| 29 | + // Handle Token model (from token retrieval) |
| 30 | + if ($this->resource instanceof Token) { |
| 31 | + return $this->formatTokenModel($this->resource); |
| 32 | + } |
| 33 | + |
| 34 | + // Fallback to parent implementation |
| 35 | + return parent::toArray($request); |
| 36 | + } |
| 37 | + |
| 38 | + /** |
| 39 | + * Format the token model into the expected array structure. |
| 40 | + * |
| 41 | + * @param Token $token |
| 42 | + * @return array |
| 43 | + */ |
| 44 | + protected function formatTokenModel(Token $token): array |
| 45 | + { |
| 46 | + // Ensure scopes is always an array |
| 47 | + $scopes = $token->scopes; |
| 48 | + if (is_string($scopes)) { |
| 49 | + $scopes = json_decode($scopes, true) ?? []; |
| 50 | + } |
| 51 | + if (!is_array($scopes)) { |
| 52 | + $scopes = []; |
| 53 | + } |
| 54 | + |
| 55 | + return [ |
| 56 | + 'id' => $token->id, |
| 57 | + 'user_id' => $token->user_id, |
| 58 | + 'client_id' => $token->client_id, |
| 59 | + 'name' => $token->name, |
| 60 | + 'scopes' => $scopes, |
| 61 | + 'revoked' => (bool) $token->revoked, |
| 62 | + 'created_at' => $token->created_at ? $token->created_at->toIso8601String() : null, |
| 63 | + 'updated_at' => $token->updated_at ? $token->updated_at->toIso8601String() : null, |
| 64 | + 'expires_at' => $token->expires_at ? $token->expires_at->toIso8601String() : null, |
| 65 | + ]; |
| 66 | + } |
9 | 67 | } |
0 commit comments