public function loginAction()
 {
     if (Service::get('security')->isAuthenticated()) {
         $redirect = new ResponseRedirect($this->generateRoute('home'));
         $redirect->send();
     }
     $errors = array();
     if ($this->getRequest()->isPost()) {
         if ($user = User::findByEmail($this->getRequest()->post('email'))) {
             if ($user->password == md5($this->getRequest()->post('password'))) {
                 Service::get('security')->setUser($user);
                 $returnUrl = Service::get('session')->getReturnUrlAndRemove();
                 if ($user->role == 'ROLE_USER') {
                     $about_access = 'view and create posts';
                 } elseif ($user->role == 'ROLE_ADMIN') {
                     $about_access = 'view, create, delete posts';
                 } else {
                     $about_access = 'view posts';
                 }
                 return $this->redirect(!empty($returnUrl) ? $returnUrl : $this->generateRoute('home'), 'info', 'Hello ' . $user->name . '. Now you can ' . $about_access . '.');
             }
         }
         array_push($errors, 'Invalid username or password');
     }
     return $this->render('login.html', array('errors' => $errors));
 }
Beispiel #2
0
 public function uploadImage($image, $alt)
 {
     try {
         $file = new File($image, 10000);
         $uploadDir = ASSETS . 'uploads/portfolio/gallery/';
         $tmp = ASSETS . 'uploads/portfolio/tmp/';
         $file->setUploadDir($tmp);
         $fileSaver = new FileSaver($file);
         if (!$file->isNormalSize()) {
             throw new \Exception('Very big file size');
         }
         if (!$fileSaver->save()) {
             throw new \Exception('File not selected');
         }
         if (!ImageHelper::isImage($fileSaver->uploadedFile, ['gif', 'png', 'jpg', 'jpeg'])) {
             throw new \Exception('File is not image');
         }
         if (file_exists($uploadDir . $file->getName())) {
             $uniqName = FileHelper::getUniqFileName($uploadDir, FileHelper::getFileExtension($file->getName()));
             $file->setName($uniqName);
         }
         FileHelper::move($fileSaver->uploadedFile, $uploadDir . $file->getName());
         $db = Service::get('db');
         $query = 'INSERT INTO ' . self::getTable() . '(name, alt) VALUES (:name, :alt)';
         $stmt = $db->prepare($query);
         if (!$stmt->execute([':name' => $file->getName(), ':alt' => $alt])) {
             throw new \Exception('File not saved into DB');
         }
         Service::get('session')->setFlushMsg('success', 'File successfully downloaded');
     } catch (\Exception $e) {
         Service::get('session')->setFlushMsg('error', $e->getMessage());
         $response = new ResponseRedirect(Request::getHost() . '/admin');
         $response->send();
     }
 }
 /**
  * @throws ServiceException
  *
  * solve exception depending from enter message (number or string)
  * if message is numeric get code from Response class and redirect to 500 html page
  * if string redirect to $redirectAddress
  */
 public function solveException()
 {
     $data = array();
     if ($this->getMessage() && is_numeric($this->getMessage())) {
         $data['code'] = $this->getMessage();
         $data['message'] = Response::getMessageByCode($this->getMessage());
         if ($this->beforeSolve) {
             $this->beforeSolveException();
         }
         $renderer = new Renderer();
         $responce = new Response($renderer::render(Service::get('config')->get500Layout(), $data), 'text/html', 202);
         $responce->send();
     } else {
         if ($this->getMessage()) {
             Service::get('session')->addFlush($this->type, $this->getMessage());
             if ($this->beforeSolve) {
                 $this->beforeSolveException();
             }
             echo $this->redirectAddress;
             $redirect = new ResponseRedirect($this->redirectAddress);
             $redirect->sendHeaders();
         } else {
             throw new ServiceException(500);
         }
     }
 }
Beispiel #4
0
 /**
  * Redirect to $url with flash msg(type and msg).
  *
  * @param $url
  * @param null $type
  * @param null $msg
  * @return ResponseRedirect
  */
 public function redirect($url, $type = null, $msg = null)
 {
     $flushmsg = Service::get('session');
     $flushmsg->setFlush($type, $msg);
     $redirect = new ResponseRedirect($url);
     $redirect->send();
 }
