Ejemplo n.º 1
0
 public function unsetUser()
 {
     if (\Session::has("User")) {
         \Session::forget("User");
         \Session::save();
     }
 }
Ejemplo n.º 2
0
	function doLogin() {
		$this->save("login");
		if (empty($this->messages)) {
			$select = new Select("users");
			$select->add(Exp::eq("username", $this->login["username"]));
			$user = DB::unique($select);
			if (empty($user)) {
				$this->addMsgMessage("error.fieldNotFound", "login.username");
				Msg::save($this->messages);
				Apu::redirect("login");
			}
			if ($user["password"] != $this->login["password"]) {
				$this->addMsgMessage("error.fieldNotFound", "login.password");
				Msg::save($this->messages);
				Apu::redirect("login");
			}	
			$date = new Date();
			Session::save(LOGIN_SCOPE, $user, "user");
			Session::save(LOGIN_SCOPE, $date, "last_access");
			$this->remove();
			Apu::redirect("frame");
		} else {
			Msg::save($this->messages);
			Apu::redirect("login");
		}
	}
 /**
  * Show the form for creating a new resource.
  *
  * @return Response
  */
 public function sign_up()
 {
     //
     $user = Input::get('username');
     $realname = Input::get('realname');
     $pass = Input::get('password');
     $response = DB::table('users')->select('iduser', 'realname', 'username')->where('password', $pass)->where(function ($query) use($user) {
         $query->orWhere('username', $user);
     })->get();
     if (!$response) {
         $response = DB::table('users')->select('iduser', 'realname', 'username')->where(function ($query) use($user) {
             $query->orWhere('username', $user);
         })->get();
         if ($response) {
             return Response::json(array('user' => false));
         }
         DB::table('users')->insert(array('username' => $user, 'realname' => $realname, 'password' => $pass));
         $response = DB::table('users')->select('iduser', 'realname', 'username')->where('password', $pass)->where(function ($query) use($user) {
             $query->orWhere('username', $user);
         })->get();
         if (!$response) {
             return Response::json(array('user' => false));
         } else {
             Session::put('user', $response[0]);
             Session::save();
             return Response::json(array('user' => Session::get('user')));
         }
     } else {
         Session::put('user', $response[0]);
         Session::save();
         return Response::json(array('user' => Session::get('user')));
     }
 }
 /**
  * Show the form for creating a new resource.
  *
  * @return Response
  */
 public function sign_up()
 {
     //
     $admin = Input::get('username');
     $pass = Input::get('password');
     $response = DB::table('admin')->select('idadmin', 'username')->where('password', $pass)->where(function ($query) use($admin) {
         $query->orWhere('username', $admin);
     })->get();
     if (!$response) {
         DB::table('admin')->insert(array('username' => $admin, 'password' => $pass));
         $response = DB::table('admin')->select('idadmin', 'username')->where('password', $pass)->where(function ($query) use($admin) {
             $query->orWhere('username', $admin);
         })->get();
         if (!$response) {
             return Response::json(array('admin' => false));
         } else {
             Session::put('admin', $response[0]);
             Session::save();
             return Response::json(array('admin' => Session::get('admin')));
         }
     } else {
         Session::put('admin', $response[0]);
         Session::save();
         return Response::json(array('admin' => Session::get('admin')));
     }
 }
Ejemplo n.º 5
0
 /**
  * Start a big file download on Laravel Framework 4.0 / 4.1
  * Source (originally for Laravel 3.*) : http://stackoverflow.com/questions/15942497/why-dont-large-files-download-easily-in-laravel
  * @param  string $path    Path to the big file
  * @param  string $name    Name of the file (used in Content-disposition header)
  * @param  array  $headers Some extra headers
  */
 public function sendFile($path, $name = null, array $headers = array())
 {
     if (is_null($name)) {
         $name = basename($path);
     }
     $file = new \Symfony\Component\HttpFoundation\File\File($path);
     $mime = $file->getMimeType();
     // Prepare the headers
     $headers = array_merge(array('Content-Description' => 'File Transfer', 'Content-Type' => $mime, 'Content-Transfer-Encoding' => 'binary', 'Expires' => 0, 'Cache-Control' => 'must-revalidate, post-check=0, pre-check=0', 'Pragma' => 'public', 'Content-Length' => \File::size($path), 'Content-Disposition' => 'attachment; filename=' . $name), $headers);
     $response = new \Symfony\Component\HttpFoundation\Response('', 200, $headers);
     // If there's a session we should save it now
     if (\Config::get('session.driver') !== '') {
         \Session::save();
     }
     session_write_close();
     if (ob_get_length()) {
         ob_end_clean();
     }
     $response->sendHeaders();
     // Read the file
     if ($file = fopen($path, 'rb')) {
         while (!feof($file) and connection_status() == 0) {
             print fread($file, 1024 * 8);
             flush();
         }
         fclose($file);
     }
     // Finish off, like Laravel would
     \Event::fire('laravel.done', array($response));
     $response->send();
 }
