/**
  * @EXT\Route(
  *     "/login",
  *     name="claro_o365_login"
  * )
  *
  * @return RedirectResponse
  */
 public function loginAction()
 {
     $this->authHelper->GetAuthenticationHeaderFor3LeggedFlow($_GET['code']);
     $jsonResponse = $this->graphHelper->getMeEntry();
     $userResponse = new O365ResponseUser($jsonResponse);
     $userManager = $this->get('claroline.manager.user_manager');
     $email = $userResponse->getEmail();
     $user = $userManager->getUserByEmail($email);
     if ($user === null) {
         $missingProperties = $userResponse->validate();
         if (count($missingProperties) > 0) {
             return $this->render('FormaLibreOfficeConnectBundle:Authentication:missingProperties.html.twig', ['missingProperties' => $missingProperties]);
         }
         $user = new User();
         $user->setFirstName($userResponse->getNickname());
         $user->setLastName($userResponse->getRealName());
         $user->setUsername($userResponse->getUsername());
         $user->setPlainPassword($userResponse->getEmail());
         $user->setMail($userResponse->getEmail());
         $user->setIsMailValidated(true);
         $userManager->createUser($user, false);
     }
     $userRepo = $this->get('doctrine.orm.entity_manager')->getRepository('ClarolineCoreBundle:User');
     $securityContext = $this->get('security.context');
     $userLoaded = $userRepo->loadUserByUsername($user->getUsername());
     $providerKey = 'main';
     $token = new UsernamePasswordToken($userLoaded, $userLoaded->getPassword(), $providerKey, $userLoaded->getRoles());
     $securityContext->setToken($token);
     $userManager->logUser($user);
     return $this->get('claroline.authentication_handler')->onAuthenticationSuccess($this->get('request'), $token);
 }
Beispiel #2
0
 /**
  * {@inheritDoc}
  */
 public function load(ObjectManager $objectManager)
 {
     /** @var \Claroline\CoreBundle\Manager\UserManager $userCreator */
     $userCreator = $this->container->get('claroline.manager.user_manager');
     /** @var \Claroline\CoreBundle\Manager\RoleManager $roleManager */
     $roleManager = $this->container->get('claroline.manager.role_manager');
     /** @var \Claroline\CoreBundle\Repository\ResourceNodeRepository $resourceRepo */
     $resourceRepo = $objectManager->getRepository('ClarolineCoreBundle:Resource\\ResourceNode');
     foreach ($this->users as $names => $role) {
         $namesArray = explode(' ', $names);
         $firstName = $namesArray[0];
         $lastName = isset($namesArray[1]) ? $namesArray[1] : '';
         $username = $firstName . ucfirst($lastName);
         $user = new User();
         $user->setAdministrativeCode('UCL-' . $username . '-' . rand(0, 1000));
         $user->setFirstName($firstName);
         $lastName = $lastName == '' ? 'Doe' : $lastName;
         $user->setLastName($lastName);
         $user->setUserName($username);
         $user->setPlainPassword($username);
         $user->setMail('mail_' . uniqid() . '@claroline.net');
         $objectManager->persist($user);
         $roleManager->associateRole($user, $this->getReference("role/{$role}"));
         if ($this->withWorkspace) {
             $userCreator->createUser($user);
             $this->addReference("workspace/{$names}", $user->getPersonalWorkspace());
             $this->addReference("directory/{$names}", $resourceRepo->findWorkspaceRoot($user->getPersonalWorkspace()));
         } else {
             $objectManager->persist($user);
         }
         $this->addReference("user/{$names}", $user);
         $objectManager->flush();
     }
 }
Beispiel #3
0
 /**
  * @param string $username
  *
  * @return User
  */
 public function user($username, $withWorkspace = false)
 {
     $user = new User();
     $user->setFirstName($username);
     $user->setLastName($username);
     $user->setUsername($username);
     $user->setPassword($username);
     $user->setMail($username . '@mail.com');
     $user->setGuid($username);
     $this->om->persist($user);
     if (!$this->userRole) {
         $this->userRole = $this->role('ROLE_USER');
         $this->om->persist($this->userRole);
     }
     $user->addRole($this->userRole);
     if ($withWorkspace) {
         $workspace = new Workspace();
         $workspace->setName($username);
         $workspace->setCreator($user);
         $workspace->setCode($username);
         $workspace->setGuid($username);
         $this->om->persist($workspace);
         $user->setPersonalWorkspace($workspace);
     }
     return $user;
 }
