Page MenuHomePhorge

No OneTemporary

diff --git a/src/aphront/configuration/AphrontDefaultApplicationConfiguration.php b/src/aphront/configuration/AphrontDefaultApplicationConfiguration.php
index 94813a1902..1600f01e2c 100644
--- a/src/aphront/configuration/AphrontDefaultApplicationConfiguration.php
+++ b/src/aphront/configuration/AphrontDefaultApplicationConfiguration.php
@@ -1,365 +1,341 @@
<?php
/**
* @group aphront
*/
class AphrontDefaultApplicationConfiguration
extends AphrontApplicationConfiguration {
public function __construct() {
}
public function getApplicationName() {
return 'aphront-default';
}
public function getURIMap() {
return $this->getResourceURIMapRules() + array(
'/(?:(?P<filter>(?:jump))/)?' =>
'PhabricatorDirectoryMainController',
'/typeahead/' => array(
'common/(?P<type>\w+)/'
=> 'PhabricatorTypeaheadCommonDatasourceController',
),
- '/login/' => array(
- '' => 'PhabricatorLoginController',
- 'email/' => 'PhabricatorEmailLoginController',
- 'etoken/(?P<token>\w+)/' => 'PhabricatorEmailTokenController',
- 'refresh/' => 'PhabricatorRefreshCSRFController',
- 'validate/' => 'PhabricatorLoginValidateController',
- 'mustverify/' => 'PhabricatorMustVerifyEmailController',
- ),
-
- '/logout/' => 'PhabricatorLogoutController',
-
- '/oauth/' => array(
- '(?P<provider>\w+)/' => array(
- 'login/' => 'PhabricatorOAuthLoginController',
- 'diagnose/' => 'PhabricatorOAuthDiagnosticsController',
- 'unlink/' => 'PhabricatorOAuthUnlinkController',
- ),
- ),
-
- '/ldap/' => array(
- 'login/' => 'PhabricatorLDAPLoginController',
- 'unlink/' => 'PhabricatorLDAPUnlinkController',
- ),
-
'/oauthserver/' => array(
'auth/' => 'PhabricatorOAuthServerAuthController',
'test/' => 'PhabricatorOAuthServerTestController',
'token/' => 'PhabricatorOAuthServerTokenController',
'clientauthorization/' => array(
'' => 'PhabricatorOAuthClientAuthorizationListController',
'delete/(?P<phid>[^/]+)/' =>
'PhabricatorOAuthClientAuthorizationDeleteController',
'edit/(?P<phid>[^/]+)/' =>
'PhabricatorOAuthClientAuthorizationEditController',
),
'client/' => array(
'' => 'PhabricatorOAuthClientListController',
'create/' => 'PhabricatorOAuthClientEditController',
'delete/(?P<phid>[^/]+)/' => 'PhabricatorOAuthClientDeleteController',
'edit/(?P<phid>[^/]+)/' => 'PhabricatorOAuthClientEditController',
'view/(?P<phid>[^/]+)/' => 'PhabricatorOAuthClientViewController',
),
),
'/~/' => array(
'' => 'DarkConsoleController',
'data/(?P<key>[^/]+)/' => 'DarkConsoleDataController',
),
'/status/' => 'PhabricatorStatusController',
'/help/' => array(
'keyboardshortcut/' => 'PhabricatorHelpKeyboardShortcutController',
),
'/notification/' => array(
'(?:(?P<filter>all|unread)/)?'
=> 'PhabricatorNotificationListController',
'panel/' => 'PhabricatorNotificationPanelController',
'individual/' => 'PhabricatorNotificationIndividualController',
'status/' => 'PhabricatorNotificationStatusController',
'clear/' => 'PhabricatorNotificationClearController',
),
'/debug/' => 'PhabricatorDebugController',
);
}
protected function getResourceURIMapRules() {
return array(
'/res/' => array(
'(?:(?P<mtime>[0-9]+)T/)?'.
'(?P<package>pkg/)?'.
'(?P<hash>[a-f0-9]{8})/'.
'(?P<path>.+\.(?:css|js|jpg|png|swf|gif))'
=> 'CelerityPhabricatorResourceController',
),
);
}
public function buildRequest() {
$request = new AphrontRequest($this->getHost(), $this->getPath());
$request->setRequestData($_GET + $_POST);
$request->setApplicationConfiguration($this);
return $request;
}
public function handleException(Exception $ex) {
$request = $this->getRequest();
// For Conduit requests, return a Conduit response.
if ($request->isConduit()) {
$response = new ConduitAPIResponse();
$response->setErrorCode(get_class($ex));
$response->setErrorInfo($ex->getMessage());
return id(new AphrontJSONResponse())
->setAddJSONShield(false)
->setContent($response->toDictionary());
}
// For non-workflow requests, return a Ajax response.
if ($request->isAjax() && !$request->isJavelinWorkflow()) {
$response = new AphrontAjaxResponse();
$response->setError(
array(
'code' => get_class($ex),
'info' => $ex->getMessage(),
));
return $response;
}
$is_serious = PhabricatorEnv::getEnvConfig('phabricator.serious-business');
$user = $request->getUser();
if (!$user) {
// If we hit an exception very early, we won't have a user.
$user = new PhabricatorUser();
}
if ($ex instanceof PhabricatorPolicyException) {
if (!$user->isLoggedIn()) {
// If the user isn't logged in, just give them a login form. This is
// probably a generally more useful response than a policy dialog that
// they have to click through to get a login form.
//
// Possibly we should add a header here like "you need to login to see
// the thing you are trying to look at".
$login_controller = new PhabricatorLoginController($request);
return $login_controller->processRequest();
}
$content = hsprintf(
'<div class="aphront-policy-exception">%s</div>',
$ex->getMessage());
$dialog = new AphrontDialogView();
$dialog
->setTitle(
$is_serious
? 'Access Denied'
: "You Shall Not Pass")
->setClass('aphront-access-dialog')
->setUser($user)
->appendChild($content);
if ($this->getRequest()->isAjax()) {
$dialog->addCancelButton('/', 'Close');
} else {
$dialog->addCancelButton('/', $is_serious ? 'OK' : 'Away With Thee');
}
$response = new AphrontDialogResponse();
$response->setDialog($dialog);
return $response;
}
if ($ex instanceof AphrontUsageException) {
$error = new AphrontErrorView();
$error->setTitle($ex->getTitle());
$error->appendChild($ex->getMessage());
$view = new PhabricatorStandardPageView();
$view->setRequest($this->getRequest());
$view->appendChild($error);
$response = new AphrontWebpageResponse();
$response->setContent($view->render());
return $response;
}
// Always log the unhandled exception.
phlog($ex);
$class = get_class($ex);
$message = $ex->getMessage();
if ($ex instanceof AphrontQuerySchemaException) {
$message .=
"\n\n".
"NOTE: This usually indicates that the MySQL schema has not been ".
"properly upgraded. Run 'bin/storage upgrade' to ensure your ".
"schema is up to date.";
}
if (PhabricatorEnv::getEnvConfig('phabricator.developer-mode')) {
$trace = $this->renderStackTrace($ex->getTrace(), $user);
} else {
$trace = null;
}
$content = hsprintf(
'<div class="aphront-unhandled-exception">'.
'<div class="exception-message">%s</div>'.
'%s'.
'</div>',
$message,
$trace);
$dialog = new AphrontDialogView();
$dialog
->setTitle('Unhandled Exception ("'.$class.'")')
->setClass('aphront-exception-dialog')
->setUser($user)
->appendChild($content);
if ($this->getRequest()->isAjax()) {
$dialog->addCancelButton('/', 'Close');
}
$response = new AphrontDialogResponse();
$response->setDialog($dialog);
return $response;
}
public function willSendResponse(AphrontResponse $response) {
return $response;
}
public function build404Controller() {
return array(new Phabricator404Controller($this->getRequest()), array());
}
public function buildRedirectController($uri) {
return array(
new PhabricatorRedirectController($this->getRequest()),
array(
'uri' => $uri,
));
}
private function renderStackTrace($trace, PhabricatorUser $user) {
$libraries = PhutilBootloader::getInstance()->getAllLibraries();
// TODO: Make this configurable?
$path = 'https://secure.phabricator.com/diffusion/%s/browse/master/src/';
$callsigns = array(
'arcanist' => 'ARC',
'phutil' => 'PHU',
'phabricator' => 'P',
);
$rows = array();
$depth = count($trace);
foreach ($trace as $part) {
$lib = null;
$file = idx($part, 'file');
$relative = $file;
foreach ($libraries as $library) {
$root = phutil_get_library_root($library);
if (Filesystem::isDescendant($file, $root)) {
$lib = $library;
$relative = Filesystem::readablePath($file, $root);
break;
}
}
$where = '';
if (isset($part['class'])) {
$where .= $part['class'].'::';
}
if (isset($part['function'])) {
$where .= $part['function'].'()';
}
if ($file) {
if (isset($callsigns[$lib])) {
$attrs = array('title' => $file);
try {
$attrs['href'] = $user->loadEditorLink(
'/src/'.$relative,
$part['line'],
$callsigns[$lib]);
} catch (Exception $ex) {
// The database can be inaccessible.
}
if (empty($attrs['href'])) {
$attrs['href'] = sprintf($path, $callsigns[$lib]).
str_replace(DIRECTORY_SEPARATOR, '/', $relative).
'$'.$part['line'];
$attrs['target'] = '_blank';
}
$file_name = phutil_tag(
'a',
$attrs,
$relative);
} else {
$file_name = phutil_tag(
'span',
array(
'title' => $file,
),
$relative);
}
$file_name = hsprintf('%s : %d', $file_name, $part['line']);
} else {
$file_name = phutil_tag('em', array(), '(Internal)');
}
$rows[] = array(
$depth--,
$lib,
$file_name,
$where,
);
}
$table = new AphrontTableView($rows);
$table->setHeaders(
array(
'Depth',
'Library',
'File',
'Where',
));
$table->setColumnClasses(
array(
'n',
'',
'',
'wide',
));
return hsprintf(
'<div class="exception-trace">'.
'<div class="exception-trace-header">Stack Trace</div>'.
'%s'.
'</div>',
$table->render());
}
}
diff --git a/src/applications/auth/application/PhabricatorApplicationAuth.php b/src/applications/auth/application/PhabricatorApplicationAuth.php
index 68a3bd3177..0a5a263042 100644
--- a/src/applications/auth/application/PhabricatorApplicationAuth.php
+++ b/src/applications/auth/application/PhabricatorApplicationAuth.php
@@ -1,47 +1,70 @@
<?php
final class PhabricatorApplicationAuth extends PhabricatorApplication {
public function shouldAppearInLaunchView() {
return false;
}
public function canUninstall() {
return false;
}
public function getBaseURI() {
return '/auth/';
}
public function buildMainMenuItems(
PhabricatorUser $user,
PhabricatorController $controller = null) {
$items = array();
if ($user->isLoggedIn()) {
$item = new PHUIListItemView();
$item->setName(pht('Log Out'));
$item->setIcon('power');
$item->setWorkflow(true);
$item->setHref('/logout/');
$item->setSelected(($controller instanceof PhabricatorLogoutController));
$items[] = $item;
}
return $items;
}
public function getRoutes() {
return array(
'/auth/' => array(
'login/(?P<pkey>[^/]+)/' => 'PhabricatorAuthLoginController',
'register/(?:(?P<akey>[^/]+)/)?' => 'PhabricatorAuthRegisterController',
'start/' => 'PhabricatorAuthStartController',
'validate/' => 'PhabricatorAuthValidateController',
),
+
+ '/login/' => array(
+ '' => 'PhabricatorLoginController',
+ 'email/' => 'PhabricatorEmailLoginController',
+ 'etoken/(?P<token>\w+)/' => 'PhabricatorEmailTokenController',
+ 'refresh/' => 'PhabricatorRefreshCSRFController',
+ 'mustverify/' => 'PhabricatorMustVerifyEmailController',
+ ),
+
+ '/logout/' => 'PhabricatorLogoutController',
+
+ '/oauth/' => array(
+ '(?P<provider>\w+)/' => array(
+ 'login/' => 'PhabricatorOAuthLoginController',
+ 'diagnose/' => 'PhabricatorOAuthDiagnosticsController',
+ 'unlink/' => 'PhabricatorOAuthUnlinkController',
+ ),
+ ),
+
+ '/ldap/' => array(
+ 'login/' => 'PhabricatorLDAPLoginController',
+ 'unlink/' => 'PhabricatorLDAPUnlinkController',
+ ),
);
}
}
diff --git a/src/applications/auth/controller/PhabricatorEmailTokenController.php b/src/applications/auth/controller/PhabricatorEmailTokenController.php
index 6681b97118..1edd109011 100644
--- a/src/applications/auth/controller/PhabricatorEmailTokenController.php
+++ b/src/applications/auth/controller/PhabricatorEmailTokenController.php
@@ -1,108 +1,100 @@
<?php
final class PhabricatorEmailTokenController
extends PhabricatorAuthController {
private $token;
public function shouldRequireLogin() {
return false;
}
public function willProcessRequest(array $data) {
$this->token = $data['token'];
}
public function processRequest() {
$request = $this->getRequest();
$token = $this->token;
$email = $request->getStr('email');
// NOTE: We need to bind verification to **addresses**, not **users**,
// because we verify addresses when they're used to login this way, and if
// we have a user-based verification you can:
//
// - Add some address you do not own;
// - request a password reset;
// - change the URI in the email to the address you don't own;
// - login via the email link; and
// - get a "verified" address you don't control.
$target_email = id(new PhabricatorUserEmail())->loadOneWhere(
'address = %s',
$email);
$target_user = null;
if ($target_email) {
$target_user = id(new PhabricatorUser())->loadOneWhere(
'phid = %s',
$target_email->getUserPHID());
}
if (!$target_email ||
!$target_user ||
!$target_user->validateEmailToken($target_email, $token)) {
$view = new AphrontRequestFailureView();
$view->setHeader(pht('Unable to Login'));
$view->appendChild(phutil_tag('p', array(), pht(
'The authentication information in the link you clicked is '.
'invalid or out of date. Make sure you are copy-and-pasting the '.
'entire link into your browser. You can try again, or request '.
'a new email.')));
$view->appendChild(hsprintf(
'<div class="aphront-failure-continue">'.
'<a class="button" href="/login/email/">%s</a>'.
'</div>',
pht('Send Another Email')));
return $this->buildStandardPageResponse(
$view,
array(
'title' => pht('Login Failure'),
));
}
// Verify email so that clicking the link in the "Welcome" email is good
// enough, without requiring users to go through a second round of email
// verification.
$unguarded = AphrontWriteGuard::beginScopedUnguardedWrites();
$target_email->setIsVerified(1);
$target_email->save();
- $session_key = $target_user->establishSession('web');
unset($unguarded);
- $request->setCookie('phusr', $target_user->getUsername());
- $request->setCookie('phsid', $session_key);
+ $this->establishWebSession($target_user);
$next = '/';
if (!PhabricatorEnv::getEnvConfig('auth.password-auth-enabled')) {
$panels = id(new PhabricatorSettingsPanelOAuth())->buildPanels();
foreach ($panels as $panel) {
if ($panel->isEnabled()) {
$next = $panel->getPanelURI();
break;
}
}
} else if (PhabricatorEnv::getEnvConfig('account.editable')) {
$next = (string)id(new PhutilURI('/settings/panel/password/'))
->setQueryParams(
array(
'token' => $token,
'email' => $email,
));
}
- $uri = new PhutilURI('/login/validate/');
- $uri->setQueryParams(
- array(
- 'phusr' => $target_user->getUsername(),
- 'next' => $next,
- ));
+ $request->setCookie('next_uri', $next);
- return id(new AphrontRedirectResponse())
- ->setURI((string)$uri);
+ return $this->buildLoginValidateResponse($target_user);
}
}
diff --git a/src/applications/auth/controller/PhabricatorLDAPLoginController.php b/src/applications/auth/controller/PhabricatorLDAPLoginController.php
index 945e78dc61..99a3628024 100644
--- a/src/applications/auth/controller/PhabricatorLDAPLoginController.php
+++ b/src/applications/auth/controller/PhabricatorLDAPLoginController.php
@@ -1,179 +1,170 @@
<?php
final class PhabricatorLDAPLoginController extends PhabricatorAuthController {
private $provider;
public function shouldRequireLogin() {
return false;
}
public function willProcessRequest(array $data) {
$this->provider = new PhabricatorLDAPProvider();
}
public function processRequest() {
if (!$this->provider->isProviderEnabled()) {
return new Aphront400Response();
}
$current_user = $this->getRequest()->getUser();
$request = $this->getRequest();
$ldap_username = $request->getCookie('phusr');
if ($request->isFormPost()) {
$ldap_username = $request->getStr('username');
try {
$envelope = new PhutilOpaqueEnvelope($request->getStr('password'));
$this->provider->auth($ldap_username, $envelope);
} catch (Exception $e) {
$errors[] = $e->getMessage();
}
if (empty($errors)) {
$ldap_info = $this->retrieveLDAPInfo($this->provider);
if ($current_user->getPHID()) {
if ($ldap_info->getID()) {
$existing_ldap = id(new PhabricatorExternalAccount())->loadOneWhere(
'accountType = %s AND accountDomain = %s AND userPHID = %s',
'ldap',
'self',
$current_user->getPHID());
if ($ldap_info->getUserPHID() != $current_user->getPHID() ||
$existing_ldap) {
$dialog = new AphrontDialogView();
$dialog->setUser($current_user);
$dialog->setTitle(pht('Already Linked to Another Account'));
$dialog->appendChild(phutil_tag('p', array(), pht(
'The LDAP account you just authorized is already '.
'linked toanother Phabricator account. Before you can link it '.
'to a different LDAP account, you must unlink the old '.
'account.')));
$dialog->addCancelButton('/settings/panel/ldap/');
return id(new AphrontDialogResponse())->setDialog($dialog);
} else {
return id(new AphrontRedirectResponse())
->setURI('/settings/panel/ldap/');
}
}
if (!$request->isDialogFormPost()) {
$dialog = new AphrontDialogView();
$dialog->setUser($current_user);
$dialog->setTitle(pht('Link LDAP Account'));
$dialog->appendChild(phutil_tag('p', array(), pht(
'Link your LDAP account to your Phabricator account?')));
$dialog->addHiddenInput('username', $request->getStr('username'));
$dialog->addHiddenInput('password', $request->getStr('password'));
$dialog->addSubmitButton(pht('Link Accounts'));
$dialog->addCancelButton('/settings/panel/ldap/');
return id(new AphrontDialogResponse())->setDialog($dialog);
}
$ldap_info->setUserPHID($current_user->getPHID());
$this->saveLDAPInfo($ldap_info);
return id(new AphrontRedirectResponse())
->setURI('/settings/panel/ldap/');
}
- if ($ldap_info->getID()) {
+ if ($ldap_info->getUserPHID()) {
$unguarded = AphrontWriteGuard::beginScopedUnguardedWrites();
$known_user = id(new PhabricatorUser())->loadOneWhere(
'phid = %s',
$ldap_info->getUserPHID());
- $session_key = $known_user->establishSession('web');
-
$this->saveLDAPInfo($ldap_info);
- $request->setCookie('phusr', $known_user->getUsername());
- $request->setCookie('phsid', $session_key);
-
- $uri = new PhutilURI('/login/validate/');
- $uri->setQueryParams(
- array(
- 'phusr' => $known_user->getUsername(),
- ));
+ $this->establishWebSession($known_user);
- return id(new AphrontRedirectResponse())->setURI((string)$uri);
+ return $this->buildLoginValidateResponse($known_user);
}
$controller = newv('PhabricatorLDAPRegistrationController',
array($this->getRequest()));
$controller->setLDAPProvider($this->provider);
$controller->setLDAPInfo($ldap_info);
return $this->delegateToController($controller);
}
}
$ldap_form = new AphrontFormView();
$ldap_form
->setUser($request->getUser())
->setAction('/ldap/login/')
->appendChild(
id(new AphrontFormTextControl())
->setLabel(pht('LDAP username'))
->setName('username')
->setValue($ldap_username))
->appendChild(
id(new AphrontFormPasswordControl())
->setLabel(pht('Password'))
->setName('password'));
$ldap_form
->appendChild(
id(new AphrontFormSubmitControl())
->setValue(pht('Login')));
$panel = new AphrontPanelView();
$panel->setWidth(AphrontPanelView::WIDTH_FORM);
$panel->appendChild(phutil_tag('h1', array(), pht('LDAP login')));
$panel->appendChild($ldap_form);
$error_view = null;
if (isset($errors) && count($errors) > 0) {
$error_view = new AphrontErrorView();
$error_view->setTitle(pht('Login Failed'));
$error_view->setErrors($errors);
}
return $this->buildStandardPageResponse(
array(
$error_view,
$panel,
),
array(
'title' => pht('Login'),
));
}
private function retrieveLDAPInfo(PhabricatorLDAPProvider $provider) {
$ldap_info = id(new PhabricatorExternalAccount())->loadOneWhere(
'accountType = %s AND accountDomain = %s AND accountID = %s',
'ldap',
'self',
$provider->retrieveUsername());
if (!$ldap_info) {
$ldap_info = id(new PhabricatorExternalAccount())
->setAccountType('ldap')
->setAccountDomain('self')
->setAccountID($provider->retrieveUsername());
}
return $ldap_info;
}
private function saveLDAPInfo(PhabricatorExternalAccount $info) {
// UNGUARDED WRITES: Logging-in users don't have their CSRF set up yet.
$unguarded = AphrontWriteGuard::beginScopedUnguardedWrites();
$info->save();
}
}
diff --git a/src/applications/auth/controller/PhabricatorLoginController.php b/src/applications/auth/controller/PhabricatorLoginController.php
index 19b589934d..e0087f452f 100644
--- a/src/applications/auth/controller/PhabricatorLoginController.php
+++ b/src/applications/auth/controller/PhabricatorLoginController.php
@@ -1,314 +1,304 @@
<?php
final class PhabricatorLoginController
extends PhabricatorAuthController {
public function shouldRequireLogin() {
return false;
}
public function processRequest() {
$request = $this->getRequest();
$user = $request->getUser();
if ($user->isLoggedIn()) {
// Kick the user out if they're already logged in.
return id(new AphrontRedirectResponse())->setURI('/');
}
if ($request->isAjax()) {
// We end up here if the user clicks a workflow link that they need to
// login to use. We give them a dialog saying "You need to login..".
if ($request->isDialogFormPost()) {
return id(new AphrontRedirectResponse())->setURI(
$request->getRequestURI());
}
$dialog = new AphrontDialogView();
$dialog->setUser($user);
$dialog->setTitle(pht('Login Required'));
$dialog->appendChild(phutil_tag('p', array(), pht(
'You must login to continue.')));
$dialog->addSubmitButton(pht('Login'));
$dialog->addCancelButton('/', pht('Cancel'));
return id(new AphrontDialogResponse())->setDialog($dialog);
}
if ($request->isConduit()) {
// A common source of errors in Conduit client configuration is getting
// the request path wrong. The client will end up here, so make some
// effort to give them a comprehensible error message.
$request_path = $this->getRequest()->getPath();
$conduit_path = '/api/<method>';
$example_path = '/api/conduit.ping';
$message =
"ERROR: You are making a Conduit API request to '{$request_path}', ".
"but the correct HTTP request path to use in order to access a ".
"Conduit method is '{$conduit_path}' (for example, ".
"'{$example_path}'). Check your configuration.";
return id(new AphrontPlainTextResponse())->setContent($message);
}
$error_view = null;
if ($request->getCookie('phusr') && $request->getCookie('phsid')) {
// The session cookie is invalid, so clear it.
$request->clearCookie('phusr');
$request->clearCookie('phsid');
$error_view = new AphrontErrorView();
$error_view->setTitle(pht('Invalid Session'));
$error_view->setErrors(array(
pht("Your login session is invalid. Try logging in again. If that ".
"doesn't work, clear your browser cookies.")
));
}
$next_uri = $request->getStr('next');
if (!$next_uri) {
$next_uri_path = $this->getRequest()->getPath();
if ($next_uri_path == '/login/') {
$next_uri = '/';
} else {
$next_uri = $this->getRequest()->getRequestURI();
}
}
if (!$request->isFormPost()) {
$request->setCookie('next_uri', $next_uri);
}
$password_auth = PhabricatorEnv::getEnvConfig('auth.password-auth-enabled');
$username_or_email = $request->getCookie('phusr');
$forms = array();
$errors = array();
if ($password_auth) {
$require_captcha = false;
$e_captcha = true;
if ($request->isFormPost()) {
if (AphrontFormRecaptchaControl::isRecaptchaEnabled()) {
$failed_attempts = PhabricatorUserLog::loadRecentEventsFromThisIP(
PhabricatorUserLog::ACTION_LOGIN_FAILURE,
60 * 15);
if (count($failed_attempts) > 5) {
$require_captcha = true;
if (!AphrontFormRecaptchaControl::processCaptcha($request)) {
if (AphrontFormRecaptchaControl::hasCaptchaResponse($request)) {
$e_captcha = pht('Invalid');
$errors[] = pht('CAPTCHA was not entered correctly.');
} else {
$e_captcha = pht('Required');
$errors[] = pht('Too many login failures recently. You must '.
'submit a CAPTCHA with your login request.');
}
}
}
}
$username_or_email = $request->getStr('username_or_email');
$user = id(new PhabricatorUser())->loadOneWhere(
'username = %s',
$username_or_email);
if (!$user) {
$user = PhabricatorUser::loadOneWithEmailAddress($username_or_email);
}
if (!$errors) {
// Perform username/password tests only if we didn't get rate limited
// by the CAPTCHA.
$envelope = new PhutilOpaqueEnvelope($request->getStr('password'));
if (!$user || !$user->comparePassword($envelope)) {
$errors[] = pht('Bad username/password.');
}
}
if (!$errors) {
- $session_key = $user->establishSession('web');
-
- $request->setCookie('phusr', $user->getUsername());
- $request->setCookie('phsid', $session_key);
-
- $uri = id(new PhutilURI('/login/validate/'))
- ->setQueryParams(
- array('phusr' => $user->getUsername()
- ));
-
- return id(new AphrontRedirectResponse())
- ->setURI((string)$uri);
+ $this->establishWebSession($user);
+ return $this->buildLoginValidateResponse($user);
} else {
$log = PhabricatorUserLog::newLog(
null,
$user,
PhabricatorUserLog::ACTION_LOGIN_FAILURE);
$log->save();
$request->clearCookie('phusr');
$request->clearCookie('phsid');
}
}
if ($errors) {
$error_view = new AphrontErrorView();
$error_view->setTitle(pht('Login Failed'));
$error_view->setErrors($errors);
}
$form = new AphrontFormView();
$form
->setUser($request->getUser())
->setAction('/login/')
->appendChild(
id(new AphrontFormTextControl())
->setLabel(pht('Username/Email'))
->setName('username_or_email')
->setValue($username_or_email))
->appendChild(
id(new AphrontFormPasswordControl())
->setLabel(pht('Password'))
->setName('password')
->setCaption(hsprintf(
'<a href="/login/email/">%s</a>',
pht('Forgot your password? / Email Login'))));
if ($require_captcha) {
$form->appendChild(
id(new AphrontFormRecaptchaControl())
->setError($e_captcha));
}
$form
->appendChild(
id(new AphrontFormSubmitControl())
->setValue(pht('Login')));
// $panel->setCreateButton('Register New Account', '/login/register/');
$forms['Phabricator Login'] = $form;
}
$ldap_provider = new PhabricatorLDAPProvider();
if ($ldap_provider->isProviderEnabled()) {
$ldap_form = new AphrontFormView();
$ldap_form
->setUser($request->getUser())
->setAction('/ldap/login/')
->appendChild(
id(new AphrontFormTextControl())
->setLabel(pht('LDAP username'))
->setName('username')
->setValue($username_or_email))
->appendChild(
id(new AphrontFormPasswordControl())
->setLabel(pht('Password'))
->setName('password'));
$ldap_form
->appendChild(
id(new AphrontFormSubmitControl())
->setValue(pht('Login')));
$forms['LDAP Login'] = $ldap_form;
}
$providers = PhabricatorOAuthProvider::getAllProviders();
foreach ($providers as $provider) {
$enabled = $provider->isProviderEnabled();
if (!$enabled) {
continue;
}
$auth_uri = $provider->getAuthURI();
$redirect_uri = $provider->getRedirectURI();
$client_id = $provider->getClientID();
$provider_name = $provider->getProviderName();
$minimum_scope = $provider->getMinimumScope();
$extra_auth = $provider->getExtraAuthParameters();
// TODO: In theory we should use 'state' to prevent CSRF, but the total
// effect of the CSRF attack is that an attacker can cause a user to login
// to Phabricator if they're already logged into some OAuth provider. This
// does not seem like the most severe threat in the world, and generating
// CSRF for logged-out users is vaugely tricky.
if ($provider->isProviderRegistrationEnabled()) {
$title = pht("Login or Register with %s", $provider_name);
$body = pht('Login or register for Phabricator using your %s account.',
$provider_name);
$button = pht("Login or Register with %s", $provider_name);
} else {
$title = pht("Login with %s", $provider_name);
$body = hsprintf(
'%s<br /><br /><strong>%s</strong>',
pht(
'Login to your existing Phabricator account using your %s account.',
$provider_name),
pht(
'You can not use %s to register a new account.',
$provider_name));
$button = pht("Log in with %s", $provider_name);
}
$auth_form = new AphrontFormView();
$auth_form
->setAction($auth_uri)
->addHiddenInput('client_id', $client_id)
->addHiddenInput('redirect_uri', $redirect_uri)
->addHiddenInput('scope', $minimum_scope);
foreach ($extra_auth as $key => $value) {
$auth_form->addHiddenInput($key, $value);
}
$auth_form
->setUser($request->getUser())
->setMethod('GET')
->appendChild(hsprintf(
'<p class="aphront-form-instructions">%s</p>',
$body))
->appendChild(
id(new AphrontFormSubmitControl())
->setValue("{$button} \xC2\xBB"));
$forms[$title] = $auth_form;
}
$panel = new AphrontPanelView();
$panel->setWidth(AphrontPanelView::WIDTH_FORM);
$panel->setNoBackground();
foreach ($forms as $name => $form) {
$panel->appendChild(phutil_tag('h1', array(), $name));
$panel->appendChild($form);
$panel->appendChild(phutil_tag('br'));
}
$login_message = PhabricatorEnv::getEnvConfig('auth.login-message');
return $this->buildApplicationPage(
array(
$error_view,
phutil_safe_html($login_message),
$panel,
),
array(
'title' => pht('Login'),
'device' => true
));
}
}
diff --git a/src/applications/auth/controller/PhabricatorLoginValidateController.php b/src/applications/auth/controller/PhabricatorLoginValidateController.php
deleted file mode 100644
index 04b08b43f4..0000000000
--- a/src/applications/auth/controller/PhabricatorLoginValidateController.php
+++ /dev/null
@@ -1,80 +0,0 @@
-<?php
-
-final class PhabricatorLoginValidateController
- extends PhabricatorAuthController {
-
- public function shouldRequireLogin() {
- return false;
- }
-
- public function processRequest() {
- $request = $this->getRequest();
-
- $failures = array();
-
- if (!strlen($request->getStr('phusr'))) {
- throw new Exception(
- "Login validation is missing expected parameters!");
- }
-
- $expect_phusr = $request->getStr('phusr');
- $actual_phusr = $request->getCookie('phusr');
- if ($actual_phusr != $expect_phusr) {
-
- if ($actual_phusr) {
- $cookie_info = "sent back a cookie with the value '{$actual_phusr}'.";
- } else {
- $cookie_info = "did not accept the cookie.";
- }
-
- $failures[] =
- "Attempted to set 'phusr' cookie to '{$expect_phusr}', but your ".
- "browser {$cookie_info}";
- }
-
- if (!$failures) {
- if (!$request->getUser()->getPHID()) {
- $failures[] = "Cookies were set correctly, but your session ".
- "isn't valid.";
- }
- }
-
- if ($failures) {
-
- $list = array();
- foreach ($failures as $failure) {
- $list[] = phutil_tag('li', array(), $failure);
- }
- $list = phutil_tag('ul', array(), $list);
-
- $view = new AphrontRequestFailureView();
- $view->setHeader(pht('Login Failed'));
- $view->appendChild(hsprintf(
- '<p>%s</p>%s<p>%s</p>',
- pht('Login failed:'),
- $list,
- pht(
- '<strong>Clear your cookies</strong> and try again.',
- hsprintf(''))));
- $view->appendChild(hsprintf(
- '<div class="aphront-failure-continue">'.
- '<a class="button" href="/login/">%s</a>'.
- '</div>',
- pht('Try Again')));
- return $this->buildStandardPageResponse(
- $view,
- array(
- 'title' => pht('Login Failed'),
- ));
- }
-
- $next = nonempty($request->getStr('next'), $request->getCookie('next_uri'));
- $request->clearCookie('next_uri');
- if (!PhabricatorEnv::isValidLocalWebResource($next)) {
- $next = '/';
- }
-
- return id(new AphrontRedirectResponse())->setURI($next);
- }
-
-}
diff --git a/src/applications/auth/controller/PhabricatorOAuthLoginController.php b/src/applications/auth/controller/PhabricatorOAuthLoginController.php
index 0feea708b8..59a8973e7c 100644
--- a/src/applications/auth/controller/PhabricatorOAuthLoginController.php
+++ b/src/applications/auth/controller/PhabricatorOAuthLoginController.php
@@ -1,305 +1,296 @@
<?php
final class PhabricatorOAuthLoginController
extends PhabricatorAuthController {
private $provider;
private $userID;
private $accessToken;
private $oauthState;
public function shouldRequireLogin() {
return false;
}
public function willProcessRequest(array $data) {
$this->provider = PhabricatorOAuthProvider::newProvider($data['provider']);
}
public function processRequest() {
$current_user = $this->getRequest()->getUser();
$provider = $this->provider;
if (!$provider->isProviderEnabled()) {
return new Aphront400Response();
}
$provider_name = $provider->getProviderName();
$provider_key = $provider->getProviderKey();
$request = $this->getRequest();
if ($request->getStr('error')) {
$error_view = id(new PhabricatorOAuthFailureView())
->setRequest($request);
return $this->buildErrorResponse($error_view);
}
$error_response = $this->retrieveAccessToken($provider);
if ($error_response) {
return $error_response;
}
$userinfo_uri = new PhutilURI($provider->getUserInfoURI());
$userinfo_uri->setQueryParam('access_token', $this->accessToken);
$userinfo_uri = (string)$userinfo_uri;
try {
$user_data_request = new HTTPSFuture($userinfo_uri);
// NOTE: GitHub requires a User-Agent header.
$user_data_request->addHeader('User-Agent', 'Phabricator');
list($body) = $user_data_request->resolvex();
$provider->setUserData($body);
} catch (PhabricatorOAuthProviderException $e) {
return $this->buildErrorResponse(new PhabricatorOAuthFailureView(), $e);
}
$provider->setAccessToken($this->accessToken);
$user_id = $provider->retrieveUserID();
$provider_key = $provider->getProviderKey();
$oauth_info = $this->retrieveOAuthInfo($provider);
if ($current_user->getPHID()) {
if ($oauth_info->getID()) {
if ($oauth_info->getUserID() != $current_user->getID()) {
$dialog = new AphrontDialogView();
$dialog->setUser($current_user);
$dialog->setTitle(pht('Already Linked to Another Account'));
$dialog->appendChild(phutil_tag(
'p',
array(),
pht(
'The %s account you just authorized is already linked to '.
'another Phabricator account. Before you can associate your %s '.
'account with this Phabriactor account, you must unlink it from '.
'the Phabricator account it is currently linked to.',
$provider_name,
$provider_name)));
$dialog->addCancelButton($provider->getSettingsPanelURI());
return id(new AphrontDialogResponse())->setDialog($dialog);
} else {
$this->saveOAuthInfo($oauth_info); // Refresh token.
return id(new AphrontRedirectResponse())
->setURI($provider->getSettingsPanelURI());
}
}
$existing_oauth = PhabricatorUserOAuthInfo::loadOneByUserAndProviderKey(
$current_user,
$provider_key);
if ($existing_oauth) {
$dialog = new AphrontDialogView();
$dialog->setUser($current_user);
$dialog->setTitle(
pht('Already Linked to an Account From This Provider'));
$dialog->appendChild(phutil_tag(
'p',
array(),
pht(
'The account you are logged in with is already linked to a %s '.
'account. Before you can link it to a different %s account, you '.
'must unlink the old account.',
$provider_name,
$provider_name)));
$dialog->addCancelButton($provider->getSettingsPanelURI());
return id(new AphrontDialogResponse())->setDialog($dialog);
}
if (!$request->isDialogFormPost()) {
$dialog = new AphrontDialogView();
$dialog->setUser($current_user);
$dialog->setTitle(pht('Link %s Account', $provider_name));
$dialog->appendChild(phutil_tag('p', array(), pht(
'Link your %s account to your Phabricator account?',
$provider_name)));
$dialog->addHiddenInput('confirm_token', $provider->getAccessToken());
$dialog->addHiddenInput('state', $this->oauthState);
$dialog->addSubmitButton('Link Accounts');
$dialog->addCancelButton($provider->getSettingsPanelURI());
return id(new AphrontDialogResponse())->setDialog($dialog);
}
$oauth_info->setUserID($current_user->getID());
$this->saveOAuthInfo($oauth_info);
return id(new AphrontRedirectResponse())
->setURI($provider->getSettingsPanelURI());
}
// Login with known auth.
if ($oauth_info->getID()) {
$unguarded = AphrontWriteGuard::beginScopedUnguardedWrites();
$known_user = id(new PhabricatorUser())->load($oauth_info->getUserID());
$request->getApplicationConfiguration()->willAuthenticateUserWithOAuth(
$known_user,
$oauth_info,
$provider);
- $session_key = $known_user->establishSession('web');
-
$this->saveOAuthInfo($oauth_info);
- $request->setCookie('phusr', $known_user->getUsername());
- $request->setCookie('phsid', $session_key);
-
- $uri = new PhutilURI('/login/validate/');
- $uri->setQueryParams(
- array(
- 'phusr' => $known_user->getUsername(),
- ));
+ $this->establishWebSession($known_user);
- return id(new AphrontRedirectResponse())->setURI((string)$uri);
+ return $this->buildLoginValidateResponse($known_user);
}
$oauth_email = $provider->retrieveUserEmail();
if ($oauth_email) {
$known_email = id(new PhabricatorUserEmail())
->loadOneWhere('address = %s', $oauth_email);
if ($known_email) {
$dialog = new AphrontDialogView();
$dialog->setUser($current_user);
$dialog->setTitle(pht('Already Linked to Another Account'));
$dialog->appendChild(phutil_tag(
'p',
array(),
pht(
'The %s account you just authorized has an email address which '.
'is already in use by another Phabricator account. To link the '.
'accounts, log in to your Phabricator account and then go to '.
'Settings.',
$provider_name)));
$dialog->addCancelButton('/login/');
return id(new AphrontDialogResponse())->setDialog($dialog);
}
}
if (!$provider->isProviderRegistrationEnabled()) {
$dialog = new AphrontDialogView();
$dialog->setUser($current_user);
$dialog->setTitle(pht('No Account Registration with %s', $provider_name));
$dialog->appendChild(phutil_tag(
'p',
array(),
pht(
'You can not register a new account using %s; you can only use '.
'your %s account to log into an existing Phabricator account which '.
'you have registered through other means.',
$provider_name,
$provider_name)));
$dialog->addCancelButton('/login/');
return id(new AphrontDialogResponse())->setDialog($dialog);
}
$controller = PhabricatorEnv::newObjectFromConfig(
'controller.oauth-registration',
array($this->getRequest()));
$controller->setOAuthProvider($provider);
$controller->setOAuthInfo($oauth_info);
$controller->setOAuthState($this->oauthState);
return $this->delegateToController($controller);
}
private function buildErrorResponse(PhabricatorOAuthFailureView $view,
Exception $e = null) {
$provider = $this->provider;
$provider_name = $provider->getProviderName();
$view->setOAuthProvider($provider);
if ($e) {
$view->setException($e);
}
return $this->buildStandardPageResponse(
$view,
array(
'title' => pht('Auth Failed'),
));
}
private function retrieveAccessToken(PhabricatorOAuthProvider $provider) {
$request = $this->getRequest();
$token = $request->getStr('confirm_token');
if ($token) {
$this->accessToken = $token;
$this->oauthState = $request->getStr('state');
return null;
}
$client_id = $provider->getClientID();
$client_secret = $provider->getClientSecret();
$redirect_uri = $provider->getRedirectURI();
$auth_uri = $provider->getTokenURI();
$code = $request->getStr('code');
$query_data = array(
'client_id' => $client_id,
'client_secret' => $client_secret,
'redirect_uri' => $redirect_uri,
'code' => $code,
) + $provider->getExtraTokenParameters();
$future = new HTTPSFuture($auth_uri, $query_data);
$future->setMethod('POST');
try {
list($response) = $future->resolvex();
} catch (Exception $ex) {
return $this->buildErrorResponse(new PhabricatorOAuthFailureView());
}
$data = $provider->decodeTokenResponse($response);
$token = idx($data, 'access_token');
if (!$token) {
return $this->buildErrorResponse(new PhabricatorOAuthFailureView());
}
$this->accessToken = $token;
$this->oauthState = $request->getStr('state');
return null;
}
private function retrieveOAuthInfo(PhabricatorOAuthProvider $provider) {
$oauth_info = PhabricatorUserOAuthInfo::loadOneByProviderKeyAndAccountID(
$provider->getProviderKey(),
$provider->retrieveUserID());
if (!$oauth_info) {
$oauth_info = new PhabricatorUserOAuthInfo(
new PhabricatorExternalAccount());
$oauth_info->setOAuthProvider($provider->getProviderKey());
$oauth_info->setOAuthUID($provider->retrieveUserID());
}
$oauth_info->setAccountURI($provider->retrieveUserAccountURI());
$oauth_info->setAccountName($provider->retrieveUserAccountName());
$oauth_info->setToken($provider->getAccessToken());
return $oauth_info;
}
private function saveOAuthInfo(PhabricatorUserOAuthInfo $info) {
// UNGUARDED WRITES: Logging-in users don't have their CSRF set up yet.
$unguarded = AphrontWriteGuard::beginScopedUnguardedWrites();
$info->save();
}
}

File Metadata

Mime Type
text/x-diff
Expires
Sun, Jan 19, 12:40 (3 w, 4 d ago)
Storage Engine
blob
Storage Format
Raw Data
Storage Handle
1124668
Default Alt Text
(47 KB)

Event Timeline