public function listAction(Application $app, Request $request) { $limit = $request->get('limit') ?: 50; $offset = $request->get('offset') ?: 0; $order_by = $request->get('order_by') ?: 'id'; $order_dir = $request->get('order_dir') == 'DESC' ? 'DESC' : 'ASC'; $numResults = $this->userManager->findCount(); $users = $this->userManager->findBy(array(), array('limit' => array($offset, $limit), 'order_by' => array($order_by, $order_dir))); foreach ($users as $user) { $user->imageUrl = $this->getGravatarUrl($user->getEmail(), 40); } $nextUrl = $prevUrl = null; if ($numResults > $limit) { $nextOffset = $offset + $limit < $numResults ? $offset + $limit : null; $prevOffset = $offset > 0 ? $offset - $limit > 0 ? $offset - $limit : 0 : null; $baseUrl = $app['url_generator']->generate('user.list') . '?limit=' . $limit . '&order_by=' . $order_by . '&order_dir=' . $order_dir; if ($nextOffset !== null) { $nextUrl = $baseUrl . '&offset=' . $nextOffset; } if ($prevOffset !== null) { $prevUrl = $baseUrl . '&offset=' . $prevOffset; } } $firstResult = $offset + 1; $lastResult = $offset + $limit > $numResults ? $numResults : $offset + $limit; return $app['twig']->render($this->listTemplate, array('layout_template' => $this->layoutTemplate, 'users' => $users, 'numResults' => $numResults, 'nextUrl' => $nextUrl, 'prevUrl' => $prevUrl, 'firstResult' => $firstResult, 'lastResult' => $lastResult)); }
public function testMigrateDown() { $username = '******'; $isEnabled = true; $confirmationToken = 'toke'; $timePasswordResetRequested = null; $this->migrator->up(); $user = new User('*****@*****.**', 'password'); $user->setUsername($username); $user->setEnabled($isEnabled); $user->setConfirmationToken($confirmationToken); $user->setTimePasswordResetRequested($timePasswordResetRequested); $this->userManager->insert($user); $userId = $user->getId(); // echo implode(";\n", $this->migrator->sqlDown()); $this->migrator->down(); $this->assertEquals($username, $this->fetchCustomField($userId, 'username')); $this->assertEquals($isEnabled, $this->fetchCustomField($userId, 'su:isEnabled')); $this->assertEquals($confirmationToken, $this->fetchCustomField($userId, 'su:confirmationToken')); $this->assertEquals($timePasswordResetRequested, $this->fetchCustomField($userId, 'su:timePasswordResetRequested')); }
public function testPasswordStrengthValidator() { $user = new User('*****@*****.**'); // By default, an empty password is not allowed. $error = $this->userManager->validatePasswordStrength($user, ''); $this->assertNotEmpty($error); // By default, any non-empty password is allowed. $error = $this->userManager->validatePasswordStrength($user, 'a'); $this->assertNull($error); // Test setting a custom validator. $this->userManager->setPasswordStrengthValidator(function (User $user, $password) { if (strlen($password) < 2) { return 'Password must have at least 2 characters.'; } }); $error = $this->userManager->validatePasswordStrength($user, 'a'); $this->assertEquals('Password must have at least 2 characters.', $error); }
protected function eventListener() { $app = $this->app; $app->on(OAuthEvents::USER, function ($event) use($app) { $this->usrToken = $event->getToken(); $this->email = $this->usrToken->getEmail(); $this->name = $this->usrToken->getUsername(); $this->usrId = $this->usrToken->getUid(); try { // // Login user $user = $this->usrManager->loadUserByUsername($this->email ?: $this->name); $this->user = $this->usrManager->refreshUser($user); $this->usrToken->setUser($this->user); $this->user->setConfirmationToken(null); $this->user->setEnabled(true); $this->usrManager->loginAsUser($this->user); $this->logger(" Try to login user from " . $this->usrToken->getService()); } catch (UsernameNotFoundException $e) { // // Register new user $this->generatePassword(); $this->user = $this->usrManager->createUser($this->email, $this->password, $this->name); $this->usrToken->setUser($this->user); $this->user->setConfirmationToken(null); $this->user->setEnabled(true); $this->user->setUsername($this->usrId); $this->usrManager->insert($this->user); $this->usrManager->loginAsUser($this->user); $app['session']->getFlashBag()->set('alert', 'Account created.'); $this->logger(" Try to register user from " . $this->usrToken->getService()); } if ($this->app['user']) { $this->setSuccessHandler($this->usrToken->getService()); } // TODO send an email with information about the user $app->after(function () use($app) { $this->usrManager->loginAsUser($this->user); if ($this->usrManager->isLoggedIn()) { $newUrl = $app['url_generator']->generate('user.view', array('id' => $this->user->getId())); return new RedirectResponse($newUrl); } }); }); return $app; }
public function listAction(Application $app, Request $request) { $order_by = $request->get('order_by') ?: 'name'; $order_dir = $request->get('order_dir') == 'DESC' ? 'DESC' : 'ASC'; $limit = (int) ($request->get('limit') ?: 50); $page = (int) ($request->get('page') ?: 1); $offset = ($page - 1) * $limit; $criteria = array(); if (!$app['security']->isGranted('ROLE_ADMIN')) { $criteria['isEnabled'] = true; } $users = $this->userManager->findBy($criteria, array('limit' => array($offset, $limit), 'order_by' => array($order_by, $order_dir))); $numResults = $this->userManager->findCount($criteria); $paginator = new Paginator($numResults, $limit, $page, $app['url_generator']->generate('user.list') . '?page=(:num)&limit=' . $limit . '&order_by=' . $order_by . '&order_dir=' . $order_dir); foreach ($users as $user) { $user->imageUrl = $this->getGravatarUrl($user->getEmail(), 40); } return $app['twig']->render($this->getTemplate('list'), array('layout_template' => $this->getTemplate('layout'), 'users' => $users, 'paginator' => $paginator, 'numResults' => $paginator->getTotalItems(), 'nextUrl' => $paginator->getNextUrl(), 'prevUrl' => $paginator->getPrevUrl(), 'firstResult' => $paginator->getCurrentPageFirstItem(), 'lastResult' => $paginator->getCurrentPageLastItem())); }
/** * Registers services on the given app. * * This method should only be used to configure services and parameters. * It should not get services. * * @param Application $app An Application instance */ public function register(Application $app) { // Default options. $app['user.options.default'] = array('templates' => array('layout' => '@user/layout.twig', 'register' => '@user/register.twig', 'register-confirmation-sent' => '@user/register-confirmation-sent.twig', 'login' => '@user/login.twig', 'login-confirmation-needed' => '@user/login-confirmation-needed.twig', 'forgot-password' => '@user/forgot-password.twig', 'reset-password' => '@user/reset-password.twig', 'view' => '@user/view.twig', 'edit' => '@user/edit.twig', 'list' => '@user/list.twig'), 'mailer' => array('enabled' => true, 'fromEmail' => array('address' => 'do-not-reply@' . (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : gethostname()), 'name' => null)), 'emailConfirmation' => array('required' => false, 'template' => '@user/email/confirm-email.twig'), 'passwordReset' => array('template' => '@user/email/reset-password.twig', 'tokenTTL' => 86400), 'userClass' => 'SimpleUser\\User', 'isUsernameRequired' => false, 'editCustomFields' => array(), 'userTableName' => 'users', 'userCustomFieldsTableName' => 'user_custom_fields'); // Initialize $app['user.options']. $app['user.options.init'] = $app->protect(function () use($app) { $options = $app['user.options.default']; if (isset($app['user.options'])) { // Merge default and configured options $options = array_replace_recursive($options, $app['user.options']); // Migrate deprecated options for backward compatibility if (isset($app['user.options']['layoutTemplate']) && !isset($app['user.options']['templates']['layout'])) { $options['templates']['layout'] = $app['user.options']['layoutTemplate']; } if (isset($app['user.options']['loginTemplate']) && !isset($app['user.options']['templates']['login'])) { $options['templates']['login'] = $app['user.options']['loginTemplate']; } if (isset($app['user.options']['registerTemplate']) && !isset($app['user.options']['templates']['register'])) { $options['templates']['register'] = $app['user.options']['registerTemplate']; } if (isset($app['user.options']['viewTemplate']) && !isset($app['user.options']['templates']['view'])) { $options['templates']['view'] = $app['user.options']['viewTemplate']; } if (isset($app['user.options']['editTemplate']) && !isset($app['user.options']['templates']['edit'])) { $options['templates']['edit'] = $app['user.options']['editTemplate']; } if (isset($app['user.options']['listTemplate']) && !isset($app['user.options']['templates']['list'])) { $options['templates']['list'] = $app['user.options']['listTemplate']; } } $app['user.options'] = $options; }); // Token generator. $app['user.tokenGenerator'] = $app->share(function ($app) { return new TokenGenerator($app['logger']); }); // User manager. $app['user.manager'] = $app->share(function ($app) { $app['user.options.init'](); $userManager = new UserManager($app->entityManager, $app); $userManager->setUserClass($app['user.options']['userClass']); $userManager->setUsernameRequired($app['user.options']['isUsernameRequired']); $userManager->setUserTableName($app['user.options']['userTableName']); $userManager->setUserCustomFieldsTableName($app['user.options']['userCustomFieldsTableName']); return $userManager; }); // Current user. $app['user'] = $app->share(function ($app) { return $app['user.manager']->getCurrentUser(); }); // User controller service. $app['user.controller'] = $app->share(function ($app) { $app['user.options.init'](); $controller = new UserController($app['user.manager']); $controller->setUsernameRequired($app['user.options']['isUsernameRequired']); $controller->setEmailConfirmationRequired($app['user.options']['emailConfirmation']['required']); $controller->setTemplates($app['user.options']['templates']); $controller->setEditCustomFields($app['user.options']['editCustomFields']); return $controller; }); // User mailer. $app['user.mailer'] = $app->share(function ($app) { $app['user.options.init'](); $missingDeps = array(); if (!isset($app['mailer'])) { $missingDeps[] = 'SwiftMailerServiceProvider'; } if (!isset($app['url_generator'])) { $missingDeps[] = 'UrlGeneratorServiceProvider'; } if (!isset($app['twig'])) { $missingDeps[] = 'TwigServiceProvider'; } if (!empty($missingDeps)) { throw new \RuntimeException('To access the SimpleUser mailer you must enable the following missing dependencies: ' . implode(', ', $missingDeps)); } $mailer = new Mailer($app['mailer'], $app['url_generator'], $app['twig']); $mailer->setFromAddress($app['user.options']['mailer']['fromEmail']['address'] ?: null); $mailer->setFromName($app['user.options']['mailer']['fromEmail']['name'] ?: null); $mailer->setConfirmationTemplate($app['user.options']['emailConfirmation']['template']); $mailer->setResetTemplate($app['user.options']['passwordReset']['template']); $mailer->setResetTokenTtl($app['user.options']['passwordReset']['tokenTTL']); if (!$app['user.options']['mailer']['enabled']) { $mailer->setNoSend(true); } return $mailer; }); // Add a custom security voter to support testing user attributes. $app['security.voters'] = $app->extend('security.voters', function ($voters) use($app) { foreach ($voters as $voter) { if ($voter instanceof RoleHierarchyVoter) { $roleHierarchyVoter = $voter; break; } } $voters[] = new EditUserVoter($roleHierarchyVoter); return $voters; }); // Helper function to get the last authentication exception thrown for the given request. // It does the same thing as $app['security.last_error'](), // except it returns the whole exception instead of just $exception->getMessage() $app['user.last_auth_exception'] = $app->protect(function (Request $request) { if ($request->attributes->has(SecurityContextInterface::AUTHENTICATION_ERROR)) { return $request->attributes->get(SecurityContextInterface::AUTHENTICATION_ERROR); } $session = $request->getSession(); if ($session && $session->has(SecurityContextInterface::AUTHENTICATION_ERROR)) { $exception = $session->get(SecurityContextInterface::AUTHENTICATION_ERROR); $session->remove(SecurityContextInterface::AUTHENTICATION_ERROR); return $exception; } }); }
public function testChangeUserColumns() { $this->userManager->setUserColumns(array('email' => 'foo')); $this->assertEquals('"foo"', $this->userManager->getUserColumns('email')); }