Beispiel #4
0
 public function user($username)
 {
     $user = new User();
     $user->setFirstName($username);
     $user->setLastName($username);
     $user->setUsername($username);
     $user->setPassword($username);
     $user->setMail($username . '@mail.com');
     $user->setGuid($username);
     $this->om->persist($user);
     if (!$this->userRole) {
         $this->userRole = new Role();
         $this->userRole->setName('ROLE_USER');
         $this->userRole->setTranslationKey('user');
         $this->om->persist($this->userRole);
     }
     $user->addRole($this->userRole);
     $workspace = new Workspace();
     $workspace->setName($username);
     $workspace->setCreator($user);
     $workspace->setCode($username);
     $workspace->setGuid($username);
     $this->om->persist($workspace);
     $user->setPersonalWorkspace($workspace);
     $this->om->flush();
     return $user;
 }
Beispiel #5
0
 private function buildUser($firstName, $lastName)
 {
     $user = new User();
     $user->setFirstName($firstName);
     $user->setLastName($lastName);
     $user->setUsername($username = strtolower($firstName . $lastName));
     $user->setPassword($username);
     $user->setMail("{$username}@mail.com");
     return $user;
 }
 protected function persistUser($username)
 {
     $user = new User();
     $user->setFirstName($username);
     $user->setLastName($username);
     $user->setUsername($username);
     $user->setPassword($username);
     $user->setMail($username . '@mail.com');
     $this->om->persist($user);
     return $user;
 }
Beispiel #7
0
 public function load(ObjectManager $manager)
 {
     $userManager = $this->container->get('claroline.manager.user_manager');
     foreach ($this->users as $properties) {
         $user = new User();
         $user->setUsername($properties['username']);
         $user->setPlainPassword($properties['username']);
         $user->setFirstName($properties['username']);
         $user->setLastName($properties['username']);
         $user->setMail($properties['username'] . '@claroline.net');
         $user->setLocale('en');
         $userManager->createUserWithRole($user, $properties['role']);
     }
 }
Beispiel #8
0
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $user = new User();
     $user->setFirstName($input->getArgument('user_first_name'));
     $user->setLastName($input->getArgument('user_last_name'));
     $user->setUsername($input->getArgument('user_username'));
     $user->setPlainPassword($input->getArgument('user_password'));
     $user->setMail($input->getArgument('user_username') . '@claro.net');
     if ($input->getOption('admin')) {
         $roleName = PlatformRoles::ADMIN;
     } elseif ($input->getOption('ws_creator')) {
         $roleName = PlatformRoles::WS_CREATOR;
     } else {
         $roleName = PlatformRoles::USER;
     }
     $this->getContainer()->get('claroline.manager.user_manager')->createUserWithRole($user, $roleName);
 }
Beispiel #9
0
 /**
  * @param string $username
  *
  * @return User
  */
 public function user($username)
 {
     $roleUser = $this->om->getRepository('ClarolineCoreBundle:Role')->findOneByName('ROLE_USER');
     $user = new User();
     $user->setFirstName($username);
     $user->setLastName($username);
     $user->setUsername($username);
     $user->setPlainPassword($username);
     $user->setMail($username . '@mail.com');
     $user->setGuid(uniqid());
     $user->addRole($roleUser);
     $user->setPublicUrl($username);
     $user->setCreationDate(new \DateTime());
     $this->container->get('claroline.manager.role_manager')->createUserRole($user);
     $this->om->persist($user);
     $this->om->flush();
     return $user;
 }
Beispiel #10
0
 /**
  * @param string $username
  * @return User
  */
 public function user($username)
 {
     $roleUser = $this->om->getRepository('ClarolineCoreBundle:Role')->findOneByName('ROLE_USER');
     if (!$roleUser) {
         $this->role('ROLE_USER');
         $this->om->flush();
         //we really need it
     }
     $user = new User();
     $user->setFirstName($username);
     $user->setLastName($username);
     $user->setUsername($username);
     $user->setPassword($username);
     $user->setMail($username . '@mail.com');
     //much better
     $this->container->get('claroline.manager.user_manager')->createUser($user, false);
     return $user;
 }
 private function getFromProviders(TokenInterface $token, $providerKey)
 {
     $drivers = $this->authenticationManager->getDrivers();
     foreach ($drivers as $driver) {
         $found = $this->authenticationManager->authenticate($driver, $token->getUsername(), $token->getCredentials());
         if ($found) {
             $data = $this->authenticationManager->findUser($driver, $token->getUsername());
             $user = new User();
             $user->setFirstName($data['first_name']);
             $user->setPlainPassword($data['password']);
             $user->setLastName($data['last_name']);
             $user->setUsername($data['username']);
             $user->setMail($data['email']);
             $user->setAuthentication($driver);
             $iser = $this->userManager->createUser($user, false);
             return new UsernamePasswordToken($user, $user->getPassword(), $providerKey, $user->getRoles());
         }
     }
     throw new AuthenticationException('Invalid username or password');
 }
