Skip to content
Open
Show file tree
Hide file tree
Changes from all 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
1 change: 0 additions & 1 deletion build/psalm-baseline.xml
Original file line number Diff line number Diff line change
Expand Up @@ -3110,7 +3110,6 @@
</file>
<file src="core/Controller/LoginController.php">
<DeprecatedMethod>
<code><![CDATA[deleteUserValue]]></code>
<code><![CDATA[getDelay]]></code>
</DeprecatedMethod>
</file>
Expand Down
105 changes: 47 additions & 58 deletions core/Controller/LoginController.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,11 @@
namespace OC\Core\Controller;

use OC\AppFramework\Http\Request;
use OC\Authentication\Login\AlternativeLoginService;
use OC\Authentication\Login\Chain;
use OC\Authentication\Login\LoginData;
use OC\Authentication\WebAuthn\Manager as WebAuthnManager;
use OC\User\Session;
use OC_App;
use OCA\User_LDAP\Configuration;
use OCA\User_LDAP\Helper;
use OCP\App\IAppManager;
Expand All @@ -30,9 +30,10 @@
use OCP\AppFramework\Http\Attribute\UseSession;
use OCP\AppFramework\Http\DataResponse;
use OCP\AppFramework\Http\RedirectResponse;
use OCP\AppFramework\Http\Response;
use OCP\AppFramework\Http\TemplateResponse;
use OCP\AppFramework\Services\IInitialState;
use OCP\Authentication\IAlternativeLogin;
use OCP\Config\IUserConfig;
use OCP\Defaults;
use OCP\IConfig;
use OCP\IL10N;
Expand All @@ -48,41 +49,40 @@
use OCP\Util;

