Merge pull request #3561 from owncloud/user

Refactor of user management
This commit is contained in:
icewind1991 2013-06-03 08:13:40 -07:00
commit 8c991d97aa
13 changed files with 1900 additions and 419 deletions

View File

@ -534,7 +534,7 @@ class Test_Encryption_Share extends \PHPUnit_Framework_TestCase {
// some hacking to simulate public link // some hacking to simulate public link
$GLOBALS['app'] = 'files_sharing'; $GLOBALS['app'] = 'files_sharing';
$GLOBALS['fileOwner'] = \Test_Encryption_Share::TEST_ENCRYPTION_SHARE_USER1; $GLOBALS['fileOwner'] = \Test_Encryption_Share::TEST_ENCRYPTION_SHARE_USER1;
\OC_User::setUserId(''); \OC_User::setUserId(false);
// get file contents // get file contents
$retrievedCryptedFile = file_get_contents('crypt://' . $this->filename); $retrievedCryptedFile = file_get_contents('crypt://' . $this->filename);

View File

@ -30,35 +30,85 @@
* post_createUser(uid, password) * post_createUser(uid, password)
* pre_deleteUser(&run, uid) * pre_deleteUser(&run, uid)
* post_deleteUser(uid) * post_deleteUser(uid)
* pre_setPassword(&run, uid, password) * pre_setPassword(&run, uid, password, recoveryPassword)
* post_setPassword(uid, password) * post_setPassword(uid, password, recoveryPassword)
* pre_login(&run, uid, password) * pre_login(&run, uid, password)
* post_login(uid) * post_login(uid)
* logout() * logout()
*/ */
class OC_User { class OC_User {
// The backend used for user management public static $userSession = null;
private static function getUserSession() {
if (!self::$userSession) {
$manager = new \OC\User\Manager();
self::$userSession = new \OC\User\Session($manager, \OC::$session);
self::$userSession->listen('\OC\User', 'preCreateUser', function ($uid, $password) {
\OC_Hook::emit('OC_User', 'pre_createUser', array('run' => true, 'uid' => $uid, 'password' => $password));
});
self::$userSession->listen('\OC\User', 'postCreateUser', function ($user, $password) {
/** @var $user \OC\User\User */
\OC_Hook::emit('OC_User', 'post_createUser', array('uid' => $user->getUID(), 'password' => $password));
});
self::$userSession->listen('\OC\User', 'preDelete', function ($user) {
/** @var $user \OC\User\User */
\OC_Hook::emit('OC_User', 'pre_deleteUser', array('run' => true, 'uid' => $user->getUID()));
});
self::$userSession->listen('\OC\User', 'postDelete', function ($user) {
/** @var $user \OC\User\User */
\OC_Hook::emit('OC_User', 'post_deleteUser', array('uid' => $user->getUID()));
});
self::$userSession->listen('\OC\User', 'preSetPassword', function ($user, $password, $recoveryPassword) {
/** @var $user \OC\User\User */
OC_Hook::emit('OC_User', 'pre_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
});
self::$userSession->listen('\OC\User', 'postSetPassword', function ($user, $password, $recoveryPassword) {
/** @var $user \OC\User\User */
OC_Hook::emit('OC_User', 'post_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
});
self::$userSession->listen('\OC\User', 'preLogin', function ($uid, $password) {
\OC_Hook::emit('OC_User', 'pre_login', array('run' => true, 'uid' => $uid, 'password' => $password));
});
self::$userSession->listen('\OC\User', 'postLogin', function ($user, $password) {
/** @var $user \OC\User\User */
\OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
});
self::$userSession->listen('\OC\User', 'logout', function () {
\OC_Hook::emit('OC_User', 'logout', array());
});
}
return self::$userSession;
}
/**
* @return \OC\User\Manager
*/
private static function getManager() {
return self::getUserSession()->getManager();
}
private static $_backends = array();
private static $_usedBackends = array(); private static $_usedBackends = array();
private static $_setupedBackends = array(); private static $_setupedBackends = array();
// Backends available (except database)
private static $_backends = array();
/** /**
* @brief registers backend * @brief registers backend
* @param $name name of the backend * @param string $backend name of the backend
* @returns true/false * @deprecated Add classes by calling useBackend with a class instance instead
* @return bool
* *
* Makes a list of backends that can be used by other modules * Makes a list of backends that can be used by other modules
*/ */
public static function registerBackend( $backend ) { public static function registerBackend($backend) {
self::$_backends[] = $backend; self::$_backends[] = $backend;
return true; return true;
} }
/** /**
* @brief gets available backends * @brief gets available backends
* @deprecated
* @returns array of backends * @returns array of backends
* *
* Returns the names of all backends. * Returns the names of all backends.
@ -69,6 +119,7 @@ class OC_User {
/** /**
* @brief gets used backends * @brief gets used backends
* @deprecated
* @returns array of backends * @returns array of backends
* *
* Returns the names of all used backends. * Returns the names of all used backends.
@ -79,33 +130,36 @@ class OC_User {
/** /**
* @brief Adds the backend to the list of used backends * @brief Adds the backend to the list of used backends
* @param $backend default: database The backend to use for user managment * @param string | OC_User_Backend $backend default: database The backend to use for user management
* @returns true/false * @return bool
* *
* Set the User Authentication Module * Set the User Authentication Module
*/ */
public static function useBackend( $backend = 'database' ) { public static function useBackend($backend = 'database') {
if($backend instanceof OC_User_Interface) { if ($backend instanceof OC_User_Interface) {
OC_Log::write('core', 'Adding user backend instance of '.get_class($backend).'.', OC_Log::DEBUG); OC_Log::write('core', 'Adding user backend instance of ' . get_class($backend) . '.', OC_Log::DEBUG);
self::$_usedBackends[get_class($backend)]=$backend; self::$_usedBackends[get_class($backend)] = $backend;
self::getManager()->registerBackend($backend);
} else { } else {
// You'll never know what happens // You'll never know what happens
if( null === $backend OR !is_string( $backend )) { if (null === $backend OR !is_string($backend)) {
$backend = 'database'; $backend = 'database';
} }
// Load backend // Load backend
switch( $backend ) { switch ($backend) {
case 'database': case 'database':
case 'mysql': case 'mysql':
case 'sqlite': case 'sqlite':
OC_Log::write('core', 'Adding user backend '.$backend.'.', OC_Log::DEBUG); OC_Log::write('core', 'Adding user backend ' . $backend . '.', OC_Log::DEBUG);
self::$_usedBackends[$backend] = new OC_User_Database(); self::$_usedBackends[$backend] = new OC_User_Database();
self::getManager()->registerBackend(self::$_usedBackends[$backend]);
break; break;
default: default:
OC_Log::write('core', 'Adding default user backend '.$backend.'.', OC_Log::DEBUG); OC_Log::write('core', 'Adding default user backend ' . $backend . '.', OC_Log::DEBUG);
$className = 'OC_USER_' . strToUpper($backend); $className = 'OC_USER_' . strToUpper($backend);
self::$_usedBackends[$backend] = new $className(); self::$_usedBackends[$backend] = new $className();
self::getManager()->registerBackend(self::$_usedBackends[$backend]);
break; break;
} }
} }
@ -116,121 +170,73 @@ class OC_User {
* remove all used backends * remove all used backends
*/ */
public static function clearBackends() { public static function clearBackends() {
self::$_usedBackends=array(); self::$_usedBackends = array();
self::getManager()->clearBackends();
} }
/** /**
* setup the configured backends in config.php * setup the configured backends in config.php
*/ */
public static function setupBackends() { public static function setupBackends() {
$backends=OC_Config::getValue('user_backends', array()); $backends = OC_Config::getValue('user_backends', array());
foreach($backends as $i=>$config) { foreach ($backends as $i => $config) {
$class=$config['class']; $class = $config['class'];
$arguments=$config['arguments']; $arguments = $config['arguments'];
if(class_exists($class)) { if (class_exists($class)) {
if(array_search($i, self::$_setupedBackends)===false) { if (array_search($i, self::$_setupedBackends) === false) {
// make a reflection object // make a reflection object
$reflectionObj = new ReflectionClass($class); $reflectionObj = new ReflectionClass($class);
// use Reflection to create a new instance, using the $args // use Reflection to create a new instance, using the $args
$backend = $reflectionObj->newInstanceArgs($arguments); $backend = $reflectionObj->newInstanceArgs($arguments);
self::useBackend($backend); self::useBackend($backend);
$_setupedBackends[]=$i; $_setupedBackends[] = $i;
} else { } else {
OC_Log::write('core', 'User backend '.$class.' already initialized.', OC_Log::DEBUG); OC_Log::write('core', 'User backend ' . $class . ' already initialized.', OC_Log::DEBUG);
} }
} else { } else {
OC_Log::write('core', 'User backend '.$class.' not found.', OC_Log::ERROR); OC_Log::write('core', 'User backend ' . $class . ' not found.', OC_Log::ERROR);
} }
} }
} }
/** /**
* @brief Create a new user * @brief Create a new user
* @param $uid The username of the user to create * @param string $uid The username of the user to create
* @param $password The password of the new user * @param string $password The password of the new user
* @returns true/false * @throws Exception
* @return bool true/false
* *
* Creates a new user. Basic checking of username is done in OC_User * Creates a new user. Basic checking of username is done in OC_User
* itself, not in its subclasses. * itself, not in its subclasses.
* *
* Allowed characters in the username are: "a-z", "A-Z", "0-9" and "_.@-" * Allowed characters in the username are: "a-z", "A-Z", "0-9" and "_.@-"
*/ */
public static function createUser( $uid, $password ) { public static function createUser($uid, $password) {
// Check the name for bad characters self::getManager()->createUser($uid, $password);
// Allowed are: "a-z", "A-Z", "0-9" and "_.@-"
if( preg_match( '/[^a-zA-Z0-9 _\.@\-]/', $uid )) {
throw new Exception('Only the following characters are allowed in a username:'
.' "a-z", "A-Z", "0-9", and "_.@-"');
}
// No empty username
if(trim($uid) == '') {
throw new Exception('A valid username must be provided');
}
// No empty password
if(trim($password) == '') {
throw new Exception('A valid password must be provided');
}
// Check if user already exists
if( self::userExistsForCreation($uid) ) {
throw new Exception('The username is already being used');
}
$run = true;
OC_Hook::emit( "OC_User", "pre_createUser", array( "run" => &$run, "uid" => $uid, "password" => $password ));
if( $run ) {
//create the user in the first backend that supports creating users
foreach(self::$_usedBackends as $backend) {
if(!$backend->implementsActions(OC_USER_BACKEND_CREATE_USER))
continue;
$backend->createUser($uid, $password);
OC_Hook::emit( "OC_User", "post_createUser", array( "uid" => $uid, "password" => $password ));
return self::userExists($uid);
}
}
return false;
} }
/** /**
* @brief delete a user * @brief delete a user
* @param $uid The username of the user to delete * @param string $uid The username of the user to delete
* @returns true/false * @return bool
* *
* Deletes a user * Deletes a user
*/ */
public static function deleteUser( $uid ) { public static function deleteUser($uid) {
$run = true; $user = self::getManager()->get($uid);
OC_Hook::emit( "OC_User", "pre_deleteUser", array( "run" => &$run, "uid" => $uid )); if ($user) {
$user->delete();
if( $run ) {
//delete the user from all backends
foreach(self::$_usedBackends as $backend) {
$backend->deleteUser($uid);
}
if (self::userExists($uid)) {
return false;
}
// We have to delete the user from all groups // We have to delete the user from all groups
foreach( OC_Group::getUserGroups( $uid ) as $i ) { foreach (OC_Group::getUserGroups($uid) as $i) {
OC_Group::removeFromGroup( $uid, $i ); OC_Group::removeFromGroup($uid, $i);
} }
// Delete the user's keys in preferences // Delete the user's keys in preferences
OC_Preferences::deleteUser($uid); OC_Preferences::deleteUser($uid);
// Delete user files in /data/ // Delete user files in /data/
OC_Helper::rmdirr(OC_Config::getValue( "datadirectory", OC::$SERVERROOT."/data" ) . '/'.$uid.'/'); OC_Helper::rmdirr(OC_Config::getValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $uid . '/');
// Emit and exit
OC_Hook::emit( "OC_User", "post_deleteUser", array( "uid" => $uid ));
return true;
}
else{
return false;
} }
} }
@ -238,75 +244,34 @@ class OC_User {
* @brief Try to login a user * @brief Try to login a user
* @param $uid The username of the user to log in * @param $uid The username of the user to log in
* @param $password The password of the user * @param $password The password of the user
* @returns true/false * @return bool
* *
* Log in a user and regenerate a new session - if the password is ok * Log in a user and regenerate a new session - if the password is ok
*/ */
public static function login( $uid, $password ) { public static function login($uid, $password) {
$run = true; return self::getUserSession()->login($uid, $password);
OC_Hook::emit( "OC_User", "pre_login", array( "run" => &$run, "uid" => $uid, "password" => $password));
if( $run ) {
$uid = self::checkPassword( $uid, $password );
$enabled = self::isEnabled($uid);
if($uid && $enabled) {
session_regenerate_id(true);
self::setUserId($uid);
self::setDisplayName($uid);
OC_Hook::emit( "OC_User", "post_login", array( "uid" => $uid, 'password'=>$password ));
return true;
}
}
return false;
} }
/** /**
* @brief Sets user id for session and triggers emit * @brief Sets user id for session and triggers emit
*/ */
public static function setUserId($uid) { public static function setUserId($uid) {
\OC::$session->set('user_id', $uid); OC::$session->set('user_id', $uid);
} }
/** /**
* @brief Sets user display name for session * @brief Sets user display name for session
*/ */
public static function setDisplayName($uid, $displayName = null) { public static function setDisplayName($uid, $displayName = null) {
$result = false; if (is_null($displayName)) {
if ($displayName ) { $displayName = $uid;
foreach(self::$_usedBackends as $backend) {
if($backend->implementsActions(OC_USER_BACKEND_SET_DISPLAYNAME)) {
if($backend->userExists($uid)) {
$result |= $backend->setDisplayName($uid, $displayName);
}
}
} }
$user = self::getManager()->get($uid);
if ($user) {
return $user->setDisplayName($displayName);
} else { } else {
$displayName = self::determineDisplayName($uid); return false;
$result = true;
} }
if (OC_User::getUser() === $uid) {
\OC::$session->set('display_name', $displayName);
}
return $result;
}
/**
* @brief get display name
* @param $uid The username
* @returns string display name or uid if no display name is defined
*
*/
private static function determineDisplayName( $uid ) {
foreach(self::$_usedBackends as $backend) {
if($backend->implementsActions(OC_USER_BACKEND_GET_DISPLAYNAME)) {
$result=$backend->getDisplayName( $uid );
if($result) {
return $result;
}
}
}
return $uid;
} }
/** /**
@ -315,36 +280,31 @@ class OC_User {
* Logout, destroys session * Logout, destroys session
*/ */
public static function logout() { public static function logout() {
OC_Hook::emit( "OC_User", "logout", array()); self::getUserSession()->logout();
session_unset();
session_destroy();
OC_User::unsetMagicInCookie();
} }
/** /**
* @brief Check if the user is logged in * @brief Check if the user is logged in
* @returns true/false * @returns bool
* *
* Checks if the user is logged in * Checks if the user is logged in
*/ */
public static function isLoggedIn() { public static function isLoggedIn() {
if( \OC::$session->get('user_id')) { if (\OC::$session->get('user_id')) {
OC_App::loadApps(array('authentication')); OC_App::loadApps(array('authentication'));
self::setupBackends(); self::setupBackends();
if (self::userExists(\OC::$session->get('user_id')) ) { return self::userExists(\OC::$session->get('user_id'));
return true;
}
} }
return false; return false;
} }
/** /**
* @brief Check if the user is an admin user * @brief Check if the user is an admin user
* @param $uid uid of the admin * @param string $uid uid of the admin
* @returns bool * @return bool
*/ */
public static function isAdminUser($uid) { public static function isAdminUser($uid) {
if(OC_Group::inGroup($uid, 'admin' )) { if (OC_Group::inGroup($uid, 'admin')) {
return true; return true;
} }
return false; return false;
@ -356,32 +316,40 @@ class OC_User {
* @return string uid or false * @return string uid or false
*/ */
public static function getUser() { public static function getUser() {
if( \OC::$session->get('user_id') ) { $uid = OC::$session->get('user_id');
return \OC::$session->get('user_id'); if (!is_null($uid)) {
} return $uid;
else{ } else {
return false; return false;
} }
} }
/** /**
* @brief get the display name of the user currently logged in. * @brief get the display name of the user currently logged in.
* @param string $uid
* @return string uid or false * @return string uid or false
*/ */
public static function getDisplayName($user=null) { public static function getDisplayName($uid = null) {
if ( $user ) { if ($uid) {
return self::determineDisplayName($user); $user = self::getManager()->get($uid);
} else if( \OC::$session->get('display_name') ) { if ($user) {
return \OC::$session->get('display_name'); return $user->getDisplayName();
} else {
return $uid;
} }
else{ } else {
$user = self::getUserSession()->getUser();
if ($user) {
return $user->getDisplayName();
} else {
return false; return false;
} }
} }
}
/** /**
* @brief Autogenerate a password * @brief Autogenerate a password
* @returns string * @return string
* *
* generates a password * generates a password
*/ */
@ -391,113 +359,90 @@ class OC_User {
/** /**
* @brief Set password * @brief Set password
* @param $uid The username * @param string $uid The username
* @param $password The new password * @param string $password The new password
* @param $recoveryPassword for the encryption app to reset encryption keys * @param string $recoveryPassword for the encryption app to reset encryption keys
* @returns true/false * @return bool
* *
* Change the password of a user * Change the password of a user
*/ */
public static function setPassword( $uid, $password, $recoveryPassword = null ) { public static function setPassword($uid, $password, $recoveryPassword = null) {
$run = true; $user = self::getManager()->get($uid);
OC_Hook::emit( "OC_User", "pre_setPassword", array( "run" => &$run, "uid" => $uid, "password" => $password, "recoveryPassword" => $recoveryPassword )); if ($user) {
return $user->setPassword($password, $recoveryPassword);
if( $run ) { } else {
$success = false;
foreach(self::$_usedBackends as $backend) {
if($backend->implementsActions(OC_USER_BACKEND_SET_PASSWORD)) {
if($backend->userExists($uid)) {
$success |= $backend->setPassword($uid, $password);
}
}
}
// invalidate all login cookies
OC_Preferences::deleteApp($uid, 'login_token');
OC_Hook::emit( "OC_User", "post_setPassword", array( "uid" => $uid, "password" => $password, "recoveryPassword" => $recoveryPassword ));
return $success;
}
else{
return false; return false;
} }
} }
/** /**
* @brief Check whether user can change his password * @brief Check whether user can change his password
* @param $uid The username * @param string $uid The username
* @returns true/false * @return bool
* *
* Check whether a specified user can change his password * Check whether a specified user can change his password
*/ */
public static function canUserChangePassword($uid) { public static function canUserChangePassword($uid) {
foreach(self::$_usedBackends as $backend) { $user = self::getManager()->get($uid);
if($backend->implementsActions(OC_USER_BACKEND_SET_PASSWORD)) { if ($user) {
if($backend->userExists($uid)) { return $user->canChangePassword();
return true; } else {
}
}
}
return false; return false;
} }
}
/** /**
* @brief Check whether user can change his display name * @brief Check whether user can change his display name
* @param $uid The username * @param string $uid The username
* @returns true/false * @return bool
* *
* Check whether a specified user can change his display name * Check whether a specified user can change his display name
*/ */
public static function canUserChangeDisplayName($uid) { public static function canUserChangeDisplayName($uid) {
if (OC_Config::getValue('allow_user_to_change_display_name', true)) { $user = self::getManager()->get($uid);
foreach(self::$_usedBackends as $backend) { if ($user) {
if($backend->implementsActions(OC_USER_BACKEND_SET_DISPLAYNAME)) { return $user->canChangeDisplayName();
if($backend->userExists($uid)) { } else {
return true;
}
}
}
}
return false; return false;
} }
/**
* @brief Check if the password is correct
* @param $uid The username
* @param $password The password
* @returns string
*
* Check if the password is correct without logging in the user
* returns the user id or false
*/
public static function checkPassword( $uid, $password ) {
foreach(self::$_usedBackends as $backend) {
if($backend->implementsActions(OC_USER_BACKEND_CHECK_PASSWORD)) {
$result=$backend->checkPassword( $uid, $password );
if($result) {
return $result;
}
}
}
} }
/** /**
* @brief Check if the password is correct * @brief Check if the password is correct
* @param string $uid The username * @param string $uid The username
* @param string $password The password * @param string $password The password
* @returns string * @return bool
*
* Check if the password is correct without logging in the user
* returns the user id or false
*/
public static function checkPassword($uid, $password) {
$user = self::getManager()->get($uid);
if ($user) {
if ($user->checkPassword($password)) {
return $user->getUID();
} else {
return false;
}
} else {
return false;
}
}
/**
* @param string $uid The username
* @return string
* *
* returns the path to the users home directory * returns the path to the users home directory
*/ */
public static function getHome($uid) { public static function getHome($uid) {
foreach(self::$_usedBackends as $backend) { $user = self::getManager()->get($uid);
if($backend->implementsActions(OC_USER_BACKEND_GET_HOME) && $backend->userExists($uid)) { if ($user) {
$result=$backend->getHome($uid); return $user->getHome();
if($result) { } else {
return $result; return OC_Config::getValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $uid;
} }
} }
}
return OC_Config::getValue( "datadirectory", OC::$SERVERROOT."/data" ) . '/' . $uid;
}
/** /**
* @brief Get a list of all users * @brief Get a list of all users
@ -506,152 +451,93 @@ class OC_User {
* Get a list of all users. * Get a list of all users.
*/ */
public static function getUsers($search = '', $limit = null, $offset = null) { public static function getUsers($search = '', $limit = null, $offset = null) {
$users = array(); $users = self::getManager()->search($search, $limit, $offset);
foreach (self::$_usedBackends as $backend) { $uids = array();
$backendUsers = $backend->getUsers($search, $limit, $offset); foreach ($users as $user) {
if (is_array($backendUsers)) { $uids[] = $user->getUID();
$users = array_merge($users, $backendUsers);
} }
} return $uids;
asort($users);
return $users;
} }
/** /**
* @brief Get a list of all users display name * @brief Get a list of all users display name
* @returns associative array with all display names (value) and corresponding uids (key) * @param string $search
* @param int $limit
* @param int $offset
* @return array associative array with all display names (value) and corresponding uids (key)
* *
* Get a list of all display names and user ids. * Get a list of all display names and user ids.
*/ */
public static function getDisplayNames($search = '', $limit = null, $offset = null) { public static function getDisplayNames($search = '', $limit = null, $offset = null) {
$displayNames = array(); $displayNames = array();
foreach (self::$_usedBackends as $backend) { $users = self::getManager()->searchDisplayName($search, $limit, $offset);
$backendDisplayNames = $backend->getDisplayNames($search, $limit, $offset); foreach ($users as $user) {
if (is_array($backendDisplayNames)) { $displayNames[$user->getUID()] = $user->getDisplayName();
$displayNames = $displayNames + $backendDisplayNames;
} }
}
asort($displayNames);
return $displayNames; return $displayNames;
} }
/** /**
* @brief check if a user exists * @brief check if a user exists
* @param string $uid the username * @param string $uid the username
* @param string $excludingBackend (default none)
* @return boolean * @return boolean
*/ */
public static function userExists($uid, $excludingBackend=null) { public static function userExists($uid) {
foreach(self::$_usedBackends as $backend) { return self::getManager()->userExists($uid);
if (!is_null($excludingBackend) && !strcmp(get_class($backend), $excludingBackend)) {
OC_Log::write('OC_User', $excludingBackend . 'excluded from user existance check.', OC_Log::DEBUG);
continue;
}
$result=$backend->userExists($uid);
if($result===true) {
return true;
}
}
return false;
}
public static function userExistsForCreation($uid) {
foreach(self::$_usedBackends as $backend) {
if(!$backend->hasUserListings())
continue;
$result=$backend->userExists($uid);
if($result===true) {
return true;
}
}
return false;
} }
/** /**
* disables a user * disables a user
* @param string $userid the user to disable *
* @param string $uid the user to disable
*/ */
public static function disableUser($userid) { public static function disableUser($uid) {
$sql = "INSERT INTO `*PREFIX*preferences` (`userid`, `appid`, `configkey`, `configvalue`) VALUES(?, ?, ?, ?)"; $user = self::getManager()->get($uid);
$stmt = OC_DB::prepare($sql); if ($user) {
if ( ! OC_DB::isError($stmt) ) { $user->setEnabled(false);
$result = $stmt->execute(array($userid, 'core', 'enabled', 'false'));
if ( OC_DB::isError($result) ) {
OC_Log::write('OC_User', 'could not enable user: '. OC_DB::getErrorMessage($result), OC_Log::ERROR);
}
} else {
OC_Log::write('OC_User', 'could not disable user: '. OC_DB::getErrorMessage($stmt), OC_Log::ERROR);
} }
} }
/** /**
* enable a user * enable a user
* @param string $userid *
* @param string $uid
*/ */
public static function enableUser($userid) { public static function enableUser($uid) {
$sql = 'DELETE FROM `*PREFIX*preferences`' $user = self::getManager()->get($uid);
." WHERE `userid` = ? AND `appid` = ? AND `configkey` = ? AND `configvalue` = ?"; if ($user) {
$stmt = OC_DB::prepare($sql); $user->setEnabled(true);
if ( ! OC_DB::isError($stmt) ) {
$result = $stmt->execute(array($userid, 'core', 'enabled', 'false'));
if ( OC_DB::isError($result) ) {
OC_Log::write('OC_User', 'could not enable user: '. OC_DB::getErrorMessage($result), OC_Log::ERROR);
}
} else {
OC_Log::write('OC_User', 'could not enable user: '. OC_DB::getErrorMessage($stmt), OC_Log::ERROR);
} }
} }
/** /**
* checks if a user is enabled * checks if a user is enabled
* @param string $userid *
* @param string $uid
* @return bool * @return bool
*/ */
public static function isEnabled($userid) { public static function isEnabled($uid) {
$sql = 'SELECT `userid` FROM `*PREFIX*preferences`' $user = self::getManager()->get($uid);
.' WHERE `userid` = ? AND `appid` = ? AND `configkey` = ? AND `configvalue` = ?'; if ($user) {
if (OC_Config::getValue( 'dbtype', 'sqlite' ) === 'oci') { //FIXME oracle hack return $user->isEnabled();
$sql = 'SELECT `userid` FROM `*PREFIX*preferences`'
.' WHERE `userid` = ? AND `appid` = ? AND `configkey` = ? AND to_char(`configvalue`) = ?';
}
$stmt = OC_DB::prepare($sql);
if ( ! OC_DB::isError($stmt) ) {
$result = $stmt->execute(array($userid, 'core', 'enabled', 'false'));
if ( ! OC_DB::isError($result) ) {
return $result->numRows() ? false : true;
} else { } else {
OC_Log::write('OC_User',
'could not check if enabled: '. OC_DB::getErrorMessage($result),
OC_Log::ERROR);
}
} else {
OC_Log::write('OC_User', 'could not check if enabled: '. OC_DB::getErrorMessage($stmt), OC_Log::ERROR);
}
return false; return false;
} }
}
/** /**
* @brief Set cookie value to use in next page load * @brief Set cookie value to use in next page load
* @param string $username username to be set * @param string $username username to be set
* @param string $token
*/ */
public static function setMagicInCookie($username, $token) { public static function setMagicInCookie($username, $token) {
$secure_cookie = OC_Config::getValue("forcessl", false); self::getUserSession()->setMagicInCookie($username, $token);
$expires = time() + OC_Config::getValue('remember_login_cookie_lifetime', 60*60*24*15);
setcookie("oc_username", $username, $expires, OC::$WEBROOT, '', $secure_cookie);
setcookie("oc_token", $token, $expires, OC::$WEBROOT, '', $secure_cookie, true);
setcookie("oc_remember_login", true, $expires, OC::$WEBROOT, '', $secure_cookie);
} }
/** /**
* @brief Remove cookie for "remember username" * @brief Remove cookie for "remember username"
*/ */
public static function unsetMagicInCookie() { public static function unsetMagicInCookie() {
unset($_COOKIE["oc_username"]); self::getUserSession()->unsetMagicInCookie();
unset($_COOKIE["oc_token"]);
unset($_COOKIE["oc_remember_login"]);
setcookie("oc_username", null, -1);
setcookie("oc_token", null, -1);
setcookie("oc_remember_login", null, -1);
} }
} }

View File

@ -58,7 +58,7 @@ abstract class OC_User_Backend implements OC_User_Interface {
/** /**
* @brief Get all supported actions * @brief Get all supported actions
* @returns bitwise-or'ed actions * @return int bitwise-or'ed actions
* *
* Returns the supported actions as int to be * Returns the supported actions as int to be
* compared with OC_USER_BACKEND_CREATE_USER etc. * compared with OC_USER_BACKEND_CREATE_USER etc.
@ -76,8 +76,8 @@ abstract class OC_User_Backend implements OC_User_Interface {
/** /**
* @brief Check if backend implements actions * @brief Check if backend implements actions
* @param $actions bitwise-or'ed actions * @param int $actions bitwise-or'ed actions
* @returns boolean * @return boolean
* *
* Returns the supported actions as int to be * Returns the supported actions as int to be
* compared with OC_USER_BACKEND_CREATE_USER etc. * compared with OC_USER_BACKEND_CREATE_USER etc.
@ -88,8 +88,8 @@ abstract class OC_User_Backend implements OC_User_Interface {
/** /**
* @brief delete a user * @brief delete a user
* @param $uid The username of the user to delete * @param string $uid The username of the user to delete
* @returns true/false * @return bool
* *
* Deletes a user * Deletes a user
*/ */
@ -127,8 +127,8 @@ abstract class OC_User_Backend implements OC_User_Interface {
/** /**
* @brief get display name of the user * @brief get display name of the user
* @param $uid user ID of the user * @param string $uid user ID of the user
* @return display name * @return string display name
*/ */
public function getDisplayName($uid) { public function getDisplayName($uid) {
return $uid; return $uid;

View File

@ -1,102 +1,106 @@
<?php <?php
/** /**
* ownCloud * ownCloud
* *
* @author Frank Karlitschek * @author Frank Karlitschek
* @copyright 2012 Frank Karlitschek frank@owncloud.org * @copyright 2012 Frank Karlitschek frank@owncloud.org
* *
* This library is free software; you can redistribute it and/or * This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
* License as published by the Free Software Foundation; either * License as published by the Free Software Foundation; either
* version 3 of the License, or any later version. * version 3 of the License, or any later version.
* *
* This library is distributed in the hope that it will be useful, * This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU AFFERO GENERAL PUBLIC LICENSE for more details. * GNU AFFERO GENERAL PUBLIC LICENSE for more details.
* *
* You should have received a copy of the GNU Affero General Public * You should have received a copy of the GNU Affero General Public
* License along with this library. If not, see <http://www.gnu.org/licenses/>. * License along with this library. If not, see <http://www.gnu.org/licenses/>.
* *
*/ */
/** /**
* dummy user backend, does not keep state, only for testing use * dummy user backend, does not keep state, only for testing use
*/ */
class OC_User_Dummy extends OC_User_Backend { class OC_User_Dummy extends OC_User_Backend {
private $users=array(); private $users = array();
/** /**
* @brief Create a new user * @brief Create a new user
* @param $uid The username of the user to create * @param string $uid The username of the user to create
* @param $password The password of the new user * @param string $password The password of the new user
* @returns true/false * @return bool
* *
* Creates a new user. Basic checking of username is done in OC_User * Creates a new user. Basic checking of username is done in OC_User
* itself, not in its subclasses. * itself, not in its subclasses.
*/ */
public function createUser($uid, $password) { public function createUser($uid, $password) {
if(isset($this->users[$uid])) { if (isset($this->users[$uid])) {
return false; return false;
}else{ } else {
$this->users[$uid]=$password; $this->users[$uid] = $password;
return true; return true;
} }
} }
/** /**
* @brief delete a user * @brief delete a user
* @param $uid The username of the user to delete * @param string $uid The username of the user to delete
* @returns true/false * @return bool
* *
* Deletes a user * Deletes a user
*/ */
public function deleteUser( $uid ) { public function deleteUser($uid) {
if(isset($this->users[$uid])) { if (isset($this->users[$uid])) {
unset($this->users[$uid]); unset($this->users[$uid]);
return true; return true;
}else{ } else {
return false; return false;
} }
} }
/** /**
* @brief Set password * @brief Set password
* @param $uid The username * @param string $uid The username
* @param $password The new password * @param string $password The new password
* @returns true/false * @return bool
* *
* Change the password of a user * Change the password of a user
*/ */
public function setPassword($uid, $password) { public function setPassword($uid, $password) {
if(isset($this->users[$uid])) { if (isset($this->users[$uid])) {
$this->users[$uid]=$password; $this->users[$uid] = $password;
return true; return true;
}else{ } else {
return false; return false;
} }
} }
/** /**
* @brief Check if the password is correct * @brief Check if the password is correct
* @param $uid The username * @param string $uid The username
* @param $password The password * @param string $password The password
* @returns string * @return string
* *
* Check if the password is correct without logging in the user * Check if the password is correct without logging in the user
* returns the user id or false * returns the user id or false
*/ */
public function checkPassword($uid, $password) { public function checkPassword($uid, $password) {
if(isset($this->users[$uid])) { if (isset($this->users[$uid])) {
return ($this->users[$uid]==$password); return ($this->users[$uid] == $password);
}else{ } else {
return false; return false;
} }
} }
/** /**
* @brief Get a list of all users * @brief Get a list of all users
* @returns array with all uids * @param string $search
* @param int $limit
* @param int $offset
* @return array with all uids
* *
* Get a list of all users. * Get a list of all users.
*/ */

228
lib/user/manager.php Normal file
View File

@ -0,0 +1,228 @@
<?php
/**
* Copyright (c) 2013 Robin Appelman <icewind@owncloud.com>
* This file is licensed under the Affero General Public License version 3 or
* later.
* See the COPYING-README file.
*/
namespace OC\User;
use OC\Hooks\PublicEmitter;
/**
* Class Manager
*
* Hooks available in scope \OC\User:
* - preSetPassword(\OC\User\User $user, string $password, string $recoverPassword)
* - postSetPassword(\OC\User\User $user, string $password, string $recoverPassword)
* - preDelete(\OC\User\User $user)
* - postDelete(\OC\User\User $user)
* - preCreateUser(string $uid, string $password)
* - postCreateUser(\OC\User\User $user, string $password)
*
* @package OC\User
*/
class Manager extends PublicEmitter {
/**
* @var \OC_User_Backend[] $backends
*/
private $backends = array();
private $cachedUsers = array();
public function __construct() {
$cachedUsers = $this->cachedUsers;
$this->listen('\OC\User', 'postDelete', function ($user) use (&$cachedUsers) {
$i = array_search($user, $cachedUsers);
if ($i !== false) {
unset($cachedUsers[$i]);
}
});
}
/**
* register a user backend
*
* @param \OC_User_Backend $backend
*/
public function registerBackend($backend) {
$this->backends[] = $backend;
}
/**
* remove a user backend
*
* @param \OC_User_Backend $backend
*/
public function removeBackend($backend) {
$this->cachedUsers = array();
if (($i = array_search($backend, $this->backends)) !== false) {
unset($this->backends[$i]);
}
}
/**
* remove all user backends
*/
public function clearBackends() {
$this->cachedUsers = array();
$this->backends = array();
}
/**
* get a user by user id
*
* @param string $uid
* @return \OC\User\User
*/
public function get($uid) {
if (isset($this->cachedUsers[$uid])) { //check the cache first to prevent having to loop over the backends
return $this->cachedUsers[$uid];
}
foreach ($this->backends as $backend) {
if ($backend->userExists($uid)) {
return $this->getUserObject($uid, $backend);
}
}
return null;
}
/**
* get or construct the user object
*
* @param string $uid
* @param \OC_User_Backend $backend
* @return \OC\User\User
*/
protected function getUserObject($uid, $backend) {
if (isset($this->cachedUsers[$uid])) {
return $this->cachedUsers[$uid];
}
$this->cachedUsers[$uid] = new User($uid, $backend, $this);
return $this->cachedUsers[$uid];
}
/**
* check if a user exists
*
* @param string $uid
* @return bool
*/
public function userExists($uid) {
$user = $this->get($uid);
return ($user !== null);
}
/**
* search by user id
*
* @param string $pattern
* @param int $limit
* @param int $offset
* @return \OC\User\User[]
*/
public function search($pattern, $limit = null, $offset = null) {
$users = array();
foreach ($this->backends as $backend) {
$backendUsers = $backend->getUsers($pattern, $limit, $offset);
if (is_array($backendUsers)) {
foreach ($backendUsers as $uid) {
$users[] = $this->getUserObject($uid, $backend);
if (!is_null($limit)) {
$limit--;
}
if (!is_null($offset) and $offset > 0) {
$offset--;
}
}
}
}
usort($users, function ($a, $b) {
/**
* @var \OC\User\User $a
* @var \OC\User\User $b
*/
return strcmp($a->getUID(), $b->getUID());
});
return $users;
}
/**
* search by displayName
*
* @param string $pattern
* @param int $limit
* @param int $offset
* @return \OC\User\User[]
*/
public function searchDisplayName($pattern, $limit = null, $offset = null) {
$users = array();
foreach ($this->backends as $backend) {
$backendUsers = $backend->getDisplayNames($pattern, $limit, $offset);
if (is_array($backendUsers)) {
foreach ($backendUsers as $uid => $displayName) {
$users[] = $this->getUserObject($uid, $backend);
if (!is_null($limit)) {
$limit--;
}
if (!is_null($offset) and $offset > 0) {
$offset--;
}
}
}
}
usort($users, function ($a, $b) {
/**
* @var \OC\User\User $a
* @var \OC\User\User $b
*/
return strcmp($a->getDisplayName(), $b->getDisplayName());
});
return $users;
}
/**
* @param string $uid
* @param string $password
* @throws \Exception
* @return bool | \OC\User\User the created user of false
*/
public function createUser($uid, $password) {
// Check the name for bad characters
// Allowed are: "a-z", "A-Z", "0-9" and "_.@-"
if (preg_match('/[^a-zA-Z0-9 _\.@\-]/', $uid)) {
throw new \Exception('Only the following characters are allowed in a username:'
. ' "a-z", "A-Z", "0-9", and "_.@-"');
}
// No empty username
if (trim($uid) == '') {
throw new \Exception('A valid username must be provided');
}
// No empty password
if (trim($password) == '') {
throw new \Exception('A valid password must be provided');
}
// Check if user already exists
if ($this->userExists($uid)) {
throw new \Exception('The username is already being used');
}
$this->emit('\OC\User', 'preCreateUser', array($uid, $password));
foreach ($this->backends as $backend) {
if ($backend->implementsActions(\OC_USER_BACKEND_CREATE_USER)) {
$backend->createUser($uid, $password);
$user = $this->getUserObject($uid, $backend);
$this->emit('\OC\User', 'postCreateUser', array($user, $password));
return $user;
}
}
return false;
}
}

173
lib/user/session.php Normal file
View File

@ -0,0 +1,173 @@
<?php
/**
* Copyright (c) 2013 Robin Appelman <icewind@owncloud.com>
* This file is licensed under the Affero General Public License version 3 or
* later.
* See the COPYING-README file.
*/
namespace OC\User;
use OC\Hooks\Emitter;
/**
* Class Session
*
* Hooks available in scope \OC\User:
* - preSetPassword(\OC\User\User $user, string $password, string $recoverPassword)
* - postSetPassword(\OC\User\User $user, string $password, string $recoverPassword)
* - preDelete(\OC\User\User $user)
* - postDelete(\OC\User\User $user)
* - preCreateUser(string $uid, string $password)
* - postCreateUser(\OC\User\User $user)
* - preLogin(string $user, string $password)
* - postLogin(\OC\User\User $user)
* - logout()
*
* @package OC\User
*/
class Session implements Emitter {
/**
* @var \OC\User\Manager $manager
*/
private $manager;
/**
* @var \OC\Session\Session $session
*/
private $session;
/**
* @var \OC\User\User $activeUser
*/
protected $activeUser;
/**
* @param \OC\User\Manager $manager
* @param \OC\Session\Session $session
*/
public function __construct($manager, $session) {
$this->manager = $manager;
$this->session = $session;
}
/**
* @param string $scope
* @param string $method
* @param callable $callback
*/
public function listen($scope, $method, $callback) {
$this->manager->listen($scope, $method, $callback);
}
/**
* @param string $scope optional
* @param string $method optional
* @param callable $callback optional
*/
public function removeListener($scope = null, $method = null, $callback = null) {
$this->manager->removeListener($scope, $method, $callback);
}
/**
* get the manager object
*
* @return \OC\User\Manager
*/
public function getManager() {
return $this->manager;
}
/**
* set the currently active user
*
* @param \OC\User\User $user
*/
public function setUser($user) {
if (is_null($user)) {
$this->session->remove('user_id');
} else {
$this->session->set('user_id', $user->getUID());
}
$this->activeUser = $user;
}
/**
* get the current active user
*
* @return \OC\User\User
*/
public function getUser() {
if ($this->activeUser) {
return $this->activeUser;
} else {
$uid = $this->session->get('user_id');
if ($uid) {
$this->activeUser = $this->manager->get($uid);
return $this->activeUser;
} else {
return null;
}
}
}
/**
* try to login with the provided credentials
*
* @param string $uid
* @param string $password
* @return bool
*/
public function login($uid, $password) {
$this->manager->emit('\OC\User', 'preLogin', array($uid, $password));
$user = $this->manager->get($uid);
if ($user) {
$result = $user->checkPassword($password);
if ($result and $user->isEnabled()) {
$this->setUser($user);
$this->manager->emit('\OC\User', 'postLogin', array($user, $password));
return true;
} else {
return false;
}
} else {
return false;
}
}
/**
* logout the user from the session
*/
public function logout() {
$this->manager->emit('\OC\User', 'logout');
$this->setUser(null);
$this->unsetMagicInCookie();
}
/**
* Set cookie value to use in next page load
*
* @param string $username username to be set
* @param string $token
*/
public function setMagicInCookie($username, $token) {
$secure_cookie = \OC_Config::getValue("forcessl", false); //TODO: DI for cookies and OC_Config
$expires = time() + \OC_Config::getValue('remember_login_cookie_lifetime', 60 * 60 * 24 * 15);
setcookie("oc_username", $username, $expires, \OC::$WEBROOT, '', $secure_cookie);
setcookie("oc_token", $token, $expires, \OC::$WEBROOT, '', $secure_cookie, true);
setcookie("oc_remember_login", true, $expires, \OC::$WEBROOT, '', $secure_cookie);
}
/**
* Remove cookie for "remember username"
*/
public function unsetMagicInCookie() {
unset($_COOKIE["oc_username"]); //TODO: DI
unset($_COOKIE["oc_token"]);
unset($_COOKIE["oc_remember_login"]);
setcookie("oc_username", null, -1);
setcookie("oc_token", null, -1);
setcookie("oc_remember_login", null, -1);
}
}

197
lib/user/user.php Normal file
View File

@ -0,0 +1,197 @@
<?php
/**
* Copyright (c) 2013 Robin Appelman <icewind@owncloud.com>
* This file is licensed under the Affero General Public License version 3 or
* later.
* See the COPYING-README file.
*/
namespace OC\User;
use OC\Hooks\Emitter;
class User {
/**
* @var string $uid
*/
private $uid;
/**
* @var string $displayName
*/
private $displayName;
/**
* @var \OC_User_Backend $backend
*/
private $backend;
/**
* @var bool $enabled
*/
private $enabled;
/**
* @var Emitter | Manager $emitter
*/
private $emitter;
/**
* @param string $uid
* @param \OC_User_Backend $backend
* @param Emitter $emitter
*/
public function __construct($uid, $backend, $emitter = null) {
$this->uid = $uid;
if ($backend->implementsActions(OC_USER_BACKEND_GET_DISPLAYNAME)) {
$this->displayName = $backend->getDisplayName($uid);
} else {
$this->displayName = $uid;
}
$this->backend = $backend;
$this->emitter = $emitter;
$enabled = \OC_Preferences::getValue($uid, 'core', 'enabled', 'true'); //TODO: DI for OC_Preferences
$this->enabled = ($enabled === 'true');
}
/**
* get the user id
*
* @return string
*/
public function getUID() {
return $this->uid;
}
/**
* get the displayname for the user, if no specific displayname is set it will fallback to the user id
*
* @return string
*/
public function getDisplayName() {
return $this->displayName;
}
/**
* set the displayname for the user
*
* @param string $displayName
* @return bool
*/
public function setDisplayName($displayName) {
if ($this->canChangeDisplayName()) {
$this->displayName = $displayName;
$result = $this->backend->setDisplayName($this->uid, $displayName);
return $result !== false;
} else {
return false;
}
}
/**
* Delete the user
*
* @return bool
*/
public function delete() {
if ($this->emitter) {
$this->emitter->emit('\OC\User', 'preDelete', array($this));
}
$result = $this->backend->deleteUser($this->uid);
if ($this->emitter) {
$this->emitter->emit('\OC\User', 'postDelete', array($this));
}
return !($result === false);
}
/**
* Check if the password is valid for the user
*
* @param $password
* @return bool
*/
public function checkPassword($password) {
if ($this->backend->implementsActions(\OC_USER_BACKEND_CHECK_PASSWORD)) {
$result = $this->backend->checkPassword($this->uid, $password);
if ($result !== false) {
$this->uid = $result;
}
return !($result === false);
} else {
return false;
}
}
/**
* Set the password of the user
*
* @param string $password
* @param string $recoveryPassword for the encryption app to reset encryption keys
* @return bool
*/
public function setPassword($password, $recoveryPassword) {
if ($this->backend->implementsActions(\OC_USER_BACKEND_SET_PASSWORD)) {
if ($this->emitter) {
$this->emitter->emit('\OC\User', 'preSetPassword', array($this, $password, $recoveryPassword));
}
$result = $this->backend->setPassword($this->uid, $password);
if ($this->emitter) {
$this->emitter->emit('\OC\User', 'postSetPassword', array($this, $password, $recoveryPassword));
}
return !($result === false);
} else {
return false;
}
}
/**
* get the users home folder to mount
*
* @return string
*/
public function getHome() {
if ($this->backend->implementsActions(\OC_USER_BACKEND_GET_HOME) and $home = $this->backend->getHome($this->uid)) {
return $home;
}
return \OC_Config::getValue("datadirectory", \OC::$SERVERROOT . "/data") . '/' . $this->uid; //TODO switch to Config object once implemented
}
/**
* check if the backend supports changing passwords
*
* @return bool
*/
public function canChangePassword() {
return $this->backend->implementsActions(\OC_USER_BACKEND_SET_PASSWORD);
}
/**
* check if the backend supports changing display names
*
* @return bool
*/
public function canChangeDisplayName() {
return $this->backend->implementsActions(\OC_USER_BACKEND_SET_DISPLAYNAME);
}
/**
* check if the user is enabled
*
* @return bool
*/
public function isEnabled() {
return $this->enabled;
}
/**
* set the enabled status for the user
*
* @param bool $enabled
*/
public function setEnabled($enabled) {
$this->enabled = $enabled;
$enabled = ($enabled) ? 'true' : 'false';
\OC_Preferences::setValue($this->uid, 'core', 'enabled', $enabled);
}
}

View File

@ -0,0 +1,99 @@
<?php
/**
* ownCloud
*
* @author Robin Appelman
* @copyright 2012 Robin Appelman icewind@owncloud.com
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
* License as published by the Free Software Foundation; either
* version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU AFFERO GENERAL PUBLIC LICENSE for more details.
*
* You should have received a copy of the GNU Affero General Public
* License along with this library. If not, see <http://www.gnu.org/licenses/>.
*
*/
/**
* Abstract class to provide the basis of backend-specific unit test classes.
*
* All subclasses MUST assign a backend property in setUp() which implements
* user operations (add, remove, etc.). Test methods in this class will then be
* run on each separate subclass and backend therein.
*
* For an example see /tests/lib/user/dummy.php
*/
abstract class Test_User_Backend extends PHPUnit_Framework_TestCase {
/**
* @var OC_User_Backend $backend
*/
protected $backend;
/**
* get a new unique user name
* test cases can override this in order to clean up created user
* @return array
*/
public function getUser() {
return uniqid('test_');
}
public function testAddRemove() {
//get the number of groups we start with, in case there are exising groups
$startCount=count($this->backend->getUsers());
$name1=$this->getUser();
$name2=$this->getUser();
$this->backend->createUser($name1, '');
$count=count($this->backend->getUsers())-$startCount;
$this->assertEquals(1, $count);
$this->assertTrue((array_search($name1, $this->backend->getUsers())!==false));
$this->assertFalse((array_search($name2, $this->backend->getUsers())!==false));
$this->backend->createUser($name2, '');
$count=count($this->backend->getUsers())-$startCount;
$this->assertEquals(2, $count);
$this->assertTrue((array_search($name1, $this->backend->getUsers())!==false));
$this->assertTrue((array_search($name2, $this->backend->getUsers())!==false));
$this->backend->deleteUser($name2);
$count=count($this->backend->getUsers())-$startCount;
$this->assertEquals(1, $count);
$this->assertTrue((array_search($name1, $this->backend->getUsers())!==false));
$this->assertFalse((array_search($name2, $this->backend->getUsers())!==false));
}
public function testLogin() {
$name1=$this->getUser();
$name2=$this->getUser();
$this->assertFalse($this->backend->userExists($name1));
$this->assertFalse($this->backend->userExists($name2));
$this->backend->createUser($name1, 'pass1');
$this->backend->createUser($name2, 'pass2');
$this->assertTrue($this->backend->userExists($name1));
$this->assertTrue($this->backend->userExists($name2));
$this->assertTrue($this->backend->checkPassword($name1, 'pass1'));
$this->assertTrue($this->backend->checkPassword($name2, 'pass2'));
$this->assertFalse($this->backend->checkPassword($name1, 'pass2'));
$this->assertFalse($this->backend->checkPassword($name2, 'pass1'));
$this->assertFalse($this->backend->checkPassword($name1, 'dummy'));
$this->assertFalse($this->backend->checkPassword($name2, 'foobar'));
$this->backend->setPassword($name1, 'newpass1');
$this->assertFalse($this->backend->checkPassword($name1, 'pass1'));
$this->assertTrue($this->backend->checkPassword($name1, 'newpass1'));
$this->assertFalse($this->backend->checkPassword($name2, 'newpass1'));
}
}

View File

@ -0,0 +1,44 @@
<?php
/**
* ownCloud
*
* @author Robin Appelman
* @copyright 2012 Robin Appelman icewind@owncloud.com
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
* License as published by the Free Software Foundation; either
* version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU AFFERO GENERAL PUBLIC LICENSE for more details.
*
* You should have received a copy of the GNU Affero General Public
* License along with this library. If not, see <http://www.gnu.org/licenses/>.
*
*/
class Test_User_Database extends Test_User_Backend {
/**
* get a new unique user name
* test cases can override this in order to clean up created user
* @return array
*/
public function getUser() {
$user=uniqid('test_');
$this->users[]=$user;
return $user;
}
public function setUp() {
$this->backend=new OC_User_Dummy();
}
public function tearDown() {
foreach($this->users as $user) {
$this->backend->deleteUser($user);
}
}
}

27
tests/lib/user/dummy.php Normal file
View File

@ -0,0 +1,27 @@
<?php
/**
* ownCloud
*
* @author Robin Appelman
* @copyright 2012 Robin Appelman icewind@owncloud.com
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
* License as published by the Free Software Foundation; either
* version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU AFFERO GENERAL PUBLIC LICENSE for more details.
*
* You should have received a copy of the GNU Affero General Public
* License along with this library. If not, see <http://www.gnu.org/licenses/>.
*
*/
class Test_User_Dummy extends Test_User_Backend {
public function setUp() {
$this->backend=new OC_User_Dummy();
}
}

304
tests/lib/user/manager.php Normal file
View File

@ -0,0 +1,304 @@
<?php
/**
* Copyright (c) 2013 Robin Appelman <icewind@owncloud.com>
* This file is licensed under the Affero General Public License version 3 or
* later.
* See the COPYING-README file.
*/
namespace Test\User;
class Manager extends \PHPUnit_Framework_TestCase {
public function testUserExistsSingleBackendExists() {
/**
* @var \OC_User_Dummy | \PHPUnit_Framework_MockObject_MockObject $backend
*/
$backend = $this->getMock('\OC_User_Dummy');
$backend->expects($this->once())
->method('userExists')
->with($this->equalTo('foo'))
->will($this->returnValue(true));
$manager = new \OC\User\Manager();
$manager->registerBackend($backend);
$this->assertTrue($manager->userExists('foo'));
}
public function testUserExistsSingleBackendNotExists() {
/**
* @var \OC_User_Dummy | \PHPUnit_Framework_MockObject_MockObject $backend
*/
$backend = $this->getMock('\OC_User_Dummy');
$backend->expects($this->once())
->method('userExists')
->with($this->equalTo('foo'))
->will($this->returnValue(false));
$manager = new \OC\User\Manager();
$manager->registerBackend($backend);
$this->assertFalse($manager->userExists('foo'));
}
public function testUserExistsNoBackends() {
$manager = new \OC\User\Manager();
$this->assertFalse($manager->userExists('foo'));
}
public function testUserExistsTwoBackendsSecondExists() {
/**
* @var \OC_User_Dummy | \PHPUnit_Framework_MockObject_MockObject $backend1
*/
$backend1 = $this->getMock('\OC_User_Dummy');
$backend1->expects($this->once())
->method('userExists')
->with($this->equalTo('foo'))
->will($this->returnValue(false));
/**
* @var \OC_User_Dummy | \PHPUnit_Framework_MockObject_MockObject $backend2
*/
$backend2 = $this->getMock('\OC_User_Dummy');
$backend2->expects($this->once())
->method('userExists')
->with($this->equalTo('foo'))
->will($this->returnValue(true));
$manager = new \OC\User\Manager();
$manager->registerBackend($backend1);
$manager->registerBackend($backend2);
$this->assertTrue($manager->userExists('foo'));
}
public function testUserExistsTwoBackendsFirstExists() {
/**
* @var \OC_User_Dummy | \PHPUnit_Framework_MockObject_MockObject $backend1
*/
$backend1 = $this->getMock('\OC_User_Dummy');
$backend1->expects($this->once())
->method('userExists')
->with($this->equalTo('foo'))
->will($this->returnValue(true));
/**
* @var \OC_User_Dummy | \PHPUnit_Framework_MockObject_MockObject $backend2
*/
$backend2 = $this->getMock('\OC_User_Dummy');
$backend2->expects($this->never())
->method('userExists');
$manager = new \OC\User\Manager();
$manager->registerBackend($backend1);
$manager->registerBackend($backend2);
$this->assertTrue($manager->userExists('foo'));
}
public function testGetOneBackendExists() {
/**
* @var \OC_User_Dummy | \PHPUnit_Framework_MockObject_MockObject $backend
*/
$backend = $this->getMock('\OC_User_Dummy');
$backend->expects($this->once())
->method('userExists')
->with($this->equalTo('foo'))
->will($this->returnValue(true));
$manager = new \OC\User\Manager();
$manager->registerBackend($backend);
$this->assertEquals('foo', $manager->get('foo')->getUID());
}
public function testGetOneBackendNotExists() {
/**
* @var \OC_User_Dummy | \PHPUnit_Framework_MockObject_MockObject $backend
*/
$backend = $this->getMock('\OC_User_Dummy');
$backend->expects($this->once())
->method('userExists')
->with($this->equalTo('foo'))
->will($this->returnValue(false));
$manager = new \OC\User\Manager();
$manager->registerBackend($backend);
$this->assertEquals(null, $manager->get('foo'));
}
public function testSearchOneBackend() {
/**
* @var \OC_User_Dummy | \PHPUnit_Framework_MockObject_MockObject $backend
*/
$backend = $this->getMock('\OC_User_Dummy');
$backend->expects($this->once())
->method('getUsers')
->with($this->equalTo('fo'))
->will($this->returnValue(array('foo', 'afoo')));
$manager = new \OC\User\Manager();
$manager->registerBackend($backend);
$result = $manager->search('fo');
$this->assertEquals(2, count($result));
$this->assertEquals('afoo', $result[0]->getUID());
$this->assertEquals('foo', $result[1]->getUID());
}
public function testSearchTwoBackendLimitOffset() {
/**
* @var \OC_User_Dummy | \PHPUnit_Framework_MockObject_MockObject $backend1
*/
$backend1 = $this->getMock('\OC_User_Dummy');
$backend1->expects($this->once())
->method('getUsers')
->with($this->equalTo('fo'), $this->equalTo(3), $this->equalTo(1))
->will($this->returnValue(array('foo1', 'foo2')));
/**
* @var \OC_User_Dummy | \PHPUnit_Framework_MockObject_MockObject $backend2
*/
$backend2 = $this->getMock('\OC_User_Dummy');
$backend2->expects($this->once())
->method('getUsers')
->with($this->equalTo('fo'), $this->equalTo(1), $this->equalTo(0))
->will($this->returnValue(array('foo3')));
$manager = new \OC\User\Manager();
$manager->registerBackend($backend1);
$manager->registerBackend($backend2);
$result = $manager->search('fo', 3, 1);
$this->assertEquals(3, count($result));
$this->assertEquals('foo1', $result[0]->getUID());
$this->assertEquals('foo2', $result[1]->getUID());
$this->assertEquals('foo3', $result[2]->getUID());
}
public function testCreateUserSingleBackendNotExists() {
/**
* @var \OC_User_Dummy | \PHPUnit_Framework_MockObject_MockObject $backend
*/
$backend = $this->getMock('\OC_User_Dummy');
$backend->expects($this->any())
->method('implementsActions')
->will($this->returnValue(true));
$backend->expects($this->once())
->method('createUser')
->with($this->equalTo('foo'), $this->equalTo('bar'));
$backend->expects($this->once())
->method('userExists')
->with($this->equalTo('foo'))
->will($this->returnValue(false));
$manager = new \OC\User\Manager();
$manager->registerBackend($backend);
$user = $manager->createUser('foo', 'bar');
$this->assertEquals('foo', $user->getUID());
}
/**
* @expectedException \Exception
*/
public function testCreateUserSingleBackendExists() {
/**
* @var \OC_User_Dummy | \PHPUnit_Framework_MockObject_MockObject $backend
*/
$backend = $this->getMock('\OC_User_Dummy');
$backend->expects($this->any())
->method('implementsActions')
->will($this->returnValue(true));
$backend->expects($this->never())
->method('createUser');
$backend->expects($this->once())
->method('userExists')
->with($this->equalTo('foo'))
->will($this->returnValue(true));
$manager = new \OC\User\Manager();
$manager->registerBackend($backend);
$manager->createUser('foo', 'bar');
}
public function testCreateUserSingleBackendNotSupported() {
/**
* @var \OC_User_Dummy | \PHPUnit_Framework_MockObject_MockObject $backend
*/
$backend = $this->getMock('\OC_User_Dummy');
$backend->expects($this->any())
->method('implementsActions')
->will($this->returnValue(false));
$backend->expects($this->never())
->method('createUser');
$backend->expects($this->once())
->method('userExists')
->with($this->equalTo('foo'))
->will($this->returnValue(false));
$manager = new \OC\User\Manager();
$manager->registerBackend($backend);
$this->assertFalse($manager->createUser('foo', 'bar'));
}
public function testCreateUserNoBackends() {
$manager = new \OC\User\Manager();
$this->assertFalse($manager->createUser('foo', 'bar'));
}
/**
* @expectedException \Exception
*/
public function testCreateUserTwoBackendExists() {
/**
* @var \OC_User_Dummy | \PHPUnit_Framework_MockObject_MockObject $backend1
*/
$backend1 = $this->getMock('\OC_User_Dummy');
$backend1->expects($this->any())
->method('implementsActions')
->will($this->returnValue(true));
$backend1->expects($this->never())
->method('createUser');
$backend1->expects($this->once())
->method('userExists')
->with($this->equalTo('foo'))
->will($this->returnValue(false));
/**
* @var \OC_User_Dummy | \PHPUnit_Framework_MockObject_MockObject $backend2
*/
$backend2 = $this->getMock('\OC_User_Dummy');
$backend2->expects($this->any())
->method('implementsActions')
->will($this->returnValue(true));
$backend2->expects($this->never())
->method('createUser');
$backend2->expects($this->once())
->method('userExists')
->with($this->equalTo('foo'))
->will($this->returnValue(true));
$manager = new \OC\User\Manager();
$manager->registerBackend($backend1);
$manager->registerBackend($backend2);
$manager->createUser('foo', 'bar');
}
}

155
tests/lib/user/session.php Normal file
View File

@ -0,0 +1,155 @@
<?php
/**
* Copyright (c) 2013 Robin Appelman <icewind@owncloud.com>
* This file is licensed under the Affero General Public License version 3 or
* later.
* See the COPYING-README file.
*/
namespace Test\User;
class Session extends \PHPUnit_Framework_TestCase {
public function testGetUser() {
$session = $this->getMock('\OC\Session\Memory', array(), array(''));
$session->expects($this->once())
->method('get')
->with('user_id')
->will($this->returnValue('foo'));
$backend = $this->getMock('OC_User_Dummy');
$backend->expects($this->once())
->method('userExists')
->with('foo')
->will($this->returnValue(true));
$manager = new \OC\User\Manager();
$manager->registerBackend($backend);
$userSession = new \OC\User\Session($manager, $session);
$user = $userSession->getUser();
$this->assertEquals('foo', $user->getUID());
}
public function testSetUser() {
$session = $this->getMock('\OC\Session\Memory', array(), array(''));
$session->expects($this->once())
->method('set')
->with('user_id', 'foo');
$manager = $this->getMock('\OC\User\Manager');
$backend = $this->getMock('OC_User_Dummy');
$user = $this->getMock('\OC\User\User', array(), array('foo', $backend));
$user->expects($this->once())
->method('getUID')
->will($this->returnValue('foo'));
$userSession = new \OC\User\Session($manager, $session);
$userSession->setUser($user);
}
public function testLoginValidPasswordEnabled() {
$session = $this->getMock('\OC\Session\Memory', array(), array(''));
$session->expects($this->once())
->method('set')
->with('user_id', 'foo');
$manager = $this->getMock('\OC\User\Manager');
$backend = $this->getMock('OC_User_Dummy');
$user = $this->getMock('\OC\User\User', array(), array('foo', $backend));
$user->expects($this->once())
->method('checkPassword')
->with('bar')
->will($this->returnValue(true));
$user->expects($this->once())
->method('isEnabled')
->will($this->returnValue(true));
$user->expects($this->any())
->method('getUID')
->will($this->returnValue('foo'));
$manager->expects($this->once())
->method('get')
->with('foo')
->will($this->returnValue($user));
$userSession = new \OC\User\Session($manager, $session);
$userSession->login('foo', 'bar');
$this->assertEquals($user, $userSession->getUser());
}
public function testLoginValidPasswordDisabled() {
$session = $this->getMock('\OC\Session\Memory', array(), array(''));
$session->expects($this->never())
->method('set');
$manager = $this->getMock('\OC\User\Manager');
$backend = $this->getMock('OC_User_Dummy');
$user = $this->getMock('\OC\User\User', array(), array('foo', $backend));
$user->expects($this->once())
->method('checkPassword')
->with('bar')
->will($this->returnValue(true));
$user->expects($this->once())
->method('isEnabled')
->will($this->returnValue(false));
$manager->expects($this->once())
->method('get')
->with('foo')
->will($this->returnValue($user));
$userSession = new \OC\User\Session($manager, $session);
$userSession->login('foo', 'bar');
}
public function testLoginInValidPassword() {
$session = $this->getMock('\OC\Session\Memory', array(), array(''));
$session->expects($this->never())
->method('set');
$manager = $this->getMock('\OC\User\Manager');
$backend = $this->getMock('OC_User_Dummy');
$user = $this->getMock('\OC\User\User', array(), array('foo', $backend));
$user->expects($this->once())
->method('checkPassword')
->with('bar')
->will($this->returnValue(false));
$user->expects($this->never())
->method('isEnabled');
$manager->expects($this->once())
->method('get')
->with('foo')
->will($this->returnValue($user));
$userSession = new \OC\User\Session($manager, $session);
$userSession->login('foo', 'bar');
}
public function testLoginNonExisting() {
$session = $this->getMock('\OC\Session\Memory', array(), array(''));
$session->expects($this->never())
->method('set');
$manager = $this->getMock('\OC\User\Manager');
$backend = $this->getMock('OC_User_Dummy');
$manager->expects($this->once())
->method('get')
->with('foo')
->will($this->returnValue(null));
$userSession = new \OC\User\Session($manager, $session);
$userSession->login('foo', 'bar');
}
}

364
tests/lib/user/user.php Normal file
View File

@ -0,0 +1,364 @@
<?php
/**
* Copyright (c) 2013 Robin Appelman <icewind@owncloud.com>
* This file is licensed under the Affero General Public License version 3 or
* later.
* See the COPYING-README file.
*/
namespace Test\User;
use OC\Hooks\PublicEmitter;
class User extends \PHPUnit_Framework_TestCase {
public function testDisplayName() {
/**
* @var \OC_User_Backend | \PHPUnit_Framework_MockObject_MockObject $backend
*/
$backend = $this->getMock('\OC_User_Backend');
$backend->expects($this->once())
->method('getDisplayName')
->with($this->equalTo('foo'))
->will($this->returnValue('Foo'));
$backend->expects($this->any())
->method('implementsActions')
->with($this->equalTo(\OC_USER_BACKEND_GET_DISPLAYNAME))
->will($this->returnValue(true));
$user = new \OC\User\User('foo', $backend);
$this->assertEquals('Foo', $user->getDisplayName());
}
public function testDisplayNameNotSupported() {
/**
* @var \OC_User_Backend | \PHPUnit_Framework_MockObject_MockObject $backend
*/
$backend = $this->getMock('\OC_User_Backend');
$backend->expects($this->never())
->method('getDisplayName');
$backend->expects($this->any())
->method('implementsActions')
->with($this->equalTo(\OC_USER_BACKEND_GET_DISPLAYNAME))
->will($this->returnValue(false));
$user = new \OC\User\User('foo', $backend);
$this->assertEquals('foo', $user->getDisplayName());
}
public function testSetPassword() {
/**
* @var \OC_User_Backend | \PHPUnit_Framework_MockObject_MockObject $backend
*/
$backend = $this->getMock('\OC_User_Dummy');
$backend->expects($this->once())
->method('setPassword')
->with($this->equalTo('foo'), $this->equalTo('bar'));
$backend->expects($this->any())
->method('implementsActions')
->will($this->returnCallback(function ($actions) {
if ($actions === \OC_USER_BACKEND_SET_PASSWORD) {
return true;
} else {
return false;
}
}));
$user = new \OC\User\User('foo', $backend);
$this->assertTrue($user->setPassword('bar',''));
}
public function testSetPasswordNotSupported() {
/**
* @var \OC_User_Backend | \PHPUnit_Framework_MockObject_MockObject $backend
*/
$backend = $this->getMock('\OC_User_Dummy');
$backend->expects($this->never())
->method('setPassword');
$backend->expects($this->any())
->method('implementsActions')
->will($this->returnValue(false));
$user = new \OC\User\User('foo', $backend);
$this->assertFalse($user->setPassword('bar',''));
}
public function testDelete() {
/**
* @var \OC_User_Backend | \PHPUnit_Framework_MockObject_MockObject $backend
*/
$backend = $this->getMock('\OC_User_Dummy');
$backend->expects($this->once())
->method('deleteUser')
->with($this->equalTo('foo'));
$user = new \OC\User\User('foo', $backend);
$this->assertTrue($user->delete());
}
public function testCheckPassword() {
/**
* @var \OC_User_Backend | \PHPUnit_Framework_MockObject_MockObject $backend
*/
$backend = $this->getMock('\OC_User_Dummy');
$backend->expects($this->once())
->method('checkPassword')
->with($this->equalTo('foo'), $this->equalTo('bar'))
->will($this->returnValue(true));
$backend->expects($this->any())
->method('implementsActions')
->will($this->returnCallback(function ($actions) {
if ($actions === \OC_USER_BACKEND_CHECK_PASSWORD) {
return true;
} else {
return false;
}
}));
$user = new \OC\User\User('foo', $backend);
$this->assertTrue($user->checkPassword('bar'));
}
public function testCheckPasswordNotSupported() {
/**
* @var \OC_User_Backend | \PHPUnit_Framework_MockObject_MockObject $backend
*/
$backend = $this->getMock('\OC_User_Dummy');
$backend->expects($this->never())
->method('checkPassword');
$backend->expects($this->any())
->method('implementsActions')
->will($this->returnValue(false));
$user = new \OC\User\User('foo', $backend);
$this->assertFalse($user->checkPassword('bar'));
}
public function testGetHome() {
/**
* @var \OC_User_Backend | \PHPUnit_Framework_MockObject_MockObject $backend
*/
$backend = $this->getMock('\OC_User_Dummy');
$backend->expects($this->once())
->method('getHome')
->with($this->equalTo('foo'))
->will($this->returnValue('/home/foo'));
$backend->expects($this->any())
->method('implementsActions')
->will($this->returnCallback(function ($actions) {
if ($actions === \OC_USER_BACKEND_GET_HOME) {
return true;
} else {
return false;
}
}));
$user = new \OC\User\User('foo', $backend);
$this->assertEquals('/home/foo', $user->getHome());
}
public function testGetHomeNotSupported() {
/**
* @var \OC_User_Backend | \PHPUnit_Framework_MockObject_MockObject $backend
*/
$backend = $this->getMock('\OC_User_Dummy');
$backend->expects($this->never())
->method('getHome');
$backend->expects($this->any())
->method('implementsActions')
->will($this->returnValue(false));
$user = new \OC\User\User('foo', $backend);
$this->assertEquals(\OC_Config::getValue("datadirectory", \OC::$SERVERROOT . "/data") . '/foo', $user->getHome());
}
public function testCanChangePassword() {
/**
* @var \OC_User_Backend | \PHPUnit_Framework_MockObject_MockObject $backend
*/
$backend = $this->getMock('\OC_User_Dummy');
$backend->expects($this->any())
->method('implementsActions')
->will($this->returnCallback(function ($actions) {
if ($actions === \OC_USER_BACKEND_SET_PASSWORD) {
return true;
} else {
return false;
}
}));
$user = new \OC\User\User('foo', $backend);
$this->assertTrue($user->canChangePassword());
}
public function testCanChangePasswordNotSupported() {
/**
* @var \OC_User_Backend | \PHPUnit_Framework_MockObject_MockObject $backend
*/
$backend = $this->getMock('\OC_User_Dummy');
$backend->expects($this->any())
->method('implementsActions')
->will($this->returnValue(false));
$user = new \OC\User\User('foo', $backend);
$this->assertFalse($user->canChangePassword());
}
public function testCanChangeDisplayName() {
/**
* @var \OC_User_Backend | \PHPUnit_Framework_MockObject_MockObject $backend
*/
$backend = $this->getMock('\OC_User_Dummy');
$backend->expects($this->any())
->method('implementsActions')
->will($this->returnCallback(function ($actions) {
if ($actions === \OC_USER_BACKEND_SET_DISPLAYNAME) {
return true;
} else {
return false;
}
}));
$user = new \OC\User\User('foo', $backend);
$this->assertTrue($user->canChangeDisplayName());
}
public function testCanChangeDisplayNameNotSupported() {
/**
* @var \OC_User_Backend | \PHPUnit_Framework_MockObject_MockObject $backend
*/
$backend = $this->getMock('\OC_User_Dummy');
$backend->expects($this->any())
->method('implementsActions')
->will($this->returnValue(false));
$user = new \OC\User\User('foo', $backend);
$this->assertFalse($user->canChangeDisplayName());
}
public function testSetDisplayNameSupported() {
/**
* @var \OC_User_Backend | \PHPUnit_Framework_MockObject_MockObject $backend
*/
$backend = $this->getMock('\OC_User_Database');
$backend->expects($this->any())
->method('implementsActions')
->will($this->returnCallback(function ($actions) {
if ($actions === \OC_USER_BACKEND_SET_DISPLAYNAME) {
return true;
} else {
return false;
}
}));
$backend->expects($this->once())
->method('setDisplayName')
->with('foo','Foo');
$user = new \OC\User\User('foo', $backend);
$this->assertTrue($user->setDisplayName('Foo'));
$this->assertEquals('Foo',$user->getDisplayName());
}
public function testSetDisplayNameNotSupported() {
/**
* @var \OC_User_Backend | \PHPUnit_Framework_MockObject_MockObject $backend
*/
$backend = $this->getMock('\OC_User_Database');
$backend->expects($this->any())
->method('implementsActions')
->will($this->returnCallback(function ($actions) {
return false;
}));
$backend->expects($this->never())
->method('setDisplayName');
$user = new \OC\User\User('foo', $backend);
$this->assertFalse($user->setDisplayName('Foo'));
$this->assertEquals('foo',$user->getDisplayName());
}
public function testSetPasswordHooks() {
$hooksCalled = 0;
$test = $this;
/**
* @var \OC_User_Backend | \PHPUnit_Framework_MockObject_MockObject $backend
*/
$backend = $this->getMock('\OC_User_Dummy');
$backend->expects($this->once())
->method('setPassword');
/**
* @param \OC\User\User $user
* @param string $password
*/
$hook = function ($user, $password) use ($test, &$hooksCalled) {
$hooksCalled++;
$test->assertEquals('foo', $user->getUID());
$test->assertEquals('bar', $password);
};
$emitter = new PublicEmitter();
$emitter->listen('\OC\User', 'preSetPassword', $hook);
$emitter->listen('\OC\User', 'postSetPassword', $hook);
$backend->expects($this->any())
->method('implementsActions')
->will($this->returnCallback(function ($actions) {
if ($actions === \OC_USER_BACKEND_SET_PASSWORD) {
return true;
} else {
return false;
}
}));
$user = new \OC\User\User('foo', $backend, $emitter);
$user->setPassword('bar','');
$this->assertEquals(2, $hooksCalled);
}
public function testDeleteHooks() {
$hooksCalled = 0;
$test = $this;
/**
* @var \OC_User_Backend | \PHPUnit_Framework_MockObject_MockObject $backend
*/
$backend = $this->getMock('\OC_User_Dummy');
$backend->expects($this->once())
->method('deleteUser');
/**
* @param \OC\User\User $user
*/
$hook = function ($user) use ($test, &$hooksCalled) {
$hooksCalled++;
$test->assertEquals('foo', $user->getUID());
};
$emitter = new PublicEmitter();
$emitter->listen('\OC\User', 'preDelete', $hook);
$emitter->listen('\OC\User', 'postDelete', $hook);
$user = new \OC\User\User('foo', $backend, $emitter);
$this->assertTrue($user->delete());
$this->assertEquals(2, $hooksCalled);
}
}