Esempio n. 1
0
 public static function checkUser()
 {
     // Предотвращение перехвата сеанса
     $sessUserId = Session::get('user_id');
     if (!isset($sessUserId)) {
         Session::destroy();
         //             unset($this->user);
         Session::setMsg('Произошла ошибка. Пожалуйста авторизуйтесь заново', 'warning');
         return FALSE;
     }
     // Предотвращение фиксации сеанса (включая ini_set('session.use_only_cookies', true);)
     $sessGenerated = Session::get('generated');
     if (!isset($sessGenerated) || $sessGenerated < time() - 30) {
         session_regenerate_id();
         $_SESSION['generated'] = time();
     }
     if ($sessUserId) {
         $userModel = new UserTableModel();
         $userModel->setId($sessUserId);
         $userModel->setTable('user');
         $username = $userModel->readRecordsById('id', 'username')[0]['username'];
         Session::set('username', $username);
         return TRUE;
     }
     return FALSE;
 }
Esempio n. 2
0
 /**
  * Add a message to a message bag
  *
  * @param $type
  * @param $message
  */
 private function add($type, $message)
 {
     // get existing message bag or create a new one
     $messages = $this->get($type);
     // merge our new messages into the message bag
     $messages->merge((array) $message);
     // put the message bag back into the session
     \Session::put($this->_key($type), $messages);
 }
Esempio n. 3
0
 public function __construct($title = '', $subTitle = '')
 {
     $this->title = $title;
     $userModel = new UserTableModel();
     $userModel->setId(Session::get('user_id'));
     $userModel->setTable('user');
     $userModel->readRecordsById('id', '`id`,`username`, `full_name`, `photo`, `email`');
     $userModel->readUserAddress();
     $userModel->readUserPhones();
     $this->setData(['title' => $title, 'subTitle' => $subTitle, 'user' => $userModel->getRecordsById()[0], 'userContacts' => $userModel->getUserContacts()]);
 }
 protected function setUserIdForDB($id = NULL)
 {
     if (!$id) {
         $id = Session::get('user_id');
     }
     try {
         $st = $this->db->prepare("SET @user_id=?");
         $st->execute([$id]);
     } catch (Exception $ex) {
         $ex->getMessage();
     }
 }
Esempio n. 5
0
 /**
  * Create a new user instance after a valid registration.
  *
  * @param  array  $data
  * @return User
  */
 public function create(array $data)
 {
     $user = User::create(['name' => $data['name'], 'email' => $data['email'], 'birthday' => $data['birthday'], 'password' => bcrypt($data['password'])]);
     $parentEmail = $data['parentEmail'];
     $parentUser = User::where('email', $parentEmail)->first();
     if ($parentUser != null) {
         $user->parent()->associate($parentUser);
         $user->save();
     } else {
         \Session::flash('flash_message', 'No account exists using that email.');
     }
     return $user;
 }
 /**
  * Create a new user instance after a valid registration.
  *
  * @param  array  $data
  * @return User
  */
 public function create(array $data)
 {
     $user = new User();
     $activation_code = str_random(60) . $data['email'];
     $user->name = $data['name'];
     $user->email = $data['email'];
     $user->password = bcrypt($data['password']);
     $user->how_know = $data['how_know'];
     $user->activation_code = $activation_code;
     if ($user->save()) {
         \Session::flash('success_message', "Activation link is send to {$data['email']}. Please activite your account");
         return view('auth.register');
     }
 }
 public function indexAction()
 {
     $fc = FrontController::getInstance();
     $model = new FrontModel();
     if ($_SERVER['REQUEST_METHOD'] === 'POST') {
         Mailer::setData($_POST);
         if (Mailer::emailHandler()) {
             Session::setUserMsg('Ваше сообщение успешно отправлено. Мы свяжемся с вами в ближайшее время', 'success');
             header('Location: ' . $_SERVER['REQUEST_URI']);
             exit;
         }
     } else {
         $output = $model->render('../views/contacts/contacts.php', 'withoutSliderAndSidebar');
         $fc->setPage($output);
     }
 }
