/** * Checks for a new password and rehashes if necessary * * @param User $entity * @param PasswordEncoderInterface $encoder * @param string $submittedPassword * * @return string */ public function checkNewPassword(User $entity, PasswordEncoderInterface $encoder, $submittedPassword) { if (!empty($submittedPassword)) { //hash the clear password submitted via the form return $encoder->encodePassword($submittedPassword, $entity->getSalt()); } return $entity->getPassword(); }
/** * @param mixed $response * * @return mixed */ public function getUser($response) { $url = 'https://www.googleapis.com/oauth2/v1/userinfo?alt=json'; if ($userDetails = $this->makeRequest($url, array(), 'GET', array('override_auth_token' => $response['access_token'], 'append_auth_token' => true))) { if (isset($userDetails['email'])) { $user = new User(); $user->setUsername($userDetails['email'])->setEmail($userDetails['email'])->setFirstName($userDetails['given_name'])->setLastName($userDetails['family_name'])->setRole($this->getUserRole()); return $user; } } return false; }
/** * Authenticate via the form using users defined in authorized_users * * @param AuthenticationEvent $event * * @return bool|void */ public function onUserFormAuthentication(AuthenticationEvent $event) { $username = $event->getUsername(); $password = $event->getToken()->getCredentials(); $user = new User(); $user->setUsername($username); $authorizedUsers = $this->parametersHelper->getParameter('authorized_users'); if (is_array($authorizedUsers) && isset($authorizedUsers[$username])) { $testUser = $authorizedUsers[$username]; $user->setPassword($testUser['password']); if ($this->encoder->isPasswordValid($user, $password)) { $user->setFirstName($testUser['firstname'])->setLastName($testUser['lastname'])->setEmail($testUser['email'])->setRole($this->em->getReference('MauticUserBundle:Role', 1)); $event->setIsAuthenticated('authorized_users', $user, true); } } }
/** * @param ObjectManager $manager */ public function load(ObjectManager $manager) { $user = new User(); $user->setFirstName('Admin'); $user->setLastName('User'); $user->setUsername('admin'); $user->setEmail('*****@*****.**'); $encoder = $this->container->get('security.encoder_factory')->getEncoder($user); $user->setPassword($encoder->encodePassword('mautic', $user->getSalt())); $user->setRole($this->getReference('admin-role')); $manager->persist($user); $manager->flush(); $this->addReference('admin-user', $user); $user = new User(); $user->setFirstName('Sales'); $user->setLastName('User'); $user->setUsername('sales'); $user->setEmail('*****@*****.**'); $encoder = $this->container->get('security.encoder_factory')->getEncoder($user); $user->setPassword($encoder->encodePassword('mautic', $user->getSalt())); $user->setRole($this->getReference('sales-role')); $manager->persist($user); $manager->flush(); $this->addReference('sales-user', $user); }
/** * Get the path to specified area. Returns relative by default with the exception of cache and log * which will be absolute regardless of $fullPath setting. * * @param string $name * @param bool $fullPath * * @return string * * @throws \InvalidArgumentException */ public function getSystemPath($name, $fullPath = false) { if ($name == 'currentTheme' || $name == 'current_theme') { $path = $this->paths['themes'] . '/' . $this->theme; } elseif ($name == 'cache' || $name == 'logs') { //these are absolute regardless as they are configurable return $name === 'cache' ? $this->kernelCacheDir : $this->kernelLogsDir; } elseif ($name == 'images') { $path = $this->imagePath; if (substr($path, -1) === '/') { $path = substr($path, 0, -1); } } elseif ($name == 'dashboard.user' || $name == 'dashboard.global') { //these are absolute regardless as they are configurable $globalPath = $this->dashboardImportDir; if (substr($globalPath, -1) === '/') { $globalPath = substr($globalPath, 0, -1); } if ($name == 'dashboard.global') { return $globalPath; } if (!($userPath = $this->dashboardUserImportDir)) { $userPath = $globalPath; } elseif (substr($userPath, -1) === '/') { $userPath = substr($userPath, 0, -1); } $userPath .= '/' . $this->user->getId(); // @todo check is_writable if (!is_dir($userPath) && !file_exists($userPath)) { mkdir($userPath, 0755); } return $userPath; } elseif (isset($this->paths[$name])) { $path = $this->paths[$name]; } elseif (strpos($name, '_root') !== false) { // Assume system root if one is not set specifically $path = $this->paths['root']; } else { throw new \InvalidArgumentException("{$name} does not exist."); } if ($fullPath) { $rootPath = !empty($this->paths[$name . '_root']) ? $this->paths[$name . '_root'] : $this->paths['root']; return $rootPath . '/' . $path; } return $path; }
/** * Get a lead's upcoming events. * * @param array $options * * @return array * * @throws \Doctrine\ORM\NoResultException * @throws \Doctrine\ORM\NonUniqueResultException */ public function getUpcomingEvents(array $options = null) { $leadIps = []; $query = $this->_em->getConnection()->createQueryBuilder(); $today = new DateTimeHelper(); $query->from(MAUTIC_TABLE_PREFIX . 'campaign_lead_event_log', 'll')->select('ll.event_id, ll.campaign_id, ll.trigger_date, ll.lead_id, e.name AS event_name, e.description AS event_description, c.name AS campaign_name, c.description AS campaign_description, CONCAT(CONCAT(l.firstname, \' \'), l.lastname) AS lead_name')->leftJoin('ll', MAUTIC_TABLE_PREFIX . 'campaign_events', 'e', 'e.id = ll.event_id')->leftJoin('ll', MAUTIC_TABLE_PREFIX . 'campaigns', 'c', 'c.id = e.campaign_id')->leftJoin('ll', MAUTIC_TABLE_PREFIX . 'leads', 'l', 'l.id = ll.lead_id')->where($query->expr()->gte('ll.trigger_date', ':today'))->setParameter('today', $today->toUtcString()); if (isset($options['lead'])) { /** @var \Mautic\CoreBundle\Entity\IpAddress $ip */ foreach ($options['lead']->getIpAddresses() as $ip) { $leadIps[] = $ip->getId(); } $query->andWhere('ll.lead_id = :leadId')->setParameter('leadId', $options['lead']->getId()); } if (isset($options['scheduled'])) { $query->andWhere('ll.is_scheduled = :scheduled')->setParameter('scheduled', $options['scheduled'], 'boolean'); } if (isset($options['eventType'])) { $query->andwhere('e.event_type = :eventType')->setParameter('eventType', $options['eventType']); } if (isset($options['type'])) { $query->andwhere('e.type = :type')->setParameter('type', $options['type']); } if (isset($options['limit'])) { $query->setMaxResults($options['limit']); } else { $query->setMaxResults(10); } $query->orderBy('ll.trigger_date'); if (!empty($ipIds)) { $query->orWhere('ll.ip_address IN (' . implode(',', $ipIds) . ')'); } if (!empty($options['canViewOthers']) && isset($this->currentUser)) { $query->andWhere('c.created_by = :userId')->setParameter('userId', $this->currentUser->getId()); } return $query->execute()->fetchAll(); }
/** * @param \Doctrine\ORM\QueryBuilder $q * @param object $filter * * @return array */ protected function addStandardSearchCommandWhereClause(&$q, $filter) { $command = $filter->command; $unique = $this->generateRandomParameterName(); $returnParameter = true; //returning a parameter that is not used will lead to a Doctrine error $expr = false; $prefix = $this->getTableAlias(); switch ($command) { case $this->translator->trans('mautic.core.searchcommand.ispublished'): $expr = $q->expr()->eq("{$prefix}.isPublished", ":{$unique}"); $forceParameters = array($unique => true); break; case $this->translator->trans('mautic.core.searchcommand.isunpublished'): $expr = $q->expr()->eq("{$prefix}.isPublished", ":{$unique}"); $forceParameters = array($unique => false); break; case $this->translator->trans('mautic.core.searchcommand.isuncategorized'): $expr = $q->expr()->orX($q->expr()->isNull("{$prefix}.category"), $q->expr()->eq("{$prefix}.category", $q->expr()->literal(''))); $returnParameter = false; break; case $this->translator->trans('mautic.core.searchcommand.ismine'): $expr = $q->expr()->eq("IDENTITY({$prefix}.createdBy)", $this->currentUser->getId()); $returnParameter = false; break; case $this->translator->trans('mautic.core.searchcommand.category'): $expr = $q->expr()->like("c.alias", ":{$unique}"); $filter->strict = true; break; } if ($expr && $filter->not) { $expr = $q->expr()->not($expr); } if (!empty($forceParameters)) { $parameters = $forceParameters; } elseif (!$returnParameter) { $parameters = array(); } else { $string = $filter->strict ? $filter->string : "%{$filter->string}%"; $parameters = array("{$unique}" => $string); } return array($expr, $parameters); }
/** * Set checkedOutBy * * @param User $checkedOutBy * * @return mixed */ public function setCheckedOutBy($checkedOutBy = null) { if ($checkedOutBy != null && !$checkedOutBy instanceof User) { $this->checkedOutBy = $checkedOutBy; } else { $this->checkedOutBy = $checkedOutBy != null ? $checkedOutBy->getId() : null; if ($checkedOutBy != null) { $this->checkedOutByUser = $checkedOutBy->getName(); } } return $this; }
/** * @param User $user * * @return string */ protected function getResetToken(User $user) { /** @var \DateTime $lastLogin */ $lastLogin = $user->getLastLogin(); $dateTime = $lastLogin instanceof \DateTime ? $lastLogin->format('Y-m-d H:i:s') : null; return hash('sha256', $user->getUsername() . $user->getEmail() . $dateTime); }
/** * @param User $user * * @return array */ public function getUserClients(User $user) { $query = $this->createQueryBuilder($this->getTableAlias()); $query->join('c.users', 'u')->where($query->expr()->eq('u.id', ':userId'))->setParameter('userId', $user->getId()); return $query->getQuery()->getResult(); }
/** * @param \Doctrine\ORM\QueryBuilder $q * @param object $filter * * @return array */ protected function addStandardSearchCommandWhereClause(&$q, $filter) { $command = $filter->command; $unique = $this->generateRandomParameterName(); $returnParameter = true; //returning a parameter that is not used will lead to a Doctrine error $expr = false; $prefix = $this->getTableAlias(); switch ($command) { case $this->translator->trans('mautic.core.searchcommand.ispublished'): $expr = $q->expr()->eq("{$prefix}.isPublished", ":{$unique}"); $forceParameters = array($unique => true); break; case $this->translator->trans('mautic.core.searchcommand.isunpublished'): $expr = $q->expr()->eq("{$prefix}.isPublished", ":{$unique}"); $forceParameters = array($unique => false); break; case $this->translator->trans('mautic.core.searchcommand.isuncategorized'): $expr = $q->expr()->orX($q->expr()->isNull("{$prefix}.category"), $q->expr()->eq("{$prefix}.category", $q->expr()->literal(''))); $returnParameter = false; break; case $this->translator->trans('mautic.core.searchcommand.ismine'): $expr = $q->expr()->eq("IDENTITY({$prefix}.createdBy)", $this->currentUser->getId()); $returnParameter = false; break; case $this->translator->trans('mautic.core.searchcommand.category'): // Find the category prefix $joins = $q->getDQLPart('join'); $catPrefix = false; foreach ($joins as $joinPrefix => $joinStatements) { /** @var Query\Expr\Join $join */ foreach ($joinStatements as $join) { if (strpos($join->getJoin(), '.category') !== false) { $catPrefix = $join->getAlias(); break; } } if ($catPrefix !== false) { break; } } if (false === $catPrefix) { $catPrefix = 'c'; } $expr = $q->expr()->like("{$catPrefix}.alias", ":{$unique}"); $filter->strict = true; break; } if ($expr && $filter->not) { $expr = $q->expr()->not($expr); } if (!empty($forceParameters)) { $parameters = $forceParameters; } elseif (!$returnParameter) { $parameters = array(); } else { $string = $filter->strict ? $filter->string : "%{$filter->string}%"; $parameters = array("{$unique}" => $string); } return array($expr, $parameters); }
/** * Converts menu config into something KNP menus expects * * @param $items * @param int $depth * @param int $defaultPriority */ public function createMenuStructure(&$items, $depth = 0, $defaultPriority = 9999) { foreach ($items as $k => &$i) { if (!is_array($i) || empty($i)) { continue; } if (isset($i['bundle'])) { // Category shortcut $bundleName = $i['bundle']; $i = ['access' => $bundleName . ':categories:view', 'route' => 'mautic_category_index', 'id' => 'mautic_' . $bundleName . 'category_index', 'routeParameters' => ['bundle' => $bundleName]]; } // Check to see if menu is restricted if (isset($i['access'])) { if ($i['access'] == 'admin') { if (!$this->user->isAdmin()) { unset($items[$k]); continue; } } elseif (!$this->security->isGranted($i['access'], 'MATCH_ONE')) { unset($items[$k]); continue; } } if (isset($i['checks'])) { $passChecks = true; foreach ($i['checks'] as $checkGroup => $checks) { foreach ($checks as $name => $value) { if ($checkGroup == 'parameters') { if ($this->getParameter($name) != $value) { $passChecks = false; break; } } elseif ($checkGroup == 'request') { if ($this->request->get($name) != $value) { $passChecks = false; break; } } } } if (!$passChecks) { unset($items[$k]); continue; } } //Set ID to route name if (!isset($i['id'])) { if (!empty($i['route'])) { $i['id'] = $i['route']; } else { $i['id'] = 'menu-item-' . uniqid(); } } //Set link attributes if (!isset($i['linkAttributes'])) { $i['linkAttributes'] = ['data-menu-link' => $i['id'], 'id' => $i['id']]; } elseif (!isset($i['linkAttributes']['id'])) { $i['linkAttributes']['id'] = $i['id']; $i['linkAttributes']['data-menu-link'] = $i['id']; } elseif (!isset($i['linkAttributes']['data-menu-link'])) { $i['linkAttributes']['data-menu-link'] = $i['id']; } $i['extras'] = []; $i['extras']['depth'] = $depth; // Note a divider if (!empty($i['divider'])) { $i['extras']['divider'] = true; } // Note a header if (!empty($i['header'])) { $i['extras']['header'] = $i['header']; } //Set the icon class for the menu item if (!empty($i['iconClass'])) { $i['extras']['iconClass'] = $i['iconClass']; } //Set the actual route name so that it's available to the menu template if (isset($i['route'])) { $i['extras']['routeName'] = $i['route']; } //Repeat for sub items if (isset($i['children'])) { $this->createMenuStructure($i['children'], $depth + 1, $defaultPriority); } // Determine if this item needs to be listed in a bundle outside it's own if (isset($i['parent'])) { if (!isset($this->orphans[$i['parent']])) { $this->orphans[$i['parent']] = []; } $this->orphans[$i['parent']][$k] = $i; unset($items[$k]); // Don't set a default priority here as it'll assume that of it's parent } elseif (!isset($i['priority'])) { // Ensure a priority for non-orphans $i['priority'] = $defaultPriority; } } }
/** * @param mixed $response * * @return mixed */ public function getUser($response) { if ($userDetails = $this->makeRequest('https://api.github.com/user', array(), 'GET', array('override_auth_token' => $response['access_token'], 'append_auth_token' => true))) { if (isset($userDetails['login'])) { $names = explode(' ', $userDetails['name']); if (count($names) > 1) { $firstname = $names[0]; unset($names[0]); $lastname = implode(' ', $names); } else { $firstname = $lastname = $names[0]; } // Get email $emails = $this->makeRequest('https://api.github.com/user/emails', array(), 'GET', array('override_auth_token' => $response['access_token'], 'append_auth_token' => true)); if (is_array($emails) && count($emails)) { foreach ($emails as $ghEmail) { if ($ghEmail['primary']) { $email = $ghEmail['email']; break; } } } if (empty($email)) { // Email could not be found so bail return false; } $user = new User(); $user->setUsername($userDetails['login'])->setEmail($email)->setFirstName($firstname)->setLastName($lastname)->setRole($this->getUserRole()); return $user; } } return false; }
/** * {@inheritDoc} */ public function __toString() { $this->__initializer__ && $this->__initializer__->__invoke($this, '__toString', array()); return parent::__toString(); }
/** * Create/update user from authentication plugins. * * @param User $user * @param bool|true $createIfNotExists * * @return User */ public function saveUser(User $user, $createIfNotExists = true) { $isNew = !$user->getId(); if ($isNew) { // Check if user exists and create one if applicable try { $user = $this->loadUserByUsername($user->getUsername(), $user->getEmail()); } catch (UsernameNotFoundException $exception) { if (!$createIfNotExists) { throw new BadCredentialsException(); } } } // Validation for User objects returned by a plugin if (!$user->getRole()) { throw new AuthenticationException('mautic.integration.sso.error.no_role'); } if (!$user->getUsername()) { throw new AuthenticationException('mautic.integration.sso.error.no_username'); } if (!$user->getEmail()) { throw new AuthenticationException('mautic.integration.sso.error.no_email'); } if (!$user->getFirstName() || !$user->getLastName()) { throw new AuthenticationException('mautic.integration.sso.error.no_name'); } // Check for plain password $plainPassword = $user->getPlainPassword(); if ($plainPassword) { // Encode plain text $user->setPassword($this->encoder->getEncoder($user)->encodePassword($plainPassword, $user->getSalt())); } elseif (!($password = $user->getPassword())) { // Generate and encode a random password $user->setPassword($this->encoder->getEncoder($user)->encodePassword(EncryptionHelper::generateKey(), $user->getSalt())); } $event = new UserEvent($user, $isNew); if ($this->dispatcher->hasListeners(UserEvents::USER_PRE_SAVE)) { $event = $this->dispatcher->dispatch(UserEvents::USER_PRE_SAVE, $event); } $this->userRepository->saveEntity($user); if ($this->dispatcher->hasListeners(UserEvents::USER_POST_SAVE)) { $this->dispatcher->dispatch(UserEvents::USER_POST_SAVE, $event); } return $user; }