PageRenderTime 26ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 0ms

/ojs/ojs-2.3.2-1/classes/security/Validation.inc.php

https://github.com/mcrider/pkpUpgradeTestSuite
PHP | 415 lines | 210 code | 62 blank | 143 comment | 43 complexity | c79506316066e0b87127646f076378ff MD5 | raw file
Possible License(s): GPL-2.0, LGPL-2.1
  1. <?php
  2. /**
  3. * @file classes/security/Validation.inc.php
  4. *
  5. * Copyright (c) 2003-2009 John Willinsky
  6. * Distributed under the GNU GPL v2. For full terms see the file docs/COPYING.
  7. *
  8. * @class Validation
  9. * @ingroup security
  10. *
  11. * @brief Class providing user validation/authentication operations.
  12. */
  13. // $Id$
  14. import('security.Role');
  15. class Validation {
  16. /**
  17. * Authenticate user credentials and mark the user as logged in in the current session.
  18. * @param $username string
  19. * @param $password string unencrypted password
  20. * @param $reason string reference to string to receive the reason an account was disabled; null otherwise
  21. * @param $remember boolean remember a user's session past the current browser session
  22. * @return User the User associated with the login credentials, or false if the credentials are invalid
  23. */
  24. function &login($username, $password, &$reason, $remember = false) {
  25. $implicitAuth = Config::getVar('security', 'implicit_auth');
  26. $reason = null;
  27. $valid = false;
  28. $userDao =& DAORegistry::getDAO('UserDAO');
  29. if ($implicitAuth) { // Implicit auth
  30. if (!Validation::isLoggedIn()) {
  31. PluginRegistry::loadCategory('implicitAuth');
  32. // Call the implicitAuth hook. It will set user.
  33. HookRegistry::call('ImplicitAuthPlugin::implicitAuth', array(&$user));
  34. $valid=true;
  35. }
  36. } else { // Regular Auth
  37. $user =& $userDao->getUserByUsername($username, true);
  38. if (!isset($user)) {
  39. // User does not exist
  40. return $valid;
  41. }
  42. if ($user->getAuthId()) {
  43. $authDao =& DAORegistry::getDAO('AuthSourceDAO');
  44. $auth =& $authDao->getPlugin($user->getAuthId());
  45. }
  46. if (isset($auth)) {
  47. // Validate against remote authentication source
  48. $valid = $auth->authenticate($username, $password);
  49. if ($valid) {
  50. $oldEmail = $user->getEmail();
  51. $auth->doGetUserInfo($user);
  52. if ($user->getEmail() != $oldEmail) {
  53. // FIXME OJS requires email addresses to be unique; if changed email already exists, ignore
  54. if ($userDao->userExistsByEmail($user->getEmail())) {
  55. $user->setEmail($oldEmail);
  56. }
  57. }
  58. }
  59. } else {
  60. // Validate against OJS user database
  61. $valid = ($user->getPassword() === Validation::encryptCredentials($username, $password));
  62. }
  63. }
  64. if (!$valid) {
  65. // Login credentials are invalid
  66. return $valid;
  67. } else {
  68. if ($user->getDisabled()) {
  69. // The user has been disabled.
  70. $reason = $user->getDisabledReason();
  71. if ($reason === null) $reason = '';
  72. $valid = false;
  73. return $valid;
  74. }
  75. // The user is valid, mark user as logged in in current session
  76. $sessionManager =& SessionManager::getManager();
  77. // Regenerate session ID first
  78. $sessionManager->regenerateSessionId();
  79. $session =& $sessionManager->getUserSession();
  80. $session->setSessionVar('userId', $user->getId());
  81. $session->setUserId($user->getId());
  82. $session->setSessionVar('username', $user->getUsername());
  83. $session->setRemember($remember);
  84. if ($remember && Config::getVar('general', 'session_lifetime') > 0) {
  85. // Update session expiration time
  86. $sessionManager->updateSessionLifetime(time() + Config::getVar('general', 'session_lifetime') * 86400);
  87. }
  88. $user->setDateLastLogin(Core::getCurrentDate());
  89. $userDao->updateObject($user);
  90. return $user;
  91. }
  92. }
  93. /**
  94. * Mark the user as logged out in the current session.
  95. * @return boolean
  96. */
  97. function logout() {
  98. $sessionManager =& SessionManager::getManager();
  99. $session =& $sessionManager->getUserSession();
  100. $session->unsetSessionVar('userId');
  101. $session->unsetSessionVar('signedInAs');
  102. $session->setUserId(null);
  103. if ($session->getRemember()) {
  104. $session->setRemember(0);
  105. $sessionManager->updateSessionLifetime(0);
  106. }
  107. $sessionDao =& DAORegistry::getDAO('SessionDAO');
  108. $sessionDao->updateObject($session);
  109. return true;
  110. }
  111. /**
  112. * Redirect to the login page, appending the current URL as the source.
  113. * @param $message string Optional name of locale key to add to login page
  114. */
  115. function redirectLogin($message = null) {
  116. $args = array();
  117. if (isset($_SERVER['REQUEST_URI'])) {
  118. $args['source'] = $_SERVER['REQUEST_URI'];
  119. }
  120. if ($message !== null) {
  121. $args['loginMessage'] = $message;
  122. }
  123. Request::redirect(null, 'login', null, null, $args);
  124. }
  125. /**
  126. * Check if a user's credentials are valid.
  127. * @param $username string username
  128. * @param $password string unencrypted password
  129. * @return boolean
  130. */
  131. function checkCredentials($username, $password) {
  132. $userDao =& DAORegistry::getDAO('UserDAO');
  133. $user =& $userDao->getUserByUsername($username, false);
  134. $valid = false;
  135. if (isset($user)) {
  136. if ($user->getAuthId()) {
  137. $authDao =& DAORegistry::getDAO('AuthSourceDAO');
  138. $auth =& $authDao->getPlugin($user->getAuthId());
  139. }
  140. if (isset($auth)) {
  141. $valid = $auth->authenticate($username, $password);
  142. } else {
  143. $valid = ($user->getPassword() === Validation::encryptCredentials($username, $password));
  144. }
  145. }
  146. return $valid;
  147. }
  148. /**
  149. * Check if a user is authorized to access the specified role in the specified journal.
  150. * @param $roleId int
  151. * @param $journalId optional (e.g., for global site admin role), the ID of the journal
  152. * @return boolean
  153. */
  154. function isAuthorized($roleId, $journalId = 0) {
  155. if (!Validation::isLoggedIn()) {
  156. return false;
  157. }
  158. if ($journalId === -1) {
  159. // Get journal ID from request
  160. $journal =& Request::getJournal();
  161. $journalId = $journal == null ? 0 : $journal->getJournalId();
  162. }
  163. $sessionManager =& SessionManager::getManager();
  164. $session =& $sessionManager->getUserSession();
  165. $user =& $session->getUser();
  166. $roleDao =& DAORegistry::getDAO('RoleDAO');
  167. return $roleDao->roleExists($journalId, $user->getId(), $roleId);
  168. }
  169. /**
  170. * Encrypt user passwords for database storage.
  171. * The username is used as a unique salt to make dictionary
  172. * attacks against a compromised database more difficult.
  173. * @param $username string username
  174. * @param $password string unencrypted password
  175. * @param $encryption string optional encryption algorithm to use, defaulting to the value from the site configuration
  176. * @return string encrypted password
  177. */
  178. function encryptCredentials($username, $password, $encryption = false) {
  179. $valueToEncrypt = $username . $password;
  180. if ($encryption == false) {
  181. $encryption = Config::getVar('security', 'encryption');
  182. }
  183. switch ($encryption) {
  184. case 'sha1':
  185. if (function_exists('sha1')) {
  186. return sha1($valueToEncrypt);
  187. }
  188. case 'md5':
  189. default:
  190. return md5($valueToEncrypt);
  191. }
  192. }
  193. /**
  194. * Generate a random password.
  195. * Assumes the random number generator has already been seeded.
  196. * @param $length int the length of the password to generate (default 8)
  197. * @return string
  198. */
  199. function generatePassword($length = 8) {
  200. $letters = 'abcdefghijkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ';
  201. $numbers = '23456789';
  202. $password = "";
  203. for ($i=0; $i<$length; $i++) {
  204. $password .= mt_rand(1, 4) == 4 ? $numbers[mt_rand(0,strlen($numbers)-1)] : $letters[mt_rand(0, strlen($letters)-1)];
  205. }
  206. return $password;
  207. }
  208. /**
  209. * Generate a hash value to use for confirmation to reset a password.
  210. * @param $userId int
  211. * @return string (boolean false if user is invalid)
  212. */
  213. function generatePasswordResetHash($userId) {
  214. $userDao =& DAORegistry::getDAO('UserDAO');
  215. if (($user = $userDao->getUser($userId)) == null) {
  216. // No such user
  217. return false;
  218. }
  219. return substr(md5($user->getId() . $user->getUsername() . $user->getPassword()), 0, 6);
  220. }
  221. /**
  222. * Suggest a username given the first and last names.
  223. * @return string
  224. */
  225. function suggestUsername($firstName, $lastName) {
  226. $initial = String::substr($firstName, 0, 1);
  227. $suggestion = String::regexp_replace('/[^a-zA-Z0-9_-]/', '', String::strtolower($initial . $lastName));
  228. $userDao =& DAORegistry::getDAO('UserDAO');
  229. for ($i = ''; $userDao->userExistsByUsername($suggestion . $i); $i++);
  230. return $suggestion . $i;
  231. }
  232. /**
  233. * Check if the user must change their password in order to log in.
  234. * @return boolean
  235. */
  236. function isLoggedIn() {
  237. $sessionManager =& SessionManager::getManager();
  238. $session =& $sessionManager->getUserSession();
  239. $userId = $session->getUserId();
  240. return isset($userId) && !empty($userId);
  241. }
  242. /**
  243. * Shortcut for checking authorization as site admin.
  244. * @return boolean
  245. */
  246. function isSiteAdmin() {
  247. return Validation::isAuthorized(ROLE_ID_SITE_ADMIN);
  248. }
  249. /**
  250. * Shortcut for checking authorization as journal manager.
  251. * @param $journalId int
  252. * @return boolean
  253. */
  254. function isJournalManager($journalId = -1) {
  255. return Validation::isAuthorized(ROLE_ID_JOURNAL_MANAGER, $journalId);
  256. }
  257. /**
  258. * Shortcut for checking authorization as editor.
  259. * @param $journalId int
  260. * @return boolean
  261. */
  262. function isEditor($journalId = -1) {
  263. return Validation::isAuthorized(ROLE_ID_EDITOR, $journalId);
  264. }
  265. /**
  266. * Shortcut for checking authorization as section editor.
  267. * @param $journalId int
  268. * @return boolean
  269. */
  270. function isSectionEditor($journalId = -1) {
  271. return Validation::isAuthorized(ROLE_ID_SECTION_EDITOR, $journalId);
  272. }
  273. /**
  274. * Shortcut for checking authorization as layout editor.
  275. * @param $journalId int
  276. * @return boolean
  277. */
  278. function isLayoutEditor($journalId = -1) {
  279. return Validation::isAuthorized(ROLE_ID_LAYOUT_EDITOR, $journalId);
  280. }
  281. /**
  282. * Shortcut for checking authorization as reviewer.
  283. * @param $journalId int
  284. * @return boolean
  285. */
  286. function isReviewer($journalId = -1) {
  287. return Validation::isAuthorized(ROLE_ID_REVIEWER, $journalId);
  288. }
  289. /**
  290. * Shortcut for checking authorization as copyeditor.
  291. * @param $journalId int
  292. * @return boolean
  293. */
  294. function isCopyeditor($journalId = -1) {
  295. return Validation::isAuthorized(ROLE_ID_COPYEDITOR, $journalId);
  296. }
  297. /**
  298. * Shortcut for checking authorization as proofreader.
  299. * @param $journalId int
  300. * @return boolean
  301. */
  302. function isProofreader($journalId = -1) {
  303. return Validation::isAuthorized(ROLE_ID_PROOFREADER, $journalId);
  304. }
  305. /**
  306. * Shortcut for checking authorization as author.
  307. * @param $journalId int
  308. * @return boolean
  309. */
  310. function isAuthor($journalId = -1) {
  311. return Validation::isAuthorized(ROLE_ID_AUTHOR, $journalId);
  312. }
  313. /**
  314. * Shortcut for checking authorization as reader.
  315. * @param $journalId int
  316. * @return boolean
  317. */
  318. function isReader($journalId = -1) {
  319. return Validation::isAuthorized(ROLE_ID_READER, $journalId);
  320. }
  321. /**
  322. * Shortcut for checking authorization as subscription manager.
  323. * @param $journalId int
  324. * @return boolean
  325. */
  326. function isSubscriptionManager($journalId = -1) {
  327. return Validation::isAuthorized(ROLE_ID_SUBSCRIPTION_MANAGER, $journalId);
  328. }
  329. /**
  330. * Check whether a user is allowed to administer another user.
  331. * @param $journalId int
  332. * @param $userId int
  333. * @return boolean
  334. */
  335. function canAdminister($journalId, $userId) {
  336. if (Validation::isSiteAdmin()) return true;
  337. if (!Validation::isJournalManager($journalId)) return false;
  338. // Check for roles in other journals that this user
  339. // doesn't have administrative rights over.
  340. $roleDao =& DAORegistry::getDAO('RoleDAO');
  341. $roles =& $roleDao->getRolesByUserId($userId);
  342. foreach ($roles as $role) {
  343. if ($role->getRoleId() == ROLE_ID_SITE_ADMIN) return false;
  344. if (
  345. $role->getJournalId() != $journalId &&
  346. !Validation::isJournalManager($role->getJournalId())
  347. ) return false;
  348. }
  349. // There were no conflicting roles.
  350. return true;
  351. }
  352. }
  353. ?>