Esempio n. 8
0
 public static function emailHandler($to = FALSE)
 {
     try {
         if (!$to) {
             $to = Helper::getSiteConfig()->contactinfo->siteMail->value;
         }
         if (empty(self::$data)) {
             throw new Exception('Класс не инициализирован должным образом');
         }
         self::emailSender((string) $to, self::$data['subject'], self::$data['message'], self::$data['email']);
         return TRUE;
     } catch (Exception $ex) {
         Session::setUserMsg('Пожалуйста, заполните все поля формы', 'danger');
         header('Location: ' . $_SERVER['REQUEST_URI']);
     }
 }
 public function updateRecord()
 {
     if (!$this->id) {
         throw new Exception('Не задан id пользователя для обновления');
     }
     try {
         $this->setUserIdForDB();
         $st = $this->db->prepare("UPDATE user SET full_name = ? WHERE id = ?");
         $st->execute([$this->fullName, $this->id]);
         $this->addresses->updateRecord();
         $this->phones->updateRecord();
         Role::updateRoleByUserId($this->db, $this->roleId, $this->id);
         Session::setMsg('Пользователь успешно обновлен', 'success');
     } catch (Exception $ex) {
         $ex->getMessage();
     }
 }
Esempio n. 10
0
 public function checkoutAction()
 {
     $fc = FrontController::getInstance();
     $model = new FrontModel();
     if ($_SERVER['REQUEST_METHOD'] === 'POST') {
         $orderModel = new OrderTableModel();
         $orderModel->setData();
         $orderModel->addRecord();
         Basket::deleteBasket();
         \app\services\Session::setMsg('Ваш заказ принят. Наш менеджер свяжется с вами в ближайшее время', 'success');
         header('Location: /');
         exit;
     } else {
         $output = $model->render('../views/order/order.php', 'withoutSliderAndSidebar');
         $fc->setPage($output);
     }
 }
Esempio n. 11
0
 protected function checkRolesForAction($action)
 {
     $reqRoles = $this->requiredRoles();
     $alterRegRoles = [];
     if ($reqRoles) {
         foreach ($reqRoles as $key => $value) {
             $alterRegRoles[strtolower($key . 'Action')] = $value;
         }
         if (array_key_exists($action = strtolower($action), $alterRegRoles)) {
             $roles = $alterRegRoles[$action];
             if (Session::get('user_id')) {
                 $user = PrivilegedUser::getUserRoleById(DB::init()->connect(), Session::get('user_id'));
             } else {
                 $user = ['role_id' => 5, 'role_name' => 'Guest'];
             }
             return in_array($user['role_id'], $roles);
         }
     }
     return TRUE;
 }
Esempio n. 12
0
 static function getRedirect()
 {
     $redirect['url'] = Session::get('redirect');
     $redirect['hash'] = Session::get('redirectHash');
     Session::unseted(['redirect', 'redirectHash']);
     return $redirect;
 }
 /**
  * @param int $imageId
  * @return bool
  */
 public function hasImageIdInSession($imageId)
 {
     $sessionIds = \Session::get(self::IMAGE_ID_SESSION_KEY, []);
     return in_array(intval($imageId), $sessionIds);
 }
Esempio n. 14
0
 public function getCookie()
 {
     $this->regenerateCookie = true;
     \Session::put('user_cookie', md5(uniqid(rand(), true)));
     return \Session::get('user_cookie');
 }
Esempio n. 15
0
 public static function topMenu($menu, $user)
 {
     $output = '';
     if (empty($menu) || !is_array($menu)) {
         return FALSE;
     }
     foreach ($menu as $v) {
         if ($user) {
             if (strstr($v->link, strtolower('login'))) {
                 $output .= ' <li><a href = "/user/profile/id/' . Session::get('user_id') . '"><i class = "' . $v->icon . '"></i>' . $user . '</a></li>' . "\n";
             } else {
                 $output .= ' <li><a href = "' . $v->link . '"><i class = "' . $v->icon . '"></i>' . $v->value . '</a></li>' . "\n";
             }
         } else {
             if (!strstr($v->link, strtolower('logout'))) {
                 $output .= ' <li><a href = "' . $v->link . '"><i class = "' . $v->icon . '"></i>' . $v->value . '</a></li>' . "\n";
             }
         }
     }
     return $output;
 }
 /**
  * @return bool
  */
 public function resignation()
 {
     $user = $this->getUser();
     if (empty($user)) {
         return false;
     }
     $guard = $this->getGuard();
     $guard->logout();
     \Session::flush();
     $this->authenticatableRepository->delete($user);
     return true;
 }