Beispiel #12
0
 /**
  * @param $username
  *
  * @return User
  */
 public function user($username)
 {
     $user = new User();
     $user->setFirstName($username);
     $user->setLastName($username);
     $user->setUsername($username);
     $user->setPassword($username);
     $user->setMail($username . '@mail.com');
     $user->setGuid($username);
     $this->om->persist($user);
     $user->addRole($this->userRole);
     $workspace = new Workspace();
     $workspace->setName($username);
     $workspace->setCreator($user);
     $workspace->setCode($username);
     $workspace->setGuid($username);
     $this->om->persist($workspace);
     $user->setPersonalWorkspace($workspace);
     return $user;
 }
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $user = new User();
     $user->setFirstName($input->getArgument('user_first_name'));
     $user->setLastName($input->getArgument('user_last_name'));
     $user->setUsername($input->getArgument('user_username'));
     $user->setPlainPassword($input->getArgument('user_password'));
     $email = $input->getArgument('user_email');
     $email = filter_var($email, FILTER_VALIDATE_EMAIL) ? $email : $email . '@debug.net';
     $user->setMail($email);
     if ($input->getOption('admin')) {
         $roleName = PlatformRoles::ADMIN;
     } elseif ($input->getOption('ws_creator')) {
         $roleName = PlatformRoles::WS_CREATOR;
     } else {
         $roleName = PlatformRoles::USER;
     }
     $userManager = $this->getContainer()->get('claroline.manager.user_manager');
     $consoleLogger = ConsoleLogger::get($output);
     $userManager->setLogger($consoleLogger);
     $userManager->createUser($user, false, [$roleName]);
 }