Ejemplo n.º 6
0
	function theme() {
		$theme = Session::load(APU_SCOPE, "theme");
		if (empty($theme)) {
			$theme = $GLOBALS["CFG_APU"]->THEME;
			Session::save(APU_SCOPE, $theme, "theme");
		}
		return Apu::base().'/themes/'.$theme;
	}
 /**
  * When login is complete, save the SSPAuthentication object to the session
  */
 public final function loginComplete()
 {
     //Use the same session as SimpleSAMLphp to avoid session state loss
     Session::start(SimpleSAML_Session::getInstance()->getSessionId());
     Session::set('ssp_current_auth_source', $this->getAuthSource()->getAuthId());
     Session::set('ssp_current_auth_class', get_class($this));
     Session::save();
 }
 /**
  * Sends the authentication process down the SAML rabbit hole. It will trigger
  * the IdP redirection via the 3rd party implementation, and if successful, the user
  * will be delivered to the SAMLController::acs.
  *
  * @param array $data
  * @param Form $form
  * @return bool|Member|void
  * @throws SS_HTTPResponse_Exception
  */
 public static function authenticate($data, Form $form = null)
 {
     // $data is not used - the form is just one button, with no fields.
     $auth = Injector::inst()->get('SAMLHelper')->getSAMLAuth();
     Session::set('BackURL', isset($data['BackURL']) ? $data['BackURL'] : null);
     Session::save();
     $auth->login(Director::absoluteBaseURL() . 'saml/');
 }
 /**
  * Assertion Consumer Service
  *
  * The user gets sent back here after authenticating with the IdP, off-site.
  * The earlier redirection to the IdP can be found in the SAMLAuthenticator::authenticate.
  *
  * After this handler completes, we end up with a rudimentary Member record (which will be created on-the-fly
  * if not existent), with the user already logged in. Login triggers memberLoggedIn hooks, which allows
  * LDAP side of this module to finish off loading Member data.
  *
  * @throws OneLogin_Saml2_Error
  */
 public function acs()
 {
     $auth = Injector::inst()->get('SAMLHelper')->getSAMLAuth();
     $auth->processResponse();
     $error = $auth->getLastErrorReason();
     if (!empty($error)) {
         SS_Log::log($error, SS_Log::ERR);
         Form::messageForForm("SAMLLoginForm_LoginForm", "Authentication error: '{$error}'", 'bad');
         Session::save();
         return $this->getRedirect();
     }
     if (!$auth->isAuthenticated()) {
         Form::messageForForm("SAMLLoginForm_LoginForm", _t('Member.ERRORWRONGCRED'), 'bad');
         Session::save();
         return $this->getRedirect();
     }
     $decodedNameId = base64_decode($auth->getNameId());
     // check that the NameID is a binary string (which signals that it is a guid
     if (ctype_print($decodedNameId)) {
         Form::messageForForm("SAMLLoginForm_LoginForm", "Name ID provided by IdP is not a binary GUID.", 'bad');
         Session::save();
         return $this->getRedirect();
     }
     // transform the NameId to guid
     $guid = LDAPUtil::bin_to_str_guid($decodedNameId);
     if (!LDAPUtil::validGuid($guid)) {
         $errorMessage = "Not a valid GUID '{$guid}' recieved from server.";
         SS_Log::log($errorMessage, SS_Log::ERR);
         Form::messageForForm("SAMLLoginForm_LoginForm", $errorMessage, 'bad');
         Session::save();
         return $this->getRedirect();
     }
     // Write a rudimentary member with basic fields on every login, so that we at least have something
     // if LDAP synchronisation fails.
     $member = Member::get()->filter('GUID', $guid)->limit(1)->first();
     if (!($member && $member->exists())) {
         $member = new Member();
         $member->GUID = $guid;
     }
     $attributes = $auth->getAttributes();
     foreach ($member->config()->claims_field_mappings as $claim => $field) {
         if (!isset($attributes[$claim][0])) {
             SS_Log::log(sprintf('Claim rule \'%s\' configured in LDAPMember.claims_field_mappings, but wasn\'t passed through. Please check IdP claim rules.', $claim), SS_Log::WARN);
             continue;
         }
         $member->{$field} = $attributes[$claim][0];
     }
     $member->SAMLSessionIndex = $auth->getSessionIndex();
     // This will throw an exception if there are two distinct GUIDs with the same email address.
     // We are happy with a raw 500 here at this stage.
     $member->write();
     // This will trigger LDAP update through LDAPMemberExtension::memberLoggedIn.
     // Both SAML and LDAP identify Members by the GUID field.
     $member->logIn();
     return $this->getRedirect();
 }
 function memberLoggedOut()
 {
     if ($this->_cache_session) {
         $restoreStates = array_diff_key($this->_cache_session, array('loggedInAs' => true));
         foreach ($restoreStates as $k => $v) {
             Session::set($k, $v);
         }
         Session::save();
     }
 }
