set() public static method

sets a specific value to a specific key of the session
public static set ( mixed $key, mixed $value )
$key mixed key
$value mixed value
示例#1
0
文件: set.php 项目: anqqa/Anqh
 /**
  * Set page width
  *
  * @param  string  $width
  */
 public function width($width)
 {
     $this->session->set('page_width', $width == 'wide' ? 'liquid' : 'fixed');
     if (request::is_ajax()) {
         return;
     }
     url::back();
 }
示例#2
0
 public function testFlush()
 {
     $this->target->set('bindable.dummy.xyzzy', 'hogefuga');
     $this->target->bind($this->bindable);
     \Phake::when($this->bindable)->getSessionContent()->thenReturn(array('hoge' => 'hogehoge', 'xyzzy' => 'piyopiyo'));
     $this->target->flush();
     $this->assertEquals(array('HOGE' => 1, 'FUGA' => 2, 'PIYO' => array('FIZZ' => 'BUZZ'), 'bindable' => array('dummy' => array('hoge' => 'hogehoge', 'xyzzy' => 'piyopiyo'))), $_SESSION);
 }
 /**
  * Automatic login user.
  *
  * @return boolean
  */
 public function autologin()
 {
     $this->session = getSession();
     $user_id = $this->authenticate();
     if ($user_id === false) {
         return false;
     }
     $this->session->set("user_id", $user_id);
     return true;
 }
示例#4
0
 public static function setUser(User $user)
 {
     self::$currentUser = $user;
     $app = ActiveRecordModel::getApplication();
     $app->processRuntimePlugins('session/before-login');
     $session = new Session();
     $session->set('User', $user->getID());
     $session->set('UserGroup', $user->userGroup->get() ? $user->userGroup->get()->getID() : 0);
     if ($app->getSessionHandler()) {
         $app->getSessionHandler()->setUser($user);
     }
     $app->processRuntimePlugins('session/login');
 }
    /**
     * Redirect the user to the change password form.
     *
     * @return SS_HTTPResponse
     */
    protected function redirectToChangePassword()
    {
        // Since this form is loaded via an iframe, this redirect must be performed via javascript
        $changePasswordForm = new ChangePasswordForm($this->controller, 'ChangePasswordForm');
        $changePasswordForm->sessionMessage(_t('Member.PASSWORDEXPIRED', 'Your password has expired. Please choose a new one.'), 'good');
        // Get redirect url
        $changePasswordURL = $this->getExternalLink('changepassword');
        if ($backURL = $this->controller->getRequest()->requestVar('BackURL')) {
            Session::set('BackURL', $backURL);
            $changePasswordURL = Controller::join_links($changePasswordURL, '?BackURL=' . urlencode($backURL));
        }
        $changePasswordURLATT = Convert::raw2att($changePasswordURL);
        $changePasswordURLJS = Convert::raw2js($changePasswordURL);
        $message = _t('CMSMemberLoginForm.PASSWORDEXPIRED', '<p>Your password has expired. <a target="_top" href="{link}">Please choose a new one.</a></p>', 'Message displayed to user if their session cannot be restored', array('link' => $changePasswordURLATT));
        // Redirect to change password page
        $this->controller->getResponse()->setStatusCode(200);
        $this->controller->getResponse()->setBody(<<<PHP
<!DOCTYPE html>
<html><body>
{$message}
<script type="application/javascript">
setTimeout(function(){top.location.href = "{$changePasswordURLJS}";}, 0);
</script>
</body></html>
PHP
);
        return $this->controller->getResponse();
    }
示例#6
0
 public function login()
 {
     if (Session::get('isLoggedIn')) {
         Messages::addMessage("info", "You are already logged in.");
         return;
     } else {
         $response = array();
         // params have to be there
         $user_name = $this->params->getValue('user_name');
         $user_password = $this->params->getValue('password');
         if ($user_name != null && $user_password != null) {
             // check if user name and password are correct
             $usr = $this->userManager->findUser($user_name, $user_password);
             if ($usr != null) {
                 // log user in
                 Session::set("user_name", $usr['user_name']);
                 Session::set("id", $usr['ID']);
                 Session::set("isLoggedIn", true);
                 return $usr;
             } else {
                 Messages::addMessage("info", "Log in user and/or password incorrect.");
                 return null;
             }
         } else {
             Messages::addMessage("warning", "'user_name' and/or 'password' parameters missing.");
             return null;
         }
     }
 }