Beispiel #14
0
 public function user($username)
 {
     $user = new User();
     $user->setFirstName($username);
     $user->setLastName($username);
     $user->setUsername($username);
     $user->setPassword($username);
     $user->setMail($username . '@mail.com');
     $user->setGuid($username);
     $user->setPublicUrl($username);
     $this->om->persist($user);
     if (!$this->userRole) {
         $this->userRole = $this->om->getRepository('ClarolineCoreBundle:Role')->findOneByName('ROLE_USER');
     }
     $user->addRole($this->userRole);
     $workspace = new Workspace();
     $workspace->setName($username);
     $workspace->setCreator($user);
     $workspace->setCode($username);
     $workspace->setGuid($username);
     $this->om->persist($workspace);
     $user->setPersonalWorkspace($workspace);
     return $user;
 }
 /**
  * @Route("/new/user.{format}", name = "claro_register_user")
  * @Method({"POST"})
  */
 public function postUserRegistrationAction($format)
 {
     $formats = array('json', 'xml');
     if (!in_array($format, $formats)) {
         return new Response("The format {$format} is not supported (supported formats are 'json', 'xml')", 400);
     }
     $status = 200;
     $content = array();
     if ($this->configHandler->getParameter('allow_self_registration')) {
         $request = $this->request;
         $user = new User();
         $user->setUsername($request->request->get('username'));
         $user->setPlainPassword($request->request->get('password'));
         $user->setFirstName($request->request->get('firstName'));
         $user->setLastName($request->request->get('lastName'));
         $user->setMail($request->request->get('mail'));
         $errorList = $this->validator->validate($user);
         if (count($errorList) > 0) {
             $status = 422;
             foreach ($errorList as $error) {
                 $content[] = array('property' => $error->getPropertyPath(), 'message' => $error->getMessage());
             }
         } else {
             $this->userManager->createUser($user);
         }
     } else {
         $status = 403;
     }
     return $format === 'json' ? new JsonResponse($content, $status) : new XmlResponse($content, $status);
 }
 /**
  * @EXT\Route(
  *     "/oauth/v2/log/{name}",
  *     name="claro_oauth_log"
  * )
  */
 public function logAction($name)
 {
     $authCode = $this->container->get('request')->query->get('code');
     $curlManager = $this->container->get('claroline.manager.curl_manager');
     $friendRequest = $this->container->get('claroline.manager.oauth_manager')->findFriendRequestByName($name);
     $access = $friendRequest->getClarolineAccess();
     $redirect = $this->container->get('request')->getSchemeAndHttpHost() . $this->container->get('router')->getContext()->getBaseUrl() . '/oauth/v2/log/' . $name;
     //request the token
     $url = $friendRequest->getHost() . '/oauth/v2/token?client_id=' . urlencode($access->getRandomId()) . '&client_secret=' . urlencode($access->getSecret()) . '&grant_type=authorization_code&redirect_uri=' . urlencode($redirect) . '&code=' . urlencode($authCode);
     $data = json_decode($curlManager->exec($url), true);
     if (isset($data['error'])) {
         return new RedirectResponse($this->container->get('router')->generate('claro_security_login'));
     }
     $accessToken = $data['access_token'];
     //maybe store the user token one way or an other ?
     $url = $friendRequest->getHost() . '/api/connected_user?access_token=' . $accessToken;
     $data = $curlManager->exec($url);
     $data = json_decode($data, true);
     $email = $data['mail'];
     $userRepo = $this->container->get('doctrine.orm.entity_manager')->getRepository('ClarolineCoreBundle:User');
     $users = $userRepo->findByMail($email);
     if (count($users) === 0) {
         $username = $data['username'];
         $users = $userRepo->findByUsername($username);
         if (count($users) > 0) {
             $username .= uniqd();
         }
         $user = new User();
         $user->setUsername($username);
         $user->setMail($email);
         $user->setFirstName($data['first_name']);
         $user->setLastName($data['last_name']);
         $pw = uniqid();
         $user->setPlainPassword($pw);
         $user = $this->container->get('claroline.manager.user_manager')->createUser($user, false);
     } else {
         $user = $users[0];
     }
     $this->container->get('claroline.authenticator')->authenticate($user->getUsername(), null, false);
     return new RedirectResponse($this->container->get('router')->generate('claro_desktop_open'));
 }
 protected static function createUser($name, array $roles = array(), Workspace $personalWorkspace = null)
 {
     $user = new User();
     $user->setFirstName($name . 'FirstName');
     $user->setLastName($name . 'LastName');
     $user->setUsername($name . 'Username');
     $user->setPlainPassword($name . 'Password');
     $user->setMail($name . '@claroline.net');
     $user->setCreationDate(self::$time);
     foreach ($roles as $role) {
         $user->addRole($role);
     }
     if ($personalWorkspace) {
         $user->setPersonalWorkspace($personalWorkspace);
     }
     self::create($name, $user);
 }
