public function connect(Application $app) { $controllers = new ControllerCollection(); $controllers->get('auth', function () use($app) { if ($app['session']->has($app['config']['prefix'] . 'authed-user')) { return $app->redirect('/'); } return $app['twig']->render('PT/pages/authenticate.html', array('auth_path' => $app['uri']->generate('authenticate'))); })->bind('authenticate'); $controllers->post('auth', function () use($app) { if ($app['request']->get('username') === $app['config']['authenticate']['username'] && $app['request']->get('password') === $app['config']['authenticate']['password']) { $userHash = $userHash = sha1($app['config']['authenticate']['username'] . $app['config']['authenticate']['password']); $currentUser = $app['session']->set($app['config']['prefix'] . 'authed-user', $userHash); return $app->redirect('/'); } else { $app['session']->setFlash('error', 'error'); $app['session']->remove($app['config']['prefix'] . 'authed-user'); return $app->redirect($app['uri']->generate('authenticate')); } })->bind('do_authenticate'); $controllers->get('deauth', function ($result) use($app) { $app['session']->remove($app['config']['prefix'] . 'authed-user'); return $app->redirect($app['uri']->generate('authenticate')); })->value('result', null)->bind('de_authenticate'); return $controllers; }
/** * Silex method that exposes routes to the app * * @param Silex\Application $app Application instance * * @return Silex\ControllerCollection Object encapsulating crafted routes */ public function connect(Application $app) { $ctrl = $app['controllers_factory']; /** * Homepage */ $ctrl->get('/', function () use($app) { $root = str_replace('index.php/', '', $app['url_generator']->generate('home')); if ($app['request']->getRequestURI() != $root) { return $app->redirect($root, Response::HTTP_MOVED_PERMANENTLY); } return $app['twig']->render('front/partials/home.twig'); })->bind('home'); /** * Admin root */ $ctrl->get('/admin', function () use($app) { return $app->redirect($app['url_generator']->generate($app['config']['admin']['root'])); }); /** * robots.txt */ $ctrl->get('/robots.txt', function () use($app) { $response = new Response('User-agent: *' . PHP_EOL . ($app['debug'] ? 'Disallow: /' : 'Sitemap: ' . $app['url_generator']->generate('home') . 'sitemap.xml')); $response->headers->set('Content-Type', 'text/plain'); return $response; }); return $ctrl; }
/** * Handle turn request then redirect to home * * @param Request $request * @return \Symfony\Component\HttpFoundation\RedirectResponse */ public function turn(Request $request) { // get the coordinate from the request $coordinate = $request->get('coordinate'); // load game session $this->loadGameSession(); switch ($coordinate) { default: // turn $message = $this->doTurn($coordinate); break; case '': $message = 'enter a coordinate'; break; case 'show': $this->getFlashBag()->set('show', '1'); $message = 'showing ships'; break; case 'reset': $this->resetGame(); $message = 'game restarted'; break; } // store message to display it next time $this->getFlashBag()->add('message', $message); // update session $this->updateGameSession(); // redirect to home page return $this->app->redirect($this->getUrlGenerator()->generate('home')); }
public function index(Application $app, $firstChar, $page) { //Page number 0 or below if ($page <= 0) { $redirectUrl = "/a-z/{$firstChar}/1"; return $app->redirect($redirectUrl); } $data = $app['programme_api']->fetchPageData($firstChar, $page); $successfulRequest = $data[0]; if ($successfulRequest) { $pageData = $data[1]; $totalProgrammes = $pageData->atoz_programmes->count; if ($totalProgrammes == 0) { return $app['twig']->render('no-results.twig', array()); } $perPage = $pageData->atoz_programmes->per_page; $numberOfPages = ceil($totalProgrammes / $perPage); if ($page > $numberOfPages) { //Page number is past last page $redirectUrl = "/a-z/{$firstChar}/{$numberOfPages}"; return $app->redirect($redirectUrl); } else { $programmes = $pageData->atoz_programmes->elements; return $app['twig']->render('az.twig', array('firstChar' => $firstChar, 'numOfPages' => $numberOfPages, 'pageNo' => $page, 'programmes' => $programmes, 'imageSize' => '240x135')); } } else { $error = $data[1]; $app->abort(500, 'jooooo'); } }
public function register(Application $app) { $app['user.hydrator'] = function () use($app) { return new UserHydrator($app['taxonomy.service'], new TermHydrator()); }; $app['user.manager'] = function () use($app) { return new UserService($app['db'], $app['user.hydrator']); }; $app['auth.mustAuthenticate'] = function (Application $app) { return function () use($app) { if (!$app['session']->has('user')) { return $app->redirect($app['url_generator']->generate('auth.login')); } }; }; $app['auth.isAdmin'] = function (Application $app) { return function () use($app) { $user = $app['session']->get('user'); if (!$user || $user->role != 'ROLE_ADMIN') { $app['session']->getFlashBag()->add('error', 'You do not have privileges for the requested page'); return $app->redirect($app['url_generator']->generate('index')); } }; }; $app['controller.auth'] = $app->share(function ($app) { return new AuthController(); }); }
public function thumbAction(Request $request, Application $app) { $source = $request->get('src', false); $width = $request->get('width', 250); // Do requested thumbnail in correct format already exists ? if ($app['flysystems']['thumbs']->has($width . "/" . $source)) { return $app->redirect($request->getBasePath() . '/thumbs/' . $width . '/' . $source, 301); } // Do requested file exists ? if (!$source || !$app['flysystems']['local']->has($source)) { return new Response("Source file not found.", 404); } try { $contents = $app['flysystems']['local']->read($source); $imageManager = new ImageManager(); $image = $imageManager->make($contents); $image->resize($width, null, function ($constraint) { $constraint->aspectRatio(); }); $info = $app['flysystems']['local']->getWithMetadata($source, ['mimetype']); $image->encode($info['mimetype']); $app['flysystems']['thumbs']->put($width . "/" . $source, $image); return $app->redirect($request->getBasePath() . '/thumbs/' . $width . '/' . $source, 301); } catch (\Exception $e) { return new Response("Erreur !", 500); } // Should not happen, everything failed. Display not found image :( return $app->redirect($request->getBasePath() . '/assets/img/' . $width . '_not-found.png', 302); }
public function connect(Application $app) { $this->app = $app; $jira = $app['controllers_factory']; $jira->get('/connect/{redirect}', function (Request $request, $redirect) use($app) { $token = $app['jira.oauth.temp_credentials']($redirect); $app['session']->set('oauth', $token); return $app->redirect($app['jira.oauth.auth_url']); })->value('redirect', null)->bind('jira-connect'); $jira->get('/callback', function ($url, $verifier) use($app) { $tempToken = $app['session']->get('oauth'); $app['jira.token'] = $tempToken; $app['jira.oauth_verifier'] = $verifier; $token = $app['jira.oauth.auth_credentials']($url); $app['session']->set('oauth', $token); return $app->redirect($url); })->convert('url', function ($url, Request $request) { if (!$request->query->has('url')) { return $this->app['jira.default_redirect']; } $url = $request->get('url'); try { return $this->app['url_generator']->generate($url); } catch (RouteNotFoundException $e) { return '/' . $url; } })->convert('verifier', function ($verifier, Request $request) { if (!$request->query->has('oauth_verifier')) { throw new \InvalidArgumentException('There was no oauth verifier in the request'); } return $request->get('oauth_verifier'); })->bind('jira-callback'); return $jira; }
private function getThingEditForm(Application $app, Request $request, $thingId) { $error = $request->query->get('error'); $repo = $app->getThingRepository(); $add = false; $thing = $repo->getById($thingId); if ($thing === null) { $defaults = null; $add = true; } else { $defaults = ['name' => $thing->getName(), 'email' => $thing->getEmail(), 'description' => $thing->getDescription()]; } $form = $app['form.factory']->createBuilder('form', $defaults)->add('name', 'text')->add('email', 'email')->add('description', 'textarea', array('required' => false))->getForm(); // handle form submission $form->handleRequest($request); if ($form->isValid()) { $data = $form->getData(); if ($add) { $thing = new Thing(); } $thing->setEmail(strtolower($data['email']))->setName($data['name'])->setDescription($data['description']); if ($add) { if (!$repo->add($thing)) { return $app->redirect($app['url_generator']->generate('things_add', array('error' => 'Failed adding thing'))); } } else { $repo->update($thing); } return $app->redirect($app['url_generator']->generate('things_index')); } return new Response($app['twig']->render('edit.html.twig', ['form' => $form->createView(), 'thing' => $thing, 'error' => $error])); }
public function connect(Application $app) { $controllers = $app['controllers_factory']; $controllers->get('/', function (Application $app, Request $request) { $body = $app['twig']->render('signup.html', array('user' => array('name' => '', 'email' => '', 'password' => '6 chars minimum'))); return new Response($body, 200); })->before(function (Request $request, Application $app) { if ($app['user.logged_in']) { return $app->redirect('/'); } }); $controllers->post('/', function (Application $app, Request $request) { $userService = $app['user.service']; $post = $request->request->all(); $user = $userService->manageFormData($post); if (\Filehosting\Service\UserService::VALIDATION_FAILED === $user) { $user = $userService->identifyUser($request->cookies->all(), false); $body = $app['twig']->render('failed.html', array('subject' => 'Validation', 'userID' => $user->getId() === null ? "" : $user->getId())); return new Response($body, 200); } $app['em']->flush(); if (null === $user->getId()) { throw new Exception("Не удалось сохранить пользователя в БД."); } $lm = $app['user.service.login_manager']; if (!$lm->isLoggedIn()) { $lm->logIn($user->getId()); } return $app->redirect("/user/{$user->getId()}"); }); return $controllers; }
public function authAction(Request $request, Application $app) { if ($app['session']->get('twitter_oauth_token') === null) { // get the request token $reply = $app['twitter']->oauth_requestToken(['oauth_callback' => $request->getUri()]); if (empty($reply)) { return new Response('Reply is empty'); } // store the token $app['twitter']->setToken($reply->oauth_token, $reply->oauth_token_secret); $app['session']->set('twitter_oauth_token', $reply->oauth_token); $app['session']->set('twitter_oauth_token_secret', $reply->oauth_token_secret); $app['session']->set('twitter_oauth_verify', true); // redirect to auth website return $app->redirect($app['twitter']->oauth_authorize()); } elseif ($request->get('oauth_verifier') !== null && $app['session']->get('twitter_oauth_verify') !== null) { // verify the token $app['twitter']->setToken($app['session']->get('twitter_oauth_token'), $app['session']->get('twitter_oauth_token_secret')); $app['session']->set('twitter_oauth_verify', null); // get the access token $reply = $app['twitter']->oauth_accessToken(['oauth_verifier' => $request->get('oauth_verifier')]); // store the token (which is different from the request token!) $app['session']->set('twitter_oauth_token', $reply->oauth_token); $app['session']->set('twitter_oauth_token_secret', $reply->oauth_token_secret); $app['session']->set('loggedin', true); $app['session']->set('twitter_screen_name', $reply->screen_name); return $app->redirect('/'); } return $app->redirect('/logout'); }
public function addAction(Request $request, Application $app) { $newStudent = new Student(); $class = $app['dao.className']->findClassname($request->request->get('classname')); $statuts = $app['dao.statutStudent']->findStatut($request->request->get('statut')); if (null !== $request->request->get('id_student')) { $newStudent->setIdStudent($request->request->get('id_student')); } $newStudent->setName($request->request->get('name')); $newStudent->setFirstname($request->request->get('firstname')); $newStudent->setBirthday($request->request->get('birthday')); $newStudent->setAddress($request->request->get('address')); $newStudent->setTel($request->request->get('phone')); $newStudent->setEmail($request->request->get('email')); $newStudent->setDtCreate(date('Y-m-d H:i:s')); $newStudent->setDtUpdate(date('Y-m-d H:i:s')); $newStudent->setClass($class); $newStudent->setStatut($statuts); $app['dao.student']->saveStudent($newStudent); $classes = $app['dao.className']->findAll(); if (null !== $request->request->get('id_student')) { $app['session']->getFlashBag()->add('success', 'L\'étudiant a bien été modifiée !'); //message flash success si réussi return $app->redirect($app['url_generator']->generate('studentslist')); } else { $app['session']->getFlashBag()->add('success', 'L\'étudiant a bien été ajouté !'); //message flash success si réussi return $app->redirect($app['url_generator']->generate('studentslist')); } }
public function uploadAction(Application $app, Request $request) { // Read file from request $file = $request->files->get('savegame'); if ($file === null) { throw new BadRequestHttpException("Savegame data not found in request. Did you chose a savegame\n before pressing Submit?"); } // // Check upload was successful if ($file->getError() !== UPLOAD_ERR_OK) { throw new BadRequestHttpException("An error occured while uploading your savegame. Please try\n again and report the problem if it persists."); } // Read the data $data = $file->openFile()->fread(4096); // Check header $header = substr($data, 0, 14); if (!in_array($header, ['ISAACNGSAVE06R', 'ISAACNGSAVE08R'])) { throw new BadRequestHttpException("Invalid file header. A savegame file should start with the\n string `ISAACNGSAVEXXR`.\n\nYou either uploaded a file wich is\n not a BOIR savegame, or the savegame version is not supported."); } // Calculate the hash which is used to identify the savegame $hash = md5($data); // If file already exists, skip the upload if ($app['archiver']->exists($hash)) { return $app->redirect('/show/' . $hash); } // Save the file $app['archiver']->save($data); // Redirect to show return $app->redirect('/show/' . $hash); }
public function editAction(Application $app, Request $request) { $usersModel = new usersModel($app); $id = (int) $request->get('id', 0); $user = $usersModel->getUser($id); $usersModel = new UsersModel($app); $user['roles'] = $usersModel->getRoles(); if (count($user)) { $form = $app['form.factory']->createBuilder(new UserForm(), $user)->getForm(); $form->handleRequest($request); if ($form->isValid()) { $data = $form->getData(); $data['role_id'] = $data['role']; $data['password'] = $app['security.encoder.digest']->encodePassword($data['password'], ''); unset($data['roles'], $data['role']); var_dump($data); $usersModel = new usersModel($app); $usersModel->saveUser($data); $app['session']->getFlashBag()->add('message', array('type' => 'success', 'content' => $app['translator']->trans('User edited'))); return $app->redirect($app['url_generator']->generate('users_index'), 301); } $this->view['id'] = $id; $this->view['form'] = $form->createView(); } else { return $app->redirect($app['url_generator']->generate('users_add'), 301); } return $app['twig']->render('users/edit.twig', $this->view); }
public function view(Request $request, Application $app, $appName, $resetPasswordKey = '') { switch ($appName) { /** @noinspection PhpMissingBreakStatementInspection */ case 'reset_password': $user = new UserModelBase(); if (!$user->readByProperty('resetPasswordKey', $resetPasswordKey)) { $app['session']->getFlashBag()->add('errorMessage', 'Your password reset cannot be completed. Please try again.'); return $app->redirect('/auth/login'); } if (!$user->hasForgottenPassword(false)) { $app['session']->getFlashBag()->add('errorMessage', 'Your password reset cannot be completed. It may have expired. Please try again.'); return $app->redirect('/auth/login'); } // no break; - intentional fall through to next case // no break; - intentional fall through to next case case 'forgot_password': case 'login': $this->setupNgView($app, $appName); $this->setupAuthView($request, $app); return $this->renderPage($app, 'angular-app'); break; default: return $this->renderPage($app, $appName); } }
/** * Отправляет пользователя на нужный url, для oauth авторизации * * @param Request $request * * @return \Symfony\Component\HttpFoundation\RedirectResponse */ public function oauthRedirectAction(Request $request) { $provider = $request->get('provider', null); if (null === $provider) { throw new BadRequestHttpException('Bad request params'); } return $this->app->redirect($this->app['gitlab_api']->getAuthUrl()); }
public function delete(Application $app, $id) { if (!$app['security.authorization_checker']->isGranted('ROLE_ADMIN')) { return $app->redirect($app['url_generator']->generate('produit_index')); } $restaurant = $app['repository.produits']->find($id); $app['repository.produits']->delete($restaurant); return $app->redirect($app['url_generator']->generate('produit_index')); }
public function addTacosAction($idTacos, Application $app) { if ($app['security.authorization_checker']->isGranted('IS_AUTHENTICATED_FULLY')) { $app['dao.cart']->addTacos($idTacos, $app['user']->getId()); return $app->redirect('/Tacosmopolite/web/index.php/cart/'); } else { return $app->redirect('/Tacosmopolite/web/index.php/login/'); } }
public function register(Application $app) { $app->match('/administration/{table}', function ($table) use($app) { if (is_null($app['silexcms.security']->getUsername())) { return $app->redirect($app['url_generator']->generate('administration_login')); } $repository = $app['silexcms.sets'][$table]->getRepository(); $schema = $repository->getSchema(); $rows = $repository->findAll(true); foreach ($rows as $row) { $data[] = array_map(function ($val) { return is_string($val) && strlen($val) > 50 ? substr(strip_tags($val), 0, 47) . '...' : $val; }, $row); } return new TransientResponse($app, $app['silexcms.template.loader']->load('administration/administration_table.html.twig'), array('table' => $table, 'fields' => $schema, 'rows' => $data)); })->bind('administration_table'); $app->match('/administration/{table}/{primaryKey}', function (Request $req, $table, $primaryKey) use($app) { if (is_null($app['silexcms.security']->getUsername())) { return $app->redirect($app['url_generator']->generate('administration_login')); } $set = $app['silexcms.sets'][$table]; $repository = $set->getRepository(); $formGenerator = new Form($set); $form = $app['form.factory']->create(new TableType($app, $table), $formGenerator->getData('_new' === $primaryKey ? null : $primaryKey)); if ($req->getMethod() === 'POST') { $form->bindRequest($req); if ($form->isValid()) { $data = $form->getData(); foreach ($data['row'] as $row) { $where = array('`' . $repository->getPrimaryKey() . '`' => $row[$repository->getPrimaryKey()]); // unset id primaryKey if ('id' === $repository->getPrimaryKey()) { unset($row[$repository->getPrimaryKey()]); } if ('_new' === $primaryKey) { $repository->insert($row); return $app->redirect($app['url_generator']->generate('administration_table', array('table' => $table))); } $repository->update($row, $where); try { // cache strategy if exist. Update cache version $app['silexcms.cache.manager']->update(); } catch (\Exception $e) { } } } } return new TransientResponse($app, $app['silexcms.template.loader']->load('administration/administration_edit.html.twig'), array('table' => $table, 'primaryKey' => $primaryKey, 'form' => $form->createView())); })->bind('administration_edit'); $app->match('/administration', function () use($app) { if (is_null($app['silexcms.security']->getUsername())) { return $app->redirect($app['url_generator']->generate('administration_login')); } $tables = array_keys($app['silexcms.sets']); return new TransientResponse($app, $app['silexcms.template.loader']->load('administration/administration_hub.html.twig'), array('tables' => $tables)); })->bind('administration_hub'); }
public function loginRedirectAction(Request $request, Application $app) { if ($app['security.authorization_checker']->isGranted('ROLE_ADMIN')) { return $app->redirect($app->path('admin_dashboard')); } if ($app['security.authorization_checker']->isGranted('IS_AUTHENTICATED_FULLY')) { return $app->redirect($app->path('frontend_home')); } return $app->redirect($app->path('login')); }
/** * Page callback: return some results. */ public function results(Request $request, Application $app, $lang, $find) { if (!preg_match("/^[a-z]{2}\$/", $lang)) { return $app->redirect('/'); } if (!preg_match("/^[a-z]+\$/", $find)) { return $app->redirect('/'); } return $app['twig']->render("results-{$lang}-{$find}.twig"); }
public function connect(Application $app) { // creates a new controller based on the default route $controllers = $app['controllers_factory']; //use session storage $app->register(new \Silex\Provider\SessionServiceProvider()); //register ldap service $app['auth.ldap'] = function () use($app) { return new \Zend\Ldap\Ldap($app['auth.ldap.options']); }; //redirect to login page if not logged inwar $app->before(function (Request $request) use($app) { //user is not logged in go to login if (null === $app['session']->get('user') && $request->get("_route") !== 'login' && $request->get("_route") !== '_auth_keepalive') { $app['session']->set('user_target', $request->getUri()); return $app->redirect('/auth/login'); } //user is logged in - go to home if ($app['session']->get('user') && $request->get("_route") == 'login') { return $app->redirect('/'); } //write close to allow concurrent requests $app['session.storage']->save(); }); $controllers->match('/login', function (Request $request) use($app) { $view_params = array('error' => null); //handle login where appropriate if ($request->get('user') && $request->get('password')) { try { //throws exception $app['auth.ldap']->bind($request->get('user'), $request->get('password')); $app['session']->set('user', array('username' => $request->get('user'))); if ($user_target = $app['session']->get('user_target')) { return $app->redirect($user_target); } else { return $app->redirect('/'); } } catch (LdapException $e) { $view_params['error'] = 'Login Failed with error code ' . $e->getcode(); } } return $app['view']->render($app['auth.template.login'] ?: 'login', $view_params); })->bind('login'); $controllers->match('/logout', function (Request $request) use($app) { $app['session']->set('user', null); return $app->redirect('/'); }); $controllers->match('/keepalive', function () use($app) { if ($app['session']->get('user')) { return new Response('', 204); } return new Response('Expired', 403); }); return $controllers; }
public function delete(Request $request, Application $app, $resourceId) { $em = $app['orm.em']; $resource = $em->getRepository('Orcamentos\\Model\\Resource')->find($resourceId); if (count($resource->getResourceQuoteCollection()) > 0) { $app['session']->getFlashBag()->add('message', 'Recurso já está ligado a algum orçamento'); return $app->redirect('/company'); } $em->remove($resource); $em->flush(); return $app->redirect('/company'); }
public function redirectAction(Request $request, Application $app) { if ($app['general_service']->isMobile()) { $locale = $app['config']['default_language']; $url = $app['url_generator']->generate($app['config']['facebook']['start_route'], array('_locale' => $locale)); return $app->redirect($url); } $cookie = new Cookie('cookie_fix', true); $response = $app->redirect($app['config']['facebook']['tab']); $response->headers->setCookie($cookie); return $response; }
function updateAction(Request $request, Application $app) { if (null === ($user = $app['session']->get('user'))) { return $app->redirect('/login'); } $em = $app['orm.em']; $categoryRepository = $em->getRepository('Category'); $Category = $categoryRepository->find($request->get('id')); $Category->setTitle($request->get('title')); $Category->setSummary($request->get('summary')); $em->flush(); return $app->redirect('/categoryAdmin'); }
function updateAction(Request $request, Application $app) { if (null === ($user = $app['session']->get('user'))) { return $app->redirect('/login'); } $em = $app['orm.em']; $userRepository = $em->getRepository('User'); $user = $userRepository->find($request->get('id')); $user->setUsername($request->get('username')); $user->setPassword($request->get('password')); $em->flush(); return $app->redirect('/userAdmin'); }
/** * Render and display project assets as a site. * * @param int|string $id * @return Response */ public function render($id, $name) { $project = $this->repo->find((int) $id); if (!$project || !$project->published) { return $this->app['twig']->render('404.twig.html'); } $path = $this->exporter->project((int) $id, false); if (!$path) { return $this->app['twig']->render('404.twig.html'); } $base = str_replace($this->app['base_dir'], $this->app['base_url'], $path); return $this->app->redirect($base . $name . '.html'); }
/** * All the controllers for the application: * * - /logout/: remove the token + revoke google oauth2 * - /connect/: redirects to the google oauth2 authorisation page * - /oauth2callback/: the oauth2 callback in which we write the token to * the cookie * * @see ControllerProviderInterface::connect */ public function connect(Application $app) { $app->before(function () use($app) { $client = $app['google_oauth.client']; $oauth2 = $app['google_oauth.service']; // The redirect uri can only be generated when the request is available // which is not in the service registering process. $client->setRedirectUri($app['url_generator']->generate('google_oauth_callback', array(), true)); if ($token = $app['session']->get('token')) { $client->setAccessToken($token); } if ($client->getAccessToken()) { $user = $oauth2->userinfo->get(); $app['user'] = $user; $app['session']->set('token', $client->getAccessToken()); $app['google_oauth_user_email'] = filter_var($user['email'], FILTER_SANITIZE_EMAIL); $app['google_oauth_user_picture'] = filter_var($user['picture'], FILTER_VALIDATE_URL); } else { $app['user'] = false; } }); // creates a new controller based on the default route $controllers = $app['controllers_factory']; $controllers->get('/logout/', function (Request $request) use($app) { $client = $app['google_oauth.client']; $app['session']->remove('token'); $client->revokeToken(); return $app->redirect('/'); })->bind('google_oauth_logout'); // Connect $controllers->get('/connect/', function (Request $request) use($app) { $client = $app['google_oauth.client']; if ($client->getAccessToken()) { $url = '/'; } else { $url = $client->createAuthUrl(); } return $app->redirect($url); })->bind('google_oauth_connect'); // Oauth2 callback $controllers->get('/oauth2callback/', function (Request $request) use($app) { $client = $app['google_oauth.client']; if ($request->get('code')) { $client->authenticate($request->get('code')); $app['session']->set('token', $client->getAccessToken()); return $app->redirect('/'); } $app->abort(404, "Nothing here!"); })->bind('google_oauth_callback'); return $controllers; }
/** * Reads uploaded file and prints cards from it. * * @param string $file * @return RedirectResponse|string */ public function printAction($file) { $home = $this->app['url_generator']->generate('home'); if (false !== strpos($file, '..')) { // Sorry kids return $this->app->redirect($home); } $file = getcwd() . '/data/uploads/' . $file; if (!is_readable($file)) { return $this->app->redirect($home); } $service = new CardsService(); $cards = $service->parseFile($file); return $this->app['twig']->render('cards/print.twig', ['cards' => $cards]); }
public function contactSentAction(Request $request, Application $app) { $data = $request->get('contact_form'); $configData = $app['configs']->getData(); $contactEmails = $configData['contact_email'] ? explode(',', $configData['contact_email']) : array('*****@*****.**'); $message = sprintf(' Salut, Ai primit un mesaj prin intermediul formularului de contact. Mesaj: %s. Primit la %s de la %s cu adresa %s.', $data['mesaj'], date('d-m-Y H:i'), $data['nume'], $data['email']); $mailer = $app['mailer']; $mailer->isSMTP(); $mailer->Host = 'localhost'; //$mailer->Username = ''; //$mailer->Password = ''; //$mailer->SMTPSecure = 'ssl'; $mailer->Port = 25; $mailer->setFrom('*****@*****.**'); $mailer->addReplyTo($data['email']); foreach ($contactEmails as $email) { $mailer->addAddress($email); } $mailer->Subject = 'Formular contact '; $mailer->Body = $message; $mailer->send(); $_SESSION['message_sent'] = TRUE; return $app->redirect('/contact', 302); }
/** * Действие страницы регистрации пользователя * * @return string */ public function registrationAction() { // если пользователь уже авторизован, переадресуем на главную $user = $this->app['session']->get('user'); if ($user) { return $this->app->redirect('/'); } /** * Возможны три варианта значения статуса регистрации * * @var null|bool $registrationStatus */ $registrationStatus = null; // получаем данные запроса $firstName = $this->request->get('first_name'); $lastName = $this->request->get('last_name'); $email = $this->request->get('email'); $password = $this->request->get('password'); $passwordConfirmation = $this->request->get('password_confirmation'); $address = $this->request->get('address'); $phone = $this->request->get('phone'); // данные для рендеринга формы регистрации $registrationFormData = array('firstName' => $firstName, 'lastName' => $lastName, 'email' => $email, 'address' => $address, 'phone' => $phone); // если пришел POST-запрос с данными формы регистрации, // то пробуем регистрировать пользователя if ($this->request->isMethod('POST')) { $registrationStatus = $this->usersModel->register($email, $password, $passwordConfirmation, $firstName, $lastName, $address, $phone); } return $this->view->render('user/registration.phtml', array('registrationFormData' => $registrationFormData, 'registrationStatus' => $registrationStatus)); }