Beispiel #5
0
 public function __construct($msg, $url, $code = 301)
 {
     $session = Service::get('session');
     $session->setReturnUrl(Service::get('request')->getUri());
     $session->addFlushMessage('info', $msg);
     $resp = new ResponseRedirect($url, $code);
     $resp->send();
 }
 public function run()
 {
     ServiceContainer::get('security')->generateToken();
     try {
         if (!ServiceContainer::get('security')->checkToken()) {
             die('Invalid token');
         }
         $map = $this->config['routes'];
         ServiceContainer::set('route', new Router($map));
         $match_route = ServiceContainer::get('route');
         $route = $match_route->findRoute();
         if (!empty($route['security'])) {
             $user = ServiceContainer::get('session')->get('authenticated');
             if (!empty($user->user_role) != 'ROLE_USER') {
                 $msg = 'Access denied, please login to your account!';
                 $fsg = ServiceContainer::get('session');
                 $fsg->setFlush('error', $msg);
                 $redirect = new ResponseRedirect(ServiceContainer::get('route')->buildRoute('security_signin'));
                 $redirect->send();
             }
         }
         if (class_exists($route['controller'])) {
             $controller = $route['controller'];
             $action = $route['action'];
             $vars = NULL;
             if (!empty($route['vars'])) {
                 $vars = $route['vars'];
             }
             $response = $this->startController($controller, $action, $vars);
         } else {
             throw new HttpNotFoundException();
         }
     } catch (HttpNotFoundException $e) {
         $error_layout = $this->config['not_found'];
         $renderer = new Renderer($error_layout, array('message' => $e->getMessage(), 'code' => $e->getCode()));
         $response = new Response($renderer->render());
     }
     $flush = ServiceContainer::get('session')->get('flush') ? ServiceContainer::get('session')->get('flush') : array();
     ServiceContainer::get('session')->unsetSession('flush');
     if ($response instanceof Response) {
         if ($response->getType() == 'html') {
             $view = $this->config['main_layout'];
             $renderer = new Renderer($view, array('content' => $response->getContent(), 'flush' => $flush));
             $wrapped = $renderer->render();
             $response = new Response($wrapped);
             $response->send();
         } elseif ($response->getType() == 'json') {
             $response = new ResponseJson();
             $response->send();
         }
     }
 }