class LoginController extends Controller {
public const LOGIN_MSG_INVALIDPASSWORD = 'invalidpassword';
public const LOGIN_MSG_USERDISABLED = 'userdisabled';
public const LOGIN_MSG_CSRFCHECKFAILED = 'csrfCheckFailed';
public const LOGIN_MSG_INVALID_ORIGIN = 'invalidOrigin';
public const string LOGIN_MSG_INVALIDPASSWORD = 'invalidpassword';
public const string LOGIN_MSG_USERDISABLED = 'userdisabled';
public const string LOGIN_MSG_CSRFCHECKFAILED = 'csrfCheckFailed';
public const string LOGIN_MSG_INVALID_ORIGIN = 'invalidOrigin';

public function __construct(
?string $appName,
string $appName,
IRequest $request,
private IUserManager $userManager,
private IConfig $config,
private ISession $session,
private Session $userSession,
private IURLGenerator $urlGenerator,
private Defaults $defaults,
private IThrottler $throttler,
private IInitialState $initialState,
private WebAuthnManager $webAuthnManager,
private IManager $manager,
private IL10N $l10n,
private IAppManager $appManager,
private readonly IUserManager $userManager,
private readonly IConfig $config,
private readonly IUserConfig $userConfig,
private readonly ISession $session,
private readonly Session $userSession,
private readonly IURLGenerator $urlGenerator,
private readonly Defaults $defaults,
private readonly IThrottler $throttler,
private readonly IInitialState $initialState,
private readonly WebAuthnManager $webAuthnManager,
private readonly IManager $manager,
private readonly IL10N $l10n,
private readonly IAppManager $appManager,
private readonly AlternativeLoginService $alternativeLoginService,
) {
parent::__construct($appName, $request);
}

/**
* @return RedirectResponse
*/
#[NoAdminRequired]
#[UseSession]
#[FrontpageRoute(verb: 'GET', url: '/logout')]
public function logout() {
public function logout(): RedirectResponse {
$loginToken = $this->request->getCookie('nc_token');
$uid = $this->userSession->getUser()?->getUID();
if ($loginToken !== null && $uid !== null) {
$this->config->deleteUserValue($uid, 'login_token', $loginToken);
$this->userConfig->deleteUserConfig($uid, 'login_token', $loginToken);
}
$this->userSession->logout();

Expand All @@ -107,22 +107,17 @@ public function logout() {
return $response;
}

/**
* @param string $user
* @param string $redirect_url
*
* @return TemplateResponse|RedirectResponse
*/
#[NoCSRFRequired]
#[PublicPage]
#[UseSession]
#[OpenAPI(scope: OpenAPI::SCOPE_IGNORE)]
#[FrontpageRoute(verb: 'GET', url: '/login')]
public function showLoginForm(?string $user = null, ?string $redirect_url = null): Response {
public function showLoginForm(?string $user = null, ?string $redirect_url = null): TemplateResponse|RedirectResponse {
if ($this->userSession->isLoggedIn()) {
return new RedirectResponse($this->urlGenerator->linkToDefaultPageUrl());
}

/** @var array|string $loginMessages */
$loginMessages = $this->session->get('loginMessages');
if (!$this->manager->isFairUseOfFreePushService()) {
if (!is_array($loginMessages)) {
Expand Down Expand Up @@ -153,13 +148,14 @@ public function showLoginForm(?string $user = null, ?string $redirect_url = null
$this->config->getSystemValueInt('remember_login_cookie_lifetime', 60 * 60 * 24 * 15) > 0
);

if (!empty($redirect_url)) {
if ($redirect_url !== null && $redirect_url !== '') {
[$url, ] = explode('?', $redirect_url);
if ($url !== $this->urlGenerator->linkToRoute('core.login.logout')) {
$this->initialState->provideInitialState('loginRedirectUrl', $redirect_url);
}
}

/** @psalm-suppress */
$this->initialState->provideInitialState(
'loginThrottleDelay',
$this->throttler->getDelay($this->request->getRemoteAddress())
Expand All @@ -185,7 +181,11 @@ public function showLoginForm(?string $user = null, ?string $redirect_url = null
Util::addHeader('meta', ['name' => 'referrer', 'content' => 'same-origin']);

$parameters = [
'alt_login' => OC_App::getAlternativeLogIns(),
'alt_login' => array_map(static fn (IAlternativeLogin $alternativeLogin): array => [
'name' => $alternativeLogin->getLabel(),
'href' => $alternativeLogin->getLink(),
'class' => $alternativeLogin->getClass(),
], $this->alternativeLoginService->getAlternativeLogins()),
'pageTitle' => $this->l10n->t('Login'),
];

Expand All @@ -203,8 +203,6 @@ public function showLoginForm(?string $user = null, ?string $redirect_url = null

/**
* Sets the password reset state
*
* @param string $username
*/
private function setPasswordResetInitialState(?string $username): void {
if ($username !== null && $username !== '') {
Expand All @@ -227,15 +225,14 @@ private function setPasswordResetInitialState(?string $username): void {
}

/**
* Sets the initial state of whether or not a user is allowed to login with their email
* Sets the initial state of whether a user is allowed to log in with their email
* initial state is passed in the array of 1 for email allowed and 0 for not allowed
*/
private function setEmailStates(): void {
$emailStates = []; // true: can login with email, false otherwise - default to true
$emailStates = []; // true: can log in with email, false otherwise - default to true

// check if user_ldap is enabled, and the required classes exist
if ($this->appManager->isAppLoaded('user_ldap')
&& class_exists(Helper::class)) {
if ($this->appManager->isAppLoaded('user_ldap') && class_exists(Helper::class)) {
$helper = Server::get(Helper::class);
$allPrefixes = $helper->getServerConfigurationPrefixes();
// check each LDAP server the user is connected too
Expand All @@ -248,15 +245,10 @@ private function setEmailStates(): void {
}

/**
* @param string|null $passwordLink
* @param IUser|null $user
*
* Users may not change their passwords if:
* - The account is disabled
* - The backend doesn't support password resets
* - The password reset function is disabled
*
* @return bool
*/
private function canResetPassword(?string $passwordLink, ?IUser $user): bool {
if ($passwordLink === 'disabled') {
Expand Down Expand Up @@ -366,29 +358,23 @@ public function tryLogin(
);
}

if ($result->getRedirectUrl() !== null) {
return new RedirectResponse($result->getRedirectUrl());
$redirectUrl = $result->getRedirectUrl();
if ($redirectUrl !== null) {
return new RedirectResponse($redirectUrl);
}
return $this->generateRedirect($redirect_url);
}

/**
* Creates a login failed response.
*
* @param string $user
* @param string $originalUser
* @param string $redirect_url
* @param string $loginMessage
*
* @return RedirectResponse
*/
private function createLoginFailedResponse(
$user,
$originalUser,
$redirect_url,
?string $user,
string $originalUser,
?string $redirect_url,
string $loginMessage,
bool $throttle = true,
) {
): RedirectResponse {
// Read current user and append if possible we need to
// return the unmodified user otherwise we will leak the login name
$args = $user !== null ? ['user' => $originalUser, 'direct' => 1] : [];
Expand All @@ -399,7 +385,7 @@ private function createLoginFailedResponse(
$this->urlGenerator->linkToRoute('core.login.showLoginForm', $args)
);
if ($throttle) {
$response->throttle(['user' => substr($user, 0, 64)]);
$response->throttle(['user' => substr($user ?? '', 0, 64)]);
}
$this->session->set('loginMessages', [
[$loginMessage], []
Expand Down Expand Up @@ -428,6 +414,9 @@ private function createLoginFailedResponse(
#[OpenAPI(scope: OpenAPI::SCOPE_DEFAULT)]
public function confirmPassword(string $password): DataResponse {
$loginName = $this->userSession->getLoginName();
if ($loginName === null) {
throw new \RuntimeException('Login name not set');
}
$loginResult = $this->userManager->checkPassword($loginName, $password);
if ($loginResult === false) {
$response = new DataResponse([], Http::STATUS_FORBIDDEN);
Expand Down
1 change: 1 addition & 0 deletions lib/composer/composer/autoload_classmap.php
Original file line number Diff line number Diff line change
Expand Up @@ -1263,6 +1263,7 @@
'OC\\Authentication\\LoginCredentials\\Credentials' => $baseDir . '/lib/private/Authentication/LoginCredentials/Credentials.php',
'OC\\Authentication\\LoginCredentials\\Store' => $baseDir . '/lib/private/Authentication/LoginCredentials/Store.php',
'OC\\Authentication\\Login\\ALoginCommand' => $baseDir . '/lib/private/Authentication/Login/ALoginCommand.php',
'OC\\Authentication\\Login\\AlternativeLoginService' => $baseDir . '/lib/private/Authentication/Login/AlternativeLoginService.php',
'OC\\Authentication\\Login\\Chain' => $baseDir . '/lib/private/Authentication/Login/Chain.php',
'OC\\Authentication\\Login\\ClearLostPasswordTokensCommand' => $baseDir . '/lib/private/Authentication/Login/ClearLostPasswordTokensCommand.php',
'OC\\Authentication\\Login\\CompleteLoginCommand' => $baseDir . '/lib/private/Authentication/Login/CompleteLoginCommand.php',
Expand Down
1 change: 1 addition & 0 deletions lib/composer/composer/autoload_static.php
Original file line number Diff line number Diff line change
Expand Up @@ -1304,6 +1304,7 @@ class ComposerStaticInit749170dad3f5e7f9ca158f5a9f04f6a2
'OC\\Authentication\\LoginCredentials\\Credentials' => __DIR__ . '/../../..' . '/lib/private/Authentication/LoginCredentials/Credentials.php',
'OC\\Authentication\\LoginCredentials\\Store' => __DIR__ . '/../../..' . '/lib/private/Authentication/LoginCredentials/Store.php',
'OC\\Authentication\\Login\\ALoginCommand' => __DIR__ . '/../../..' . '/lib/private/Authentication/Login/ALoginCommand.php',
'OC\\Authentication\\Login\\AlternativeLoginService' => __DIR__ . '/../../..' . '/lib/private/Authentication/Login/AlternativeLoginService.php',
'OC\\Authentication\\Login\\Chain' => __DIR__ . '/../../..' . '/lib/private/Authentication/Login/Chain.php',
'OC\\Authentication\\Login\\ClearLostPasswordTokensCommand' => __DIR__ . '/../../..' . '/lib/private/Authentication/Login/ClearLostPasswordTokensCommand.php',
'OC\\Authentication\\Login\\CompleteLoginCommand' => __DIR__ . '/../../..' . '/lib/private/Authentication/Login/CompleteLoginCommand.php',
Expand Down
113 changes: 113 additions & 0 deletions lib/private/Authentication/Login/AlternativeLoginService.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
<?php

declare(strict_types=1);

/**
* SPDX-FileCopyrightText: 2025 Nextcloud GmbH
* SPDX-FileContributor: Carl Schwan
* SPDX-License-Identifier: AGPL-3.0-or-later
*/

namespace OC\Authentication\Login;

use OC\AppFramework\Bootstrap\Coordinator;
use OCP\Authentication\IAlternativeLogin;
use OCP\Authentication\IAlternativeLoginProvider;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\ContainerInterface;
use Psr\Log\LoggerInterface;
use Throwable;

class AlternativeLoginService {
public function __construct(
private readonly Coordinator $coordinator,
private readonly LoggerInterface $logger,
private readonly ContainerInterface $container,
) {

}

/**
* @return list<IAlternativeLogin>
*/
public function getAlternativeLogins(): array {
$result = [];

foreach ($this->coordinator->getRegistrationContext()->getAlternativeLoginProviders() as $registration) {
if (!in_array(IAlternativeLoginProvider::class, class_implements($registration->getService()), true)) {
$this->logger->error('Alternative login option {option} does not implement {interface} and is therefore ignored.', [
'option' => $registration->getService(),
'interface' => IAlternativeLoginProvider::class,
'app' => $registration->getAppId(),
]);
continue;
}

try {
/** @var IAlternativeLoginProvider $provider */
$provider = $this->container->get($registration->getService());
} catch (ContainerExceptionInterface $e) {
$this->logger->error('Alternative login option {option} can not be initialized.',
[
'exception' => $e,
'option' => $registration->getService(),
'app' => $registration->getAppId(),
]);
continue;
}

foreach ($provider->getAlternativeLogins() as $alternativeLogin) {
try {
$alternativeLogin->load();

$result[] = $alternativeLogin;
} catch (Throwable $e) {
$this->logger->error('Alternative login option {option} had an error while loading.',
[
'exception' => $e,
'option' => $registration->getService(),
'app' => $registration->getAppId(),
]);
}
}
}

foreach ($this->coordinator->getRegistrationContext()->getAlternativeLogins() as $registration) {
if (!in_array(IAlternativeLogin::class, class_implements($registration->getService()), true)) {
$this->logger->error('Alternative login option {option} does not implement {interface} and is therefore ignored.', [
'option' => $registration->getService(),
'interface' => IAlternativeLogin::class,
'app' => $registration->getAppId(),
]);
continue;
}

try {
/** @var IAlternativeLogin $provider */
$provider = $this->container->get($registration->getService());
} catch (ContainerExceptionInterface $e) {
$this->logger->error('Alternative login option {option} can not be initialized.',
[
'exception' => $e,
'option' => $registration->getService(),
'app' => $registration->getAppId(),
]);
}

try {
$provider->load();

$result[] = $provider;
} catch (Throwable $e) {
$this->logger->error('Alternative login option {option} had an error while loading.',
[
'exception' => $e,
'option' => $registration->getService(),
'app' => $registration->getAppId(),
]);
}
}

return $result;
}
}
Loading
Loading