示例#7
0
 public function register()
 {
     $response = array();
     // params have to be there
     $usr = $this->params->getValue('username');
     $pwd = $this->params->getValue('password');
     $encrypt = md5($pwd);
     $fname = $this->params->getValue('firstname');
     $lname = $this->params->getValue('lastname');
     $email = $this->params->getValue('email');
     echo $usr . " " . $pwd . " " . $fname . " " . $lname . " " . $email . " " . $encrypt;
     if ($usr != null && $pwd != null && $fname != null && $lname != null && $email != null) {
         // check if user name and password are correct
         $user = $this->userManager->addUser($fname, $lname, $usr, $encrypt, $email);
         if ($user != null) {
             // log user in
             Session::set("username", $user['username']);
             Session::set("id", $user['ID']);
             Session::set("isLoggedIn", true);
             return $user;
             return $user['ID'];
             return $encrypt;
             //return $response;
         } else {
             Messages::addMessage("warning", "'user_name' and/or 'password' parameters missing.");
             return null;
             return $usr;
         }
     }
 }
示例#8
0
 public function loginAction()
 {
     $userInfo = Session::get('user');
     if ($userInfo['login'] == true && $userInfo['time'] + TIME_LOGIN >= time()) {
         URL::redirect('default', 'user', 'index');
     }
     $this->_view->_title = 'Login';
     if (@$this->_arrParam['form']['token'] > 0) {
         $validate = new Validate($this->_arrParam['form']);
         $email = $this->_arrParam['form']['email'];
         $password = md5($this->_arrParam['form']['password']);
         $query = "SELECT `id` FROM `user` WHERE `email` = '{$email}' AND `password` = '{$password}'";
         $validate->addRule('email', 'existRecord', array('database' => $this->_model, 'query' => $query));
         $validate->run();
         if ($validate->isValid() == true) {
             $infoUser = $this->_model->infoItem($this->_arrParam);
             $arraySession = array('login' => true, 'info' => $infoUser, 'time' => time(), 'group_acp' => $infoUser['group_acp']);
             Session::set('user', $arraySession);
             URL::redirect('default', 'user', 'index');
         } else {
             $this->_view->errors = $validate->showErrorsPublic();
         }
     }
     $this->_view->render('index/login');
 }
