Add a user

@Route("/add", name="KunstmaanUserManagementBundle_settings_users_add", methods={"GET", "POST"})
@Template("@KunstmaanUserManagement/Users/add.html.twig")

@param \Symfony\Component\HttpFoundation\Request $request

@return array
766705
public function addAction(Request $request)
    {
        $this->denyAccessUnlessGranted('ROLE_SUPER_ADMIN');

        $user = $this->getUserClassInstance();

        $options = array('password_required' => true, 'langs' => $this->container->getParameter('kunstmaan_admin.admin_locales'), 'validation_groups' => array('Registration'), 'data_class' => get_class($user));
        $formTypeClassName = $user->getFormTypeClass();
        $formType = new $formTypeClassName();

        if ($formType instanceof RoleDependentUserFormInterface) {
            // to edit groups and enabled the current user should have ROLE_SUPER_ADMIN
            $options['can_edit_all_fields'] = $this->isGranted('ROLE_SUPER_ADMIN');
        }

        $form = $this->createForm(
            $formTypeClassName,
            $user,
            $options
        );

        if ($request->isMethod('POST')) {
            $form->handleRequest($request);
            if ($form->isSubmitted() && $form->isValid()) {
                $user->setPasswordChanged(true);
                /* @var UserManager $userManager */
                $userManager = $this->container->get('fos_user.user_manager');
                $userManager->updateUser($user, true);

                $this->addFlash(
                    FlashTypes::SUCCESS,
                    $this->container->get('translator')->trans('kuma_user.users.add.flash.success.%username%', [
                        '%username%' => $user->getUsername(),
                    ])
                );

                return new RedirectResponse($this->generateUrl('KunstmaanUserManagementBundle_settings_users'));
            }
        }

        return array(
            'form' => $form->createView(),
        );
    }
718394
public function register(Request $request)
    {
        $attributes = request()->validate(User::$rules);

        // create new user
        $user = User::create([
            'firstname'          => $attributes['firstname'],
            'lastname'           => $attributes['lastname'],
            'email'              => $attributes['email'],
            'password'           => bcrypt($attributes['password']),
            'confirmation_token' => 'confirmation_token', // will generate a new unique token
        ]);

        // add user roles
        // send email
        // log activity
        event(new UserRegistered($user, input('token')));

        alert()->success('Thank you,',
            'your account has been created, please check your inbox for further instructions.');

        log_activity('Register', $user->fullname . ' registered.');

        return redirect(route('login'));
    }
263027
public function updateValueAction(Request $request)
    {
        $name = $request->get('name');
        $value = $request->get('value');

        $manager = $this->get('ongr_settings.settings_manager');
        $manager->update($name, ['value' => $value]);

        return new JsonResponse(['error' => false]);
    }
23399
public function update(Request $request)
    {
        $user = \App\User::findOrfail($request->user_id);

        $user->email = $request->email;
        $user->name = $request->name;
        $user->password = Hash::make($request->password);

        $user->save();

        return redirect('scaffold-users');
    }
364069
public function register(Request $request)
    {
        $user = new User();
        $form = $this
            ->createForm(new UserRegistrationType(), $user)
            ->handleRequest($request)
        ;

        //@TODO: Check if username and email are unique

        if($form->isSubmitted() && $form->isValid()) {
            $helper = new UserHelper($this->container);
            $helper->setPassword($user, $user->getPassword());

            $user->setRegistrationToken(hash("sha1",rand()));
            $user->setRegistrationTime(new \DateTime());

            $groupRepository = $this->getDoctrine()->getRepository('FOMUserBundle:Group');
            foreach($this->container->getParameter('fom_user.self_registration_groups') as $groupTitle) {
                $group = $groupRepository->findOneByTitle($groupTitle);
                if($group) {
                    $user->addGroups($group);
                } else {
                    $msg = sprintf('Self-registration group "%s" not found for user "%s"',
                        $groupTitle,
                        $user->getUsername());
                    $this->get('logger')->err($msg);
                }

            }

            $this->sendEmail($user);

            $em = $this->getDoctrine()->getManager();
            $em->persist($user);
            $em->flush();

            $helper->giveOwnRights($user);

            return $this->redirect($this->generateUrl('fom_user_registration_send'));
        }

        return array(
            'user' => $user,
            'form' => $form->createView(),
            'form_name' => $form->getName());
    }
