Skip to content

Commit cc421c4

Browse files
committed
refactor: move Traits/UserProvider into UserModel
1 parent 59bca13 commit cc421c4

File tree

2 files changed

+68
-82
lines changed

2 files changed

+68
-82
lines changed

src/Authentication/Traits/UserProvider.php

Lines changed: 0 additions & 79 deletions
This file was deleted.

src/Models/UserModel.php

Lines changed: 68 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,15 +3,12 @@
33
namespace CodeIgniter\Shield\Models;
44

55
use CodeIgniter\Model;
6-
use CodeIgniter\Shield\Authentication\Traits\UserProvider as UserProviderTrait;
76
use CodeIgniter\Shield\Entities\User;
87
use Faker\Generator;
98
use InvalidArgumentException;
109

1110
class UserModel extends Model
1211
{
13-
use UserProviderTrait;
14-
1512
protected $table = 'users';
1613
protected $primaryKey = 'id';
1714
protected $returnType = User::class;
@@ -119,4 +116,72 @@ public function fake(Generator &$faker): User
119116
'active' => true,
120117
]);
121118
}
119+
120+
/**
121+
* Locates a User object by ID.
122+
*
123+
* @param int|string $id
124+
*/
125+
public function findById($id): ?User
126+
{
127+
return $this->find($id);
128+
}
129+
130+
/**
131+
* Locate a User object by the given credentials.
132+
*
133+
* @param array<string, string> $credentials
134+
*/
135+
public function findByCredentials(array $credentials): ?User
136+
{
137+
// Email is stored in an identity so remove that here
138+
$email = $credentials['email'] ?? null;
139+
unset($credentials['email']);
140+
141+
$prefix = $this->db->DBPrefix;
142+
143+
// any of the credentials used should be case-insensitive
144+
foreach ($credentials as $key => $value) {
145+
$this->where("LOWER({$prefix}users.{$key})", strtolower($value));
146+
}
147+
148+
if (! empty($email)) {
149+
$data = $this->select('users.*, auth_identities.secret as email, auth_identities.secret2 as password_hash')
150+
->join('auth_identities', 'auth_identities.user_id = users.id')
151+
->where('auth_identities.type', 'email_password')
152+
->where("LOWER({$prefix}auth_identities.secret)", strtolower($email))
153+
->asArray()
154+
->first();
155+
156+
if ($data === null) {
157+
return null;
158+
}
159+
160+
$email = $data['email'];
161+
unset($data['email']);
162+
$password_hash = $data['password_hash'];
163+
unset($data['password_hash']);
164+
165+
$user = new User($data);
166+
$user->email = $email;
167+
$user->password_hash = $password_hash;
168+
169+
return $user;
170+
}
171+
172+
return $this->first();
173+
}
174+
175+
/**
176+
* Find a User object by their ID and "remember-me" token.
177+
*
178+
* @param int|string $id
179+
*/
180+
public function findByRememberToken($id, string $token): ?User
181+
{
182+
return $this->where([
183+
'id' => $id,
184+
'remember_me' => trim($token),
185+
])->first();
186+
}
122187
}

0 commit comments

Comments
 (0)