示例#9
0
 /**
  * Forgot password
  */
 private function forgotpwd()
 {
     if (isset($_POST['forgotpwd'])) {
         $email = $_POST['email'];
         if (!Validate::len($email)) {
             $error = 'Email character count must be between 4 and 64';
         } elseif (!Validate::email($email)) {
             $error = 'Please enter a valid email';
         }
         if (!$error) {
             $user = User::where('email', $email)->select('id')->findOne();
             if (!$user) {
                 $error = 'Email address not found';
             }
         }
         if ($error) {
             View::error('user/forgotpwd', $error);
         }
         // Makes an internal session
         $pwd = Session::set('pwd', $user->id, 0);
         View::set('session_pwd', $pwd);
         Base::sendMail($email, 'forgotpwd');
         Base::redirect('', 'Go to your email and follow the instructions');
     } elseif (isset($_GET['pwd'])) {
     }
 }
 /**
  * Default method
  * @return [type] [description]
  */
 public function index()
 {
     if (Session::get('logined') !== null) {
         if (Session::get('logined')) {
             $this->getUserLogin();
             exit;
         }
     }
     $auth = new Authenticate();
     if (isset($_POST['user_id']) && isset($_POST['id_token'])) {
         $user_id = $_POST['user_id'];
         $id_token = $_POST['id_token'];
         if ($auth->checkLogin($user_id, $id_token)) {
             Session::init();
             Session::set('id_token', $id_token);
             Session::set('user_id', $user_id);
             Session::set('logined', true);
             echo json_encode('success');
             exit;
         } else {
             echo json_encode('need login with google ID');
             exit;
         }
     } else {
         echo json_encode('need login with google ID');
         exit;
     }
 }
 /**
  * @param $data
  * @param $form
  * @return bool|SS_HTTPResponse
  */
 function Register($data, $form)
 {
     // Set session array individually as setting the password breaks the form.
     $sessionArray = array('Email' => $data['Email']);
     // Check for existing member email address
     if ($existingUser = DataObject::get_one('Member', "Email = '" . Convert::raw2sql($data['Email']) . "'")) {
         $form->AddErrorMessage('Email', _t('RegistrationPage.EmailValidationText', 'Sorry, that email address already exists. Please choose another.'), 'validation');
         Session::set('FormInfo.Form_RegistrationForm.data', $sessionArray);
         return $this->redirectBack();
     }
     // Otherwise create new member and log them in
     $Member = new Member();
     $form->saveInto($Member);
     $Member->write();
     $Member->login();
     // Find or create the 'user' group
     if (!($userGroup = DataObject::get_one('Group', "Code = 'users'"))) {
         $userGroup = new Group();
         $userGroup->Code = 'users';
         $userGroup->Title = 'Users';
         $userGroup->Write();
         $userGroup->Members()->add($Member);
     }
     // Add member to user group
     $userGroup->Members()->add($Member);
     // Get profile page otherwise display warning.
     if ($ProfilePage = DataObject::get_one('EditProfilePage')) {
         $name = $data['FirstName'] ?: ($name = $data['Email']);
         $this->setFlash(_t('RegistrationPage.RegisteredSuccessText', 'Welcome ' . $name . ', your account has been created!'), 'success');
         return $this->redirect($ProfilePage->Link());
     } else {
         $this->setFlash(_t('RegistrationPage.RegisteredWarningText', 'Please add a "Edit Profile Page" in your SiteTree to enable profile editing'), 'warning');
         return $this->redirect(Director::absoluteBaseURL());
     }
 }
示例#12
0
 /**
  * logout
  *
  * @param void
  * @return void
  */
 public static function logout()
 {
     Load::lib('auth');
     Load::lib('session');
     Session::set(SESSION_KEY, false);
     Auth::destroy_identity();
 }
示例#13
0
 /**
  * 确认注册【设定密码】
  * @method registerAction
  * @return [type]         [description]
  * @author NewFuture
  */
 public function registerAction()
 {
     $msg = '信息注册失败!';
     if ($regInfo = Session::get('reg')) {
         Session::del('reg');
         if (Input::post('password', $password, 'trim') === false) {
             /*密码未md5*/
             $this->error('密码错误', '/');
         } elseif (!$password) {
             /*未设置密码*/
             $password = $regInfo['password'];
         }
         $regInfo['password'] = Encrypt::encryptPwd($password, $regInfo['number']);
         if ($id = UserModel::insert($regInfo)) {
             /*注册成功*/
             $regInfo['id'] = $id;
             $token = Auth::token($regInfo);
             Cookie::set('token', [$id => $token]);
             unset($regInfo['password']);
             Session::set('user', $regInfo);
             $msg = '信息注册成功!';
         }
     }
     $this->jump('/', $msg);
 }
示例#14
0
 public function ingresar()
 {
     try {
         $user = $this->getTexto('txtLogin');
         $pass = $this->getTexto('txtContraseña');
         if (!empty($user) && !empty($pass)) {
             $objUser = $this->_login->getUsuario($user);
             if ($objUser) {
                 if (strtolower($objUser[0]->getUsername()) == $user && $objUser[0]->getPassword() == crypt($pass, 'SMSYS')) {
                     Session::set('SESS_USER', $objUser[0]->getUsername());
                     if (Session::get('SESS_ERRLOGIN') != null) {
                         Session::destroy('SESS_ERRLOGIN');
                     }
                     header('Location: ' . BASE_URL . 'sistema');
                 } else {
                     //Session::set('SESS_ERRLOGIN',$user.' '.$pass);
                     Session::set('SESS_ERRLOGIN', 'Usuario o contraseña incorrectos');
                     header('Location: ' . BASE_URL . 'login');
                 }
             } else {
                 //Session::set('SESS_ERRLOGIN',$user.' '.$pass);
                 Session::set('SESS_ERRLOGIN', 'No existe ese usuario registrado');
                 header('Location: ' . BASE_URL . 'login');
             }
         }
     } catch (Exception $ex) {
         echo $ex->getMessage();
     }
 }