894140
public function updateAction(Request $request)
    {
        $schemaAlias = $request->attributes->get('schema');

        $this->isGrantedOr403($schemaAlias);

        $settingsManager = $this->getSettingsManager();
        $settings = $settingsManager->load($schemaAlias);

        $isApiRequest = $this->isApiRequest($request);

        $form = $this
            ->getSettingsFormFactory()
            ->create($schemaAlias, $settings, $isApiRequest ? ['csrf_protection' => false] : [])
        ;

        if ($form->handleRequest($request)->isValid()) {
            $messageType = 'success';
            try {
                $settingsManager->save($settings);
                $message = $this->getTranslator()->trans('sylius.settings.update', [], 'flashes');
            } catch (ValidatorException $exception) {
                $message = $this->getTranslator()->trans($exception->getMessage(), [], 'validators');
                $messageType = 'error';
            }

            if ($isApiRequest) {
                return $this->handleView($this->view(null, Response::HTTP_NO_CONTENT));
            }

            $request->getSession()->getBag('flashes')->add($messageType, $message);

            if ($request->headers->has('referer')) {
                return $this->redirect($request->headers->get('referer'));
            }
        }

        return $this->render($request->attributes->get('template', 'SyliusSettingsBundle:Settings:update.html.twig'), [
            'settings' => $settings,
            'form' => $form->createView(),
        ]);
    }
781625
public function getCurrentUserStructureAction(Request $request)
    {
        $ret = [
          "meta_fields" => $this->listUserAuthorizedMetadataFields($this->getAuthenticatedUser()),
          "aggregable_fields" => $this->buildUserFieldList(ElasticsearchOptions::getAggregableTechnicalFields(), ['choices']),
          "technical_fields" => $this->buildUserFieldList(media_subdef::getTechnicalFieldsList()),
        ];

        return Result::create($request, $ret)->createResponse();
    }
499543
public function register(Request $request): Response
    {
        $contentTypeIdentifier = $this->getConfigResolver()->getParameter('user.content_type_identifier', 'ngsite');
        $contentType = $this->getRepository()->getContentTypeService()->loadContentTypeByIdentifier($contentTypeIdentifier);
        $languages = $this->getConfigResolver()->getParameter('languages');
        $userCreateStruct = $this->userService->newUserCreateStruct(
            null,
            null,
            null,
            $languages[0],
            $contentType
        );

        $userCreateStruct->enabled = (bool) $this->getConfigResolver()->getParameter('user.auto_enable', 'ngsite');
        $userCreateStruct->alwaysAvailable = (bool) $contentType->defaultAlwaysAvailable;

        $data = new DataWrapper($userCreateStruct, $userCreateStruct->contentType);

        $formBuilder = $this->formFactory->createBuilder(
            CreateUserType::class,
            $data,
            [
                'translation_domain' => 'ngsite_user',
            ]
        );

        $form = $formBuilder->getForm();
        $form->handleRequest($request);

        if (!$form->isValid()) {
            return $this->render(
                $this->getConfigResolver()->getParameter('template.user.register', 'ngsite'),
                [
                    'form' => $form->createView(),
                ]
            );
        }

        $users = $this->userService->loadUsersByEmail($form->getData()->payload->email);

        if (!empty($users)) {
            return $this->render(
                $this->getConfigResolver()->getParameter('template.user.register', 'ngsite'),
                [
                    'form' => $form->createView(),
                    'error' => 'email_in_use',
                ]
            );
        }

        try {
            $this->userService->loadUserByLogin($form->getData()->payload->login);

            return $this->render(
                $this->getConfigResolver()->getParameter('template.user.register', 'ngsite'),
                [
                    'form' => $form->createView(),
                    'error' => 'username_taken',
                ]
            );
        } catch (NotFoundException $e) {
            // do nothing
        }

        $userGroupId = $this->getConfigResolver()->getParameter('user.user_group_content_id', 'ngsite');

        $preUserRegisterEvent = new UserEvents\PreRegisterEvent($data->payload);
        $this->eventDispatcher->dispatch(SiteEvents::USER_PRE_REGISTER, $preUserRegisterEvent);
        $data->payload = $preUserRegisterEvent->getUserCreateStruct();

        /** @var \eZ\Publish\API\Repository\Values\User\User $newUser */
        $newUser = $this->getRepository()->sudo(
            static function (Repository $repository) use ($data, $userGroupId): User {
                $userGroup = $repository->getUserService()->loadUserGroup($userGroupId);

                return $repository->getUserService()->createUser(
                    $data->payload,
                    [$userGroup]
                );
            }
        );

        $userRegisterEvent = new UserEvents\PostRegisterEvent($newUser);
        $this->eventDispatcher->dispatch(SiteEvents::USER_POST_REGISTER, $userRegisterEvent);

        if ($newUser->enabled) {
            return $this->render(
                $this->getConfigResolver()->getParameter('template.user.register_success', 'ngsite')
            );
        }

        if ($this->getConfigResolver()->getParameter('user.require_admin_activation', 'ngsite')) {
            return $this->render(
                $this->getConfigResolver()->getParameter('template.user.activate_admin_activation_pending', 'ngsite')
            );
        }

        return $this->render(
            $this->getConfigResolver()->getParameter('template.user.activate_sent', 'ngsite')
        );
    }
