/** * Checks the given invitation token for validity * * Returns TRUE if, and only if, the following is confirmed: * 1. is a SHA1 hash * 2. exists in the database * 3. is unique * 4. has not been used up (nobody been registered using this yet) * * @param token * @return boolean */ public static function valid($token) { // 1 if (!preg_match('#\\A[0-9a-f]{40}\\z#', $token)) { return FALSE; } // Get object values $object = Model_Invite::factory(NULL); // 2, 3, 4 $results = DB::select('*')->from($object->table())->where($object->pk(), '=', $token)->where('invitee', 'is', NULL)->execute()->count(); if ($results !== 1) { return FALSE; } return TRUE; }
/** * Registration procedure (from a given invitation) */ public function action_register() { $token = arr::get($_GET, 'token', NULL); if (!Model_Invite::valid($token)) { $this->message_add('Din inbjudan är ogiltig.', 'error'); // TODO: better message $this->request->redirect_back(); } else { $invite = Model_Invite::factory($token)->load(); } // Registrera användare if (!empty($_POST)) { $_POST['email'] = $invite->email; $_POST['logins'] = 0; $user = Sprig::factory('user', $_POST); /** * The following is executed as a transaction, and rolls * back if something goes wrong */ try { // Start transaction DB::query(NULL, 'BEGIN')->execute(); $user->create(); $user->add('roles', array(Sprig::factory('role', array('name' => 'login'))->load(), Sprig::factory('role', array('name' => 'ängel'))->load()))->update(); // Make invite invalid $invite->values(array('invitee' => $user->id))->update(); // Commit transaction DB::query(NULL, 'COMMIT')->execute(); // Log in! $this->auth->login($_POST['username'], $_POST['password']); // Welcome message and redirect to control panel $this->message_add(sprintf('Välkommen, %s! Du är nu registrerad och inloggad. Jag tog mig också friheten att dirigera dig till forumet.', html::chars($user->username))); // TODO: Make message $this->request->redirect('forum', 303); } catch (Exception $e) { // Rollback transaction (innodb ftw) DB::query(NULL, 'ROLLBACK')->execute(); // Non-validation errors are re-thrown and logged if (!$e instanceof Validate_Exception) { throw $e; } // Show validation errors foreach ($e->array->errors('user/register') as $error) { $this->message_add($error, 'error'); } } $this->request->reload(); } $this->template->content = View::factory('user/register')->set('invite', $invite); }