예제 #1
0
 public function getCookie(Slim\Slim &$app)
 {
     if (empty($app->getCookie('username'))) {
         //setting cokkie if the user doesn't have it
         $generateToken = new Token();
         $cookieKey = md5($generateToken->generatePassword(8));
         $app->setCookie('username', $cookieKey, time() + 86400 * 4);
     }
     $cookie = $app->getCookie('username');
     return $cookie;
 }
예제 #2
0
 /**
  * Test get cookie when cookie does not exist
  */
 public function testGetCookieThatDoesNotExist()
 {
     \Slim\Environment::mock(array('SCRIPT_NAME' => '/foo', 'PATH_INFO' => '/bar'));
     $s = new \Slim\Slim();
     $this->assertNull($s->getCookie('foo'));
 }
예제 #3
0
    // Login
    $event = json_decode($app->request()->getBody());
    $p = json_decode(json_encode($event), True);
    // Reading options from POST/PUT
    $cookie = genUuid();
    $output = apiLogin($db, $p, $cookie);
    if ($output['code'] == 200) {
        // User is authenticated, need to set the cookie
        $app->setCookie('unetlab_session', $cookie, SESSION, '/api/', $_SERVER['SERVER_NAME'], False, False);
    }
    $app->response->setStatus($output['code']);
    $app->response->setBody(json_encode($output));
});
$app->get('/api/auth/logout', function () use($app, $db) {
    // Logout (DELETE request does not work with cookies)
    $cookie = $app->getCookie('unetlab_session');
    $app->deleteCookie('unetlab_session');
    $output = apiLogout($db, $cookie);
    $app->response->setStatus($output['code']);
    $app->response->setBody(json_encode($output));
});
$app->get('/api/auth', function () use($app, $db) {
    list($user, $tenant, $output) = apiAuthorization($db, $app->getCookie('unetlab_session'));
    if ($user === False) {
        // Set 401 not 412 for this page only -> used to refresh after a logout
        $output['code'] = 401;
        $app->response->setStatus($output['code']);
        $app->response->setBody(json_encode($output));
        return;
    }
    if (checkFolder(BASE_LAB . $user['folder']) !== 0) {
예제 #4
0
require_once 'func/db_connect.php';
//DATABASE CONNECTIONS
require_once 'func/base64_decode.php';
//BASE 64 IMAGE UPLOAD
require_once 'func/security_csrf.php';
//SECURITY
require_once 'settings.php';
//SETTINGS
$app = new \Slim\Slim(array('cookies.encrypt' => COOKIECRYPT, 'cookies.secret_key' => COOKIEKEY, 'cookies.cipher' => MCRYPT_RIJNDAEL_256, 'cookies.cipher_mode' => MCRYPT_MODE_CBC));
$app->response->headers->set('Content-Type', 'application/json');
$app->group('/content', function () use($app) {
    $app->response->headers->set('Content-Type', 'application/json');
    $app->map('/get', function () use($app) {
        //if(isset($data->token) && security_token($token)){
        //if(security_token($token)){
        if ($app->getCookie('aco-lan') !== null) {
            $lan = $app->getCookie('aco-lan');
        } else {
            $app->redirect($app->urlFor('setLanguage', array('lan' => substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2))));
        }
        if ($app->getCookie('aco-user') !== null) {
            $app->redirect($app->urlFor('getModified'));
        } else {
            $app->redirect($app->urlFor('getFinished'));
        }
        /*}else{
              $app->halt(403, json_encode([   'type' => 'error',
                                              'title' => 'Forbidden Request',
                                              'message' => 'You do not have the permission to call this request.']));
          }*/
    })->via('GET', 'PUT', 'POST', 'DELETE')->name('getContent');
예제 #5
0
파일: router.php 프로젝트: shangwo/letter
    try {
        $app->render("firstindex.html");
    } catch (Exception $e) {
        $app->notfound();
    }
});
$app->get("/secindex", function () use($app) {
    try {
        $app->render("secindex.html");
    } catch (Exception $e) {
        $app->notfound();
    }
});
$app->get("/thirdindex/:uid/:type", function ($uid, $type) use($app, $databases) {
    try {
        $ftype = $app->getCookie("ctype");
        $stype = $app->getCookie("csectype");
        $ttype = $app->getCookie("csort");
        $f = $databases->insert("history", array("uuid" => $uid, "ftype" => $ftype, "stype" => $stype, "ttype" => $ttype));
        if ($type > 2) {
            $datas = $databases->select("user", "expire", array("uuid" => $uid, "ORDER" => array("id DESC", "time DESC")));
            if (count($datas) > 0) {
                $now = time();
                if ($now > $datas[0]) {
                    $app->redirect("../../buy");
                } else {
                    $app->render("thirdindex.html");
                }
            } else {
                $app->redirect("../../buy");
            }
예제 #6
0
$view->parserExtensions = array(new \Slim\Views\TwigExtension());
$view->setTemplatesDirectory(__DIR__ . "/../templates/");
$twig = $view->getEnvironment();
$app->container->singleton('PDO', function () use($app) {
    return new PDO("mysql:host=" . $app->config('dbhost') . ";dbname=" . $app->config('dbname'), $app->config('username'), $app->config('pass'));
});
$app->container->singleton('filesMapper', function () use($app) {
    return new Filehosting\Mappers\FilesMapper($app->PDO);
});
$app->container->singleton('commentsMapper', function () use($app) {
    return new Filehosting\Mappers\CommentsMapper($app->PDO);
});
$app->container->singleton('filesHelper', function () use($app) {
    return new Filehosting\Helpers\FilesHelper(__DIR__, $app->filesMapper, $app->config('safeExtensions'), $app->config('maxsize'));
});
if (!$app->getCookie('token')) {
    $app->setCookie('token', Filehosting\Helpers\FilesHelper::generateToken(), '90 days');
}
$token = $app->getCookie('token');
$view->setData('filesHelper', $app->filesHelper);
$app->map("/", function () use($app) {
    $error = "";
    if ($_FILES) {
        $files = $app->filesMapper;
        $file = new Filehosting\File();
        $postData = array('name' => $_FILES['userfile']['name'], 'size' => $_FILES['userfile']['size'], 'tmp_name' => $_FILES['userfile']['tmp_name'], 'error' => $_FILES['userfile']['error']);
        $error = $app->filesHelper->validateFileUpload($postData);
        if (!$error) {
            $app->filesHelper->uploadFile($file, $postData, $app->getCookie('token'));
            $id = $file->getId();
            $app->redirect("/files/{$id}");
예제 #7
0
});
$app->post('/new', function () use($app, $config) {
    $pseudo = $app->request()->post('pseudo');
    if ($pseudo) {
        $random = substr(str_shuffle(MD5(microtime())), 0, 10);
        $sql = "INSERT INTO stat(pseudo, random) VALUES (:pseudo, :random)";
        $q = $app->db->prepare($sql);
        $q->execute(array(':pseudo' => $pseudo, ':random' => $random));
        $app->setCookie('foo', 'bar', '2 days');
        header('Location: ' . $config['baseUrl'] . '/' . $random);
    }
    exit;
});
$app->get('/trolled(/:random)', function ($random = null) use($app) {
    if ($random) {
        if (!$app->getCookie('foo')) {
            $sql = "UPDATE stat SET nbTrolled = nbTrolled + 1 WHERE random = :random";
            $q = $app->db->prepare($sql);
            $q->execute(array(':random' => $random));
            $app->setCookie('foo', 'bar', '2 days');
        }
    }
    $image = file_get_contents("public/img/trolldance.gif");
    $app->response->header('Content-Type', 'content-type: image/gif');
    echo $image;
});
$app->get('/(:random)(/(:bonus))', function ($random = null) use($app, $config) {
    $websites = $app->db->query('SELECT * FROM website ORDER BY websiteName')->fetchAll();
    $pseudo = null;
    $nbTrolled = null;
    if ($random) {
예제 #8
0
$loader = new Twig_Loader_Filesystem('src/App/view');
Twig_Autoloader::register();
$twig = new Twig_Environment($loader, array());
$app = new \Slim\Slim(array('view' => new \Slim\Views\Twig()));
$app->config = (require __DIR__ . '/app/config/config.php');
$app->add(new \Slim\Middleware\SessionCookie(array()));
$em = new EM($app);
$em = $em->getEntityManager();
/*****************/
/****** WEB ******/
/*****************/
$app->get('/', function () use($app, $twig) {
    echo $twig->render('index.php', array('flash' => isset($_SESSION['slim.flash']) ? $_SESSION['slim.flash'] : null));
})->name('home');
$app->get('/like/:path', function ($path) use($app, $twig, $em) {
    $vote = $app->getCookie("{$path}");
    if ($vote) {
        $app->flash('danger', "Vous avez déjà liké.");
        $app->redirect($app->urlFor('home', array()));
    } else {
        $qr = $em->getRepository("App\\Entity\\QRCode")->findOneBy(array('path' => $path));
        if ($qr == null) {
            $app->notFound();
        }
        $qr->increment();
        $cl = new ClickLog();
        $em->persist($cl);
        $qr->addClickLog($cl);
        $em->persist($qr);
        $em->flush();
        $app->setCookie("{$path}", true);
예제 #9
0
\Slim\Route::setDefaultConditions(array('hash' => '[a-z0-9]{8}'));
// Initialize layout and store it, and use it right away
// as the view for non-XHR requests
$view = new \library\App\Layout();
$view->setTemplatesDirectory($app->config('templates.path'));
$app->config('view', $view);
if (!$app->request->isXhr()) {
    $app->view($view);
}
// Routes
$app->get('/', function () use($app) {
    $crontab = new Crontab();
    $systemUser = new SystemUser();
    $simpleForm = new AddJob\SimpleForm();
    $advancedForm = new AddJob\AdvancedForm();
    $showAlertAtUnavailable = $app->getCookie('showAlertAtUnavailable');
    $app->view->setData('showAlertAtUnavailable', $showAlertAtUnavailable !== null ? (bool) $showAlertAtUnavailable : true);
    $app->render('index.phtml', array('crontab' => $crontab, 'systemUser' => $systemUser, 'isAtCommandAvailable' => At::isAvailable(), 'atCommandErrorOutput' => At::getErrorOutput(), 'simpleForm' => $simpleForm, 'advancedForm' => $advancedForm));
});
/**
 * Groups cron job related routes.
 */
$app->group('/job', function () use($app) {
    /**
     * Should be used as a route middleware to allow for the response
     * to be JSON in the route's callable.
     * 
     * @return void
     */
    $setupJsonResponse = function () {
        $app = \Slim\Slim::getInstance();
예제 #10
0
\Slim\Slim::registerAutoloader();
// date_default_timezone_set('Asia/Chongqing');
$app = new \Slim\Slim();
$app->gwAddress = trim(shell_exec('uci get wifidog.settings.gateway_host'));
$app->gwPort = trim(shell_exec('uci get wifidog.settings.gatewayport'));
$app->gwName = trim(shell_exec('uci get wifidog.settings.gateway_hostname'));
$app->timeLimit = trim(shell_exec('uci get wifidog.settings.client_time_limit'));
$app->gwMac = preg_replace('/(.+)HWaddr (.+)/i', '${2}', trim(shell_exec('ifconfig br-lan | grep HWaddr')));
$app->gwId = str_replace(':', '', $app->gwMac);
$app->get('/hello/:name', function ($name) use($app) {
    echo "Hello, " . $name . "<br>";
});
$app->get('/login', function () use($app) {
    $db = $app->dao;
    parse_str($app->environment['QUERY_STRING']);
    $isReturnUser = $app->getCookie('is_return_user');
    // $user = $db->query("SELECT * FROM users WHERE mac = '{$mac}'");
    if (!$isReturnUser) {
        // echo 'mac was not found.';
        $app->render('touch.php', array('mac' => $mac, 'title' => $app->gwName));
    } else {
        $app->render('touch.php', array('title' => $app->gwName));
    }
    $db = null;
});
$app->post('/users', function () use($app) {
    $db = $app->dao;
    $params = $app->request->post();
    $user = $db->query("SELECT * FROM users WHERE phone = '{$params['phone']}'")->fetch();
    if (!$user) {
        $db->exec("INSERT INTO users (phone, mac)\n\t\t\t\t\tVALUES ('{$params['phone']}', '{$params['mac']}')");
예제 #11
0
파일: api.php 프로젝트: qwexak/unetlab
    // Login
    $event = json_decode($app->request()->getBody());
    $p = json_decode(json_encode($event), True);
    // Reading options from POST/PUT
    $cookie = genUuid();
    $output = apiLogin($db, $p, $cookie);
    if ($output['code'] == 200) {
        // User is authenticated, need to set the cookie
        $app->setCookie('unetlab_session', $cookie, SESSION, '/api/', $_SERVER['HTTP_HOST'], False, False);
    }
    $app->response->setStatus($output['code']);
    $app->response->setBody(json_encode($output));
});
$app->get('/api/auth/logout', function () use($app, $db) {
    // Logout (DELETE request does not work with cookies)
    $cookie = $app->getCookie('unetlab_session');
    $app->deleteCookie('unetlab_session');
    $output = apiLogout($db, $cookie);
    $app->response->setStatus($output['code']);
    $app->response->setBody(json_encode($output));
});
$app->get('/api/auth', function () use($app, $db) {
    list($user, $tenant, $output) = apiAuthorization($db, $app->getCookie('unetlab_session'));
    if ($user === False) {
        $app->response->setStatus($output['code']);
        $app->response->setBody(json_encode($output));
        return;
    }
    $output['code'] = 200;
    $output['status'] = 'success';
    $output['message'] = $GLOBALS['messages']['90002'];
예제 #12
0
        $sort = "default_sort";
    }
    if ($sort == "access") {
        $sort = "public";
    }
    if ($sort == "provider") {
        $sort = "default_sort";
    }
    //read contents of json config file
    $config_file_string = file_get_contents('services.json');
    //parse json content into associative array
    $json = json_decode($config_file_string, true);
    //sort array by sort option
    sksort($json, $sort, "true");
    //if there is a sort cookie present and $sort is default order by sort cookie
    $sort_cookie = $app->getCookie('sort_cookie');
    if (isset($sort_cookie)) {
        $costum_order = unserialize($sort_cookie);
        if ($costum_order != NULL && !empty($costum_order)) {
            //check if lengths are the same (only sort if logged in and see all services)
            if (count($costum_order) == count($json)) {
                //only costum resort if default sort is chosen
                if ($sort == 'default_sort') {
                    $json = resort_array($json, $costum_order);
                }
            }
        }
    }
    get_services_json($json, $env['logged_in']);
});
$app->get('/user', function () use($env) {
예제 #13
0
파일: index.php 프로젝트: V3N0m21/Uppu3
                $app->render('login_form.html', array('message' => $error, 'data' => $_POST));
                return;
            }
        }
    }
    $app->render('login_form.html', array('data' => $_POST, 'page' => $page));
})->via('GET', 'POST')->name('login');
$app->get('/logout', function () use($app) {
    $app->loginHelper->logout();
    $app->redirect('/');
});
$app->map('/register', function () use($app) {
    if ($app->request->isGet()) {
        $app->render('register.html');
    } else {
        $cookie = $app->getCookie('token');
        if (!$cookie) {
            $cookie = HashGenerator::generateSalt();
            $app->setCookie('token', $cookie, '1 month');
        }
        $validation = new \Uppu3\Helper\DataValidator();
        $userHelper = new \Uppu3\Helper\UserHelper($_POST, $app->em, $cookie);
        $user = $userHelper->user;
        $validation->validateUser($user, $_POST);
        if (empty($validation->error)) {
            $userHelper->userSave($app->request->params('password'), $cookie, $app->em);
            $id = $userHelper->user->getId();
            $app->loginHelper->authenticateUser($userHelper->user);
            $app->redirect("users/{$id}");
        } else {
            $app->render('register.html', array('errors' => $validation->error, 'data' => $_POST));
예제 #14
0
파일: index.php 프로젝트: Astaen/fredi
//importation des fonctions de
require "class/bdd.php";
require "models/Club.php";
require "models/User.php";
require "models/Member.php";
require "models/Note.php";
require "models/Fee.php";
session_start();
$app = new \Slim\Slim();
$app->setName('FREDI');
$app->config(array('templates.path' => './views'));
//Protection des routes
$app->hook('slim.before.dispatch', function () use($app) {
    $accessible = array('login', 'about', 'signin');
    //Ces routes ne nécessitent pas d'être authentifié
    if (!isset($_SESSION['logged']) && !$app->getCookie('fredi')) {
        if (!in_array($app->router->getCurrentRoute()->getName(), $accessible)) {
            $app->redirect('login');
        }
    }
    if (!isset($_SESSION['logged']) && $app->getCookie('fredi')) {
        $cookie = explode("==", $app->getCookie('fredi'));
        $email = $cookie[0];
        $password = $cookie[1];
        $user = new User();
        //Si l'utilisateur existe
        $user->id_user = $user->exists($email, $password, true);
        if ($user->id_user) {
            //On récupère les infos de l'utilisateurs
            $user = $user->fetch();
            $_SESSION['logged'] = true;