示例#15
0
 public function before()
 {
     parent::before();
     $flag = $this->getNotOpenidAllowed();
     if ($flag) {
         return;
     }
     if (!\Session::get('wechat', false) && !\Input::get('openid', false)) {
         //获取到openid之后跳转的参数列表
         //$params = \handler\mp\UrlTool::createLinkstring(\Input::get());
         //本站域名
         $baseUrl = \Config::get('base_url');
         $url = $baseUrl . \Input::server('REQUEST_URI');
         $toUrl = urlencode($url);
         $callback = "{$baseUrl}wxapi/oauth2_callback?to_url={$toUrl}";
         $account = \Session::get('WXAccount', \Model_WXAccount::find(1));
         $url = \handler\mp\Tool::createOauthUrlForCode($account->app_id, $callback);
         \Response::redirect($url);
     } else {
         if (!\Session::get('wechat', false)) {
             $wxopenid = \Model_WechatOpenid::query()->where(['openid' => \Input::get('openid')])->get_one();
             if (!$wxopenid) {
                 \Session::set_flash('msg', ['status' => 'err', 'msg' => '未找到您的微信信息,无法确认您的身份! 系统无法为您提供服务!', 'title' => '拒绝服务']);
                 return $this->show_mesage();
             }
             \Session::set('wechat', $wxopenid->wechat);
             \Session::set('OpenID', $wxopenid);
             \Auth::force_login($wxopenid->wechat->user_id);
         } else {
             if (!\Auth::check() && \Session::get('wechat')->user_id) {
                 \Auth::force_login(\Session::get('wechat')->user_id);
             }
         }
     }
 }
 /**
  * Handles validating the final step and writing the tickets data to the
  * registration object.
  */
 public function finish($data, $form)
 {
     parent::finish($data, $form);
     $step = $this->getCurrentStep();
     $datetime = $this->getController()->getDateTime();
     $registration = $this->session->getRegistration();
     $ticketsStep = $this->getSavedStepByClass('EventRegisterTicketsStep');
     $tickets = $ticketsStep->loadData();
     // Check that the requested tickets are still available.
     if (!$this->validateTickets($tickets['Tickets'], $form)) {
         Session::set("FormInfo.{$form->FormName()}.data", $form->getData());
         $this->controller->redirectBack();
         return false;
     }
     // Validate the final step.
     if (!$step->validateStep($data, $form)) {
         Session::set("FormInfo.{$form->FormName()}.data", $form->getData());
         $this->controller->redirectBack();
         return false;
     }
     $this->session->delete();
     // If the registrations is already valid, then send a details email.
     if ($registration->Status == 'Valid') {
         EventRegistrationDetailsEmail::factory($registration)->send();
     }
     $this->extend('onRegistrationComplete', $registration);
     $this->controller->redirect(Controller::join_links($datetime->Event()->Link(), 'registration', $registration->ID, '?token=' . $registration->Token));
 }