Beispiel #18
0
 public function validate($value, Constraint $constraint)
 {
     $mode = $constraint->getDefaultOption();
     $lines = str_getcsv(file_get_contents($value), PHP_EOL);
     $authDrivers = $this->authenticationManager->getDrivers();
     foreach ($lines as $line) {
         $linesTab = explode(';', $line);
         $nbElements = count($linesTab);
         if (trim($line) != '') {
             if ($nbElements < 5) {
                 $this->context->addViolation($constraint->message);
                 return;
             }
         }
     }
     $usernames = array();
     $mails = array();
     if ($mode === 1) {
         $currentDate = new \DateTime();
         $timestamp = $currentDate->getTimestamp();
         $fakeUsername = '******' . $timestamp . '@@@';
         $fakeMail = 'fake_email_' . $timestamp . '@fake-' . $timestamp . '-claroline-connect.com';
     }
     foreach ($lines as $i => $line) {
         if (trim($line) != '') {
             $user = explode(';', $line);
             $firstName = $user[0];
             $lastName = $user[1];
             $username = $user[2];
             $pwd = $user[3];
             $email = $user[4];
             if (isset($user[5])) {
                 $code = trim($user[5]) === '' ? null : $user[5];
             } else {
                 $code = null;
             }
             if (isset($user[6])) {
                 $phone = trim($user[6]) === '' ? null : $user[6];
             } else {
                 $phone = null;
             }
             if (isset($user[7])) {
                 $authentication = trim($user[7]) === '' ? null : $user[7];
             } else {
                 $authentication = null;
             }
             if (isset($user[8])) {
                 $modelName = trim($user[7]) === '' ? null : $user[7];
             } else {
                 $modelName = null;
             }
             !array_key_exists($email, $mails) ? $mails[$email] = array($i + 1) : ($mails[$email][] = $i + 1);
             !array_key_exists($username, $usernames) ? $usernames[$username] = array($i + 1) : ($usernames[$username][] = $i + 1);
             $existingUser = null;
             if ($mode === 1) {
                 try {
                     $existingUser = $this->userManager->getUserByUsernameOrMail($username, $email);
                 } catch (NonUniqueResultException $e) {
                     $msg = $this->translator->trans('line_number', array('%line%' => $i + 1), 'platform');
                     $msg .= ' ' . $this->translator->trans('username_and_email_from_two_different_users', array('%username%' => $username, '%email%' => $email), 'platform');
                     $this->context->addViolation($msg);
                     continue;
                 }
             }
             if (!is_null($existingUser)) {
                 // For an update, we will validate user with a fake username and email
                 $upperExistingUsername = strtoupper(trim($existingUser->getUsername()));
                 $upperExistingMail = strtoupper(trim($existingUser->getMail()));
                 $upperUsername = strtoupper(trim($username));
                 $upperMail = strtoupper(trim($email));
                 if ($upperExistingUsername === $upperUsername && $upperExistingMail === $upperMail) {
                     $existingUser->setUsername($fakeUsername);
                     $existingUser->setMail($fakeMail);
                 } elseif ($upperExistingUsername === $upperUsername) {
                     $existingUser->setUsername($fakeUsername);
                     $existingUser->setMail($email);
                 } else {
                     $existingUser->setUsername($username);
                     $existingUser->setMail($fakeMail);
                 }
                 $existingUser->setFirstName($firstName);
                 $existingUser->setLastName($lastName);
                 $existingUser->setPlainPassword($pwd);
                 $existingUser->setAdministrativeCode($code);
                 $existingUser->setPhone($phone);
                 $errors = $this->validator->validate($existingUser, array('registration', 'Default'));
                 $existingUser->setUsername($username);
                 $existingUser->setMail($email);
             } else {
                 $newUser = new User();
                 $newUser->setFirstName($firstName);
                 $newUser->setLastName($lastName);
                 $newUser->setUsername($username);
                 $newUser->setPlainPassword($pwd);
                 $newUser->setMail($email);
                 $newUser->setAdministrativeCode($code);
                 $newUser->setPhone($phone);
                 $errors = $this->validator->validate($newUser, array('registration', 'Default'));
             }
             if ($authentication) {
                 if (!in_array($authentication, $authDrivers)) {
                     $msg = $this->translator->trans('authentication_invalid', array('%authentication%' => $authentication, '%line%' => $i + 1), 'platform') . ' ';
                     $this->context->addViolation($msg);
                 }
             }
             foreach ($errors as $error) {
                 $this->context->addViolation($this->translator->trans('line_number', array('%line%' => $i + 1), 'platform') . ' ' . $error->getInvalidValue() . ' : ' . $error->getMessage());
             }
         }
     }
     if ($modelName) {
         $model = $this->om->getRepository('ClarolineCoreBundle:Model\\WorkspaceModel')->findOneByName($modelName);
         if (!$model) {
             $msg = $this->translator->trans('model_invalid', array('%model%' => $modelName, '%line%' => $i + 1), 'platform') . ' ';
             $this->context->addViolation($msg);
         }
     }
     foreach ($usernames as $username => $lines) {
         if (count($lines) > 1) {
             $msg = $this->translator->trans('username_found_at', array('%username%' => $username, '%lines%' => $this->getLines($lines)), 'platform') . ' ';
             $this->context->addViolation($msg);
         }
     }
     foreach ($mails as $mail => $lines) {
         if (count($lines) > 1) {
             $msg = $this->translator->trans('email_found_at', array('%email%' => $mail, '%lines%' => $this->getLines($lines)), 'platform') . ' ';
             $this->context->addViolation($msg);
         }
     }
 }
