Skip to content

Commit 5b4e102

Browse files
authored
feat: Add ParseUser::logInAs method (#486)
1 parent dfe2957 commit 5b4e102

File tree

2 files changed

+54
-0
lines changed

2 files changed

+54
-0
lines changed

src/Parse/ParseUser.php

+27
Original file line numberDiff line numberDiff line change
@@ -157,6 +157,33 @@ public static function logIn($username, $password)
157157
return $user;
158158
}
159159

160+
/**
161+
* Uses the master key to log in and return a valid ParseUser, or throws if invalid.
162+
*
163+
* @param $userId
164+
*
165+
* @throws ParseException
166+
*
167+
* @return ParseUser
168+
*/
169+
public static function logInAs($userId)
170+
{
171+
if (!$userId) {
172+
throw new ParseException(
173+
'Cannot log in as user with an empty user id',
174+
200
175+
);
176+
}
177+
$data = ['userId' => $userId];
178+
$result = ParseClient::_request('POST', 'loginAs', '', json_encode($data), true);
179+
$user = new static();
180+
$user->_mergeAfterFetch($result);
181+
$user->handleSaveResult(true);
182+
ParseClient::getStorage()->set('user', $user);
183+
184+
return $user;
185+
}
186+
160187
/**
161188
* Logs in with Facebook details, or throws if invalid.
162189
*

tests/Parse/ParseUserTest.php

+27
Original file line numberDiff line numberDiff line change
@@ -83,6 +83,33 @@ public function testLoginWrongPassword()
8383
ParseUser::logIn('asdf', 'bogus');
8484
}
8585

86+
public function testLoginAsSuccess()
87+
{
88+
$user = new ParseUser();
89+
$user->setUsername('plainusername');
90+
$user->setPassword('plainpassword');
91+
$user->signUp();
92+
93+
$id = $user->getObjectId();
94+
$loggedInUser = ParseUser::logInAs($id);
95+
$this->assertTrue($loggedInUser->isAuthenticated());
96+
$this->assertEquals('plainusername', $loggedInUser->get('username'));
97+
98+
ParseUser::logOut();
99+
}
100+
101+
public function testLoginAsEmptyUsername()
102+
{
103+
$this->expectException('Parse\ParseException', 'Cannot log in as user with an empty user id.');
104+
ParseUser::logInAs('');
105+
}
106+
107+
public function testLoginAsNonexistentUser()
108+
{
109+
$this->expectException('Parse\ParseException', 'user not found.');
110+
ParseUser::logInAs('a1b2c3d4e5');
111+
}
112+
86113
public function testLoginWithFacebook()
87114
{
88115
$this->expectException(

0 commit comments

Comments
 (0)