示例#17
0
 /**
  * Display a listing of the resource.
  *
  * @return Response
  */
 public function getIndex()
 {
     if (Request::segment(2) == 'search') {
         $input = Session::get('search') && !Input::get('search_category') ? Session::get('search') : Input::only(array('search_category', 'search_keyword'));
         switch ($input['search_category']) {
             case '0':
                 return Redirect::to('gateway');
                 break;
             case 'owner':
                 $gateways = Gateway::whereHas('user', function ($q) {
                     $q->where('username', 'LIKE', '%' . Input::get('search_keyword') . '%');
                 })->get();
                 break;
             default:
                 if (Auth::user()->status == 2) {
                     $gateways = Gateway::where($input['search_category'], 'LIKE', '%' . $input['search_keyword'] . '%')->get();
                 } else {
                     $gateways = Gateway::where('user_id', Auth::user()->id)->where($input['search_category'], 'LIKE', '%' . $input['search_keyword'] . '%')->get();
                 }
                 break;
         }
         Session::set('search', $input);
     } else {
         Session::remove('search');
         $input = array('search_category' => '', 'search_keyword' => '');
         $gateways = Auth::user()->status == 2 ? Gateway::all() : Gateway::where('user_id', Auth::user()->id)->get();
     }
     return View::make('gateway.index')->with('gateways', $gateways)->with('selected', $input);
 }
 /**
  * Proccess payment : create paypal form and return it 
  * @return type
  */
 public function proccessPayment()
 {
     // $payPalForm = new PaymentForm\PaymentFormPaypal($this->config, $this->order);
     // return $payPalForm->createForm();
     $config = array('mode' => $this->config['mode'], 'acct1.UserName' => $this->config['user_name'], 'acct1.Password' => $this->config['password'], 'acct1.Signature' => $this->config['signature']);
     $paypalService = new \PayPal\Service\PayPalAPIInterfaceServiceService($config);
     $paymentDetails = new \PayPal\EBLBaseComponents\PaymentDetailsType();
     $itemDetails = new \PayPal\EBLBaseComponents\PaymentDetailsItemType();
     $itemDetails->Name = 'Order ID: ' . $this->order->id;
     $itemAmount = $this->getOrderTotal();
     $itemDetails->Amount = $itemAmount;
     $itemQuantity = 1;
     $itemDetails->Quantity = $itemQuantity;
     $paymentDetails->PaymentDetailsItem[0] = $itemDetails;
     $orderTotal = new \PayPal\CoreComponentTypes\BasicAmountType();
     $orderTotal->currencyID = $this->config['currency'];
     $orderTotal->value = $itemAmount * $itemQuantity;
     $paymentDetails->OrderTotal = $orderTotal;
     $paymentDetails->PaymentAction = 'Sale';
     $setECReqDetails = new \PayPal\EBLBaseComponents\SetExpressCheckoutRequestDetailsType();
     $setECReqDetails->PaymentDetails[0] = $paymentDetails;
     $setECReqDetails->CancelURL = $this->config['cancel_url'];
     $setECReqDetails->ReturnURL = $this->config['return_url'];
     $setECReqType = new \PayPal\PayPalAPI\SetExpressCheckoutRequestType();
     $setECReqType->Version = $this->config['version'];
     $setECReqType->SetExpressCheckoutRequestDetails = $setECReqDetails;
     $setECReq = new \PayPal\PayPalAPI\SetExpressCheckoutReq();
     $setECReq->SetExpressCheckoutRequest = $setECReqType;
     $setECResponse = $paypalService->SetExpressCheckout($setECReq);
     \Session::set('paypal.token', $setECResponse->Token);
     \Response::redirect(\PayPal\Core\PPConstants::IPN_SANDBOX_ENDPOINT . '?' . $this->config['param'] . $setECResponse->Token);
 }
