/** * check if private key is set * * @return boolean */ public function isPrivateKeySet() { $key = $this->session->get('privateKey'); if (is_null($key)) { return false; } return true; }
/** * Returns the current token or throws an exception if none is found. * * @return string * @throws \Exception */ public function getToken() { $token = $this->session->get('requesttoken'); if (empty($token)) { throw new \Exception('Session does not contain a requesttoken'); } return $token; }
protected function initializeSession() { $encryptedSessionData = $this->session->get(self::encryptedSessionName); try { $this->sessionValues = json_decode($this->crypto->decrypt($encryptedSessionData, $this->passphrase), true); } catch (\Exception $e) { $this->sessionValues = []; } }
public function testUnwrappingGet() { $unencryptedValue = 'foobar'; $encryptedValue = $this->crypto->encrypt($unencryptedValue); $this->wrappedSession->expects($this->once())->method('get')->with('encrypted_session_data')->willReturnCallback(function () use($encryptedValue) { return $encryptedValue; }); $this->assertSame($unencryptedValue, $this->wrappedSession->get('encrypted_session_data')); }
public function manipulateStorageConfig(StorageConfig &$storage) { $encrypted = $this->session->get('password::sessioncredentials/credentials'); if (!isset($encrypted)) { throw new InsufficientDataForMeaningfulAnswerException('No session credentials saved'); } $credentials = json_decode($this->crypto->decrypt($encrypted), true); $storage->setBackendOption('user', $this->session->get('loginname')); $storage->setBackendOption('password', $credentials['password']); }
/** * Get a value from the session * * @param string $key * @return string|null Either the value or null */ public function get($key) { $encryptedValue = $this->session->get($key); if ($encryptedValue === null) { return null; } try { $value = $this->crypto->decrypt($encryptedValue, $this->passphrase); return json_decode($value); } catch (\Exception $e) { return null; } }
/** * Get the timezone of the current user, based on his session information and config data * * @param bool|int $timestamp * @return \DateTimeZone */ public function getTimeZone($timestamp = false) { $timeZone = $this->config->getUserValue($this->session->get('user_id'), 'core', 'timezone', null); if ($timeZone === null) { if ($this->session->exists('timezone')) { return $this->guessTimeZoneFromOffset($this->session->get('timezone'), $timestamp); } $timeZone = $this->getDefaultTimeZone(); } try { return new \DateTimeZone($timeZone); } catch (\Exception $e) { \OCP\Util::writeLog('datetimezone', 'Failed to created DateTimeZone "' . $timeZone . "'", \OCP\Util::DEBUG); return new \DateTimeZone($this->getDefaultTimeZone()); } }
/** * Makes sure the user is already properly authenticated when a password is required and none * was provided * * @param array|bool $linkItem * * @throws CheckException */ private function checkSession($linkItem) { // Not authenticated ? if (!$this->session->exists('public_link_authenticated') || $this->session->get('public_link_authenticated') !== $linkItem['id']) { throw new CheckException("Missing password", Http::STATUS_UNAUTHORIZED); } }
/** * Makes sure the user is already properly authenticated when a password is required and none * was provided * * @param IShare $share * * @throws CheckException */ private function checkSession($share) { // Not authenticated ? if (!$this->session->exists('public_link_authenticated') || $this->session->get('public_link_authenticated') !== (string) $share->getId()) { throw new CheckException("Missing password", Http::STATUS_UNAUTHORIZED); } }
/** * get private key for decrypt all operation * * @return string * @throws PrivateKeyMissingException */ public function getDecryptAllKey() { $privateKey = $this->session->get('decryptAllKey'); if (is_null($privateKey) && $this->decryptAllModeActivated()) { throw new PrivateKeyMissingException('No private key found while in decrypt all mode'); } elseif (is_null($privateKey)) { throw new PrivateKeyMissingException('Please activate decrypt all mode first'); } return $privateKey; }
/** * @param IToken $token */ private function updateToken(IToken $token) { // To save unnecessary DB queries, this is only done once a minute $lastTokenUpdate = $this->session->get('last_token_update') ?: 0; $now = $this->timeFacory->getTime(); if ($lastTokenUpdate < $now - 60) { $this->tokenProvider->updateToken($token); $this->session->set('last_token_update', $now); } }
/** * Get the timezone of the current user, based on his session information and config data * * @return \DateTimeZone */ public function getTimeZone() { $timeZone = $this->config->getUserValue($this->session->get('user_id'), 'core', 'timezone', null); if ($timeZone === null) { if ($this->session->exists('timezone')) { $offsetHours = $this->session->get('timezone'); // Note: the timeZone name is the inverse to the offset, // so a positive offset means negative timeZone // and the other way around. if ($offsetHours > 0) { return new \DateTimeZone('Etc/GMT-' . $offsetHours); } else { return new \DateTimeZone('Etc/GMT+' . abs($offsetHours)); } } else { return new \DateTimeZone('UTC'); } } return new \DateTimeZone($timeZone); }
/** * @param \Sabre\DAV\Server $server * @param $realm * @return bool */ private function auth(\Sabre\DAV\Server $server, $realm) { if (\OC_User::handleApacheAuth() || $this->userSession->isLoggedIn() && is_null($this->session->get(self::DAV_AUTHENTICATED))) { $user = $this->userSession->getUser()->getUID(); \OC_Util::setupFS($user); $this->currentUser = $user; $this->session->close(); return true; } return parent::authenticate($server, $realm); }
/** * Validates a username and password * * This method should return true or false depending on if login * succeeded. * * @param string $username * @param string $password * * @return bool * @throws \Sabre\DAV\Exception\NotAuthenticated */ protected function validateUserPass($username, $password) { try { $share = $this->shareManager->getShareByToken($username); } catch (ShareNotFound $e) { return false; } $this->share = $share; \OC_User::setIncognitoMode(true); // check if the share is password protected if ($share->getPassword() !== null) { if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) { if ($this->shareManager->checkPassword($share, $password)) { return true; } else { if ($this->session->exists('public_link_authenticated') && $this->session->get('public_link_authenticated') === $share->getId()) { return true; } else { if (in_array('XMLHttpRequest', explode(',', $this->request->getHeader('X-Requested-With')))) { // do not re-authenticate over ajax, use dummy auth name to prevent browser popup http_response_code(401); header('WWW-Authenticate', 'DummyBasic real="ownCloud"'); throw new \Sabre\DAV\Exception\NotAuthenticated('Cannot authenticate over ajax calls'); } return false; } } } else { if ($share->getShareType() === \OCP\Share::SHARE_TYPE_REMOTE) { return true; } else { return false; } } } else { return true; } }
/** * get the login name of the current user * * @return string */ public function getLoginName() { if ($this->activeUser) { return $this->session->get('loginname'); } else { $uid = $this->session->get('user_id'); if ($uid) { $this->activeUser = $this->manager->get($uid); return $this->session->get('loginname'); } else { return null; } } }
/** * @PublicPage * @NoCSRFRequired * @UseSession * * @param string $user * @param string $redirect_url * @param string $remember_login * * @return TemplateResponse|RedirectResponse */ public function showLoginForm($user, $redirect_url, $remember_login) { if ($this->userSession->isLoggedIn()) { return new RedirectResponse(OC_Util::getDefaultPageUrl()); } $parameters = array(); $loginMessages = $this->session->get('loginMessages'); $errors = []; $messages = []; if (is_array($loginMessages)) { list($errors, $messages) = $loginMessages; } $this->session->remove('loginMessages'); foreach ($errors as $value) { $parameters[$value] = true; } $parameters['messages'] = $messages; if (!is_null($user) && $user !== '') { $parameters['loginName'] = $user; $parameters['user_autofocus'] = false; } else { $parameters['loginName'] = ''; $parameters['user_autofocus'] = true; } if (!empty($redirect_url)) { $parameters['redirect_url'] = $redirect_url; } $parameters['canResetPassword'] = true; $parameters['resetPasswordLink'] = $this->config->getSystemValue('lost_password_link', ''); if (!$parameters['resetPasswordLink']) { if (!is_null($user) && $user !== '') { $userObj = $this->userManager->get($user); if ($userObj instanceof IUser) { $parameters['canResetPassword'] = $userObj->canChangePassword(); } } } $parameters['alt_login'] = OC_App::getAlternativeLogIns(); $parameters['rememberLoginAllowed'] = OC_Util::rememberLoginAllowed(); $parameters['rememberLoginState'] = !empty($remember_login) ? $remember_login : 0; if (!is_null($user) && $user !== '') { $parameters['loginName'] = $user; $parameters['user_autofocus'] = false; } else { $parameters['loginName'] = ''; $parameters['user_autofocus'] = true; } return new TemplateResponse($this->appName, 'login', $parameters, 'guest'); }
/** * Authenticate a link item with the given password. * Or use the session if no password is provided. * * This is a modified version of Helper::authenticate * TODO: Try to merge back eventually with Helper::authenticate * * @param \OCP\Share\IShare $share * @param string|null $password * @return bool */ private function linkShareAuth(\OCP\Share\IShare $share, $password = null) { if ($password !== null) { if ($this->shareManager->checkPassword($share, $password)) { $this->session->set('public_link_authenticated', (string) $share->getId()); } else { return false; } } else { // not authenticated ? if (!$this->session->exists('public_link_authenticated') || $this->session->get('public_link_authenticated') !== (string) $share->getId()) { return false; } } return true; }
/** * @param RequestInterface $request * @param ResponseInterface $response * @return array */ private function auth(RequestInterface $request, ResponseInterface $response) { if (\OC_User::handleApacheAuth() || $this->userSession->isLoggedIn() && is_null($this->session->get(self::DAV_AUTHENTICATED)) || $this->userSession->isLoggedIn() && $this->session->get(self::DAV_AUTHENTICATED) === $this->userSession->getUser()->getUID() && $request->getHeader('Authorization') === null) { $user = $this->userSession->getUser()->getUID(); \OC_Util::setupFS($user); $this->currentUser = $user; $this->session->close(); return [true, $this->principalPrefix . $user]; } if (!$this->userSession->isLoggedIn() && in_array('XMLHttpRequest', explode(',', $request->getHeader('X-Requested-With')))) { // do not re-authenticate over ajax, use dummy auth name to prevent browser popup $response->addHeader('WWW-Authenticate', 'DummyBasic realm="' . $this->realm . '"'); $response->setStatus(401); throw new \Sabre\DAV\Exception\NotAuthenticated('Cannot authenticate over ajax calls'); } return parent::check($request, $response); }
/** * @param \Sabre\DAV\Server $server * @param string $realm * @return bool */ private function auth(\Sabre\DAV\Server $server, $realm) { if (\OC_User::handleApacheAuth() || $this->userSession->isLoggedIn() && is_null($this->session->get(self::DAV_AUTHENTICATED))) { $user = $this->userSession->getUser()->getUID(); \OC_Util::setupFS($user); $this->currentUser = $user; $this->session->close(); return true; } if ($server->httpRequest->getHeader('X-Requested-With') === 'XMLHttpRequest') { // do not re-authenticate over ajax, use dummy auth name to prevent browser popup $server->httpResponse->addHeader('WWW-Authenticate', 'DummyBasic realm="' . $realm . '"'); $server->httpResponse->setStatus(401); throw new \Sabre\DAV\Exception\NotAuthenticated('Cannot authenticate over ajax calls'); } return parent::authenticate($server, $realm); }
/** * @param RequestInterface $request * @param ResponseInterface $response * @return array * @throws NotAuthenticated */ private function auth(RequestInterface $request, ResponseInterface $response) { $forcedLogout = false; if (!$this->request->passesCSRFCheck() && $this->requiresCSRFCheck()) { // In case of a fail with POST we need to recheck the credentials if ($this->request->getMethod() === 'POST') { $forcedLogout = true; } else { $response->setStatus(401); throw new \Sabre\DAV\Exception\NotAuthenticated('CSRF check not passed.'); } } if ($forcedLogout) { $this->userSession->logout(); } else { if ($this->twoFactorManager->needsSecondFactor()) { throw new \Sabre\DAV\Exception\NotAuthenticated('2FA challenge not passed.'); } if (\OC_User::handleApacheAuth() || $this->userSession->isLoggedIn() && is_null($this->session->get(self::DAV_AUTHENTICATED)) || $this->userSession->isLoggedIn() && $this->session->get(self::DAV_AUTHENTICATED) === $this->userSession->getUser()->getUID() && $request->getHeader('Authorization') === null) { $user = $this->userSession->getUser()->getUID(); \OC_Util::setupFS($user); $this->currentUser = $user; $this->session->close(); return [true, $this->principalPrefix . $user]; } } if (!$this->userSession->isLoggedIn() && in_array('XMLHttpRequest', explode(',', $request->getHeader('X-Requested-With')))) { // do not re-authenticate over ajax, use dummy auth name to prevent browser popup $response->addHeader('WWW-Authenticate', 'DummyBasic realm="' . $this->realm . '"'); $response->setStatus(401); throw new \Sabre\DAV\Exception\NotAuthenticated('Cannot authenticate over ajax calls'); } $data = parent::check($request, $response); if ($data[0] === true) { $startPos = strrpos($data[1], '/') + 1; $user = $this->userSession->getUser()->getUID(); $data[1] = substr_replace($data[1], $user, $startPos); } return $data; }
/** * @NoAdminRequired * @UseSession * * @param string $oldPassword * @param string $newPassword * @return DataResponse */ public function updatePrivateKeyPassword($oldPassword, $newPassword) { $result = false; $uid = $this->userSession->getUser()->getUID(); $errorMessage = $this->l->t('Could not update the private key password.'); //check if password is correct $passwordCorrect = $this->userManager->checkPassword($uid, $newPassword); if ($passwordCorrect === false) { // if check with uid fails we need to check the password with the login name // e.g. in the ldap case. For local user we need to check the password with // the uid because in this case the login name is case insensitive $loginName = $this->ocSession->get('loginname'); $passwordCorrect = $this->userManager->checkPassword($loginName, $newPassword); } if ($passwordCorrect !== false) { $encryptedKey = $this->keyManager->getPrivateKey($uid); $decryptedKey = $this->crypt->decryptPrivateKey($encryptedKey, $oldPassword, $uid); if ($decryptedKey) { $encryptedKey = $this->crypt->encryptPrivateKey($decryptedKey, $newPassword, $uid); $header = $this->crypt->generateHeader(); if ($encryptedKey) { $this->keyManager->setPrivateKey($uid, $header . $encryptedKey); $this->session->setPrivateKey($decryptedKey); $result = true; } } else { $errorMessage = $this->l->t('The old password was not correct, please try again.'); } } else { $errorMessage = $this->l->t('The current log-in password was not correct, please try again.'); } if ($result === true) { $this->session->setStatus(Session::INIT_SUCCESSFUL); return new DataResponse(['message' => (string) $this->l->t('Private key password successfully updated.')]); } else { return new DataResponse(['message' => (string) $errorMessage], Http::STATUS_BAD_REQUEST); } }
/** * Hook listener on post login * * @param array $params */ public function authenticate(array $params) { $userId = $params['uid']; $credentials = ['user' => $this->session->get('loginname'), 'password' => $params['password']]; $this->credentialsManager->store($userId, self::CREDENTIALS_IDENTIFIER, $credentials); }