Beispiel #19
0
 /**
  * Import users from an array.
  * There is the array format:
  * @todo some batch processing
  *
  * array(
  *     array(firstname, lastname, username, pwd, email, code, phone),
  *     array(firstname2, lastname2, username2, pwd2, email2, code2, phone2),
  *     array(firstname3, lastname3, username3, pwd3, email3, code3, phone3),
  * )
  *
  * @param array    $users
  * @param string   $authentication an authentication source
  * @param boolean  $mail           do the users need to be mailed
  * @param \Closure $logger         an anonymous function allowing to log actions
  *
  * @return array
  */
 public function importUsers(array $users, $sendMail = true, $logger = null, $additionalRoles = array())
 {
     $returnValues = array();
     //keep these roles before the clear() will mess everything up. It's not what we want.
     $tmpRoles = $additionalRoles;
     $additionalRoles = [];
     //I need to do that to import roles from models. Please don't ask why, I have no f*****g idea.
     $this->objectManager->clear();
     foreach ($tmpRoles as $role) {
         if ($role) {
             $additionalRoles[] = $this->objectManager->merge($role);
         }
     }
     $roleUser = $this->roleManager->getRoleByName('ROLE_USER');
     $max = $roleUser->getMaxUsers();
     $total = $this->countUsersByRoleIncludingGroup($roleUser);
     if ($total + count($users) > $max) {
         throw new AddRoleException();
     }
     $lg = $this->platformConfigHandler->getParameter('locale_language');
     $this->objectManager->startFlushSuite();
     $i = 1;
     $j = 0;
     foreach ($users as $user) {
         $firstName = $user[0];
         $lastName = $user[1];
         $username = $user[2];
         $pwd = $user[3];
         $email = trim($user[4]);
         if (isset($user[5])) {
             $code = trim($user[5]) === '' ? null : $user[5];
         } else {
             $code = null;
         }
         if (isset($user[6])) {
             $phone = trim($user[6]) === '' ? null : $user[6];
         } else {
             $phone = null;
         }
         if (isset($user[7])) {
             $authentication = trim($user[7]) === '' ? null : $user[7];
         } else {
             $authentication = null;
         }
         if (isset($user[8])) {
             $modelName = trim($user[8]) === '' ? null : $user[8];
         } else {
             $modelName = null;
         }
         if ($modelName) {
             $model = $this->objectManager->getRepository('Claroline\\CoreBundle\\Entity\\Model\\WorkspaceModel')->findOneByName($modelName);
         } else {
             $model = null;
         }
         $newUser = new User();
         $newUser->setFirstName($firstName);
         $newUser->setLastName($lastName);
         $newUser->setUsername($username);
         $newUser->setPlainPassword($pwd);
         $newUser->setMail($email);
         $newUser->setAdministrativeCode($code);
         $newUser->setPhone($phone);
         $newUser->setLocale($lg);
         $newUser->setAuthentication($authentication);
         $this->createUser($newUser, $sendMail, $additionalRoles, $model, $username . uniqid());
         $this->objectManager->persist($newUser);
         $returnValues[] = $firstName . ' ' . $lastName;
         if ($logger) {
             $logger(" [UOW size: " . $this->objectManager->getUnitOfWork()->size() . "]");
         }
         if ($logger) {
             $logger(" User {$j} ({$username}) being created");
         }
         $i++;
         $j++;
         if ($i % self::MAX_USER_BATCH_SIZE === 0) {
             if ($logger) {
                 $logger(" [UOW size: " . $this->objectManager->getUnitOfWork()->size() . "]");
             }
             $this->objectManager->forceFlush();
             if ($logger) {
                 $logger(" flushing users...");
             }
             $tmpRoles = $additionalRoles;
             $this->objectManager->clear();
             $additionalRoles = [];
             foreach ($tmpRoles as $toAdd) {
                 if ($toAdd) {
                     $additionalRoles[] = $this->objectManager->merge($toAdd);
                 }
             }
             if ($this->container->get('security.token_storage')->getToken()) {
                 $this->objectManager->merge($this->container->get('security.token_storage')->getToken()->getUser());
             }
         }
     }
     $this->objectManager->endFlushSuite();
     return $returnValues;
 }