Beispiel #7
0
 /**
  * Method initiates the application's work
  *
  * @throws AccessException
  */
 public function run()
 {
     Service::get('security')->generateToken();
     try {
         if (!Service::get('security')->checkToken()) {
             throw new AccessException('tokens aren\'t the same');
         }
         //gets necessary information from Router
         $route = Service::get('router')->start();
         // if there are restrictions of rights, will check user's rights
         if (!empty($route['security'])) {
             $user = Service::get('session')->get('user');
             if (is_object($user)) {
                 if (array_search($user->getRole(), $route['security']) === false) {
                     throw new AccessException('access denied');
                 }
             } else {
                 Service::get('session')->setReturnUrl(Service::get('router')->buildRoute($route['_name']));
                 $redirect = new ResponseRedirect(Service::get('router')->buildRoute($this->config['security']['login_route']));
                 $redirect->send();
             }
         }
         $this->savePathToView($route['controller']);
         Service::get('session')->setReturnUrl(Service::get('request')->getRequestInfo('uri'));
         $vars = null;
         if (!empty($route['vars'])) {
             $vars = $route['vars'];
         }
         $response = $this->startController($route['controller'], $route['action'], $vars);
     } catch (AccessException $e) {
         echo $e->getMessage();
         die;
     } catch (HttpNotFoundException $e) {
         $redirect = new ResponseRedirect(Service::get('router')->buildRoute('/'));
         $redirect->send();
     } catch (ServerErrorException $e) {
         $renderer = new Renderer($e->layout, array('message' => $e->message, 'code' => $e->code));
         $response = new Response($renderer->render());
         $response->send();
         die;
     }
     if ($response->getType() == 'html') {
         $flush = Service::get('session')->get('flush') ? Service::get('session')->get('flush') : array();
         Service::get('session')->delFromSess('flush');
         $content['content'] = $response->getContent();
         $content['flush'] = $flush;
         $renderer = new Renderer($this->config['main_layout'], $content);
         $response = new Response($renderer->render());
     }
     $response->send();
 }
 /**
  * @throws BadResponseTypeException
  * @throws Exception\RendererException
  */
 public function run()
 {
     $router = Service::get('router');
     $route = $router->parseRoute();
     $renderer = Service::get('renderer');
     $renderer->assign(array('user' => Service::get('security')->getUser(), 'flush' => Service::get('session')->getFlush()));
     require_once '../src/Blog/Controller/PostController.php';
     try {
         $response = $this->processRoute();
         if (empty($route)) {
             throw new HttpNotFoundException('Route not found');
         }
         if (isset($route['security'])) {
             if (!Service::get('security')->isAuthenticated()) {
                 throw new AuthRequiredException('Please. login first!');
             } elseif (!Service::get('security')->isGranted($route['security'])) {
                 throw new AccessDeniedException('Access denied!');
             }
         }
         $controllerReflection = new \ReflectionClass($route['controller']);
         $action = $route['action'] . 'Action';
         if ($controllerReflection->hasMethod($action)) {
             $controller = $controllerReflection->newInstance();
             //					var_dump($controller); die;
             $actionReflection = $controllerReflection->getMethod($action);
             $response = $actionReflection->invokeArgs($controller, $route['params']);
         }
     } catch (HttpNotFoundException $e) {
         echo $e->getMessage();
     } catch (AuthRequiredException $e) {
         $url = Service::get('router')->buildRoute(Service::get('security')->getLoginRoute());
         $response = new ResponseRedirect($url, null, 'Please, login first!');
         //            var_dump(Service::get('request')->getUri()); die;
         $response->setReturnUrl(Service::get('request')->getUri());
     } catch (AccessDeniedException $e) {
         echo $e->getMessage();
     } catch (\Exception $e) {
         $renderer = new Renderer(Service::get('config')->error_500);
         $renderer->assign(array('message' => $e->getMessage(), 'code' => $e->getCode()));
         $response = new Response($renderer->render(), $e->getCode(), 'Internal Server Error');
         echo $e->getMessage();
     }
     $response->send();
 }
 public function signinAction()
 {
     if (Service::get('security')->isAuthenticated()) {
         $redirect = new ResponseRedirect($this->generateRoute('home'));
         $redirect->send();
     }
     $errors = array();
     if ($this->getRequest()->isPost()) {
         try {
             $user = new User();
             $user->email = $this->getRequest()->post('email');
             $user->password = md5($this->getRequest()->post('password'));
             $user->role = 'ROLE_USER';
             $user->save();
             return $this->redirect($this->generateRoute('home'));
         } catch (DatabaseException $e) {
             $errors = array($e->getMessage());
         }
     }
     return $this->render('signin.html', array('errors' => $errors));
 }
 /**
  * Sign up new User
  *
  * @return \Framework\Response\Response
  */
 public function signupAction()
 {
     if (ServiceContainer::get('security')->isAuthenticated()) {
         $redirect = new ResponseRedirect($this->generateRoute('performance_home'));
         $redirect->send();
     }
     $errors = array();
     if ($this->getRequest()->isPost() == 'POST') {
         try {
             $user = new User();
             $user->name = $this->getRequest()->post('name');
             $user->email = $this->getRequest()->post('email');
             $user->password = md5($this->getRequest()->post('password'));
             $user->user_role = 'ROLE_USER';
             $user->save();
             return $this->redirect($this->generateRoute('security_signin'));
         } catch (\Exception $e) {
             $errors = array($e->getMessage());
         }
     }
     return $this->render('signup.html', array('errors' => $errors));
 }
