<?php
class UsersController extends AppController {

    var $name = 'Users';
    var $components = array('Auth','Email','Otp'); // Not necessary if declared in your app controller
    function beforeFilter() {
        $this->Auth->allow('login','register','otpregister', 'message','success');
    }
    /**
     *  The AuthComponent provides the needed functionality
     *  for login, so you can leave this function blank.
     */
    function login() {
    }

    function message(){

    }

    function success(){}

    // bogues method - remove when moving from demo to prod
    function verysecure(){

    }

    function logout() {
        $this->redirect($this->Auth->logout());
    }
    
    function register() {
        if (!empty($this->data)) {

            $username = $this->data["User"]["username"];
            $user = $this->User->FindByUsername($username);

                if(!$user){
                    // TODO validate that username is in an EMAIL format

                    // create an non-active user (with random password)
                    $randomPass = $this->Auth->password($this->generatePassword());
                    $user = array(
                                'User' => array(
                                'password' => $randomPass,
                                'username' =>$username,

                                ),

                            );
                            $this->User->create();
                            $this->User->save($user);

                    // setup the TIME TO LIVE (valid until date) for the next two days
                    $now = microtime(true);
                    $ttl =$now + 48*3600; // the invitation is good for the next two days

                    // create the OTP - TTL = time to live
                    $otp = $this->Otp->createOTP(array('user'=>$username,'password'=>$randomPass,'ttl'=> $ttl) );

                    $link = '<a href="http://' . $_SERVER['SERVER_NAME'] . Dispatcher::baseUrl()."/users/otpregister/".$username."/".$ttl."/".$otp.'"> Registration link</a>';
                     // send mail
                    $this->Email->from    = "admin@somedomain.com";
                    $this->Email->to      = $username;

                    $this->Email->subject = "Website Registration";
                    $this->Email->sendAs = 'html';


                    $body = "Please use the following link to access the website:<br>";
                    $body .= $link;

                    $this->Email->send($body);
                    $this->Session->setFlash("Email send, please check your email for your CakeOTP");
                    $this->redirect("/");
                }else{
                   $this->Session->setFlash("This user is already in the system, please try another email");
                  
                }
            
           
        }
    }

    // after clicking the link in the registration email the user will be sent here
    function otpregister($email,$ttl,$otp) {
            if($email){
                $user = $this->User->FindByUsername($email);
                if($user){
                    $passwordHash = $user["User"]["password"];

                    $now = microtime(true);
                    // check expiration date. the experation date should be greater them now.
                    if($now <  $ttl){
                        // validate OTP
                        if($this->Otp->authenticateOTP($otp,array('user'=>$email,'password'=>$passwordHash,'ttl'=> $ttl)) ){
                               if($this->data){
                                   // set the password
                                   $password = $this->data["User"]["pass"];
                                   $this->User->id =  $user["User"]["id"];

                                   if(strlen($password)<6){
                                    $this->Session->setFlash("Password Must be at least 6 characters long. Please enter a longer password.");

                                   }else if ($this->Auth->password($this->data["User"]["password"]) != $this->Auth->password($password)) {

                                       $this->Session->setFlash( 'Password and Confirmation password do not match. Please try again.');
                                   }else{

                                     $this->User->saveField('password',   $this->Auth->password($password));
                                      //$this->Session->setFlash( 'Password Changed');
                                     $this->redirect(array('action' => 'success'));
                                   }

                               }
                               $this->set('email',$email);
                               $this->set('ttime',$ttl);
                               $this->set('hash',$otp);

                        }else{
                            $this->Session->setFlash("Invalid request. Please contact the website administration.");
                            $this->redirect(array('action' => 'message'));

                        }
                    }else{
                        $this->Session->setFlash("Your invitation has expired. Please contact the website administration.");
                        $this->redirect(array('action' => 'message'));
                    }
                }
            }
            //TODO: handle invalid request with no parameters
	}





     function generatePassword($length=6, $strength=0){
		$vowels = 'aeuy';
		$consonants = 'bdghjmnpqrstvz';
		if ($strength & 1) {
			$consonants .= 'BDGHJLMNPQRSTVWXZ';
		}
		if ($strength & 2) {
			$vowels .= "AEUY";
		}
		if ($strength & 4) {
			$consonants .= '23456789';
		}
		if ($strength & 8) {
			$consonants .= '@#$%';
		}

		$password = '';
		$alt = time() % 2;
		for ($i = 0; $i < $length; $i++) {
			if ($alt == 1) {
				$password .= $consonants[(rand() % strlen($consonants))];
				$alt = 0;
			} else {
				$password .= $vowels[(rand() % strlen($vowels))];
				$alt = 1;
			}
		}
		return $password;
	}

}

?>