Beispiel #20
0
 private function createAdminUser(ContainerInterface $container, OutputInterface $output)
 {
     $output->writeln('Creating first admin user...');
     $userManager = $container->get('claroline.manager.user_manager');
     $user = new User();
     $user->setFirstName($this->adminSettings->getFirstName());
     $user->setLastName($this->adminSettings->getLastName());
     $user->setUsername($this->adminSettings->getUsername());
     $user->setPlainPassword($this->adminSettings->getPassword());
     $user->setMail($this->adminSettings->getEmail());
     $roleAdmin = $container->get('claroline.manager.role_manager')->getRoleByName('ROLE_ADMIN');
     $userManager->createUser($user, false, array($roleAdmin));
 }
 private function createActivity($name)
 {
     $user = new User();
     $user->setFirstName('John');
     $user->setLastName('Doe');
     $user->setUsername('jdoe');
     $user->setMail('*****@*****.**');
     $user->setPassword('123');
     $workspace = new Workspace();
     $workspace->setName('w1');
     $workspace->setCode('abc');
     $workspace->setGuid('abc123');
     $workspace->setCreator($user);
     $type = new ResourceType();
     $type->setName('activity');
     $node = new ResourceNode();
     $node->setName($name);
     $node->setClass('FooClass');
     $node->setCreator($user);
     $node->setResourceType($type);
     $node->setWorkspace($workspace);
     $activity = new Activity();
     $activity->setResourceNode($node);
     $activity->setDescription('activity...');
     $this->om->persist($user);
     $this->om->persist($workspace);
     $this->om->persist($type);
     $this->om->persist($node);
     $this->om->persist($activity);
     return $activity;
 }
