'array', 'user_id' => 'int', 'r_' . AdminAcl::RESOURCE_USERS => 'int', 'r_' . AdminAcl::RESOURCE_ALLOCATIONS => 'int', 'r_' . AdminAcl::RESOURCE_DATABASE_HOSTS => 'int', 'r_' . AdminAcl::RESOURCE_SERVER_DATABASES => 'int', 'r_' . AdminAcl::RESOURCE_EGGS => 'int', 'r_' . AdminAcl::RESOURCE_LOCATIONS => 'int', 'r_' . AdminAcl::RESOURCE_NESTS => 'int', 'r_' . AdminAcl::RESOURCE_NODES => 'int', 'r_' . AdminAcl::RESOURCE_SERVERS => 'int', ]; /** * Fields that are mass assignable. */ protected $fillable = [ 'identifier', 'token', 'allowed_ips', 'memo', 'last_used_at', ]; /** * Fields that should not be included when calling toArray() or toJson() * on this model. */ protected $hidden = ['token']; /** * Rules to protect against invalid data entry to DB. */ public static array $validationRules = [ 'user_id' => 'required|exists:users,id', 'key_type' => 'present|integer|min:0|max:4', 'identifier' => 'required|string|size:16|unique:api_keys,identifier', 'token' => 'required|string', 'memo' => 'required|nullable|string|max:500', 'allowed_ips' => 'nullable|array', 'allowed_ips.*' => 'string', 'last_used_at' => 'nullable|date', 'r_' . AdminAcl::RESOURCE_USERS => 'integer|min:0|max:3', 'r_' . AdminAcl::RESOURCE_ALLOCATIONS => 'integer|min:0|max:3', 'r_' . AdminAcl::RESOURCE_DATABASE_HOSTS => 'integer|min:0|max:3', 'r_' . AdminAcl::RESOURCE_SERVER_DATABASES => 'integer|min:0|max:3', 'r_' . AdminAcl::RESOURCE_EGGS => 'integer|min:0|max:3', 'r_' . AdminAcl::RESOURCE_LOCATIONS => 'integer|min:0|max:3', 'r_' . AdminAcl::RESOURCE_NESTS => 'integer|min:0|max:3', 'r_' . AdminAcl::RESOURCE_NODES => 'integer|min:0|max:3', 'r_' . AdminAcl::RESOURCE_SERVERS => 'integer|min:0|max:3', ]; protected $dates = [ self::CREATED_AT, self::UPDATED_AT, 'last_used_at', ]; /** * Returns the user this token is assigned to. */ public function user(): BelongsTo { return $this->belongsTo(User::class); } /** * Required for support with Laravel Sanctum. * * @see \Laravel\Sanctum\Guard::supportsTokens() */ public function tokenable(): BelongsTo { return $this->user(); } /** * Finds the model matching the provided token. */ public static function findToken(string $token): ?self { $identifier = substr($token, 0, self::IDENTIFIER_LENGTH); $model = static::where('identifier', $identifier)->first(); if (!is_null($model) && decrypt($model->token) === substr($token, strlen($identifier))) { return $model; } return null; } /** * Returns the standard prefix for API keys in the system. */ public static function getPrefixForType(int $type): string { Assert::oneOf($type, [self::TYPE_ACCOUNT, self::TYPE_APPLICATION]); return $type === self::TYPE_ACCOUNT ? 'ptlc_' : 'ptla_'; } /** * Generates a new identifier for an API key. */ public static function generateTokenIdentifier(int $type): string { $prefix = self::getPrefixForType($type); return $prefix . Str::random(self::IDENTIFIER_LENGTH - strlen($prefix)); } }