Advertisement
NinoSkopac

NAuthentication register method source

Apr 2nd, 2016
123
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 6.61 KB | None | 0 0
  1.     /**
  2.      * Account registration method.
  3.      *
  4.      * Validates the input received and inserts it into the database. By default, this method will also send the activation email, and require the user to activate (verify the email address) its account before being able to log in. If $Account_Activation_Required is set to *false* in the Config file, then this method will not send the activation email, but it will instead activate the account automatically, and, will instead of the *activation token*, return *user id*.
  5.      *
  6.      * *Example:*
  7.      * ```php
  8.      * // assumes $_POST is coming from a registration form, and can look something like this:
  9.      * $_POST = array(
  10.      *     'email' => 'jane.doe@gmail.com'
  11.      *     'password' => 'my_password_456'
  12.      *     // optionally, more fields
  13.      * );
  14.      *
  15.      * \NAuthentication\Auth::register($_POST);
  16.      * ```
  17.      *
  18.      * @param string[] $userData Supplied user credentials to insert into the database records. This will usually be email address and password. Passed as an array, where field names are array indexes, and field values are array values.
  19.      *
  20.      * @throws NAuthException
  21.      *
  22.      * @return string|int By default, returns user's activation token which was sent to the supplied email address. The token is to be used in activate() method. If $Account_Activation_Required is set to *false* in the Config file, user ID (UID) will be returned instead.
  23.      */
  24.     public static function register(array $userData) {
  25.         // If either, but not both email or password fields are enforced, that's an NAuthException (password requires email to verify)
  26.         if (in_array('email', Config::$Mandatory_Params) xor in_array('password', Config::$Mandatory_Params)) {
  27.             throw new NAuthException(Config::$Auth_Exception_Messages['emailPasswordDependency'] . __METHOD__, 14);
  28.         }
  29.        
  30.         $expectedVsSupplied = array_diff_key(array_flip(Config::$Mandatory_Params), $userData);
  31.        
  32.         if (count($expectedVsSupplied) > 0) {
  33.             throw new NAuthException(Config::$Auth_Exception_Messages['mandatoryParamsMissing'] . implode(", ", array_flip($expectedVsSupplied)), 11);
  34.         }
  35.        
  36.         // Mandatory params mustn't be empty
  37.         foreach (Config::$Mandatory_Params as $mandatoryParam) {
  38.             if (empty($userData[$mandatoryParam])) {
  39.                 throw new NAuthException(Config::$Auth_Exception_Messages['mandatoryParamEmpty'] . $mandatoryParam . ' in ' . __METHOD__, 12);
  40.             }
  41.         }
  42.        
  43.         if (isset($userData['email'])) {
  44.             if (!filter_var($userData['email'], FILTER_VALIDATE_EMAIL)) throw new NAuthException(Config::$Auth_Exception_Messages['invalidEmailFormat'], 1);
  45.            
  46.             if (self::userExists(['email' => $userData['email'], 'activated' => 'Y'])) {
  47.                 throw new NAuthException(Config::$Auth_Exception_Messages['userEmailAlreadyExists'], 2);
  48.             }
  49.         }
  50.        
  51.         // check if there are any input fields that don't have a coresponding database field, and throw an NAuthException if there are (there's an identical check in authenticate(), but that simply discards any non-existing fields)
  52.         $usersTableFields = Utils::getTableFields(Config::$Users_Tablename);
  53.        
  54.         $neededFieldsVsExistingFields = array_diff_key($userData, array_flip($usersTableFields));
  55.        
  56.         if (count($neededFieldsVsExistingFields) > 0) {
  57.             $usedFieldsNotInDatabase = implode(', ', array_flip($neededFieldsVsExistingFields));
  58.            
  59.             throw new NAuthException(
  60.                 Config::$Auth_Exception_Messages['missingDatabaseFields'] . 'Used fields which are not in database: ' . $usedFieldsNotInDatabase . ' in table ' . Config::$Users_Tablename . ', at ' . __METHOD__, 4
  61.             );
  62.         }
  63.        
  64.         if (isset($userData['password'])) {
  65.             if (strlen($userData['password']) < Config::$Minimum_Password_Length) throw new NAuthException(Config::$Auth_Exception_Messages['passwordTooShort'] . Config::$Minimum_Password_Length, 5);
  66.            
  67.             $userData['password'] = password_hash($userData['password'], PASSWORD_BCRYPT);
  68.         }
  69.        
  70.         $link = Utils::getDatabaseInstance();
  71.        
  72.         if (self::isIPWithinRetriesLimit('register', (isset($userData['email']) ? $userData['email'] : NULL)) === false) {
  73.             // in case user already tried to sign up, but the activation email never came, and the user didn't use the
  74.             // resendActivationEmail feature, resend it for the user
  75.             $activationToken = self::getTokenFromLogs('register', (isset($userData['email']) ? $userData['email'] : NULL));
  76.            
  77.             if (is_null($activationToken)) {
  78.                 // this should never execute, except if someone edited tablesCleanUp() intervals on their own and and messed it up (rows in the logs table should always have longer lifetime than the rows in activations table)
  79.                 throw new NAuthException(Config::$Auth_Exception_Messages['registerLimitExceed'], 27);
  80.             }
  81.            
  82.             return self::resendActivationEmail($activationToken);
  83.         }
  84.        
  85.         // PART ONE: Insert User into DB
  86.         $sql = Utils::generatePdoInsertSql($userData, Config::$Users_Tablename);
  87.         $stmt = $link->prepare($sql);
  88.         $stmt = Utils::bindPdoParams($stmt, $userData);
  89.        
  90.         if (!$stmt->execute()) {
  91.             throw new NAuthException(Config::$Auth_Exception_Messages['registrationQueryFailed'], 6);
  92.         }
  93.        
  94.         $uid = $link->lastInsertId();
  95.         $stmt = null;
  96.        
  97.         // PART TWO: Generate activation token and insert it into DB
  98.         $activationToken = self::insertTokenToDatabase($uid, 'activation', $link);
  99.        
  100.         // PART THREE: Compose and send activation email
  101.         if (Config::$Account_Activation_Required) {
  102.             if (isset($userData['email'])) {
  103.                 $activationMessage = self::composeEmailMessage('activation', $activationToken);
  104.                 $sendEmail = self::sendEmail($userData['email'], Config::$Account_Activation_Subject, $activationMessage);
  105.             }
  106.            
  107.             self::addIPToLog('register', (isset($userData['email']) ? $userData['email'] : NULL), $activationToken);
  108.         } else {
  109.             return self::activate($activationToken, $link);
  110.         }
  111.        
  112.         // GC
  113.         if (1/100 === 50) {
  114.             self::tablesCleanUp($link);
  115.         }
  116.        
  117.         return $activationToken;
  118.     }
  119.  
  120.  
  121. // Pastebin comment: more at http://nauthentication.recgr.com/
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement