Skip to content

feat: Add ParseUser::logInAs method #486

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 7 commits into from
Apr 29, 2023
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions src/Parse/ParseUser.php
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,33 @@ public static function logIn($username, $password)
return $user;
}

/**
* Uses the master key to log in and return a valid ParseUser, or throws if invalid.
*
* @param $userId
*
* @throws ParseException
*
* @return ParseUser
*/
public static function logInAs($userId)
{
if (!$userId) {
throw new ParseException(
'Cannot log in as user with an empty user id',
200
);
}
$data = ['userId' => $userId];
$result = ParseClient::_request('POST', 'loginAs', '', json_encode($data), true);
$user = new static();
$user->_mergeAfterFetch($result);
$user->handleSaveResult(true);
ParseClient::getStorage()->set('user', $user);

return $user;
}

/**
* Logs in with Facebook details, or throws if invalid.
*
Expand Down
27 changes: 27 additions & 0 deletions tests/Parse/ParseUserTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,33 @@ public function testLoginWrongPassword()
ParseUser::logIn('asdf', 'bogus');
}

public function testLoginAsSuccess()
{
$user = new ParseUser();
$user->setUsername('plainusername');
$user->setPassword('plainpassword');
$user->signUp();

$id = $user->getObjectId();
$loggedInUser = ParseUser::logInAs($id);
$this->assertTrue($loggedInUser->isAuthenticated());
$this->assertEquals('plainusername', $loggedInUser->get('username'));

ParseUser::logOut();
}

public function testLoginAsEmptyUsername()
{
$this->expectException('Parse\ParseException', 'Cannot log in as user with an empty user id.');
ParseUser::logInAs('');
}

public function testLoginAsNonexistentUser()
{
$this->expectException('Parse\ParseException', 'user not found.');
ParseUser::logInAs('a1b2c3d4e5');
}

public function testLoginWithFacebook()
{
$this->expectException(
Expand Down