3 * Check for valid user via login form or stored cookie. Returns true or an error message
6 function yourls_is_valid_user() {
12 // Allow plugins to short-circuit the whole function
13 $pre = yourls_apply_filter( 'shunt_is_valid_user', null );
14 if ( null !== $pre ) {
15 $valid = ( $pre === true ) ;
19 // $unfiltered_valid : are credentials valid? Boolean value. It's "unfiltered" to allow plugins to eventually filter it.
20 $unfiltered_valid = false;
23 if( isset( $_GET['action'] ) && $_GET['action'] == 'logout' ) {
24 yourls_do_action( 'logout' );
25 yourls_store_cookie( null );
26 return yourls__( 'Logged out successfully' );
29 // Check cookies or login request. Login form has precedence.
31 yourls_do_action( 'pre_login' );
33 // Determine auth method and check credentials
35 // API only: Secure (no login or pwd) and time limited token
36 // ?timestamp=12345678&signature=md5(totoblah12345678)
38 isset( $_REQUEST['timestamp'] ) && !empty($_REQUEST['timestamp'] ) &&
39 isset( $_REQUEST['signature'] ) && !empty($_REQUEST['signature'] )
42 yourls_do_action( 'pre_login_signature_timestamp' );
43 $unfiltered_valid = yourls_check_signature_timestamp();
47 // API only: Secure (no login or pwd)
48 // ?signature=md5(totoblah)
50 !isset( $_REQUEST['timestamp'] ) &&
51 isset( $_REQUEST['signature'] ) && !empty( $_REQUEST['signature'] )
54 yourls_do_action( 'pre_login_signature' );
55 $unfiltered_valid = yourls_check_signature();
59 // API or normal: login with username & pwd
60 ( isset( $_REQUEST['username'] ) && isset( $_REQUEST['password'] )
61 && !empty( $_REQUEST['username'] ) && !empty( $_REQUEST['password'] ) )
63 yourls_do_action( 'pre_login_username_password' );
64 $unfiltered_valid = yourls_check_username_password();
68 // Normal only: cookies
70 isset( $_COOKIE[ yourls_cookie_name() ] ) )
72 yourls_do_action( 'pre_login_cookie' );
73 $unfiltered_valid = yourls_check_auth_cookie();
76 // Regardless of validity, allow plugins to filter the boolean and have final word
77 $valid = yourls_apply_filter( 'is_valid_user', $unfiltered_valid );
81 yourls_do_action( 'login' );
83 // (Re)store encrypted cookie if needed
84 if ( !yourls_is_API() ) {
85 yourls_store_cookie( YOURLS_USER );
87 // Login form : redirect to requested URL to avoid re-submitting the login form on page reload
88 if( isset( $_REQUEST['username'] ) && isset( $_REQUEST['password'] ) && isset( $_SERVER['REQUEST_URI'] ) ) {
89 $url = $_SERVER['REQUEST_URI'];
90 yourls_redirect( $url );
99 yourls_do_action( 'login_failed' );
101 if ( isset( $_REQUEST['username'] ) || isset( $_REQUEST['password'] ) ) {
102 return yourls__( 'Invalid username or password' );
104 return yourls__( 'Please log in' );
109 * Check auth against list of login=>pwd. Sets user if applicable, returns bool
112 function yourls_check_username_password() {
113 global $yourls_user_passwords;
114 if( isset( $yourls_user_passwords[ $_REQUEST['username'] ] ) && yourls_check_password_hash( $_REQUEST['username'], $_REQUEST['password'] ) ) {
115 yourls_set_user( $_REQUEST['username'] );
122 * Check a submitted password sent in plain text against stored password which can be a salted hash
125 function yourls_check_password_hash( $user, $submitted_password ) {
126 global $yourls_user_passwords;
128 if( !isset( $yourls_user_passwords[ $user ] ) )
131 if ( yourls_has_phpass_password( $user ) ) {
132 // Stored password is hashed with phpass
133 list( , $hash ) = explode( ':', $yourls_user_passwords[ $user ] );
134 $hash = str_replace( '!', '$', $hash );
135 return ( yourls_phpass_check( $submitted_password, $hash ) );
136 } else if( yourls_has_md5_password( $user ) ) {
137 // Stored password is a salted md5 hash: "md5:<$r = rand(10000,99999)>:<md5($r.'thepassword')>"
138 list( , $salt, ) = explode( ':', $yourls_user_passwords[ $user ] );
139 return( $yourls_user_passwords[ $user ] == 'md5:'.$salt.':'.md5( $salt . $submitted_password ) );
141 // Password stored in clear text
142 return( $yourls_user_passwords[ $user ] == $submitted_password );
147 * Overwrite plaintext passwords in config file with phpassed versions.
150 * @param string $config_file Full path to file
151 * @return true if overwrite was successful, an error message otherwise
153 function yourls_hash_passwords_now( $config_file ) {
154 if( !is_readable( $config_file ) )
155 return 'cannot read file'; // not sure that can actually happen...
157 if( !is_writable( $config_file ) )
158 return 'cannot write file';
160 // Include file to read value of $yourls_user_passwords
161 // Temporary suppress error reporting to avoid notices about redeclared constants
162 $errlevel = error_reporting();
163 error_reporting( 0 );
164 require $config_file;
165 error_reporting( $errlevel );
167 $configdata = file_get_contents( $config_file );
168 if( $configdata == false )
169 return 'could not read file';
171 $to_hash = 0; // keep track of number of passwords that need hashing
172 foreach ( $yourls_user_passwords as $user => $password ) {
173 if ( !yourls_has_phpass_password( $user ) && !yourls_has_md5_password( $user ) ) {
175 $hash = yourls_phpass_hash( $password );
176 // PHP would interpret $ as a variable, so replace it in storage.
177 $hash = str_replace( '$', '!', $hash );
179 $pattern = "/[$quotes]${user}[$quotes]\s*=>\s*[$quotes]" . preg_quote( $password, '-' ) . "[$quotes]/";
180 $replace = "'$user' => 'phpass:$hash' /* Password encrypted by YOURLS */ ";
182 $configdata = preg_replace( $pattern, $replace, $configdata, -1, $count );
183 // There should be exactly one replacement. Otherwise, fast fail.
185 yourls_debug_log( "Problem with preg_replace for password hash of user $user" );
186 return 'preg_replace problem';
192 return 0; // There was no password to encrypt
194 $success = file_put_contents( $config_file, $configdata );
195 if ( $success === FALSE ) {
196 yourls_debug_log( 'Failed writing to ' . $config_file );
197 return 'could not write file';
203 * Hash a password using phpass
206 * @param string $password password to hash
207 * @return string hashed password
209 function yourls_phpass_hash( $password ) {
210 $hasher = yourls_phpass_instance();
211 return $hasher->HashPassword( $password );
215 * Check a clear password against a phpass hash
218 * @param string $password clear (eg submitted in a form) password
219 * @param string $hash hash supposedly generated by phpass
220 * @return bool true if the hash matches the password once hashed by phpass, false otherwise
222 function yourls_phpass_check( $password, $hash ) {
223 $hasher = yourls_phpass_instance();
224 return $hasher->CheckPassword( $password, $hash );
228 * Helper function: create new instance or return existing instance of phpass class
231 * @param int $iteration iteration count - 8 is default in phpass
232 * @param bool $portable flag to force portable (cross platform and system independant) hashes - false to use whatever the system can do best
233 * @return object a PasswordHash instance
235 function yourls_phpass_instance( $iteration = 8, $portable = false ) {
236 $iteration = yourls_apply_filter( 'phpass_new_instance_iteration', $iteration );
237 $portable = yourls_apply_filter( 'phpass_new_instance_portable', $portable );
239 if( !class_exists( 'PasswordHash' ) ) {
240 require_once( YOURLS_INC.'/phpass/PasswordHash.php' );
243 static $instance = false;
244 if( $instance == false ) {
245 $instance = new PasswordHash( $iteration, $portable );
253 * Check to see if any passwords are stored as cleartext.
256 * @return bool true if any passwords are cleartext
258 function yourls_has_cleartext_passwords() {
259 global $yourls_user_passwords;
260 foreach ( $yourls_user_passwords as $user => $pwdata ) {
261 if ( !yourls_has_md5_password( $user ) && !yourls_has_phpass_password( $user ) ) {
269 * Check if a user has a hashed password
271 * Check if a user password is 'md5:[38 chars]'.
272 * TODO: deprecate this when/if we have proper user management with password hashes stored in the DB
275 * @param string $user user login
276 * @return bool true if password hashed, false otherwise
278 function yourls_has_md5_password( $user ) {
279 global $yourls_user_passwords;
280 return( isset( $yourls_user_passwords[ $user ] )
281 && substr( $yourls_user_passwords[ $user ], 0, 4 ) == 'md5:'
282 && strlen( $yourls_user_passwords[ $user ] ) == 42 // http://www.google.com/search?q=the+answer+to+life+the+universe+and+everything
287 * Check if a user's password is hashed with PHPASS.
289 * Check if a user password is 'phpass:[lots of chars]'.
290 * TODO: deprecate this when/if we have proper user management with password hashes stored in the DB
293 * @param string $user user login
294 * @return bool true if password hashed with PHPASS, otherwise false
296 function yourls_has_phpass_password( $user ) {
297 global $yourls_user_passwords;
298 return( isset( $yourls_user_passwords[ $user ] )
299 && substr( $yourls_user_passwords[ $user ], 0, 7 ) == 'phpass:'
304 * Check auth against encrypted COOKIE data. Sets user if applicable, returns bool
307 function yourls_check_auth_cookie() {
308 global $yourls_user_passwords;
309 foreach( $yourls_user_passwords as $valid_user => $valid_password ) {
310 if ( yourls_salt( $valid_user ) == $_COOKIE[ yourls_cookie_name() ] ) {
311 yourls_set_user( $valid_user );
319 * Check auth against signature and timestamp. Sets user if applicable, returns bool
322 function yourls_check_signature_timestamp() {
323 // Timestamp in PHP : time()
324 // Timestamp in JS: parseInt(new Date().getTime() / 1000)
325 global $yourls_user_passwords;
326 foreach( $yourls_user_passwords as $valid_user => $valid_password ) {
329 md5( $_REQUEST['timestamp'].yourls_auth_signature( $valid_user ) ) == $_REQUEST['signature']
331 md5( yourls_auth_signature( $valid_user ).$_REQUEST['timestamp'] ) == $_REQUEST['signature']
334 yourls_check_timestamp( $_REQUEST['timestamp'] )
336 yourls_set_user( $valid_user );
344 * Check auth against signature. Sets user if applicable, returns bool
347 function yourls_check_signature() {
348 global $yourls_user_passwords;
349 foreach( $yourls_user_passwords as $valid_user => $valid_password ) {
350 if ( yourls_auth_signature( $valid_user ) == $_REQUEST['signature'] ) {
351 yourls_set_user( $valid_user );
359 * Generate secret signature hash
362 function yourls_auth_signature( $username = false ) {
363 if( !$username && defined('YOURLS_USER') ) {
364 $username = YOURLS_USER;
366 return ( $username ? substr( yourls_salt( $username ), 0, 10 ) : 'Cannot generate auth signature: no username' );
370 * Check if timestamp is not too old
373 function yourls_check_timestamp( $time ) {
375 // Allow timestamp to be a little in the future or the past -- see Issue 766
376 return yourls_apply_filter( 'check_timestamp', abs( $now - $time ) < YOURLS_NONCE_LIFE, $time );
380 * Store new cookie. No $user will delete the cookie.
383 function yourls_store_cookie( $user = null ) {
386 $time = time() - 3600;
388 global $yourls_user_passwords;
389 if( isset($yourls_user_passwords[$user]) ) {
390 $pass = $yourls_user_passwords[$user];
392 die( 'Stealing cookies?' ); // This should never happen
394 $time = time() + YOURLS_COOKIE_LIFE;
397 $domain = yourls_apply_filter( 'setcookie_domain', parse_url( YOURLS_SITE, 1 ) );
398 $secure = yourls_apply_filter( 'setcookie_secure', yourls_is_ssl() );
399 $httponly = yourls_apply_filter( 'setcookie_httponly', true );
401 // Some browsers refuse to store localhost cookie
402 if ( $domain == 'localhost' )
405 if ( !headers_sent( $filename, $linenum ) ) {
406 // Set httponly if the php version is >= 5.2.0
407 if( version_compare( phpversion(), '5.2.0', 'ge' ) ) {
408 setcookie( yourls_cookie_name(), yourls_salt( $user ), $time, '/', $domain, $secure, $httponly );
410 setcookie( yourls_cookie_name(), yourls_salt( $user ), $time, '/', $domain, $secure );
413 // For some reason cookies were not stored: action to be able to debug that
414 yourls_do_action( 'setcookie_failed', $user );
415 yourls_debug_log( "Could not store cookie: headers already sent in $filename on line $linenum" );
423 function yourls_set_user( $user ) {
424 if( !defined( 'YOURLS_USER' ) )
425 define( 'YOURLS_USER', $user );
429 * Get YOURLS cookie name
431 * The name is unique for each install, to prevent mismatch between sho.rt and very.sho.rt -- see #1673
433 * TODO: when multi user is implemented, the whole cookie stuff should be reworked to allow storing multiple users
436 * @return string unique cookie name for a given YOURLS site
438 function yourls_cookie_name() {
439 return 'yourls_' . yourls_salt( YOURLS_SITE );