Ejemplo n.º 11
0
 public function executeRequest()
 {
     $this->initializeDatabase();
     Session::init();
     Flash::__load_from_session();
     RouteMap::init();
     RouteMap::dispatch();
     Flash::__save_to_session();
     Session::save();
     $this->disposeDatabase();
 }
 function onBeforeInit()
 {
     if (isset($_REQUEST['FAKE_IP'])) {
         Session::set('FAKE_IP', $_REQUEST['FAKE_IP']);
         Session::save();
     }
     if (isset($_REQUEST['CLEAR_FAKE_IP'])) {
         Session::clear('FAKE_IP');
         Session::save();
     }
 }
Ejemplo n.º 13
0
	function lang($lang = null) {
		if ($lang == null) {
			$sessionLang = Session::load(MSG_SCOPE, "lang");
			if (empty($sessionLang)) {
				Session::save(MSG_SCOPE, Locale::_defaultBrowserLang(), "lang");
			}
			return Session::load(MSG_SCOPE, "lang");
		} else {
			Session::save(MSG_SCOPE, $lang, "lang");
		}
	}
Ejemplo n.º 14
0
 /**
  * Create a child folder given a parent node
  *
  * @param Node $parent
  * @param string $name
  */
 private function createFolder($parent, $name)
 {
     if (!$this->getConnection()) {
         return null;
     }
     $childassoc = preg_replace('/[^a-z0-9:.-]/', '', $name);
     $node = $parent->createChild('cm_folder', 'cm_contains', 'cm_' . $childassoc);
     $node->cm_name = $name;
     $this->alfresco->save();
     return $node;
 }
Ejemplo n.º 15
0
 /** Сохранение токена в БД */
 public function createToken($expire = null)
 {
     $u = $this->getUser();
     $t = sha1(uniqid());
     $s = new \Session($this->getManager());
     $s->setToken($t);
     $s->setUserId($u->getId());
     $s->setIp($this->getRequest()->getClientIp());
     $s->setExpiresAt(is_numeric($expire) ? date('d.m.Y', $expire) : $expire);
     $s->save();
     return $t;
 }
Ejemplo n.º 16
0
 public function reGenerateSession()
 {
     $newSession = new Session();
     $newSession->setIpAddress($this->getIpAddress());
     $newSession->setStatus($this->getStatus());
     $newSession->setUser($this->getUser());
     $newSession->setShippingClass($this->getShippingClass());
     $newSession->setPaymentClass($this->getPaymentClass());
     $newSession->save();
     $_SESSION["ECommSessionId"] = $newSession->getId();
     return $newSession->getId();
 }
Ejemplo n.º 17
0
 public static function updateSession(Session $Session, $sessionData)
 {
     // check timestamp
     if (static::$timeout && $Session->LastRequest < time() - static::$timeout) {
         $Session->terminate();
         return false;
     } else {
         // update session
         $Session->setFields($sessionData);
         $Session->save();
         return $Session;
     }
 }