Beispiel #11
0
 /**
  * Check Security
  *
  * @param $route
  * @throws \Exception
  *
  * @return void
  */
 private function _checkSecurity($route)
 {
     Service::get('security')->generateToken();
     if ((new Request())->isPost() && !Service::get('security')->checkToken()) {
         Service::get('session')->setFlash('error', self::TOKEN_NOT_EXIST);
         $redirect = new ResponseRedirect((new Request())->getURI());
         $redirect->send();
     }
     if (!empty($route['security'])) {
         $user = Service::get('session')->get('authenticated');
         if (is_object($user)) {
             $user_info = get_object_vars($user);
         }
         $user_info['role'] = isset($user_info['role']) ? $user_info['role'] : null;
         if (!in_array($user_info['role'], $route['security'])) {
             Service::get('session')->setFlash('error', self::ACCESS_DENIED);
             Service::get('session')->setReturnUrl();
             $redirect = new ResponseRedirect(Service::get('router')->generateRoute($this->_config['security']['login_route']));
             $redirect->send();
         }
     }
 }
 /**
  * Create Router class and call function that
  * process URL address
  *
  * Check using reflection presence of necessary class
  * of controller and his methods
  *
  * Create Response class
  */
 public function run()
 {
     $response = null;
     $router = new Router(include '../app/config/routes.php');
     $route = $router->parseUrl(trim(strip_tags($_SERVER['REQUEST_URI'])));
     try {
         if (!empty($route)) {
             $controllerReflection = new \ReflectionClass($route['controller']);
             $action = $route['action'] . 'Action';
             if ($controllerReflection->hasMethod($action)) {
                 // Control user role
                 if ($action != 'indexAction' && $action != 'loginAction' && $action != 'signinAction') {
                     if ($_SESSION['role'] != 'ROLE_USER') {
                         throw new AuthRequredException('You must login');
                     }
                 }
                 $controller = $controllerReflection->newInstance();
                 if ($controller instanceof Controller) {
                     $actionReflection = $controllerReflection->getMethod($action);
                     ActiveRecord::getDBCon();
                     $response = $actionReflection->invokeArgs($controller, $route['params']);
                     if ($response instanceof Response) {
                         $response->send();
                         // Close database connection
                         call_user_func(Service::get('event')->trigger('db_close'));
                     } else {
                         throw new BadResponseTypeException('Missing type of response');
                     }
                 } else {
                     throw new BadControllerTypeException('Missing type of controller');
                 }
             }
         } else {
             throw new HttpNotFoundException('Route not found');
         }
     } catch (HttpNotFoundException $e) {
         // Render 404 or just show msg
         $error = $e->getMessage();
         include Service::get('config')->get('error_404');
     } catch (AuthRequredException $e) {
         // Reroute to login page
         Service::get('session')->addFlush('error', $e->getMessage());
         $response = new ResponseRedirect("/login");
         $response->sendHeaders();
     } catch (InvalidArgumentException $e) {
         echo $e->getMessage();
     } catch (BadResponseTypeException $e) {
         echo $e->getMessage();
     } catch (BadPathTypeException $e) {
         echo $e->getMessage();
     } catch (\PDOException $e) {
         echo $e->getMessage();
     } catch (DatabaseException $e) {
         echo $e->getMessage();
     } catch (InvalidTypeException $e) {
         echo $e->getMessage();
     } catch (BadControllerTypeException $e) {
         echo $e->getMessage();
     } catch (\Exception $e) {
         // Do 500 layout...
         include Service::get('config')->get('error_500');
     }
 }