示例#19
0
 public function postLogin()
 {
     if (Request::ajax()) {
         $userdata = array('usuario' => Input::get('usuario'), 'password' => Input::get('password'));
         if (Auth::attempt($userdata, Input::get('remember', 0))) {
             //buscar los permisos de este usuario y guardarlos en sesion
             $query = "SELECT m.nombre as modulo, s.nombre as submodulo,\n                        su.agregar, su.editar, su.eliminar,\n                        CONCAT(m.path,'.', s.path) as path, m.icon\n                        FROM modulos m \n                        JOIN submodulos s ON m.id=s.modulo_id\n                        JOIN submodulo_usuario su ON s.id=su.submodulo_id\n                        WHERE su.estado = 1 AND m.estado = 1 AND s.estado = 1\n                        and su.usuario_id = ?\n                        ORDER BY m.nombre, s.nombre ";
             $res = DB::select($query, array(Auth::id()));
             $menu = array();
             $accesos = array();
             foreach ($res as $data) {
                 $modulo = $data->modulo;
                 //$accesos[] = $data->path;
                 array_push($accesos, $data->path);
                 if (isset($menu[$modulo])) {
                     $menu[$modulo][] = $data;
                 } else {
                     $menu[$modulo] = array($data);
                 }
             }
             $usuario = Usuario::find(Auth::id());
             Session::set('language', 'Español');
             Session::set('language_id', 'es');
             Session::set('menu', $menu);
             Session::set('accesos', $accesos);
             Session::set('perfilId', $usuario['perfil_id']);
             Session::set("s_token", md5(uniqid(mt_rand(), true)));
             Lang::setLocale(Session::get('language_id'));
             return Response::json(array('rst' => '1', 'estado' => Auth::user()->estado));
         } else {
             $m = '<strong>Usuario</strong> y/o la <strong>contraseña</strong>';
             return Response::json(array('rst' => '2', 'msj' => 'El' . $m . 'son incorrectos.'));
         }
     }
 }
 public function run()
 {
     /*
      * md5 is a 32 bit hash
      */
     $statement = $this->db->prepare("SELECT id, role FROM users WHERE login = :user AND password = :pass");
     $statement->execute(array(':user' => $_POST['user'], ':pass' => Hash::create('sha256', $_POST['pass'], HASH_KEY)));
     /*
      * The Obj returned by $statement was 'Array of Arrays'
      */
     $result = $statement->fetchAll();
     //$statement returns an Array of objects
     //print_r($result);
     //echo '</br>';
     $data = $result['0'];
     //print_r($data);
     //echo '</br>role='.$data['role'];
     $count = $statement->rowCount();
     if ($count > 0) {
         //log in the user
         Session::init();
         Session::set('userid', $data['id']);
         Session::set('role', $data['role']);
         Session::set('loggedIn', true);
         header('location: ../dashboard');
     } else {
         //show an error
         header('location: ../login');
     }
 }
 /**
  *	Attempt to regenerate the current security token.
  */
 public function regenerateToken()
 {
     // Restrict this functionality to administrators.
     $user = Member::currentUserID();
     if (Permission::checkMember($user, 'ADMIN')) {
         // Attempt to create a random hash.
         $regeneration = $this->service->generateHash();
         if ($regeneration) {
             // Instantiate the new security token.
             $token = APIwesomeToken::create();
             $token->Hash = $regeneration['hash'];
             $token->AdministratorID = $user;
             $token->write();
             // Temporarily use the session to display the new security token key.
             Session::set('APIwesomeToken', "{$regeneration['key']}:{$regeneration['salt']}");
         } else {
             // Log the failed security token regeneration.
             SS_Log::log('APIwesome security token regeneration failed.', SS_Log::ERR);
             Session::set('APIwesomeToken', -1);
         }
         // Determine where the request came from.
         $from = $this->getRequest()->getVar('from');
         $redirect = $from ? $from : 'admin/json-xml/';
         return $this->redirect($redirect);
     } else {
         return $this->httpError(404);
     }
 }
示例#22
0
 /**
  * Initializes the dropbox connection
  *
  * @param   array   $params  Any connection params needed
  * @return  \League\Flysystem\Dropbox\DropboxAdapter
  **/
 public static function init($params = [])
 {
     // Get the params
     $pparams = Plugin::params('filesystem', 'dropbox');
     if (isset($params['app_token'])) {
         $accessToken = $params['app_token'];
     } else {
         $info = ['key' => isset($params['app_key']) ? $params['app_key'] : $pparams->get('app_key'), 'secret' => isset($params['app_secret']) ? $params['app_secret'] : $pparams->get('app_secret')];
         \Session::set('dropbox.app_key', $info['key']);
         \Session::set('dropbox.app_secret', $info['secret']);
         \Session::set('dropbox.connection_to_set_up', Request::getVar('connection', 0));
         $appInfo = \Dropbox\AppInfo::loadFromJson($info);
         $clientIdentifier = 'hubzero-cms/2.0';
         $redirectUri = trim(Request::root(), '/') . '/developer/callback/dropboxAuthorize';
         $csrfTokenStore = new \Dropbox\ArrayEntryStore($_SESSION, 'dropbox-auth-csrf-token');
         $oauth = new \Dropbox\WebAuth($appInfo, $clientIdentifier, $redirectUri, $csrfTokenStore);
         // Redirect to dropbox
         // We hide the return url in the state field...that's not exactly what
         // it was intended for, but it does the trick
         $return = Request::getVar('return') ? Request::getVar('return') : Request::current(true);
         $return = base64_encode($return);
         App::redirect($oauth->start($return));
     }
     $app_secret = isset($params['app_secret']) ? $params['app_secret'] : $pparams->get('app_secret');
     // Create the client
     $client = new \Dropbox\Client($accessToken, $app_secret);
     // Return the adapter
     return new \League\Flysystem\Dropbox\DropboxAdapter($client, isset($params['subdir']) ? $params['subdir'] : null);
 }
 /**
  * Allow this controller to be viewed when the site is in draft mode.
  */
 function init()
 {
     $draftsecurity = Session::get('unsecuredDraftSite');
     Session::set("unsecuredDraftSite", true);
     parent::init();
     Session::set("unsecuredDraftSite", $draftsecurity);
 }