613309
public function editAction(Request $request)
    {
        $user = $this->getUser();
        $form = $this->createForm(
            UserProfileType::class,
            $user,
            [
                'label' => 'user.profile.title',
                'action' => $this->getCurrentUri($request),
                'attr' => [
                    'novalidate' => 'novalidate',
                ],
                'method' => 'post',
            ]
        );

        $form->handleRequest($request);
        if ($form->isSubmitted() && $form->isValid()) {
            $this->get(UserManagerInterface::class)->save($user);

            $this->addFlash('success', 'eavmanager.flash.edit.success');

            return $this->redirectToRoute(
                'eavmanager_user.profile.edit',
                [
                    'id' => $user->getId(),
                ]
            );
        }

        return [
            'form' => $form->createView(),
            'user' => $user,
        ];
    }
1105597
public function add($request)
    {
        $this->onBefore($request);
        array_push($this->_requests, $request);
        curl_multi_add_handle($this->_mh, $request->curl);
        $this->_updated = true;
    }
348637
public function loadUserGroups(Request $request)
    {
        $restUserGroups = array();
        if ($request->query->has('id')) {
            $userGroup = $this->userService->loadUserGroup($request->query->get('id'), Language::ALL);
            $userGroupContentInfo = $userGroup->getVersionInfo()->getContentInfo();
            $userGroupMainLocation = $this->locationService->loadLocation($userGroupContentInfo->mainLocationId);
            $contentType = $this->contentTypeService->loadContentType($userGroupContentInfo->contentTypeId);

            $restUserGroups = array(
                new Values\RestUserGroup(
                    $userGroup,
                    $contentType,
                    $userGroupContentInfo,
                    $userGroupMainLocation,
                    $this->contentService->loadRelations($userGroup->getVersionInfo())
                ),
            );
        } elseif ($request->query->has('roleId')) {
            $restUserGroups = $this->loadUserGroupsAssignedToRole($request->query->get('roleId'));
        } elseif ($request->query->has('remoteId')) {
            $restUserGroups = array(
                $this->loadUserGroupByRemoteId($request),
            );
        }

        if ($this->getMediaType($request) === 'application/vnd.ez.api.usergrouplist') {
            return new Values\UserGroupList($restUserGroups, $request->getPathInfo());
        }

        return new Values\UserGroupRefList($restUserGroups, $request->getPathInfo());
    }
1258040
public function registerAction(Request $request)
    {
        /** @var UserManager $userManager */
        $userManager = $this->get('sik_industries.user_manager');
        $user = $userManager->createUser();
        $form = $this->createForm(new UserRegistrationForm(), $user);
        $form->submit($request);

        if ($form->isValid()) {
            /** @var EQM $eqm */
            $userManager->insert($user);

            $response = $this->redirect($this->generateUrl('dashboard'));
        } else {
            $response = ['form' => $form->createView()];
        }

        return $response;
    }
919483
public function loadUserGroupByRemoteId(Request $request)
    {
        $contentInfo = $this->contentService->loadContentInfoByRemoteId($request->query->get('remoteId'));
        $userGroup = $this->userService->loadUserGroup($contentInfo->id, Language::ALL);
        $userGroupLocation = $this->locationService->loadLocation($contentInfo->mainLocationId);
        $contentType = $this->contentTypeService->loadContentType($contentInfo->contentTypeId);

        return new Values\RestUserGroup(
            $userGroup,
            $contentType,
            $contentInfo,
            $userGroupLocation,
            $this->contentService->loadRelations($userGroup->getVersionInfo())
        );
    }
152456
private function setRequest(Request $request)
    {
        $this->mergeVisitorActivityData([
            'method'      => $request->method(),
            'is_ajax'     => $request->ajax(),
            'is_secure'   => $request->isSecure(),
            'is_json'     => $request->isJson(),
            'wants_json'  => $request->wantsJson(),
        ]);

        $this->request = $request;

        return $this;
    }
1118493
public function get(Request $request)
    {
        $userEntity = $request->attributes->get('user');

        if ($userEntity === null) {
            $userEntity = $this->getUser();
        } elseif ($userEntity === false) {
            return $this->createNotFoundResponse();
        }

        return $this->userArrayWithoutPassword($userEntity);
    }
100215
public function postProfile(Request $request)
    {
        $user = $this->getAuthenticatedUser();

        if ($this->service->update($user->id, $request->all())) {
            return response()->json(compact('user'));
        }

        return response()->json(['error' => 'Could not update user']);
    }
300977
public function postAction(Request $request)
    {
        try {
            $this->checkArguments($request);
            $locale = $this->getRequestParameter($request, 'locale', true);
            $data = $request->request->all();
            $data['contactId'] = $request->query->get('contactId');
            $user = $this->getUserManager()->save($data, $locale);
            $view = $this->view($user, 200);
        } catch (UsernameNotUniqueException $exc) {
            $view = $this->view($exc->toArray(), 409);
        } catch (MissingPasswordException $exc) {
            $view = $this->view($exc->toArray(), 400);
        } catch (EmailNotUniqueException $exc) {
            $view = $this->view($exc->toArray(), 409);
        } catch (RestException $re) {
            $view = $this->view($re->toArray(), 400);
        }

        $this->addSerializationGroups($view);

        return $this->handleView($view);
    }