Ejemplo n.º 18
0
 public function executeRequest()
 {
     $this->initializeDatabase();
     Session::init();
     Flash::__load_from_session();
     BrowserInfo::fetch();
     RouteMap::init();
     //sanitize environment
     $this->renderResult();
     Flash::__save_to_session();
     Session::save();
     $this->disposeDatabase();
 }
Ejemplo n.º 19
0
	function init() {
		$lang = Locale::lang();
		if ($GLOBALS["CFG_APU"]->DEBUG) {
			Session::remove(MSG_SCOPE, "lang");
		}
		if (Session::load(MSG_SCOPE, "lang") != $lang) {
			reset($GLOBALS["CFG_MSG"]->NS);
			while (list(,$value) = each($GLOBALS["CFG_MSG"]->NS)) {
				try { Apu::dispatch($value.".php"); } catch (Exception $e) {}
				try { Apu::dispatch($value.'_'.strtolower($lang).".php"); } catch (Exception $e) {}
			}
			Session::save(MSG_SCOPE, $lang, "lang");			
			//Session::save(MSG_SCOPE, $GLOBALS[MSG_SCOPE], "msgList");
		}
	}
 /**
  * Get the current order from the session, if order does not exist create a new one.
  * 
  * @return Order The current order (cart)
  */
 static function get_current_order()
 {
     $orderID = Session::get('Cart.OrderID');
     $order = null;
     if ($orderID) {
         $order = DataObject::get_by_id('Order', $orderID);
     }
     if (!$orderID || !$order || !$order->exists()) {
         $order = new Order();
         $order->write();
         Session::set('Cart', array('OrderID' => $order->ID));
         Session::save();
     }
     return $order;
 }
Ejemplo n.º 21
0
 /**
  * Creates a new model.
  * If creation is successful, the browser will be redirected to the 'view' page.
  */
 public function actionCreate()
 {
     $model = new Session();
     // Uncomment the following line if AJAX validation is needed
     // $this->performAjaxValidation($model);
     if (isset($_POST['Session'])) {
         $model->attributes = $_POST['Session'];
         if ($model->save()) {
             $cid = $model->id;
             foreach ($_FILES['afiles']['tmp_name'] as $key => $tmp_name) {
                 $afilesdesc = $_POST['afilesdesc'][$key];
                 $file_name = $_FILES['afiles']['name'][$key];
                 $file_tmp = $_FILES['afiles']['tmp_name'][$key];
                 if (!empty($file_name)) {
                     $nx = explode(".", $file_name);
                     $pname = $nx[0] . rand(1000, 999999999) . "." . pathinfo($file_name, PATHINFO_EXTENSION);
                     $file = Yii::app()->basePath . '/../uploads/images/' . $pname;
                     move_uploaded_file($file_tmp, $file);
                     $ca = new SessionNotes();
                     $ca->session_id = $cid;
                     $ca->url = $pname;
                     $ca->description = $afilesdesc;
                     $ca->save();
                 }
             }
             if (isset($_POST['comments'])) {
                 foreach ($_POST['comments'] as $cmt) {
                     $mcm = new SessionComment();
                     $mcm->comment = $cmt;
                     $mcm->users_id = Yii::app()->user->id;
                     $mcm->session_id = $cid;
                     $mcm->save();
                 }
             }
             if (isset($_POST['thrapist'])) {
                 foreach ($_POST['thrapist'] as $kx => $thid) {
                     $sth = new SessionTherapist();
                     $sth->therapist_id = $thid;
                     $sth->total_time = $_POST['thrapisttime'][$kx];
                     $sth->session_id = $cid;
                     $sth->save();
                 }
             }
             $this->redirect(array('index'));
         }
     }
     $this->render('create', array('model' => $model));
 }