Beispiel #13
0
 public function run()
 {
     //print_r($_SERVER);
     $logger = Service::get('logger');
     $router = Service::get('router');
     $route = $router->attemptToFindRoute();
     //Service::get('logger')->log(Password::hash('mirana1111'));
     //print_r($route);
     //Service::get('security')->clear();
     //$size = ImageHelper::getImageSize('C:\xampp\htdocs\portfolio\web\uploads\portfolio\gallery\2.jpg');
     //Service::get('logger')->log($size[1]);
     try {
         if (empty($route)) {
             throw new HttpNotFoundException();
         } else {
             if (isset($route['security'])) {
                 $user = Service::get('security')->getUser();
                 if (isset($route['security']['login_route'])) {
                     Service::get('security')->loginRoute = $route['security']['login_route'];
                 }
                 if (is_null($user)) {
                     $host = Request::getHost();
                     $redirect = new ResponseRedirect($host . Service::get('security')->loginRoute);
                     $redirect->send();
                 }
                 $role = $route['security']['role'];
                 if ($role !== $user->role) {
                     Service::get('session')->setFlushMsg('warning', '�� ���������� ����');
                     $host = Request::getHost();
                     $redirect = new ResponseRedirect($host);
                     $redirect->send();
                 }
                 /*
                                    $c = 0;
                                    for ( ; ; )
                                    {
                                        if ($c > count($routeSecurity) - 1)
                                        {
                                            break;
                                        }
                 
                                        switch($routeSecurity[$c])
                                        {
                                            case 'ROLE_USER':
                                                $user = $security->getUser();
                                                if(is_null($user))
                                                {
                                                    $host = Request::getHost();
                                                    $redirect = new ResponseRedirect($host.$security->loginRoute);
                                                    $redirect->send();
                                                    break;
                                                }
                                                else
                                                {
                 
                                                    break;
                                                }
                                            //continue security
                                        }
                                        ++$c;
                                    }
                 */
             }
             $controllerClass = $route['controller'];
             if (!class_exists($controllerClass)) {
                 $logger->log('Maybe it`s problem with incorrect routes', 'FATAL');
                 throw new ServerException('CrAsHeD!!!! SERVER ERROR', 500);
             }
             $controller = new $controllerClass();
             $action = $route['action'] . 'Action';
             if (!method_exists($controller, $action)) {
                 $logger->log('Maybe it`s problem with incorrect routes', 'FATAL');
                 throw new ServerException('CrAsHeD!!!! SERVER ERROR', 500);
             }
             $reflMethod = new \ReflectionMethod($controllerClass, $action);
             $response = $reflMethod->invokeArgs($controller, isset($route['variables']) ? $route['variables'] : []);
             $response->send();
         }
     } catch (HttpNotFoundException $e) {
         $e->show404page();
     } catch (ServerException $e) {
         $e->crashed();
     } catch (DatabaseException $e) {
         die('Database error: ' . $e->getMessage());
     } catch (\Exception $e) {
     }
     // print_r(Post::find('all'));
     //$request = Service::get('request');
     //echo $request->getFullUrl();
     /*
     $htmlPurifierBuilder = new HtmlPurifierBuilder();
     $purifier = $htmlPurifierBuilder->execute();
     $purifier->delInvalidTags(true);
     echo $purifier->purify('<script> awdasfasfafa</script>');
     */
     //$logger = Service::get('logger');
     //$logger->log('suck');
     //print_r($route);
     // $test = new TestController();
     // echo $test->generateRoute('add_post');
     // $response = $test->render('ok.html');
     // $response->send();
 }
Beispiel #14
0
 public function run()
 {
     Service::get('security')->generateToken();
     if (!Service::get('security')->checkToken()) {
         die('Token not exist');
     }
     $map = $this->config['routes'];
     Service::set('route', new Router($map));
     $match_route = Service::get('route');
     $route = $match_route->findRoute();
     if (!empty($route['security'])) {
         $user = Service::get('session')->get('authenticated');
         if (is_object($user)) {
             $user_role = get_object_vars($user);
         }
         if (!empty($user_role['role'] !== 'ROLE_ADMIN')) {
             $msg = 'Access Denied! Only the administrator can create new posts.';
             $fsg = Service::get('session');
             $fsg->setFlush('error', $msg);
             $redirect = new ResponseRedirect(Service::get('route')->buildRoute($this->config['security']['login_route']));
             $redirect->send();
         }
     }
     try {
         if (class_exists($route['controller'])) {
             $controller = new $route['controller']();
             $action = $route['action'] . 'Action';
             if (isset($route['vars'])) {
                 $vars = $route['vars'];
             }
             $controller_reflection = new \ReflectionClass($route['controller']);
             if ($controller_reflection->hasMethod($action)) {
                 $method = new \ReflectionMethod($controller, $action);
                 $params = $method->getParameters();
                 if (empty($params)) {
                     $response = $method->invoke(new $controller());
                 } else {
                     $response = $method->invokeArgs(new $controller(), $vars);
                 }
             }
         } else {
             throw new HttpNotFoundException('Oops, Not Found', 404);
         }
     } catch (HttpNotFoundException $e) {
         $error_layout = $this->config['error_500'];
         $renderer = new Renderer($error_layout, array('message' => $e->getMessage(), 'code' => $e->getCode()));
         $response = new Response($renderer->render());
     }
     $flush = Service::get('session')->get('flush') ? Service::get('session')->get('flush') : array();
     Service::get('session')->unsetSession('flush');
     Service::get('session')->setReturnUrl(Service::get('request')->getRequestInfo('uri'));
     try {
         if ($response instanceof Response) {
             if ($response->type == 'html') {
                 $view = $this->config['main_layout'];
                 $renderer = new Renderer($view, array('content' => $response->getContent(), 'flush' => $flush));
                 $wrapped = $renderer->render();
                 $response = new Response($wrapped);
             }
             $response->send();
         } else {
             throw new BadResponseException('Bad response', 500);
         }
     } catch (BadResponseException $e) {
         echo $e->getMessage();
     }
 }