Esempio n. 17
0
 public static function setUserMsg($body, $type = 'info')
 {
     Session::set('userMsg', ['type' => $type, 'body' => $body]);
 }
Esempio n. 18
0
         default : $t = '';
             break;
     }
     ?>
     <div class="box" id="msg">
         <div class="alert alert-<?php 
echo $msg['type'];
?>
">
             <button type="button" class="close" data-dismiss="alert" aria-hidden="true">x</button>
             <h4><?php 
echo $t;
?>
</h4>
     <?php 
echo $msg['body'];
?>
         </div>
     </div>
     <? Session::delete('msg'); ?>
 <? endif; ?>
<script type="text/javascript">
    var msg = $('#msg');
    $('.close').click('on', function () {
        msg.fadeOut();
    });
//    $(function () {
//        msg.hide();
//        msg.slideDown();
//    });
</script>
Esempio n. 19
0
<?php

use app\controllers\FrontController;
use app\helpers\Basket;
use app\services\Session;
/* Пути по-умолчанию для поиска файлов */
set_include_path(get_include_path() . PATH_SEPARATOR . 'app/controllers' . PATH_SEPARATOR . 'app/models' . PATH_SEPARATOR . 'app/services' . PATH_SEPARATOR . 'app/helpers' . PATH_SEPARATOR . 'app/tests' . PATH_SEPARATOR . 'app/widgets' . PATH_SEPARATOR . 'app/dataContainers');
/* Автозагрузчик классов */
spl_autoload_register(function ($class) {
    require_once $class . '.class.php';
});
//классы composer
require_once '/app/extensions/vendor/autoload.php';
Session::init();
Basket::init();
/* Инициализация и запуск FrontController */
$controller = FrontController::getInstance();
$controller->route();
/* Вывод данных */
echo $controller->getPage();
Esempio n. 20
0
 protected function get_user_id()
 {
     //        @session_start();
     return Session::get('user_id');
 }
Esempio n. 21
0
 public function validateAction()
 {
     $fc = FrontController::getInstance();
     $model = new UserTableModel();
     $model->setTable('user');
     if (empty($fc->getParams()['email']) && empty($fc->getParams()['key'])) {
         header('Location: /');
         exit;
     }
     $model->setValidateUserData($fc->getParams());
     if ($model->checkValidKey()) {
         $output = $model->render('../views/user/validate.php', 'withoutSliderAndSidebarAndFooter');
         $fc->setPage($output);
     } else {
         Session::setMsg('Невозможно активировать данный аккаунт. Пожалуйста зарегистрируйтесь заново', 'warning');
         header('Location: /user/login');
         exit;
     }
 }
Esempio n. 22
0
 private function clearAvatarAction()
 {
     $dir = Path::USERIMG_UPLOAD_DIR . Session::get('user_id');
     Helper::clearDir($dir);
 }
Esempio n. 23
0
echo $author['username'];
?>
</p>
                <input type="hidden" name="id" value="<?php 
echo $article['id'];
?>
"/>
                <input type="hidden" name="author" value="<?php 
echo $author['id'];
?>
"/>
                <div class="form-group">
                    <input type="submit" class="btn btn-primary pull-right" value="Обновить"/>
                </div>
            </div>
        </form>
    </div>
