Example #1
1
 /**
  * Attempt to create a user, given a user email and a password
  */
 function create($email, $password, $idSession)
 {
     $user = new User();
     $userRow = $user->findByEmail($email);
     $config = new Config();
     $configRow = $config->fetchAll()->current();
     // Does this user exist?
     if ($userRow) {
         // Check the password
         if ($userRow->password == md5($password)) {
             // Delete a possibly existing session. Safer.
             $db = Zend_Db_Table::getDefaultAdapter();
             $db->query("DELETE FROM Session WHERE idSession = '{$idSession}'");
             // Insert in Session, for 2 hours
             $sessionRow = $this->createRow();
             $sessionRow->idSession = $idSession;
             $sessionRow->id_user = $userRow->id;
             $this->tempsLimite = date("U") + 7200;
             $sessionRow->roles = $userRow->roles;
             $sessionRow->save();
             return true;
         }
         return false;
     } else {
         return false;
     }
 }
 public function getUser()
 {
     if ($this->_user === false) {
         $this->_user = User::findByEmail($this->email);
     }
     return $this->_user;
 }
Example #3
0
 public function routeShutdown(Zend_Controller_Request_Abstract $request)
 {
     $logger = Zend_Registry::get('logger');
     $auth = Zend_Auth::getInstance();
     $logger->debug('Login -- hasIdentity ' . var_export($auth->hasIdentity(), true) . '. module: ' . $request->getModuleName() . '. _onAllowLogOutAccess: ' . var_export($this->_onAllowLogOutAccess($request), true));
     if (!$auth->hasIdentity() && $request->getModuleName() !== 'Auth' && !$this->_onAllowLogOutAccess($request)) {
         $request->setModuleName("Auth")->setControllerName("index")->setActionName("login");
     } elseif ($auth->hasIdentity()) {
         $session = DZend_Session_Namespace::get('session');
         if (!isset($session->user)) {
             $userModel = new User();
             $session->user = $userModel->findByEmail($auth->getIdentity());
         }
         DZend_Session_Namespace::close();
     }
 }