Beispiel #22
0
 /**
  * Import users from an array.
  * There is the array format:.
  *
  * @todo some batch processing
  *
  * array(
  *     array(firstname, lastname, username, pwd, email, code, phone),
  *     array(firstname2, lastname2, username2, pwd2, email2, code2, phone2),
  *     array(firstname3, lastname3, username3, pwd3, email3, code3, phone3),
  * )
  *
  * @param array    $users
  * @param string   $authentication an authentication source
  * @param bool     $mail           do the users need to be mailed
  * @param \Closure $logger         an anonymous function allowing to log actions
  *
  * @return array
  */
 public function importUsers(array $users, $sendMail = true, $logger = null, $additionalRoles = [], $enableEmailNotifaction = false, $options = [])
 {
     //build options
     if (!isset($options['ignore-update'])) {
         $options['ignore-update'] = false;
     }
     $returnValues = [];
     $skipped = [];
     //keep these roles before the clear() will mess everything up. It's not what we want.
     $tmpRoles = $additionalRoles;
     $additionalRoles = [];
     //I need to do that to import roles from models. Please don't ask why, I have no f*****g idea.
     $this->objectManager->clear();
     foreach ($tmpRoles as $role) {
         if ($role) {
             $additionalRoles[] = $this->objectManager->merge($role);
         }
     }
     $roleUser = $this->roleManager->getRoleByName('ROLE_USER');
     $max = $roleUser->getMaxUsers();
     $total = $this->countUsersByRoleIncludingGroup($roleUser);
     if ($total + count($users) > $max) {
         throw new AddRoleException();
     }
     $lg = $this->platformConfigHandler->getParameter('locale_language');
     $this->objectManager->startFlushSuite();
     $i = 1;
     $j = 0;
     $countCreated = 0;
     $countUpdated = 0;
     foreach ($users as $user) {
         $firstName = $user[0];
         $lastName = $user[1];
         $username = $user[2];
         $pwd = $user[3];
         $email = trim($user[4]);
         if (isset($user[5])) {
             $code = trim($user[5]) === '' ? null : $user[5];
         } else {
             $code = null;
         }
         if (isset($user[6])) {
             $phone = trim($user[6]) === '' ? null : $user[6];
         } else {
             $phone = null;
         }
         if (isset($user[7])) {
             $authentication = trim($user[7]) === '' ? null : $user[7];
         } else {
             $authentication = null;
         }
         if (isset($user[8])) {
             $modelName = trim($user[8]) === '' ? null : $user[8];
         } else {
             $modelName = null;
         }
         if (isset($user[9])) {
             $groupName = trim($user[9]) === '' ? null : $user[9];
         } else {
             $groupName = null;
         }
         if (isset($user[10])) {
             $organizationName = trim($user[10]) === '' ? null : $user[10];
         } else {
             $organizationName = null;
         }
         $hasPersonalWorkspace = isset($user[11]) ? (bool) $user[11] : false;
         $isMailValidated = isset($user[12]) ? (bool) $user[12] : false;
         $isMailNotified = isset($user[13]) ? (bool) $user[13] : $enableEmailNotifaction;
         if ($modelName) {
             $model = $this->objectManager->getRepository('Claroline\\CoreBundle\\Entity\\Model\\WorkspaceModel')->findOneByName($modelName);
         } else {
             $model = null;
         }
         if ($organizationName) {
             $organizations = [$this->objectManager->getRepository('Claroline\\CoreBundle\\Entity\\Organization\\Organization')->findOneByName($organizationName)];
         } else {
             $organizations = [];
         }
         $group = $groupName ? $this->groupManager->getGroupByName($groupName) : null;
         if ($groupName) {
             $group = $this->groupManager->getGroupByNameAndScheduledForInsert($groupName);
             if (!$group) {
                 $group = new Group();
                 $group->setName($groupName);
                 $group = $this->groupManager->insertGroup($group);
             }
         } else {
             $group = null;
         }
         $userEntity = $this->userRepo->findOneByMail($email);
         if (!$userEntity) {
             $userEntity = $this->userRepo->findOneByUsername($username);
             if (!$userEntity && $code !== null) {
                 //the code isn't required afaik
                 $userEntity = $this->userRepo->findOneByAdministrativeCode($code);
             }
         }
         if ($userEntity && $options['ignore-update']) {
             if ($logger) {
                 $logger(" Skipping  {$userEntity->getUsername()}...");
             }
             continue;
         }
         $isNew = false;
         if (!$userEntity) {
             $isNew = true;
             $userEntity = new User();
             $userEntity->setPlainPassword($pwd);
             ++$countCreated;
         } else {
             if (!empty($pwd)) {
                 $userEntity->setPlainPassword($pwd);
             }
             ++$countUpdated;
         }
         $userEntity->setUsername($username);
         $userEntity->setMail($email);
         $userEntity->setFirstName($firstName);
         $userEntity->setLastName($lastName);
         $userEntity->setAdministrativeCode($code);
         $userEntity->setPhone($phone);
         $userEntity->setLocale($lg);
         $userEntity->setAuthentication($authentication);
         $userEntity->setIsMailNotified($isMailNotified);
         $userEntity->setIsMailValidated($isMailValidated);
         if ($options['single-validate']) {
             $errors = $this->validator->validate($userEntity);
             if (count($errors) > 0) {
                 $skipped[$i] = $userEntity;
                 if ($isNew) {
                     --$countCreated;
                 } else {
                     --$countUpdated;
                 }
                 continue;
             }
         }
         if (!$isNew && $logger) {
             $logger(" User {$j} ({$username}) being updated...");
             $this->roleManager->associateRoles($userEntity, $additionalRoles);
         }
         if ($isNew) {
             if ($logger) {
                 $logger(" User {$j} ({$username}) being created...");
             }
             $this->createUser($userEntity, $sendMail, $additionalRoles, $model, $username . uniqid(), $organizations, $hasPersonalWorkspace, false);
         }
         $this->objectManager->persist($userEntity);
         $returnValues[] = $firstName . ' ' . $lastName;
         if ($group) {
             $this->groupManager->addUsersToGroup($group, [$userEntity]);
         }
         if ($logger) {
             $logger(' [UOW size: ' . $this->objectManager->getUnitOfWork()->size() . ']');
         }
         ++$i;
         ++$j;
         if ($i % self::MAX_USER_BATCH_SIZE === 0) {
             if ($logger) {
                 $logger(' [UOW size: ' . $this->objectManager->getUnitOfWork()->size() . ']');
             }
             $this->objectManager->forceFlush();
             if ($logger) {
                 $logger(' flushing users...');
             }
             $tmpRoles = $additionalRoles;
             $this->objectManager->clear();
             $additionalRoles = [];
             foreach ($tmpRoles as $toAdd) {
                 if ($toAdd) {
                     $additionalRoles[] = $this->objectManager->merge($toAdd);
                 }
             }
             if ($this->tokenStorage->getToken()) {
                 $this->objectManager->merge($this->tokenStorage->getToken()->getUser());
             }
         }
     }
     $this->objectManager->endFlushSuite();
     if ($logger) {
         $logger($countCreated . ' users created.');
         $logger($countUpdated . ' users updated.');
     }
     foreach ($skipped as $key => $user) {
         $logger('The user ' . $user . ' was skipped at line ' . $key . ' because it failed the validation pass.');
     }
     return $returnValues;
 }