2FAuth/app/Api/v1/Resources/UserAuthenticationResource.php

77 lines
2.3 KiB
PHP
Raw Normal View History

2024-04-15 00:44:18 +02:00
<?php
namespace App\Api\v1\Resources;
use Carbon\CarbonInterface;
use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Support\Carbon;
use Jenssegers\Agent\Agent;
/**
* @property mixed $id
2024-04-20 19:03:44 +02:00
* @property string $ip_address
* @property string $user_agent
* @property string $browser
* @property string $platform
* @property string $device
* @property Carbon|null $login_at
* @property Carbon|null $logout_at
* @property bool $login_successful
* @property string|null $duration
* @property string|null $login_method
2024-04-15 00:44:18 +02:00
*/
class UserAuthenticationResource extends JsonResource
2024-04-15 00:44:18 +02:00
{
/**
* A user agent parser instance.
*
* @var mixed
*/
protected $agent;
/**
* Create a new resource instance.
*
* @param mixed $resource
* @return void
*/
public function __construct($resource)
{
2024-09-26 23:50:01 +02:00
$this->agent = new Agent;
2024-04-15 00:44:18 +02:00
$this->agent->setUserAgent($resource->user_agent);
parent::__construct($resource);
}
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
$tz = $request->user()?->preferences['timezone'] ?? config('app.timezone');
2024-04-15 00:44:18 +02:00
return [
2024-04-20 19:03:44 +02:00
'id' => $this->id,
'ip_address' => $this->ip_address,
'user_agent' => $this->user_agent,
'browser' => $this->agent->browser(),
'platform' => $this->agent->platform(),
'device' => $this->agent->deviceType(),
'login_at' => $this->login_at
2024-04-26 08:01:20 +02:00
? Carbon::parse($this->login_at)->tz($tz)->toDayDateTimeString()
: null,
2024-04-20 19:03:44 +02:00
'logout_at' => $this->logout_at
? Carbon::parse($this->logout_at)->tz($tz)->toDayDateTimeString()
: null,
2024-04-15 00:44:18 +02:00
'login_successful' => $this->login_successful,
'duration' => $this->logout_at
? Carbon::parse($this->logout_at)->diffForHumans(Carbon::parse($this->login_at), ['syntax' => CarbonInterface::DIFF_ABSOLUTE])
: null,
2024-04-26 08:01:20 +02:00
'login_method' => $this->login_method,
2024-04-15 00:44:18 +02:00
];
}
}