</section>
<script type="text/javascript" src="/app/template/backend/js/blog/articles.js"></script>
<script src="https://cdn.ckeditor.com/4.4.3/standard/ckeditor.js"></script>
<script>
    CKEDITOR.replace('ckeditorAddAtricle', {
        height: 350,
        filebrowserBrowseUrl: '/app/extensions/filemanager/dialog.php?akey=<?php 
echo Session::get('generated');
?>
&type=2&editor=ckeditor',
//        filebrowserUploadUrl: '/app/extensions/filemanager/dialog.php?akey=<? //= Session::get('generated')  ?>&type=2&editor=ckeditor',
//        filebrowserImageBrowseUrl: '/app/extensions/filemanager/dialog.php?akey=<? //= Session::get('generated')  ?>&type=2&editor=ckeditor'
    });
</script>
Esempio n. 24
0
 private function redirToAuth()
 {
     Session::set('referer', $_SERVER['REQUEST_URI']);
     if (!Session::get('user_id')) {
         if ($this->getController() === 'AdminController') {
             header('Location: /admin/login');
             exit;
         } else {
             header('Location: /user/login');
             exit;
         }
     } else {
         $model = new Model();
         $output = $model->render('../views/status/403.php', 'status');
         $this->setPage($output);
     }
 }
<form action="/order/checkout" class="order_form" method="post" id="courier_delivery">
    <input type="hidden" class="user_id" name="user_id" value="<?php 
echo \app\services\Session::get('user_id');
?>
"/>
    <input type="hidden" class="delivery_type" name="delivery_type" value="1"/>
    <div class="row area checkout_area courier_delivery_box" style="display: none;">
        <div class="col-sm-6">
            <div class="chose_area" style="padding: 30px 20px;">
                <h4 class="title text-center">Выберите предпочитаемый адрес доставки из списка:</h4>
                <div class="form-group box_address">
                    <label class="control-label" for="user_address">Адрес</label>
                    <div class="input-group">
                        <select name="user_address" class="user_address">
                        </select>
                        <span class="input-group-btn">
                            <button class="btn btn-default address_cancel" style="height: 28px;" type="button"><i class="glyphicon glyphicon-remove"></i></button>
                        </span>
                    </div>
                </div>
                <div class="new_user_address">
                    <h2 class="or center-block" style="margin-top: 0">ИЛИ</h2>
                    <h4 class="title text-center">Укажите адрес доставки:</h4>
                    <div class="form-group">
                        <label class="control-label" for="city">Населенный пункт (город, поселок)</label>
                        <input type="text" name="city" id="city" class="form-control"/>
                    </div>
                    <div class="form-group">
                        <label class="control-label" for="street">Улица</label>
                        <input type="text" name="street" id="street" class="form-control"/>
                    </div>
 public function set($key, $value)
 {
     \Session::put($this->sessionPrefix . $key, $value);
 }
Esempio n. 27
0
 private function checkCreds()
 {
     try {
         $st = $this->db->prepare("SELECT `id`, `username`, `email`, `password_hash`, `validated` FROM {$this->table} WHERE `username` = :username");
         $st->execute([':username' => $this->login]);
         if ($st->rowCount() === 1) {
             $user = $st->fetch(PDO::FETCH_ASSOC);
             if (!$user['validated']) {
                 Session::setMsg('Для входа необходимо активировать ваш аккаунт при помощи письма, отправленного на ваш электронный ящик ранее', 'warning');
                 return FALSE;
             }
             if (User::confirmPassword($user['password_hash'], $this->password)) {
                 return $user;
             }
         }
         Session::setMsg('Неверный логин или пароль', 'danger');
         return FALSE;
     } catch (Exception $ex) {
         $ex->getMessage();
     }
 }
Esempio n. 28
0
 public function addArticleAction()
 {
     $fc = FrontController::getInstance();
     $model = new AdminModel('Блог', 'Новая статья');
     $articleModel = new ArticleTableModel();
     if ($_SERVER['REQUEST_METHOD'] === 'POST') {
         $articleModel->setData();
         $articleModel->addRecord();
         Session::setMsg('Статья успешно добавлена', 'success');
         header('Location: /admin/blog');
         exit;
     } else {
         $output = $model->render('../views/admin/blog/addarticle.php', 'admin');
         $fc->setPage($output);
     }
 }