示例#24
0
 public function run($static = false)
 {
     $form = new Form();
     $form->post('login')->val('blank')->post('password')->val('blank');
     if (!$form->submit()) {
         // Error
         $this->_error($static);
         return false;
     }
     $data = $form->fetch();
     $login = $data['login'];
     $password = Hash::create('sha256', $data['password'], PASS_HASH_KEY);
     $query = "SELECT userid, login, role FROM user WHERE login = :login AND password = :password";
     if (!($result = $this->db->select($query, array(':login' => $login, ':password' => $password)))) {
         $this->_error($static);
         return false;
     }
     Session::init();
     Session::set('userid', $result[0]['userid']);
     Session::set('login', $result[0]['login']);
     Session::set('role', $result[0]['role']);
     Session::set('loggedIn', true);
     if ($static) {
         header('location:' . URL . 'dashboard');
     }
     echo json_encode('success');
 }
示例#25
0
 /**
  * Will return location data given a user's ip address.
  * @param string $ip The ip address to backtrace.
  * @return array
  */
 public static function lookupIp($ip = null)
 {
     // Log whether the ip was null
     $wasNull = false;
     // Let's see if we've done this recently for this session
     if ($ip == null && Session::exists('backtrace_ip')) {
         return Session::get('backtrace_ip');
     }
     // Choose the ip to use
     if ($ip == null) {
         $wasNull = true;
         $ip = Session::getIpAddress();
     }
     // Format the host string for the api
     $host = sprintf(self::IP_BACKTRACE_HOST, $ip);
     // Get the response from the api
     $response = Utils::curl_get_contents($host);
     $data = unserialize($response);
     // Return the info in an array
     $result = array('ip' => $ip, 'city' => $data['geoplugin_city'], 'state' => $data['geoplugin_region'], 'state_full' => $data['geoplugin_regionName'], 'area_code' => $data['geoplugin_areaCode'], 'dma' => $data['geoplugin_dmaCode'], 'country_code' => $data['geoplugin_countryCode'], 'country_name' => $data['geoplugin_countryName'], 'continent_code' => $data['geoplugin_continentCode'], 'latitude' => $data['geoplugin_latitude'], 'longitude' => $data['geoplugin_longitude'], 'currency_code' => $data['geoplugin_currencyCode'], 'currency_symbol' => $data['geoplugin_currencySymbol']);
     // Now let's get the zip code
     $latLongLookup = self::lookupLatLong($result['latitude'], $result['longitude']);
     $result['zip'] = $latLongLookup['zip'];
     // Save this for future reference, if this was the current user's ip
     if ($wasNull) {
         Session::set('backtrace_ip', $result);
     }
     // Now let's return the result
     return $result;
 }
 /**
  * This does not actually perform any validation, but just creates the
  * initial registration object.
  */
 public function validateStep($data, $form)
 {
     $form = $this->getForm();
     $datetime = $form->getController()->getDateTime();
     $confirmation = $datetime->Event()->RegEmailConfirm;
     $registration = $this->getForm()->getSession()->getRegistration();
     // If we require email validation for free registrations, then send
     // out the email and mark the registration. Otherwise immediately
     // mark it as valid.
     if ($confirmation) {
         $email = new Email();
         $config = SiteConfig::current_site_config();
         $registration->TimeID = $datetime->ID;
         $registration->Status = 'Unconfirmed';
         $registration->write();
         if (Member::currentUserID()) {
             $details = array('Name' => Member::currentUser()->getName(), 'Email' => Member::currentUser()->Email);
         } else {
             $details = $form->getSavedStepByClass('EventRegisterTicketsStep');
             $details = $details->loadData();
         }
         $link = Controller::join_links($this->getForm()->getController()->Link(), 'confirm', $registration->ID, '?token=' . $registration->Token);
         $regLink = Controller::join_links($datetime->Event()->Link(), 'registration', $registration->ID, '?token=' . $registration->Token);
         $email->setTo($details['Email']);
         $email->setSubject(sprintf('Confirm Registration For %s (%s)', $datetime->getTitle(), $config->Title));
         $email->setTemplate('EventRegistrationConfirmationEmail');
         $email->populateTemplate(array('Name' => $details['Name'], 'Registration' => $registration, 'RegLink' => $regLink, 'Title' => $datetime->getTitle(), 'SiteConfig' => $config, 'ConfirmLink' => Director::absoluteURL($link)));
         $email->send();
         Session::set("EventRegistration.{$registration->ID}.message", $datetime->Event()->EmailConfirmMessage);
     } else {
         $registration->Status = 'Valid';
         $registration->write();
     }
     return true;
 }