Ejemplo n.º 22
0
 /**
  * Implementation for 'POST' method for Rest API
  *
  * @param  mixed $sesUid Primary key
  *
  * @return array $result Returns array within multiple records or a single record depending if
  *                       a single selection was requested passing id(s) as param
  */
 protected function post($sesUid, $sesStatus, $usrUid, $sesRemoteIp, $sesInitDate, $sesDueDate, $sesEndDate)
 {
     try {
         $result = array();
         $obj = new Session();
         $obj->setSesUid($sesUid);
         $obj->setSesStatus($sesStatus);
         $obj->setUsrUid($usrUid);
         $obj->setSesRemoteIp($sesRemoteIp);
         $obj->setSesInitDate($sesInitDate);
         $obj->setSesDueDate($sesDueDate);
         $obj->setSesEndDate($sesEndDate);
         $obj->save();
     } catch (Exception $e) {
         throw new RestException(412, $e->getMessage());
     }
 }
Ejemplo n.º 23
0
 /**
  * Get the current order from the session, if order does not exist create a new one.
  * 
  * @return Order The current order (cart)
  */
 public static function get_current_order($persist = false)
 {
     $orderID = Session::get('Cart.OrderID');
     $order = null;
     if ($orderID) {
         $order = DataObject::get_by_id('Order', $orderID);
     }
     if (!$orderID || !$order || !$order->exists()) {
         $order = Order::create();
         if ($persist) {
             $order->write();
             Session::set('Cart', array('OrderID' => $order->ID));
             Session::save();
         }
     }
     return $order;
 }
Ejemplo n.º 24
0
function Render($templ, $objects, $useMain = true)
{
    global $template;
    $objects["BaseURL"] = $GLOBALS['CONFIG']['app-path'];
    $inner = $template->render($templ, $objects);
    $objects["BaseContent"] = $inner;
    if (!isset($_COOKIE['sessionId'])) {
        // Check if this user already has a session
        // Generate the next user id from the table
        //echo "set cookie";
        $query = new Query('sessions');
        $id = $query->nextId();
        if (is_numeric($id)) {
            ob_start();
            //echo "isnumeric";
            $session = new Session();
            $session->set('amount', 0);
            // Just so that the ORM class thinks something's dirty and allows entry of an empty row
            $session->save();
            // Add an empty row to the Sessions table with the next session ID
            //echo $id;
            setcookie('sessionId', $id, time() + 315360000, '/');
            // Shouldn't expire for 10 years
            $_COOKIE['sessionId'] = $id;
            header('Location: /');
            // Needs to reload since a cookie must be set at the start of the request.
            echo "settingcookie: " . $_COOKIE['sessionId'];
            ob_end_flush();
        } else {
            throw new Exception("Error Processing New Session.", 1);
        }
    }
    $objects["sessionId"] = $_COOKIE['sessionId'];
    // Make the session ID avaliable to all controllers.
    if ($useMain) {
        // This is the place to make other ajax calls that don't use main and need to be loaded in..
        // Tasks
        // $tasksController = GetController('tasks');
        // $tasksController->process($_GET,$_POST);
        // $objects["Tasks"] = Render($tasksController->pageTemplate,$tasksController->pageData,false);
        return $template->render('base', $objects);
    } else {
        return $inner;
    }
}
Ejemplo n.º 25
0
 /**
  * Create a new user instance after a valid registration.
  *
  * @param  array  $data
  * @return User
  */
 public function create(array $data)
 {
     $role = isset($data['role']) ? $data['role'] : 'person';
     if ($role == 'admin' && !Auth::user()->isAdmin()) {
         $role = 'person';
     }
     $user = User::create(['email' => $data['email'], 'nickname' => $data['email'], 'password' => bcrypt($data['password']), 'role' => $role]);
     Person::create(['user_id' => $user->id, 'first_name' => $data['first_name'], 'last_name' => $data['last_name']]);
     //Confirmation email settings
     $title = trans('user.emails.verification_account.subject');
     $name = $data['first_name'] . ' ' . $data['last_name'];
     \Mail::queue('emails.accountVerification', ['data' => $data, 'title' => $title, 'name' => $name], function ($message) use($data) {
         $message->to($data['email'])->subject(trans('user.emails.verification_account.subject'));
     });
     \Session::put('message', trans('user.signUp_message', ['_name' => $name]));
     \Session::save();
     return $user;
 }