Example #4
0
             throw new Exception("Invalid ID message");
         }
         $message->setUnread(true, Session::getSessionEmail())->doUpdate();
     } catch (Exception $e) {
         $errors["unread"] = $e->getMessage();
     }
 } else {
     if (isset($_POST["sent"])) {
         $form = "sent";
         $to = Tools::prepareUserArgString($_POST["email"]);
         $subject = Tools::prepareUserArgString($_POST["subject"]);
         $texte = Tools::prepareUserArgString($_POST["message"]);
         if (!Tools::verifyEmail($to)) {
             $errors["email"] = "Invalid email format";
         } else {
             if (User::findByEmail($to) == null) {
                 $errors["email"] = "Unknow email address";
             } else {
                 try {
                     $message = Message::create($subject, $texte, Session::getSessionEmail(), $to);
                 } catch (Exception $e) {
                     $errors["other"] = $e->getMessage();
                 }
             }
         }
     } else {
         if (isset($get)) {
             if (Tools::isStringValid($get) && isGetType($type)) {
                 $type = $get;
                 if (!isNew($type)) {
                     $id = Tools::prepareUserArgInteger($_GET["id"]);
Example #5
0
<?php

session_start();
try {
    // Get email address from request body
    $email = filter_input(INPUT_POST, 'email');
    // Get password from request body
    $password = filter_input(INPUT_POST, 'password');
    // Find account with email address (THIS IS PSUEDO-CODE)
    $user = User::findByEmail($email);
    // Verify password with account password hash
    if (password_verify($password, $user->password_hash) === false) {
        throw new Exception('Invalid password');
    }
    // Re-hash password if necessary (see note below)
    $currentHashAlgorithm = PASSWORD_DEFAULT;
    $currentHashOptions = array('cost' => 15);
    $passwordNeedsRehash = password_needs_rehash($user->password_hash, $currentHashAlgorithm, $currentHashOptions);
    if ($passwordNeedsRehash === true) {
        // Save new password hash (THIS IS PSUEDO-CODE)
        $user->password_hash = password_hash($password, $currentHashAlgorithm, $currentHashOptions);
        $user->save();
    }
    // Save login status to session
    $_SESSION['user_logged_in'] = 'yes';
    $_SESSION['user_email'] = $email;
    // Redirect to profile page
    header('HTTP/1.1 302 Redirect');
    header('Location: /user-profile.php');
} catch (Exception $e) {
    header('HTTP/1.1 401 Unauthorized');
Example #6
0
<?php

include_once 'includes/config.php';
/*
 * Traitement du formulaire.
 */
if (Session::isAlreadyConnected()) {
    $usr = User::findByEmail(Session::getSessionEmail());
    if ($usr == null) {
        $errors["other"] = "Impossible to load your data.";
    } else {
        if (isset($_POST["changepwd"])) {
            $errors = array();
            $formValid = true;
            $old = Tools::prepareUserArgString($_POST["old"]);
            $new = Tools::prepareUserArgString($_POST["new"]);
            $new2 = Tools::prepareUserArgString($_POST["new2"]);
            if (!$usr->isPasswordCorrect($old)) {
                $formValid = false;
                $errors["old"] = "The old password is not correct.";
            }
            if (!Tools::verifyPassword($new)) {
                $formValid = false;
                $errors["new"] = "You must insert a valid password see password <a href=\"#\">hint</a>.";
            }
            // Si non-identique.
            if ($new !== $new2) {
                $formValid = false;
                $errors["new2"] = "You must insert the same password twice.";
            }
            if ($formValid) {
Example #7
0
 /**
  *
  * @param string $email        	
  * @param string $password        	
  * @param string $right        	
  * @param boolean $actif        	
  */
 public static function create($email, $password, $right, $actif)
 {
     // Vérifie que les champs soit du bon format.
     if (!Tools::isStringValid($email) || !Tools::isStringValid($password) || !Tools::isStringValid($right) || !Tools::isBooleanValid($actif)) {
         throw new Exception("Invalid user arguments type.");
     }
     // Vérifie s'il s'agit d'un email.
     if (!Tools::verifyEmail($email)) {
         throw new Exception("Invalid email format.");
     }
     // Vérifie que l'utilisateur n'existe pas déjà.
     if (User::findByEmail($email) != null) {
         throw new Exception("Invalid email, user already exist.");
     }
     // Crée un nouvel utilisateur.
     $user = new User();
     // Récupère le droit utilisateur.
     $user->right = Right::findByName($right);
     if ($user->right == null) {
         throw new Exception("Invalid right.");
     }
     // Set les autres paramètres
     $user->id = null;
     $user->email = $email;
     $user->photo = "";
     $user->salt = Tools::randomSalt();
     $user->password = Tools::doHash($password, $user->salt);
     $user->actif = $actif;
     try {
         // Effectue une connexion à la DB.
         $pdo = DBconnect();
         // Commence la transaction.
         $pdo->beginTransaction();
         // Prépare la requête.
         $stmt = $pdo->prepare("INSERT INTO t_user(email, password, salt, actif, fk_right) VALUES (:email, :password, :salt, :actif, :fk_right)");
         $stmt->bindParam(":email", $user->email);
         $stmt->bindParam(":password", $user->password);
         $stmt->bindParam(":salt", $user->salt);
         $stmt->bindParam(":actif", $user->actif);
         $stmt->bindParam(":fk_right", $user->right->getId());
         if ($stmt->execute()) {
             $pdo->commit();
         } else {
             throw new Exception();
         }
     } catch (Exception $e) {
         // Revient en arrière si une erreur c'est produite.
         $pdo->rollBack();
         // Envoie à nouveau une exception.
         throw new Exception("Create user aborted , an error occurated.");
     } finally {
         // Ferme le traitement.
         $stmt->closeCursor();
         // Ferme la connexion vers la base de donnée.
         $pdo = null;
     }
 }
    /**
     * Send the user password reset email
     *
     * @param string $email  Email address
     * @return void
     */
    public function sendPasswordReset($email)
    {
        $user = User::findByEmail($email);
        if ($user !== null) {
            if ($user->startPasswordReset()) {
                // Note hardcoded protocol
                $url = 'http://' . $_SERVER['HTTP_HOST'] . '/reset_password.php?token=' . $user->password_reset_token;
                $body = <<<EOT

<p>Please click on the following link to reset your password.</p>

<p><a href="{$url}">{$url}</a></p>

EOT;
                Mail::send($user->name, $user->email, 'Password reset', $body);
            }
        }
    }
Example #9
0
    $request = json_decode($postdata);
    error_log("The request is: ");
    error_log(print_r($request, true));
    error_log("The request token is: {$request->token}");
    error_log("The request email is: {$request->email}");
    if (!isset($request->token)) {
        echo json_encode(array('status' => 'error', 'error' => 'couldn\'t get the token from post request'));
        exit;
    }
    if (!isset($request->email)) {
        echo json_encode(array('status' => 'error', 'error' => 'couldn\'t get the user\'s email from post request'));
        exit;
    }
    // First, find the user_id of the person who just logged in
    $userEmail = $request->email;
    $loggedInUser = User::findByEmail($userEmail);
    error_log("The user found by the email is: ");
    error_log(print_r($loggedInUser, true));
    $curUserId = $loggedInUser->id;
    error_log("The user id is: {$curUserId}");
    $userDeviceToken = $request->token;
    error_log("The user's device token is {$userDeviceToken}");
    $success = User::updateUserDeviceToken($curUserId, $userDeviceToken);
    if ($success) {
        Log::user("Successfully updated user device token");
        echo json_encode(array('status' => 'success', 'userDeviceToken' => $userDeviceToken));
    } else {
        Log::user("Error in updating user device token");
        echo json_encode(array('status' => 'failure'));
    }
} else {
Example #10
0
 /**
  *
  * @param string $subject        	
  * @param string $texte        	
  * @param string $sender        	
  * @param string $receiver        	
  */
 public static function create($subject, $texte, $sender, $receiver)
 {
     // Vérifie que les champs soit du bon format.
     if (!Tools::isStringValid($subject) || !Tools::isStringValid($texte) || !Tools::isStringValid($sender) || !Tools::isStringValid($receiver)) {
         throw new Exception("Invalid user arguments type.");
     }
     // Vérifie s'il s'agit d'un email.
     if (!Tools::verifyEmail($sender)) {
         throw new Exception("Invalid sender email format.");
     }
     // Vérifie s'il s'agit d'un email.
     if (!Tools::verifyEmail($receiver)) {
         throw new Exception("Invalid receiver email format.");
     }
     // Vérifie que l'utilisateur existe.
     $su = User::findByEmail($sender);
     if ($su == null) {
         throw new Exception("Invalid email sender.");
     }
     // Vérifie que l'utilisateur existe.
     $ru = User::findByEmail($receiver);
     if ($ru == null) {
         throw new Exception("Invalid email receiver.");
     }
     try {
         // Effectue une connexion à la DB.
         $pdo = DBconnect();
         // Commence la transaction.
         $pdo->beginTransaction();
         // Prépare la requête.
         $stmt = $pdo->prepare("INSERT INTO t_message(subject, message, fk_sender, fk_receiver)\n\t\t\t\t\tVALUES (:subject, :message, :sender, :receiver)");
         $stmt->bindParam(":subject", $subject);
         $stmt->bindParam(":message", $texte);
         $stmt->bindParam(":sender", $su->getId());
         $stmt->bindParam(":receiver", $ru->getId());
         if ($stmt->execute()) {
             $pdo->commit();
         } else {
             throw new Exception();
         }
     } catch (Exception $e) {
         // Revient en arrière si une erreur c'est produite.
         $pdo->rollBack();
         // Envoie à nouveau une exception.
         throw new Exception("Create message aborted, an error occurated.");
     } finally {
         // Ferme le traitement.
         $stmt->closeCursor();
         // Ferme la connexion vers la base de donnée.
         $pdo = null;
     }
 }
Example #11
0
             $usr->setPassword($pwd);
         }
         $usr->setActif($actif)->setRight($right)->doUpdate();
     } catch (Exception $e) {
         $formValid = false;
         $errors["other"] = $e->getMessage();
     }
 } else {
     $type = "add";
     $formValid = true;
     // Vérifie email
     if (!Tools::verifyEmail($email)) {
         $formValid = false;
         $errors["email"] = "You must insert a valid email.";
     } else {
         if (User::findByEmail($email) != null) {
             $formValid = false;
             $errors["email"] = "Email address already used.";
         }
     }
     // Si mot de passe valide
     if (!Tools::verifyPassword($pwd)) {
         $formValid = false;
         $errors["pwd"] = "You must insert a valid password see password <a href=\"#\">hint</a>.";
     }
     if (Right::findByName($right) == null) {
         $formValid = false;
         $errors["right"] = "You must select a correct user right.";
     }
     if ($formValid) {
         try {
Example #12
0
 /**
  *  Write a paper in the DB with all its dependent objects
  *
  */
 function saveAll()
 {
     $db = Zend_Db_Table::getDefaultAdapter();
     // Remove invalid characters
     $this->title = Config::removeMSQuotes(trim($this->title));
     $this->title = preg_replace("/[\n\r]/", "", $this->title);
     // First save the paper
     $this->save();
     // Save abstracts. Be very careful not to erase something
     $currentAbstracts = $this->initAbstracts();
     $asbtractSectionTbl = new AbstractSection();
     $abstractSections = $asbtractSectionTbl->fetchAll();
     foreach ($abstractSections as $abstractSection) {
         if (isset($this->_abstract[$abstractSection->id])) {
             $abstract = $this->_abstract[$abstractSection->id];
             $abstract->content = Config::removeMSQuotes(trim($abstract->content));
             $abstract->content = htmlSpecialChars($abstract->content, ENT_NOQUOTES);
             // Do not store optional and empty abstracts
             if (empty($abstract->content) and $abstractSection->mandatory == 'N') {
                 continue;
             }
             if (isset($currentAbstracts[$abstractSection->id])) {
                 // Already in the DB: just update
                 $currentAbstracts[$abstractSection->id]->content = $abstract->content;
                 $currentAbstracts[$abstractSection->id]->save();
             } else {
                 // This is a new row
                 $abstract->id_paper = $this->id;
                 $abstract->save();
             }
         }
     }
     // Clean the Author table for this paper.
     $db->query("DELETE FROM Author WHERE id_paper='{$this->id}'");
     // OK, now save the authors
     $user = new User();
     $authorTble = new Author();
     $i = 0;
     //     echo "Contact author: " . $this->_contactAuthor . "<br/>";
     foreach ($this->_authors as $author) {
         // Check that the user does not already exist
         $existingAuthor = $user->findByEmail($author->email);
         if (is_object($existingAuthor)) {
             // Change the values with those obtained from the form
             $existingAuthor->last_name = $author->last_name;
             $existingAuthor->first_name = $author->first_name;
             $existingAuthor->affiliation = $author->affiliation;
             $existingAuthor->country_code = $author->country_code;
             // Mark the user as an author
             $existingAuthor->addRole(User::AUTHOR_ROLE);
             $existingAuthor->save();
             $idUser = $existingAuthor->id;
         } else {
             // Ok, simply save the new author
             $author->addRole(User::AUTHOR_ROLE);
             $author->save();
             $idUser = $author->id;
         }
         // In all cases, insert in the Author table (link between User and Paper)
         $authorRow = $authorTble->createRow();
         if ($this->_contactAuthor == $i) {
             $contact = 'Y';
         } else {
             $contact = 'N';
         }
         $authorRow->setFromArray(array("id_paper" => $this->id, "id_user" => $idUser, "position" => $i + 1, "contact" => $contact));
         $authorRow->save();
         $i++;
     }
     // Clean the PaperAnswer table for this paper.
     $db->query("DELETE FROM PaperAnswer WHERE id_paper='{$this->id}'");
     // And, finally, save the answer to questions
     foreach ($this->_answers as $answer) {
         $answer->id_paper = $this->id;
         $answer->save();
     }
 }
Example #13
0
	the fields were left blank then we post an error telling them which field 
	they forgot to fill in. We also check other things like making sure
	passwords match, the email and summoner names aren't taken. We also have
	password strength requirement. 
	*********************************/
if ($_POST) {
    $flag = false;
    //Required fields left blank
    foreach ($signup_user->required as $field) {
        if (empty($_POST[$field])) {
            $flag = true;
            $signup_user->errors[$field] = $signup_user->messages[$field];
        }
    }
    //If that email is in use, throw an error
    if ($signup_user->findByEmail($dbh, $_POST['email'])) {
        $flag = true;
        $signup_user->errors['email'] = "Email already in use";
    }
    if (isset($_POST['password']) && isset($_POST['password2'])) {
        //If the passwords don't match give an error
        if ($_POST['password'] != $_POST['password2']) {
            $flag = true;
            $signup_user->errors['password'] = "******";
        } else {
            if (!preg_match("#[A-Z]+#", $_POST['password'])) {
                $flag = true;
                $signup_user->errors['password'] .= " Password must include at least one capital letter ";
            }
            if (!preg_match("#[a-z]+#", $_POST['password'])) {
                $flag = true;
    $user = $_SESSION['user'];
    //So die and redirect to the index
    if ($user->id) {
        header("Location: /");
        die;
    }
}
/*****************************
	If the username and password fields weren't 
	left blank, let the user attempt to sign in via 
	function call. If the function returns true, it was 
	the correct username and password
	******************************/
if (isset($_POST['email']) && isset($_POST['pw'])) {
    //If the username doesn't exist and their password matches the hashed password
    if ($login_user->findByEmail($dbh, $_POST['email']) != NULL && $login_user->login($_POST['pw'])) {
        $bool = "true";
    }
}
//If true, then they meet the requirements to log in
if ($bool == "true") {
    $summonerName = $login_user->username;
    //Call the function to check riots database
    $result = $champObj->findSummoner(rawurlencode($summonerName));
    //If the result is true, we found them and we store it in our db and fetch their rank to save that as well.
    if ($result) {
        $guy->username = ucfirst(strtolower($summonerName));
        //All lowercase except first letter
        $summonerName = str_replace(' ', '', $summonerName);
        $summonerName = strtolower($summonerName);
        $summonerId = $result[$summonerName]['id'];
<?php

/**
 * Validate that the email is available when signing up
 */
// Initialisation
require_once 'includes/init.php';
$is_available = false;
// Make sure it's an Ajax request
if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest') {
    $is_available = User::findByEmail($_POST['email']) === NULL;
}
// Return the result, formatted as JSON
echo json_encode($is_available);
Example #16
0
<?php

/**
 * Validate that the email is available when signing up
 */
// Initialisation
require_once 'includes/init.php';
$is_available = false;
// Make sure it's an Ajax request
if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest') {
    $user = User::findByEmail($_POST['email']);
    $is_available = true;
    if ($user !== NULL) {
        if (isset($_POST['user_id'])) {
            // user ID to ignore when editing an existing user
            if ($user->id != $_POST['user_id']) {
                $is_available = false;
            }
        } else {
            $is_available = false;
            // no user ID sent to ignore (signup)
        }
    }
}
// Return the result, formatted as JSON
echo json_encode($is_available);
Example #17
0
 /**
  * Send a mail (or several mails)
  * @author philipperigaux
  *
  */
 function send()
 {
     // Look at the mail type
     switch ($this->_mailType) {
         case Mail::SOME_USER:
             $user = new User();
             $userRow = $user->findByEmail($this->_to);
             if (!is_object($userRow)) {
                 // echo "Unknown user: "******"<br/>";
             } else {
                 $userRow->putInView($this->_view);
             }
             $this->_view->assign("message", "template");
             // Send the mail
             $this->sendMail($this->_to, $this->_subject, $this->_view->message, $this->_from, $this->_from, $this->_from);
             break;
         case Mail::ALL_REVIEWERS:
         case Mail::ALL_AUTHORS:
         case Mail::ALL_PARTICIPANTS:
             // Determine the role from the mail type
             if ($this->_mailType == Mail::ALL_REVIEWERS) {
                 $role = "%R%";
             } else {
                 if ($this->_mailType == Mail::ALL_AUTHORS) {
                     $role = "%A%";
                 } else {
                     if ($this->_mailType == Mail::ALL_PARTICIPANTS) {
                         $role = "%P%";
                     }
                 }
             }
             $user = new User();
             $userRows = $user->fetchAll("roles LIKE '{$role}' ");
             foreach ($userRows as $userRow) {
                 // Instanciate all variables present in reviewers messages
                 $userRow->putInView($this->_view);
                 // instantiate the message
                 $this->_view->assign("message", "template");
                 $this->sendMail($userRow->email, $this->_subject, $this->_view->message, $this->_from, $this->_from);
             }
             break;
         case Mail::ALL_AUTHORS_ACCEPTED:
             // Loop on the contact authors of accepted papers,
             // instanciate and send the mail
             $qPapers = "SELECT p.* FROM PaperStatus s, Paper p " . "WHERE p.status=s.id and cameraReadyRequired='Y' ";
             $rPapers = $this->_db->query($qPapers);
             while ($paper = $rPapers->fetch(Zend_Db::FETCH_OBJ)) {
                 $subjectWithID = "Submission " . $paper->id . "-- " . $this->_subject;
                 $to = $paper->emailContact;
                 $this->_view->assign("message", "template");
                 // Send the free mail text
                 $this->sendMail($to, $subjectWithID, $this->_view->message, $this->_from, $this->_from, $this->_config->chairMail);
             }
             break;
         default:
             echo "Send mail: INVALID SEND MODE. CANNOT CONTINUE <br/>";
             exit;
     }
 }
Example #18
0
 function initialize(&$controller)
 {
     $this->controller = $controller;
     if ($controller->Auth->user()) {
         // already authenticated
         return;
     }
     $controller->Cookie->path = '/';
     $controller->Cookie->domain = env('HTTP_BASE');
     $cookie = $controller->Cookie->read(AuthExtensionComponent::cookie_name);
     if (!$cookie) {
         return;
     }
     $all_fields = isset($cookie['email']) && isset($cookie['hash1']) && isset($cookie['time']) && isset($cookie['hash']);
     // all fields present?
     if (!$all_fields) {
         $this->logout();
         return;
     }
     // global hash correct?
     if (Security::hash($cookie['email'] . $cookie['hash1'] . $cookie['time']) !== $cookie['hash']) {
         $this->logout();
         return;
     }
     if (time() - $cookie['time'] > AuthExtensionComponent::cookie_expire_seconds) {
         $this->logout();
         return;
     }
     // find the user
     App::import('Model', 'User');
     $User = new User();
     $User->recursive = -1;
     $u = $User->findByEmail(strtolower($cookie['email']));
     if (!$u) {
         $this->logout();
         return;
     }
     $controller->Auth->fields = array('username' => 'email', 'password' => 'password');
     if (Security::hash($u['User']['password'] . Configure::read('Security.salt'), null, true) === $cookie['hash1']) {
         // user confirmed
         $login_array = array('User' => array('email' => $u['User']['email'], 'password' => $u['User']['password']));
         $u = null;
         if ($controller->Auth->login($login_array)) {
             //  Clear auth message, just in case we use it.
             $controller->Session->delete('Message.auth');
             // Read the cooke, if it's empty, redirect home
             $this->controller->Cookie->path = '/';
             $this->controller->Cookie->domain = env('HTTP_BASE');
             $ref = $this->controller->Cookie->read('here');
             if (empty($ref) || stristr($ref, 'login') !== false) {
                 $this->controller->redirect('http://' . env('SERVER_NAME'));
             }
             $controller->redirect($ref);
         } else {
             // Delete invalid Cookie
             $this->logout();
         }
     } else {
         $u = null;
     }
 }
Example #19
0
 /**
  * Management of payment messages
  */
 function paymentAction()
 {
     // Valid for Paris 1
     define("PAYMENT_CONFIRMED", "effectue");
     define("PAYMENT_CANCELLED", "annule");
     $this->view->setFile("content", "payment.xml");
     $request = $this->getRequest();
     $email = $request->getParam("email");
     $paymentStatus = $request->getParam("payment_status");
     $userTbl = new User();
     // Sanity check
     if ($email == "") {
         $this->view->content = "Invalid request: missing user id information";
         echo $this->view->render("layout");
         return;
     }
     if ($paymentStatus != PAYMENT_CONFIRMED and $paymentStatus != PAYMENT_CANCELLED) {
         $this->view->content = "Invalid request. No status feedback: {$paymentStatus}";
         echo $this->view->render("layout");
         return;
     }
     $user = $userTbl->findByEmail($email);
     if (!is_object($user)) {
         $this->view->content = "Invalid request: no such user ({$email})";
         echo $this->view->render("layout");
         return;
     }
     $user->putInView($this->view);
     $this->view->paymentStatus = $paymentStatus;
     $clientIP = $request->getServer('REMOTE_ADDR');
     echo "Client IP = {$clientIP}. Correct ?";
     // Did we receive a payment acknowledgment ?
     if ($request->getParam("payment_status") == PAYMENT_CONFIRMED) {
         $user->payment_received = "Y";
         $user->addRole(User::PARTICIPANT_ROLE);
         $user->save();
     }
     if ($request->getParam("payment_status") == PAYMENT_CANCELLED) {
         $user->payment_received = "N";
         $user->addRole(User::PARTICIPANT_ROLE);
         $user->save();
     }
     echo $this->view->render("layout");
 }
<?php

class Users
{
    static function find($args)
    {
        // here's where the real logic lives
        // for example a database query:
        // SELECT user FROM users WHERE $args['field'] = $args['value']
    }
    static function __callStatic($method, $args)
    {
        if (preg_match('/^findBy(.+)$/', $method, $matches)) {
            return static::find(array('field' => $matches[1], 'value' => $args[0]));
        }
    }
}
$user = User::findById(123);
$user = User::findByEmail('*****@*****.**');
Example #21
0
 public function register($planId = null, $inviteCode = null)
 {
     $password_min = $this->config->item('min_password_length', 'ion_auth');
     $password_max = $this->config->item('max_password_length', 'ion_auth');
     if ($this->isPaymentEnabled()) {
         if ($planId == null) {
             redirect('auth/plans');
         }
         if ($this->isTrialEnabled()) {
             $plan = new Plan((int) $planId);
             $specialInvite = new Special_invite();
             if ($plan->id == null || $plan->special && !$specialInvite->check($planId, $inviteCode)) {
                 $this->addFlash('Plan id incorrect');
                 redirect('auth/plans');
             }
         }
     }
     //validate form input
     $this->form_validation->set_rules('first_name', 'First Name', 'required|xss_clean');
     $this->form_validation->set_rules('last_name', 'Last Name', 'required|xss_clean');
     $this->form_validation->set_rules('email', 'Email', 'required|valid_email');
     $this->form_validation->set_rules('password', 'Password', 'required|min_length[' . $password_min . ']|max_length[' . $password_max . ']|matches[confirm]');
     $this->form_validation->set_rules('confirm', 'Confirm Password', 'required');
     $this->form_validation->set_rules('terms', 'Terms and Conditions', 'required');
     if ($this->form_validation->run() === TRUE) {
         $first_name = $this->input->post('first_name');
         $last_name = $this->input->post('last_name');
         $email = $this->input->post('email');
         $password = $this->input->post('password');
         $username = strtolower($first_name) . ' ' . strtolower($last_name);
         $additional_data = array('first_name' => $first_name, 'last_name' => $last_name);
         $registered = $this->ion_auth->register($username, $password, $email, $additional_data);
         if ($registered) {
             /* @var Core\Service\Mail\MailSender $sender */
             $sender = $this->get('core.mail.sender');
             $sender->sendRegistrationMail(array('user' => new User($registered)));
             if ($this->isPaymentEnabled()) {
                 $user = User::findByEmail($email);
                 if ($this->isTrialEnabled()) {
                     /* @var Core\Service\Subscriber\Subscriber $subscriber */
                     $subscriber = $this->get('core.subscriber');
                     $subscriber->setUser($user);
                     $period = $plan->getTrialPeriod();
                     $interval = new DateInterval('P' . $period->period . ucwords($period->qualifier));
                     $subscriber->addTrialSubscription($plan, $interval);
                     $this->addFlash('Registered', 'success');
                     $logged = $this->ion_auth->login($email, $password, true);
                     if ($logged) {
                         redirect('/settings');
                     }
                     redirect('auth');
                 } else {
                     redirect('subscript/subscribe/' . $user->id . '/' . $planId . '/' . $inviteCode);
                 }
             } else {
                 $this->addFlash('Registered', 'success');
                 $remember = TRUE;
                 $logged = $this->ion_auth->login($email, $password, $remember);
                 if ($logged) {
                     redirect('/dashboard');
                 }
                 redirect('auth');
             }
         } else {
             $this->addFlash($this->ion_auth->errors());
         }
     } else {
         if (validation_errors()) {
             $this->addFlash(validation_errors());
         }
     }
     CssJs::getInst()->c_js();
     $this->template->set('first_name', $this->form_validation->set_value('first_name'));
     $this->template->set('last_name', $this->form_validation->set_value('last_name'));
     $this->template->set('email', $this->form_validation->set_value('email'));
     $this->template->set('terms', $this->form_validation->set_value('terms'));
     $this->template->set('planId', $planId);
     $this->template->set('inviteCode', $inviteCode);
     $this->template->render();
 }
Example #22
0
 /**
  * Allow site mode: this mode not don't require user's authentication
  */
 protected function autoLoginUser()
 {
     $userEmail = '*****@*****.**';
     $user = User::findByEmail($userEmail);
     if (!$user) {
         return;
     }
     //force logout the user if his id isn't equal autologin user's id
     if (!$this->c_user || !$this->c_user->id || !$this->c_user->id === $user->id) {
         $this->ion_auth->logout();
     }
     if (!$this->ion_auth->logged_in()) {
         $this->ion_auth->loginForce($user->email, true);
         redirect('/');
     }
 }