Skip to content

Commit 838ca9a

Browse files
committed
feat: add TokenLoginModel
1 parent 06a51fe commit 838ca9a

File tree

1 file changed

+75
-0
lines changed

1 file changed

+75
-0
lines changed

src/Models/TokenLoginModel.php

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
<?php
2+
3+
namespace CodeIgniter\Shield\Models;
4+
5+
use CodeIgniter\I18n\Time;
6+
use CodeIgniter\Model;
7+
use CodeIgniter\Shield\Entities\Login;
8+
use Exception;
9+
use Faker\Generator;
10+
11+
class TokenLoginModel extends Model
12+
{
13+
use CheckQueryReturnTrait;
14+
15+
protected $table = 'auth_token_logins';
16+
protected $primaryKey = 'id';
17+
protected $returnType = Login::class;
18+
protected $useSoftDeletes = false;
19+
protected $allowedFields = [
20+
'ip_address',
21+
'user_agent',
22+
'identifier',
23+
'user_id',
24+
'date',
25+
'success',
26+
];
27+
protected $useTimestamps = false;
28+
protected $validationRules = [
29+
'ip_address' => 'required',
30+
'identifier' => 'required',
31+
'user_agent' => 'permit_empty|string',
32+
'user_id' => 'permit_empty|integer',
33+
'date' => 'required|valid_date',
34+
];
35+
protected $validationMessages = [];
36+
protected $skipValidation = false;
37+
38+
/**
39+
* @param int|string|null $userId
40+
*/
41+
public function recordLoginAttempt(
42+
string $identifier,
43+
bool $success,
44+
?string $ipAddress = null,
45+
?string $userAgent = null,
46+
$userId = null
47+
): void {
48+
$return = $this->insert([
49+
'ip_address' => $ipAddress,
50+
'user_agent' => $userAgent,
51+
'identifier' => $identifier,
52+
'user_id' => $userId,
53+
'date' => date('Y-m-d H:i:s'),
54+
'success' => (int) $success,
55+
]);
56+
57+
$this->checkQueryReturn($return);
58+
}
59+
60+
/**
61+
* Generate a fake login for testing
62+
*
63+
* @throws Exception
64+
*/
65+
public function fake(Generator &$faker): Login
66+
{
67+
return new Login([
68+
'ip_address' => $faker->ipv4,
69+
'identifier' => 'token: ' . random_string('crypto', 64),
70+
'user_id' => fake(UserModel::class)->id,
71+
'date' => Time::parse('-1 day')->toDateTimeString(),
72+
'success' => true,
73+
]);
74+
}
75+
}

0 commit comments

Comments
 (0)