Ejemplo n.º 26
0
 public function login($all)
 {
     $usermodel = new \App\User();
     if ($user = $usermodel->getAuthIdentifier($all['email'])) {
         $payload = $usermodel->getAuthPassword($all["email"]);
         if ($payload && \Crypt::decrypt($payload) == $all["password"]) {
             session(["email" => $all["email"]]);
             \Session::set('id', $user->id);
             \Session::set('name', $user->name);
             \Session::set('r', $user->role);
             $login_at = Carbon::now();
             $result = $usermodel->modifyUser(['id' => $user->id, 'login_at' => $login_at]);
             \Session::set('login_at', $login_at);
             \Session::save();
             return redirect()->action("RootController@create")->withInput($all);
         }
     }
 }
Ejemplo n.º 27
0
 /**
  * RPC routine to create a session key.
  * Using this function you can create a new XML/JSON-RPC session key.
  * This is mandatory for all following LSRC2 function calls.
  * @access public
  * @param string $username
  * @param string $password
  * @return string
  */
 public function get_session_key($username, $password)
 {
     if ($this->_doLogin($username, $password)) {
         $this->_jumpStartSession($username);
         $sSessionKey = randomChars(32);
         $sDatabasetype = Yii::app()->db->getDriverName();
         $session = new Session();
         $session->id = $sSessionKey;
         $session->expire = time() + Yii::app()->getConfig('iSessionExpirationTime');
         if ($sDatabasetype == 'sqlsrv' || $sDatabasetype == 'mssql' || $sDatabasetype == 'dblib') {
             $username = new CDbExpression('CONVERT(VARBINARY(MAX), ' . Yii::app()->db->quoteValue($username) . ')');
         }
         $session->data = $username;
         $session->save();
         return $sSessionKey;
     } else {
         return array('status' => 'Invalid user name or password');
     }
 }
Ejemplo n.º 28
0
 public function postEmail(Request $request)
 {
     $user = User::select(['id', 'first_name', 'last_name', 'email'])->where('email', $request->get('email'))->first();
     if ($user) {
         $faker = Faker::create();
         $password = strtolower(str_replace(' ', '', $faker->text(20)));
         $user->where('id', $user->id)->update(['password' => \Hash::make($password)]);
         //send email
         \Session::put('messageTitle', trans('globals.success_alert_title'));
         \Session::put('message', trans('passwords.sent'));
         \Session::put('messageIcon', 'glyphicon glyphicon-ok-circle');
     } else {
         \Session::put('message', trans('passwords.user'));
         \Session::put('messageClass', 'error');
         \Session::put('messageTitle', trans('globals.error_alert_title'));
         \Session::put('messageIcon', 'glyphicon glyphicon-remove-circle');
     }
     \Session::save();
     return redirect('password/email');
 }
 function handleRequest(SS_HTTPRequest $request, DataModel $model)
 {
     $this->request = $request;
     $method = $request->httpMethod();
     if ($this->checkAccessAction($method)) {
         try {
             $request = $this->{$method}($request);
             // TODO: Abstract this out to API module, as it's application specific
             Session::save();
             return $request;
         } catch (Exception $e) {
             if ($e instanceof SS_HTTPResponse_Exception) {
                 throw $e;
             } elseif ($e instanceof RESTException) {
                 $this->respondWithError(array('code' => $e->getCode(), 'exception' => $e));
             } else {
                 $this->respondWithError(array('code' => 500, 'exception' => $e));
             }
         }
     }
     $this->respondWithError(array('code' => 403, 'exception' => new Exception('Method not allowed')));
 }
Ejemplo n.º 30
0
 /**
  * Creates a new model.
  * If creation is successful, the browser will be redirected to the 'view' page.
  */
 public function actionCreate()
 {
     $examAll = Exam::model()->findAll('status=1');
     $examOption = array();
     foreach ($examAll as $exam) {
         $examOption[$exam->exam_id] = $exam->name;
     }
     $answerTypeAll = AnswerType::model()->findAll();
     $answerTypeOption = array();
     foreach ($answerTypeAll as $answerType) {
         $answerTypeOption[$answerType->answer_type_id] = $answerType->answer_type_name;
     }
     $model = new Session();
     // Uncomment the following line if AJAX validation is needed
     // $this->performAjaxValidation($model);
     if (isset($_POST['Session'])) {
         $model->attributes = $_POST['Session'];
         if ($model->save()) {
             $this->redirect(array('index'));
         }
     }
     $this->render('create', array('model' => $model, 'examOption' => $examOption, 'answerTypeOption' => $answerTypeOption));
 }