示例#27
0
 function __construct()
 {
     Session::init();
     Session::set('active', "services");
     Session::set('title', "Услуги");
     parent::__construct();
 }
 public function onAfterWrite()
 {
     if ($this->authToken) {
         // store the new token so it can be displayed later
         Session::set('member_auth_token_' . $this->owner->ID, $this->authToken);
     }
 }
示例#29
0
 public function testMemberGroupRelationForm()
 {
     Session::set('loggedInAs', $this->idFromFixture('GroupTest_Member', 'admin'));
     $adminGroup = $this->objFromFixture('Group', 'admingroup');
     $parentGroup = $this->objFromFixture('Group', 'parentgroup');
     $childGroup = $this->objFromFixture('Group', 'childgroup');
     // Test single group relation through checkboxsetfield
     $form = new GroupTest_MemberForm($this, 'Form');
     $member = $this->objFromFixture('GroupTest_Member', 'admin');
     $form->loadDataFrom($member);
     $checkboxSetField = $form->Fields()->fieldByName('Groups');
     $checkboxSetField->setValue(array($adminGroup->ID => $adminGroup->ID, $parentGroup->ID => $parentGroup->ID));
     $form->saveInto($member);
     $updatedGroups = $member->Groups();
     $this->assertEquals(2, count($updatedGroups->column()), "Adding a toplevel group works");
     $this->assertContains($adminGroup->ID, $updatedGroups->column('ID'));
     $this->assertContains($parentGroup->ID, $updatedGroups->column('ID'));
     // Test unsetting relationship
     $form->loadDataFrom($member);
     $checkboxSetField = $form->Fields()->fieldByName('Groups');
     $checkboxSetField->setValue(array($adminGroup->ID => $adminGroup->ID));
     $form->saveInto($member);
     $member->flushCache();
     $updatedGroups = $member->Groups();
     $this->assertEquals(1, count($updatedGroups->column()), "Removing a previously added toplevel group works");
     $this->assertContains($adminGroup->ID, $updatedGroups->column('ID'));
     // Test adding child group
 }
示例#30
0
 public function checkLogin()
 {
     $Member = D('Member');
     $username = trim(dhtml($_POST['username']));
     $password = trim(dhtml($_POST['password']));
     $seccode = trim($_POST['seccode']);
     if ($username == '') {
         $this->error('用户名不能为空!!!');
     } elseif ($password == '') {
         $this->error('密码不能为空!!!');
     } elseif (md5($seccode) != Session::get('verify')) {
         $this->error('验证码错误!!!');
     }
     $map = array();
     $map["username"] = $username;
     $user = $Member->find($map);
     if (false === $user) {
         $this->error('用户名不存在!!!');
     } else {
         if ($user['password'] != md5($password)) {
             $this->error('密码错误!!!');
         }
         if ($user['ischecked'] != 1) {
             $this->error('用户被锁定');
         }
         if ($user['groupid'] == 2) {
             $this->error('用户组被限制登录系统,请联系管理员');
         }
         Session::set(C('USER_AUTH_KEY'), $user['id']);
         Session::set('username', $user['username']);
         Session::set('groupid', $user['groupid']);
         $this->redirect('index', 'Index');
     }
 }