/** * Authenticates the given user. If successful, an instance * of the user is returned. * * @param User $user The user to authenticate * @throws InvalidLoginDataException Thrown if the user's credentials are not valid */ public function authenticate(User $user) { $result = PartKeepr::getEM()->getRepository("PartKeepr\\User\\User")->findOneBy(array("username" => $user->getUsername(), "password" => $user->getHashedPassword())); if ($result == null) { throw new InvalidLoginDataException(); } else { return $result; } }
/** * Creates a new user. * * @see PartKeepr\Service.RestfulService::create() */ public function create() { if (!SessionManager::getCurrentSession()->getUser()->isAdmin()) { throw new \Exception("Permission denied"); } $this->requireParameter("username"); $user = new User(); $user->deserialize($this->getParameters()); UserManager::getInstance()->createUser($user); return array("data" => $user->serialize()); }
/** * (non-PHPdoc) * @see PartKeepr\Service.RestfulService::update() */ public function update() { $this->requireParameter("id"); $stockEntry = StockEntry::loadById($this->getParameter("id")); if (!SessionManager::getCurrentSession()->getUser()->isAdmin() && !(SessionManager::getCurrentSession()->getUser() && $stockEntry->getUser() && SessionManager::getCurrentSession()->getUser()->getId() == $stockEntry->getUser()->getId())) { throw new \Exception("Permission denied"); } /* It's not allowed to edit a price for a removal */ if (!$stockEntry->isRemoval()) { $stockEntry->setPrice(abs($this->getParameter("price"))); } /** * Only an admin user may correct the in&out stock levels */ if (SessionManager::getCurrentSession()->getUser()->isAdmin()) { if ($this->getParameter("direction") == "out") { $stockEntry->setStockLevel(-abs($this->getParameter("stockLevel"))); } else { $stockEntry->setStockLevel($this->getParameter("stockLevel")); } } if (SessionManager::getCurrentSession()->getUser()->isAdmin()) { try { $stockEntry->setUser(User::loadById($this->getParameter("user_id"))); } catch (\Exception $e) { $stockEntry->setUser(null); } } $stockEntry->setComment($this->getParameter("comment")); PartKeepr::getEM()->flush(); return array("data" => $stockEntry->serialize()); }
/** * Deletes a key-value combination from the database. * * (non-PHPdoc) * @see PartKeepr\Service.RestfulService::destroy() */ public function destroy() { if ($this->hasParameter("user_id") && SessionManager::getCurrentSession()->getUser()->isAdmin()) { UserPreference::deletePreference(User::loadById($this->getParameter("user_id")), $this->getParameter("key")); } else { UserPreference::deletePreference($this->getUser(), $this->getParameter("key")); } }
public function run() { $dql = "SELECT COUNT(u) FROM PartKeepr\\User\\User u WHERE u.username = :username OR u.admin = :admin"; $query = $this->entityManager->createQuery($dql); $query->setParameter("username", "admin"); $query->setParameter("admin", true); if ($query->getSingleScalarResult() == 0) { $user = new User(); $user->setUsername("admin"); $user->setPassword("admin"); $user->setAdmin(true); $this->entityManager->persist($user); $this->entityManager->flush(); $this->logMessage("Admin User created"); } else { $this->logMessage("Skipped admin user creation, because an user named 'admin'" . "or another user with an admin flag already exists"); } }
/** * Logs in the given user. If the login was successful, a session is automatically started. * * @return array The data * @throws InvalidLoginDataException * * @ServiceCall(description="Authenticates a user against the system", * documentation="Authenticates a user and starts a new session upon success.", * returnValues={ * @ServiceReturnValue( * name="username", * type="string:50", * description="The logged in username" * ), * @ServiceReturnValue( * name="sessionid", * type="string:50", * description="The session ID" * ), * @ServiceReturnValue( * name="admin", * type="boolean", * description="True if the logged in user has admin rights" * ), * @ServiceReturnValue( * name="userPreferences", * type="UserPreference[]", * description="An array of UserPreferences" * ) * }, * parameters={ * @ServiceParameter( name="username", * type="string:50", * required=true, * description="The username to authenticate" * ), * @ServiceParameter( name="password", * type="string:32", * required=true, * description="The password, hashed in MD5" * ) * }) * */ public function login() { $this->requireParameter("username"); $this->requireParameter("password"); /* Build a temporary user */ $user = new User(); $user->setRawUsername($this->getParameter("username")); $user->setHashedPassword($this->getParameter("password")); $authenticatedUser = UserManager::getInstance()->authenticate($user); if ($authenticatedUser !== false) { /* Start Session */ $session = SessionManager::getInstance()->startSession($authenticatedUser); $session->getUser()->updateSeen(); $aPreferences = array(); foreach ($session->getUser()->getPreferences() as $result) { $aPreferences[] = $result->serialize(); } return array("sessionid" => $session->getSessionID(), "username" => $this->getParameter("username"), "admin" => $session->getUser()->isAdmin(), "userPreferences" => array("response" => array("data" => $aPreferences))); } else { throw new InvalidLoginDataException(); } }
/** * Initializes a bootstrapped PartKeepr environment. * * This is done within a function because we don't want to pollute the globals, which would give the following message * during unit tests: * * "PDOException: You cannot serialize or unserialize PDO instances" */ function initializeEnvironment() { PartKeepr::initialize("test"); $tool = new \Doctrine\ORM\Tools\SchemaTool(PartKeepr::getEM()); $classes = PartKeepr::getClassMetaData(); $tool->dropDatabase(); $tool->createSchema($classes); /* Some very basic installation things */ PartCategoryManager::getInstance()->ensureRootExists(); /* Create a blank admin user */ $user = new User(); $user->setUsername("admin"); $user->setPassword("admin"); $user->setAdmin(true); PartKeepr::getEM()->persist($user); /* Create a blank regular user */ $user2 = new User(); $user2->setUsername("regular"); $user2->setPassword("regular"); $user2->setAdmin(false); PartKeepr::getEM()->persist($user2); PartKeepr::getEM()->flush(); }
/** * Assigns the "regular" user for this test and deletes all user preferences for testing * (non-PHPdoc) * @see PHPUnit_Framework_TestCase::setUp() */ protected function setUp() { $this->user = User::loadByName("regular"); $this->deleteUserPreferences(); }
public function __construct(User $user, $preferenceKey) { $message = sprintf(PartKeepr::i18n("User preference %s not found for user %s (%s)"), $preferenceKey, $user->getUsername(), $user->getId()); parent::__construct($message); }
/** * (non-PHPdoc) * @see PartKeepr\Service.RestfulService::create() */ public function create() { $entity = PartManager::getInstance()->createEntity($this->getParameters()); if ($this->getParameter("initialStockLevel") > 0) { try { $user = User::loadById($this->getParameter("initialStockLevelUser")); } catch (\Exception $e) { $user = SessionManager::getCurrentSession()->getUser(); } $stock = new StockEntry($entity, intval($this->getParameter("initialStockLevel")), $user); if ($this->getParameter("initialStockLevelPricePerItem") == true) { $price = floatval($this->getParameter("initialStockLevelPrice")); } else { $price = floatval($this->getParameter("initialStockLevelPrice")) / $this->getParameter("initialStockLevel"); } if ($price != 0) { $stock->setPrice($price); } PartKeepr::getEM()->persist($stock); PartKeepr::getEM()->flush(); $entity->updateStockLevel(); PartKeepr::getEM()->flush(); } return array("data" => $entity->serialize()); }
/** * Makes sure that an exception is thrown when attempting to delete a preference if the user is not persistant yet. * * @expectedException PartKeepr\Util\Exceptions\EntityNotPersistantException */ public function testDeleteNonPersistantUserPreference() { $user = new User(); $user->deletePreference("test"); }
public function testBasics() { $user = new User(); $user->setUsername("felicitus"); $this->assertEquals($user->getUsername(), "felicitus"); $user->setUsername("Timo A. Hummel"); $this->assertEquals($user->getUsername(), "Timo A. Hummel"); $user->setPassword("foobar"); $hashedPassword = "******"; $this->assertEquals($user->comparePassword("foobar"), true, "Error comparing passwords: PasswordTest01"); $this->assertEquals($user->compareHashedPassword($hashedPassword), true, "Error comparing passwords: PasswordTest02"); $user->setHashedPassword($hashedPassword); $this->assertEquals($user->comparePassword("foobar"), true, "Error comparing passwords: PasswordTest03"); $this->assertEquals($user->compareHashedPassword($hashedPassword), true, "Error comparing passwords: PasswordTest04"); }
/* Fill parameters with most common options */ $aParameters = array(); $aParameters["doctrine_orm_version"] = \Doctrine\ORM\Version::VERSION; $aParameters["doctrine_dbal_version"] = \Doctrine\DBAL\Version::VERSION; $aParameters["doctrine_common_version"] = \Doctrine\Common\Version::VERSION; $aParameters["php_version"] = phpversion(); /* HTTP auth */ if (Configuration::getOption("partkeepr.auth.http", false) === true) { if (!isset($_SERVER["PHP_AUTH_USER"])) { // @todo Redirect to permission denied page die("Permission denied"); } try { $user = User::loadByName($_SERVER['PHP_AUTH_USER']); } catch (\Doctrine\ORM\NoResultException $e) { $user = new User(); $user->setUsername($_SERVER['PHP_AUTH_USER']); $user->setPassword("invalid"); PartKeepr::getEM()->persist($user); PartKeepr::getEM()->flush(); } $session = SessionManager::getInstance()->startSession($user); $aParameters["autoLoginUsername"] = $user->getUsername(); $aParameters["auto_start_session"] = $session->getSessionID(); $aPreferences = array(); foreach ($user->getPreferences() as $result) { $aPreferences[] = $result->serialize(); } $aParameters["userPreferences"] = array("response" => array("data" => $aPreferences)); } \Twig_Autoloader::register();
private function authenticateByUsername($username, $password) { /* Build a temporary user */ $user = new User(); $user->setRawUsername($username); $user->setHashedPassword($password); $authenticatedUser = UserManager::getInstance()->authenticate($user); if ($authenticatedUser !== false) { /* Start Session */ $session = SessionManager::getInstance()->startSession($authenticatedUser); return $session->getSessionID(); } else { throw new InvalidLoginDataException(); } }