File tree Expand file tree Collapse file tree 3 files changed +63
-0
lines changed
Expand file tree Collapse file tree 3 files changed +63
-0
lines changed Original file line number Diff line number Diff line change @@ -242,6 +242,17 @@ public function getPasswordHash(): ?string
242242 return $ this ->password_hash ;
243243 }
244244
245+ /**
246+ * Returns the previous login information for this user
247+ */
248+ public function previousLogin (): ?Login
249+ {
250+ /** @var LoginModel $logins */
251+ $ logins = model (LoginModel::class);
252+
253+ return $ logins ->previousLogin ($ this );
254+ }
255+
245256 /**
246257 * Returns the last login information for this user as
247258 */
Original file line number Diff line number Diff line change @@ -67,6 +67,19 @@ public function recordLoginAttempt(
6767 $ this ->checkQueryReturn ($ return );
6868 }
6969
70+ /**
71+ * Returns the previous login information for the user,
72+ * useful to display to the user the last time the account
73+ * was accessed.
74+ */
75+ public function previousLogin (User $ user ): ?Login
76+ {
77+ return $ this ->where ('success ' , 1 )
78+ ->where ('user_id ' , $ user ->id )
79+ ->orderBy ('id ' , 'desc ' )
80+ ->limit (1 , 1 )->first ();
81+ }
82+
7083 /**
7184 * Returns the last login information for the user
7285 */
Original file line number Diff line number Diff line change @@ -114,6 +114,45 @@ public function testLastLogin(): void
114114 $ this ->assertInstanceOf (Time::class, $ last ->date );
115115 }
116116
117+ public function testPreviousLogin (): void
118+ {
119+ fake (
120+ UserIdentityModel::class,
121+ ['user_id ' => $ this ->user ->id , 'type ' => Session::ID_TYPE_EMAIL_PASSWORD , 'secret ' => 'foo@example.com ' ]
122+ );
123+
124+ // No logins found.
125+ $ this ->assertNull ($ this ->user ->previousLogin ());
126+
127+ $ login1 = fake (
128+ LoginModel::class,
129+ ['id_type ' => 'email ' , 'identifier ' => $ this ->user ->email , 'user_id ' => $ this ->user ->id ]
130+ );
131+
132+ // The very most login is skipped.
133+ $ this ->assertNull ($ this ->user ->previousLogin ());
134+
135+ fake (
136+ LoginModel::class,
137+ ['id_type ' => 'email ' , 'identifier ' => $ this ->user ->email , 'user_id ' => $ this ->user ->id ]
138+ );
139+ fake (
140+ LoginModel::class,
141+ [
142+ 'id_type ' => 'email ' ,
143+ 'identifier ' => $ this ->user ->email ,
144+ 'user_id ' => $ this ->user ->id ,
145+ 'success ' => false ,
146+ ]
147+ );
148+
149+ $ previous = $ this ->user ->previousLogin ();
150+
151+ $ this ->assertInstanceOf (Login::class, $ previous ); // @phpstan-ignore-line
152+ $ this ->assertSame ($ login1 ->id , $ previous ->id );
153+ $ this ->assertInstanceOf (Time::class, $ previous ->date );
154+ }
155+
117156 /**
118157 * @see https://github.com/codeigniter4/shield/issues/103
119158 */
You can’t perform that action at this time.
0 commit comments