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; }
/** * Test delete cookie * * This method ensures that the `Set-Cookie:` HTTP response * header is set. The implementation of setting the response * cookie is tested separately in another file. */ public function testDeleteCookie() { \Slim\Environment::mock(array('SCRIPT_NAME' => '/foo', 'PATH_INFO' => '/bar', 'COOKIE' => 'foo=bar; foo2=bar2')); $s = new \Slim\Slim(); $s->get('/bar', function () use($s) { $s->setCookie('foo', 'bar'); $s->deleteCookie('foo'); }); $s->call(); $cookie = $s->response->cookies->get('foo'); $this->assertEquals(1, count($s->response->cookies)); $this->assertEquals('', $cookie['value']); $this->assertLessThan(time(), $cookie['expires']); }
} // Define output for unprivileged requests $forbidden = array('code' => 401, 'status' => 'forbidden', 'message' => $GLOBALS['messages']['90032']); /*************************************************************************** * Authentication **************************************************************************/ $app->post('/api/auth/login', function () use($app, $db) { // 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) {
/** * Test delete cookie * * This method ensures that the `Set-Cookie:` HTTP response * header is set. The implementation of setting the response * cookie is tested separately in another file. */ public function testDeleteCookie() { \Slim\Environment::mock(array('SCRIPT_NAME' => '/foo', 'PATH_INFO' => '/bar', 'COOKIE' => 'foo=bar; foo2=bar2')); $s = new \Slim\Slim(); $s->get('/bar', function () use($s) { $s->setCookie('foo', 'bar'); $s->deleteCookie('foo'); }); $s->call(); list($status, $header, $body) = $s->response()->finalize(); $cookies = explode("\n", $header['Set-Cookie']); $this->assertEquals(1, count($cookies)); $this->assertEquals(1, preg_match('@^foo=;@', $cookies[0])); }
$result = $sql_lan->fetch(); $query = 'SELECT lan FROM Language WHERE preset != 0 AND preset IS NOT NULL'; $sql_lan = $db->prepare($query); $sql_lan->execute(); $sql_lan->setFetchMode(PDO::FETCH_OBJ); $presult = $sql_lan->fetch(); } catch (Exception $e) { $app->halt(503, json_encode(['type' => 'error', 'title' => 'Oops, something went wrong!', 'message' => $e->getMessage()])); } finally { $db = null; } } else { $app->halt(503, json_encode(['type' => 'error', 'title' => 'Oops, something went wrong!', 'message' => 'No database connection'])); } if (empty($result)) { $app->setCookie('aco-lan', $presult->lan, '180 days'); } else { $app->setCookie('aco-lan', $result->lan, '180 days'); } $app->redirect($app->urlFor('getContent')); })->via('GET', 'PUT', 'DELETE')->name('setLanguage'); $app->put('/set/toggle/:lan', function ($lan) use($app) { $data = json_decode($app->request->getBody()); if (isset($data->toggle)) { $toggle = $data->toggle; } if (isset($data->token) && security_token($data->token)) { if (($db = connectToMySql()) !== false) { try { $query = 'UPDATE Language SET toggle = ? WHERE lan = ?'; $sql_lan = $db->prepare($query);
$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}"); }
} // Define output for unprivileged requests $forbidden = array('code' => 401, 'status' => 'forbidden', 'message' => $GLOBALS['messages']['90032']); /*************************************************************************** * Authentication **************************************************************************/ $app->post('/api/auth/login', function () use($app, $db) { // 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->get('/hello/:name', function ($name) { echo "Hello, {$name}"; }); $app->get('/test/:name', function ($name) use($app) { $headers = $app->request->headers; var_dump($headers); echo "Hello, {$name}"; }); // response $app->post('/books', function () use($app) { //Create book $body = $app->request->getBody(); echo $body; $app->response->setStatus(400); $app->setCookie('foo', 'bar', '2 days'); $app->deleteCookie('foo'); // Overwrite response body $app->response->setBody('Foo'); // Append response body $app->response->write('Bar'); // response json string with application/json header $arr = array("name" => "jerry", "age" => 25); $app->response->json($arr); }); $app->delete('/books/:id', function ($id) { //Delete book identified by $id }); $app->get('/archive(/:year(/:month(/:day)))', function ($year = 2010, $month = 12, $day = 05) { echo sprintf('%s-%s-%s', $year, $month, $day); });
$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); //Render $title = $qr->getTitle(); $counter = $qr->getCounter(); $app->flash('success', "Merci pour le Like."); $app->redirect($app->urlFor('home', array())); //echo $twig->render('like.php',array('name' => $title , 'counter' => $counter)); //$app->response->setStatus(200); } })->name('like')->conditions(['path' => '[0-9a-zA-Z]+']); $app->get('/redirect/:path', function ($path) use($app, $twig, $em) { $vote = $app->getCookie("{$path}"); $qr = $em->getRepository("App\\Entity\\QRCode")->findOneBy(array('path' => $path)); if ($qr == null) { $app->notFound(); }
} 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']}')"); } else { $db->exec("UPDATE users SET mac = '{$params['mac']}', updated_at = datetime('now', 'localtime') WHERE id = {$user['id']}"); } $db = null; $app->setCookie('is_return_user', true, '365 days'); $app->halt(200, '{ "error": "" }'); }); $app->get('/portal', function () use($app) { $app->render('show.php', array('title' => $app->gwName, 'id' => $app->gwId)); }); $app->get('/portal/touch', function () use($app) { $db = $app->dao; $uuid = $app->uuid; $id = $app->uuid; $offset = $app->timeLimit; $db->exec("INSERT INTO connections (id, token, expires_on)\n\t\t\t\t\tVALUES ('{$id}', '{$uuid}', datetime(datetime('now','localtime'), '+{$offset} minutes'))"); $db = null; $app->redirect("http://{$app->gwAddress}:{$app->gwPort}/wifidog/auth?token={$uuid}"); }); $app->get('/ping', function () use($app) {
//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) { get_user_info_json($env['loggin_info']); }); $app->post('/sort', function () use($app) { // $costum_order = $app->request()->post('order'); $costum_order = explode(',', $app->request()->post('order')); $app->setCookie('sort_cookie', serialize($costum_order), time() + 5 * 60); }); $app->run();
} } $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)); } } })->via('GET', 'POST');