gluon-web-remote

Web remote Administration for big size of gluon routers
git clone git://archive.git.mtrnord.blog/MTRNord/gluon-web-remote.git
Log | Files | Refs | README

RegistrationModel.php (10213B)


      1 <?php
      2 
      3 /**
      4  * Class RegistrationModel
      5  *
      6  * Everything registration-related happens here.
      7  */
      8 class RegistrationModel
      9 {
     10 	/**
     11 	 * Handles the entire registration process for DEFAULT users (not for people who register with
     12 	 * 3rd party services, like facebook) and creates a new user in the database if everything is fine
     13 	 *
     14 	 * @return boolean Gives back the success status of the registration
     15 	 */
     16 	public static function registerNewUser()
     17 	{
     18 		// TODO this could be written simpler and cleaner
     19 
     20 		// clean the input
     21 		$user_name = strip_tags(Request::post('user_name'));
     22 		$user_email = strip_tags(Request::post('user_email'));
     23 		$user_password_new = Request::post('user_password_new');
     24 		$user_password_repeat = Request::post('user_password_repeat');
     25 
     26 		// stop registration flow if registrationInputValidation() returns false (= anything breaks the input check rules)
     27 		$validation_result = self::registrationInputValidation(Request::post('captcha'), $user_name, $user_password_new, $user_password_repeat, $user_email);
     28 		if (!$validation_result) {
     29 			return false;
     30 		}
     31 
     32 		// crypt the password with the PHP 5.5's password_hash() function, results in a 60 character hash string.
     33 		// @see php.net/manual/en/function.password-hash.php for more, especially for potential options
     34 		$user_password_hash = password_hash($user_password_new, PASSWORD_DEFAULT);
     35 
     36         // make return a bool variable, so both errors can come up at once if needed
     37         $return = true;
     38 
     39 		// check if username already exists
     40 		if (UserModel::doesUsernameAlreadyExist($user_name)) {
     41 			Session::add('feedback_negative', Text::get('FEEDBACK_USERNAME_ALREADY_TAKEN'));
     42 			$return = false;
     43 		}
     44 
     45 		// check if email already exists
     46 		if (UserModel::doesEmailAlreadyExist($user_email)) {
     47 			Session::add('feedback_negative', Text::get('FEEDBACK_USER_EMAIL_ALREADY_TAKEN'));
     48 			$return = false;
     49 		}
     50 
     51         	// if Username or Email were false, return false
     52         	if(!$return) return false;
     53 
     54 		// generate random hash for email verification (40 char string)
     55 		$user_activation_hash = sha1(uniqid(mt_rand(), true));
     56 
     57 		// write user data to database
     58 		if (!self::writeNewUserToDatabase($user_name, $user_password_hash, $user_email, time(), $user_activation_hash)) {
     59 			Session::add('feedback_negative', Text::get('FEEDBACK_ACCOUNT_CREATION_FAILED'));
     60             return false; // no reason not to return false here
     61 		}
     62 
     63 		// get user_id of the user that has been created, to keep things clean we DON'T use lastInsertId() here
     64 		$user_id = UserModel::getUserIdByUsername($user_name);
     65 
     66 		if (!$user_id) {
     67 			Session::add('feedback_negative', Text::get('FEEDBACK_UNKNOWN_ERROR'));
     68 			return false;
     69 		}
     70 
     71 		// send verification email
     72 		if (self::sendVerificationEmail($user_id, $user_email, $user_activation_hash)) {
     73 			Session::add('feedback_positive', Text::get('FEEDBACK_ACCOUNT_SUCCESSFULLY_CREATED'));
     74 			return true;
     75 		}
     76 
     77 		// if verification email sending failed: instantly delete the user
     78 		self::rollbackRegistrationByUserId($user_id);
     79 		Session::add('feedback_negative', Text::get('FEEDBACK_VERIFICATION_MAIL_SENDING_FAILED'));
     80 		return false;
     81 	}
     82 
     83 	/**
     84 	 * Validates the registration input
     85 	 *
     86 	 * @param $captcha
     87 	 * @param $user_name
     88 	 * @param $user_password_new
     89 	 * @param $user_password_repeat
     90 	 * @param $user_email
     91 	 *
     92 	 * @return bool
     93 	 */
     94 	public static function registrationInputValidation($captcha, $user_name, $user_password_new, $user_password_repeat, $user_email)
     95 	{
     96         $return = true;
     97 
     98 		// perform all necessary checks
     99 		if (!CaptchaModel::checkCaptcha($captcha)) {
    100 			Session::add('feedback_negative', Text::get('FEEDBACK_CAPTCHA_WRONG'));
    101             $return = false;
    102 		}
    103 
    104         // if username, email and password are all correctly validated, but make sure they all run on first sumbit
    105         if (self::validateUserName($user_name) AND self::validateUserEmail($user_email) AND self::validateUserPassword($user_password_new, $user_password_repeat) AND $return) {
    106             return true;
    107         }
    108 
    109 		// otherwise, return false
    110 		return false;
    111 	}
    112 
    113     /**
    114      * Validates the username
    115      *
    116      * @param $user_name
    117      * @return bool
    118      */
    119     public static function validateUserName($user_name)
    120     {
    121         if (empty($user_name)) {
    122             Session::add('feedback_negative', Text::get('FEEDBACK_USERNAME_FIELD_EMPTY'));
    123             return false;
    124         }
    125 
    126         // if username is too short (2), too long (64) or does not fit the pattern (aZ09)
    127         if (!preg_match('/^[a-zA-Z0-9]{2,64}$/', $user_name)) {
    128             Session::add('feedback_negative', Text::get('FEEDBACK_USERNAME_DOES_NOT_FIT_PATTERN'));
    129             return false;
    130         }
    131 
    132         return true;
    133     }
    134 
    135     /**
    136      * Validates the email
    137      *
    138      * @param $user_email
    139      * @return bool
    140      */
    141     public static function validateUserEmail($user_email)
    142     {
    143         if (empty($user_email)) {
    144             Session::add('feedback_negative', Text::get('FEEDBACK_EMAIL_FIELD_EMPTY'));
    145             return false;
    146         }
    147 
    148         // validate the email with PHP's internal filter
    149         // side-fact: Max length seems to be 254 chars
    150         // @see http://stackoverflow.com/questions/386294/what-is-the-maximum-length-of-a-valid-email-address
    151         if (!filter_var($user_email, FILTER_VALIDATE_EMAIL)) {
    152             Session::add('feedback_negative', Text::get('FEEDBACK_EMAIL_DOES_NOT_FIT_PATTERN'));
    153             return false;
    154         }
    155 
    156         return true;
    157     }
    158 
    159     /**
    160      * Validates the password
    161      *
    162      * @param $user_password_new
    163      * @param $user_password_repeat
    164      * @return bool
    165      */
    166     public static function validateUserPassword($user_password_new, $user_password_repeat)
    167     {
    168         if (empty($user_password_new) OR empty($user_password_repeat)) {
    169             Session::add('feedback_negative', Text::get('FEEDBACK_PASSWORD_FIELD_EMPTY'));
    170             return false;
    171         }
    172 
    173         if ($user_password_new !== $user_password_repeat) {
    174             Session::add('feedback_negative', Text::get('FEEDBACK_PASSWORD_REPEAT_WRONG'));
    175             return false;
    176         }
    177 
    178         if (strlen($user_password_new) < 6) {
    179             Session::add('feedback_negative', Text::get('FEEDBACK_PASSWORD_TOO_SHORT'));
    180             return false;
    181         }
    182 
    183         return true;
    184     }
    185 
    186 	/**
    187 	 * Writes the new user's data to the database
    188 	 *
    189 	 * @param $user_name
    190 	 * @param $user_password_hash
    191 	 * @param $user_email
    192 	 * @param $user_creation_timestamp
    193 	 * @param $user_activation_hash
    194 	 *
    195 	 * @return bool
    196 	 */
    197 	public static function writeNewUserToDatabase($user_name, $user_password_hash, $user_email, $user_creation_timestamp, $user_activation_hash)
    198 	{
    199 		$database = DatabaseFactory::getFactory()->getConnection();
    200 
    201 		// write new users data into database
    202 		$sql = "INSERT INTO users (user_name, user_password_hash, user_email, user_creation_timestamp, user_activation_hash, user_provider_type)
    203                     VALUES (:user_name, :user_password_hash, :user_email, :user_creation_timestamp, :user_activation_hash, :user_provider_type)";
    204 		$query = $database->prepare($sql);
    205 		$query->execute(array(':user_name' => $user_name,
    206 		                      ':user_password_hash' => $user_password_hash,
    207 		                      ':user_email' => $user_email,
    208 		                      ':user_creation_timestamp' => $user_creation_timestamp,
    209 		                      ':user_activation_hash' => $user_activation_hash,
    210 		                      ':user_provider_type' => 'DEFAULT'));
    211 		$count =  $query->rowCount();
    212 		if ($count == 1) {
    213 			return true;
    214 		}
    215 
    216 		return false;
    217 	}
    218 
    219 	/**
    220 	 * Deletes the user from users table. Currently used to rollback a registration when verification mail sending
    221 	 * was not successful.
    222 	 *
    223 	 * @param $user_id
    224 	 */
    225 	public static function rollbackRegistrationByUserId($user_id)
    226 	{
    227 		$database = DatabaseFactory::getFactory()->getConnection();
    228 
    229 		$query = $database->prepare("DELETE FROM users WHERE user_id = :user_id");
    230 		$query->execute(array(':user_id' => $user_id));
    231 	}
    232 
    233 	/**
    234 	 * Sends the verification email (to confirm the account).
    235 	 * The construction of the mail $body looks weird at first, but it's really just a simple string.
    236 	 *
    237 	 * @param int $user_id user's id
    238 	 * @param string $user_email user's email
    239 	 * @param string $user_activation_hash user's mail verification hash string
    240 	 *
    241 	 * @return boolean gives back true if mail has been sent, gives back false if no mail could been sent
    242 	 */
    243 	public static function sendVerificationEmail($user_id, $user_email, $user_activation_hash)
    244 	{
    245 		$body = Config::get('EMAIL_VERIFICATION_CONTENT') . Config::get('URL') . Config::get('EMAIL_VERIFICATION_URL')
    246 		        . '/' . urlencode($user_id) . '/' . urlencode($user_activation_hash);
    247 
    248 		$mail = new Mail;
    249 		$mail_sent = $mail->sendMail($user_email, Config::get('EMAIL_VERIFICATION_FROM_EMAIL'),
    250 			Config::get('EMAIL_VERIFICATION_FROM_NAME'), Config::get('EMAIL_VERIFICATION_SUBJECT'), $body
    251 		);
    252 
    253 		if ($mail_sent) {
    254 			Session::add('feedback_positive', Text::get('FEEDBACK_VERIFICATION_MAIL_SENDING_SUCCESSFUL'));
    255 			return true;
    256 		} else {
    257 			Session::add('feedback_negative', Text::get('FEEDBACK_VERIFICATION_MAIL_SENDING_ERROR') . $mail->getError() );
    258 			return false;
    259 		}
    260 	}
    261 
    262 	/**
    263 	 * checks the email/verification code combination and set the user's activation status to true in the database
    264 	 *
    265 	 * @param int $user_id user id
    266 	 * @param string $user_activation_verification_code verification token
    267 	 *
    268 	 * @return bool success status
    269 	 */
    270 	public static function verifyNewUser($user_id, $user_activation_verification_code)
    271 	{
    272 		$database = DatabaseFactory::getFactory()->getConnection();
    273 
    274 		$sql = "UPDATE users SET user_active = 1, user_activation_hash = NULL
    275                 WHERE user_id = :user_id AND user_activation_hash = :user_activation_hash LIMIT 1";
    276 		$query = $database->prepare($sql);
    277 		$query->execute(array(':user_id' => $user_id, ':user_activation_hash' => $user_activation_verification_code));
    278 
    279 		if ($query->rowCount() == 1) {
    280 			Session::add('feedback_positive', Text::get('FEEDBACK_ACCOUNT_ACTIVATION_SUCCESSFUL'));
    281 			return true;
    282 		}
    283 
    284 		Session::add('feedback_negative', Text::get('FEEDBACK_ACCOUNT_ACTIVATION_FAILED'));
    285 		return false;
    286 	}
    287 }