44
55namespace Codeception \Module \Laravel ;
66
7+ use Illuminate \Auth \GuardHelpers ;
78use Illuminate \Contracts \Auth \Authenticatable ;
89
910trait InteractsWithAuthentication
@@ -40,6 +41,60 @@ public function amLoggedAs($user, string $guardName = null): void
4041 );
4142 }
4243
44+ /**
45+ * Set the given user object to the current or specified Guard.
46+ */
47+ public function amActingAs (Authenticatable $ user , string $ guardName = null ): void
48+ {
49+ if (isset ($ user ->wasRecentlyCreated ) && $ user ->wasRecentlyCreated ) {
50+ $ user ->wasRecentlyCreated = false ;
51+ }
52+
53+ $ this ->getAuth ()->guard ($ guardName )->setUser ($ user );
54+
55+ $ this ->getAuth ()->shouldUse ($ guardName );
56+ }
57+
58+ /**
59+ * Assert that the user is authenticated as the given user.
60+ */
61+ public function assertAuthenticatedAs (Authenticatable $ user , string $ guardName = null ): void
62+ {
63+ $ expected = $ this ->getAuth ()->guard ($ guardName )->user ();
64+
65+ $ this ->assertNotNull ($ expected , 'The current user is not authenticated. ' );
66+
67+ $ this ->assertInstanceOf (
68+ get_class ($ expected ), $ user ,
69+ 'The currently authenticated user is not who was expected '
70+ );
71+
72+ $ this ->assertSame (
73+ $ expected ->getAuthIdentifier (), $ user ->getAuthIdentifier (),
74+ 'The currently authenticated user is not who was expected '
75+ );
76+ }
77+
78+ /**
79+ * Assert that the given credentials are valid.
80+ */
81+ public function assertCredentials (array $ credentials , string $ guardName = null ): void
82+ {
83+ $ this ->assertTrue (
84+ $ this ->hasCredentials ($ credentials , $ guardName ), 'The given credentials are invalid. '
85+ );
86+ }
87+
88+ /**
89+ * Assert that the given credentials are invalid.
90+ */
91+ public function assertInvalidCredentials (array $ credentials , string $ guardName = null ): void
92+ {
93+ $ this ->assertFalse (
94+ $ this ->hasCredentials ($ credentials , $ guardName ), 'The given credentials are valid. '
95+ );
96+ }
97+
4398 /**
4499 * Check that user is not authenticated.
45100 */
@@ -64,6 +119,20 @@ public function logout(): void
64119 $ this ->getAuth ()->logout ();
65120 }
66121
122+ /**
123+ * Return true if the credentials are valid, false otherwise.
124+ */
125+ protected function hasCredentials (array $ credentials , string $ guardName = null ): bool
126+ {
127+ /** @var GuardHelpers $guard */
128+ $ guard = $ this ->getAuth ()->guard ($ guardName );
129+ $ provider = $ guard ->getProvider ();
130+
131+ $ user = $ provider ->retrieveByCredentials ($ credentials );
132+
133+ return $ user && $ provider ->validateCredentials ($ user , $ credentials );
134+ }
135+
67136 /**
68137 * Return true if the user is authenticated, false otherwise.
69138 */
0 commit comments