Register a new user from the front-end registration form

Use the LaSalle Command Bus

@param  \Illuminate\Http\Request  $request
@return \Illuminate\Http\Response
519804
public function postRegister(Request $request) {

        if (config('lasallecmsusermanagement.auth_users_registration_front_end_require_terms_of_service')) {
            if (!$request->input('terms-of-service')) {
                return redirect()->route('auth.register')
                    ->withInput($request->only('name', 'email', 'phone_country_code', 'phone_number'))
                    ->withErrors([
                        'terms-of-service' => 'Please read our Terms of Service',
                    ]);
            }
        }

        $response = $this->dispatchFrom(CreateRegisterUserCommand::class, $request);

        Session::flash('status_code', $response['status_code'] );

        if ($response['status_text'] == "validation_failed") {
            Session::flash('message', $response['errorMessages']->first());
            // Return to the edit form with error messages
            return Redirect::back()
                ->withInput($response['data'])
                ->withErrors($response['errorMessages']);
        }

        if ($response['status_text'] == "persist_failed") {
            $message = "Processing error. Please try again.";
            Session::flash('message', $message);
            // Return to the edit form with error messages
            return Redirect::back()
                ->withInput($response['data'])
                ->withErrors($message);
        }

        // User registration was successful


        // Login registrant
        if (config('lasallecmsusermanagement.auth_frontend_registration_successful_auto_login')) {
            $userId = $this->userRepository->findUserIdByEmail($response['data']['email']);
            Auth::loginUsingId($userId);
        }


        // Fire the custom event
        event(new FrontendRegistrationWasSuccessful($response));


        // Display the registration confirmation view, if the config says so
        if (config('auth.auth_display_register_confirmation_view_after_successful_frontend_registration')) {
            return view('usermanagement::frontend.'.$this->frontend_template_name.'.register_confirmed.register_confirmed', [
                'title'          => 'Register Confirmation',
                'username'       => strtoupper($response['data']['name']),
                'isUserLoggedIn' => Auth::check(),
            ]);
        }


        // $name = strtoupper($response['data']['name']);
        $message = 'You successfully registered!';
        Session::flash('message', $message);

        return Redirect::route('home');
    }
420448
protected function registered(Request $request, $user)
    {
        $survUser = User::find($user->id);
        $log = new SLUsersActivity;
        $log->UserActUser = $survUser->id;
        $adminRoleID = 15; // but let's double-check this system
        $admDef = SLDefinitions::where('DefDatabase', 1)
            ->where('DefSet', 'User Roles')
            ->where('DefSubset', 'administrator')
            ->first();
        if ($admDef && isset($admDef->DefID)) {
            $adminRoleID = $admDef->DefID;
        }
        $hasAdmins = SLUsersRoles::where('RoleUserRID', $adminRoleID) // role id of 'administrator'
            ->get();
        if ($hasAdmins->isEmpty()) {
            $survUser->assignRole('administrator');
            $log->UserActCurrPage = 'NEW SYSTEM ADMINISTRATOR!';
        } elseif ($request->has('newVolunteer') && intVal($request->newVolunteer) == 1) {
            $survUser->assignRole('volunteer');
            $log->UserActCurrPage = 'NEW VOLUNTEER!';
        }
        $log->save();
        $domainPath = '';
        $appUrl = SLDefinitions::where('DefDatabase', 1)
            ->where('DefSet', 'System Settings')
            ->where('DefSubset', 'app-url')
            ->first();
        if ($appUrl && isset($appUrl->DefDescription)) {
            $domainPath = $appUrl->DefDescription;
        }
        if ($request->has('previous') && trim($request->get('previous')) != '') {
            session()->put('redirLoginSurvey', time());
            session()->put('previousUrl', trim($request->get('previous')));
        }
        return redirect($domainPath . '/afterLogin');
    }
62058
public function createAccountAction(Request $request)
    {
        $selfRegistration = $this
            ->get('claroline.config.platform_config_handler')
            ->getParameter('allow_self_registration');
        if ($selfRegistration) {
            $session = $request->getSession();
            $service = $session->get('claroline.oauth.resource_owner');
            $translator = $this->get('translator');
            $translator->setLocale($request->getLocale());

            return $this->get('claroline.oauth.manager')->createNewAccount($request, $translator, $service);
        }

        return $this->redirectToRoute('claco_oauth_check_connexion');
    }
1359255
public function register(Request $request, EventDispatcherInterface $dispatcher, TranslatorInterface $translator, UserPasswordEncoderInterface $encoder, \Swift_Mailer $mailer)
    {
        // Check Auth
        if ($this->checkAuth()) {
            return $this->redirectToRoute($this->getParameter('pd_user.login_redirect'));
        }

        // Check Disable Register
        if (!$this->getParameter('pd_user.user_registration')) {
            $this->addFlash('error', $translator->trans('security.registration_disable'));

            return $this->redirectToRoute('security_login');
        }

        // Create User
        $user = $this->getParameter('pd_user.user_class');
        $user = new $user();
        if (!$user instanceof UserInterface) {
            throw new InvalidArgumentException();
        }

        // Dispatch Register Event
        if ($response = $dispatcher->dispatch(UserEvent::REGISTER_BEFORE, new UserEvent($user))->getResponse()) {
            return $response;
        }

        // Create Form
        $form = $this->createForm($this->getParameter('pd_user.register_type'), $user, [
            'profile_class' => $this->getParameter('pd_user.profile_class')
        ]);

        // Handle Form Submit
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            // Get Doctrine
            $em = $this->getDoctrine()->getManager();

            // Encode Password
            $password = $encoder->encodePassword($user, $form->get('plainPassword')->getData());
            $user->setPassword($password);

            // User Confirmation
            if ($this->getParameter('pd_user.email_confirmation')) {
                // Disable User
                $user->setEnabled(false);

                // Create Confirmation Token
                if (empty($user->getConfirmationToken()) || null === $user->getConfirmationToken()) {
                    $user->createConfirmationToken();
                }

                // Send Confirmation Email
                $emailBody = [
                    'confirmationUrl' => $this->generateUrl('security_register_confirm',
                        ['token' => $user->getConfirmationToken()],
                        UrlGeneratorInterface::ABSOLUTE_URL),
                ];
                $this->sendEmail($user, $mailer, 'Account Confirmation', $emailBody, 'Register');
            } else {
                // Send Welcome
                if ($this->getParameter('pd_user.welcome_email')) {
                    $this->sendEmail($user, $mailer, 'Registration', 'Welcome', 'Welcome');
                }
            }

            // User Add Default Group
            if ($group = $this->getParameter('pd_user.default_group')) {
                $getGroup = $em->getRepository($this->getParameter('pd_user.group_class'))->find($group);
                if ((null !== $getGroup) and $getGroup instanceof GroupInterface) {
                    $user->addGroup($getGroup);
                }
            }

            // Save User
            $em->persist($user);
            $em->flush();

            // Dispatch Register Event
            if ($response = $dispatcher->dispatch(UserEvent::REGISTER, new UserEvent($user))->getResponse()) {
                return $response;
            }

            // Register Success
            return $this->render($this->getParameter('pd_user.template_path') . '/Registration/registerSuccess.html.twig', [
                'user' => $user,
            ]);
        }

        // Render
        return $this->render($this->getParameter('pd_user.template_path') . '/Registration/register.html.twig', [
            'form' => $form->createView(),
        ]);
    }
727811
public function createAction(Request $request)
    {
        $entity = new User();
        $form = $this->createCreateForm($entity);
        $form->handleRequest($request);

        if ($form->isValid()) {
            $userService = $this->get("flowcode.user");
            $userService->create($entity);

            return $this->redirect($this->generateUrl('admin_user_show', array('id' => $entity->getId())));
        }

        return array(
            'entity' => $entity,
            'form' => $form->createView(),
        );
    }
22927
public function createAction(Request $request)
    {
        $this->isAllowed('BUSINESS_MANAGE_ROLE');

        $model = new RegistrationRole();
        $form = $this->createCreateForm($model);
        $form->handleRequest($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();

            $selectedApps = array();
            foreach ($model->applications as $selectedApp) {
                $selectedApps[] = $selectedApp->getId();
            }

            foreach ($model->rolesByApplication as $app) {
                if (in_array($app->getId(), $selectedApps)) {
                    $permissions = null === $app->getRole()
                        ? array()
                        : $app->getRole()->getPermissions();

                    $role = new Role();
                    $role->setName($model->role->getName());
                    $role->setApplication($app);
                    $role->setPermissions($permissions);
                    $em->persist($role);
                }
            }

            $em->flush();
            $this->get('session')->getFlashBag()->add('success', 'role.flash.created');

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

        return $this->render('CanalTPSamEcoreSecurityBundle:Role:new.html.twig', array(
            'entity' => $model,
            'form'   => $form->createView(),
        ));
    }
1098013
public function postLogin(Request $request)
    {

        $this->validate($request, ['username' => 'required|min:3|max:255', 'password' => 'required',]);

        $credentials = $request->only('username', 'password');
        $credentials[ 'enabled' ] = 1;

        if (Auth::attempt($credentials, $request->has('remember'))) {
            return redirect()->intended($this->getRedirectUrl());
        } else {
            return redirect(route('login'))->withInput($request->except(['password']))
                                           ->withErrors([$this->getFailedLoginMessage()]);
        }

    }
391082
public function sendEmailAction(Request $request)
    {
        $username = $request->request->get('username');

        /** @var $userManager \FOS\UserBundle\Model\UserManagerInterface */
        $userManager = $this->get('fos_user.user_manager');

        $user = $userManager->findUserByUsernameOrEmail($username);

        $ttl = $this->container->getParameter('fos_user.resetting.retry_ttl');

        if (null !== $user && !$user->isPasswordRequestNonExpired($ttl)) {
            if (!$user->isAccountNonLocked()) {
                return new RedirectResponse($this->get('router')->generate('networking_init_cms_admin_resetting_request'));
            }

            if (null === $user->getConfirmationToken()) {
                /** @var $tokenGenerator TokenGeneratorInterface */
                $tokenGenerator = $this->get('fos_user.util.token_generator');
                $user->setConfirmationToken($tokenGenerator->generateToken());
            }

            $this->sendResettingEmailMessage($user);
            $user->setPasswordRequestedAt(new \DateTime());
            $userManager->updateUser($user);
        }

        return new RedirectResponse($this->generateUrl('networking_init_cms_admin_resetting_check_email', [
            'username' => $username,
        ]));
    }
1173425
public function activationForm(Request $request): Response
    {
        $form = $this->createActivationForm();
        $form->handleRequest($request);

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

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

        $activationRequestEvent = new UserEvents\ActivationRequestEvent(
            $form->get('email')->getData(),
            $users[0] ?? null
        );

        $this->eventDispatcher->dispatch(SiteEvents::USER_ACTIVATION_REQUEST, $activationRequestEvent);

        return $this->render(
            $this->getConfigResolver()->getParameter('template.user.activate_sent', 'ngsite')
        );
    }
765702
public function login (Request $request, User $user, $registration = false)
    {
        // Check for email validation
        if ($this->requiresEmailValidation()) {
            if (!$user->isEmailVerified()) {
                $request->getSession()->set ('catlab-non-verified-user-id', $user->getId());
                return Response::redirect(URLBuilder::getURL($this->routepath . '/notverified'));
            }
        }

        $request->getSession()->set('catlab-user-id', $user->getId());
        return $this->postLogin($request, $user, $registration);
    }
282794
public function register(Request $request, Users $users)
    {
        // if registration is closed, deny access
        if (!config('back-project.registration_open')) {
            abort(403, trans('back-project::base.registration_closed'));
        }
        $this->validator($request->all())->validate();
        //$this->guard()->login($this->create($request->all()));
        $user = $users->create($request->all());

        event(new Registered($user->id));

        if ($users->getModel()->count() == 1) {
            $user->assignRole('administrator');
        } else {
            $user->assignRole('user');
        }

        Alert::add('success', trans('back-project::base.registration_email'))->flash();

        return redirect(route('login'));
    }
250964
public function registration(Request $request)
    {
        if (!config('laraflock.dashboard.registration')) {
            Flash::error(trans('dashboard::dashboard.flash.registration.not_active'));

            return redirect()->route('auth.login');
        }

        try {
            $this->authRepositoryInterface->register($request->all());
        } catch (FormValidationException $e) {
            Flash::error($e->getMessage());

            return redirect()
              ->route('auth.register')
              ->withErrors($e->getErrors())
              ->withInput();
        } catch (RolesException $e) {
            Flash::error($e->getMessage());

            return redirect()
              ->route('auth.register')
              ->withInput();
        }

        if (!config('laraflock.dashboard.activations')) {
            Flash::success(trans('dashboard::dashboard.flash.registration.activated'));

            return redirect()->route('auth.login');
        }

        Flash::success(trans('dashboard::dashboard.flash.registration.created'));

        return redirect()->route('auth.login');
    }
1106670
public function registerAction($request)
    {
        $modelUser = new ModelUser();
        $data = $request->get('data');
        $error = false;

        if ($this->isAuthenticated()) {
            $this->setMessage('error', 'You are logged in');
            $error = true;
        }

        if (!filter_var($data['model']['email'], FILTER_VALIDATE_EMAIL)) {
            $this->setMessage('error', 'That is not an Email');
            $error = true;
        }

        if ($modelUser->findByName($data['model']['username'])) {
            $this->setMessage('error', 'Your account exists');
            $error = true;
        }

        if ($modelUser->findByEmail($data['model']['email'])) {
            $this->setMessage('error', 'Your Email is already registered');
            $error = true;
        }

        if (empty($data['model']['password'])) {
            $this->setMessage('error', 'You need to select a password');
            $error = true;
        }

        if (empty($data['model']['email'])) {
            $this->setMessage('error', 'You need to select an email');
            $error = true;
        }

        if (empty($data['model']['username'])) {
            $this->setMessage('error', 'You need to select an User Name');
            $error = true;
        }

        if (!$error) {
            $modelUser->resetObject();
            $modelUser->username = $data['model']['username'];
            $modelUser->password = md5($data['model']['password']);
            $modelUser->email = $data['model']['email'];
            $modelUser->address = $data['model']['address'];
            $modelUser->phone = $data['model']['phone'];
            $modelUser->save();
            return $this->twig()->render('user\registerAction.twig');
        } else {
            return $this->twig()->render('user\register.twig', array(
                'data' => $data
            ));
        }

    }
646023
public function register(Request $request)
    {
        $data = $request->only('email', 'password');

        return DB::transaction(function() use ($data) {
            $user = User::create([
                'name' => $data['email'],
                'email' => $data['email'],
                'password' => bcrypt($data['password']),
            ]);

            $user = $this->service->create($user, $data['password']);
            $token = JWTAuth::fromUser($user);

            return response()->json(compact('token'));
        });
    }
1116320
public function postRegister(RegisterRequest $request)
    {
        if (! \Setting::get('user::enable-registration')) {
            return redirect()->route('login');
        }

        \Auth::login($this->create($request->all()));

        return redirect($this->redirectPath());
    }
1146905
public function store(Request $request)
    {
        // Validate the form data
        $result = $this->validate($request, [
            'email' => 'required|email|max:255|unique:users',
            'password' => 'required|confirmed|min:6',
        ]);

        // Assemble registration credentials and attributes
        $credentials = [
            'email' => trim($request->get('email')),
            'password' => $request->get('password'),
            'first_name' => $request->get('first_name', null),
            'last_name' => $request->get('last_name', null)
        ];
        $activate = (bool)$request->get('activate', false);

        // Attempt the registration
        $result = $this->authManager->register($credentials, $activate);

        if ($result->isFailure()) {
            return $result->dispatch;
        }

        // Do we need to send an activation email?
        if (!$activate) {
            $code = $result->activation->getCode();
            $email = $result->user->email;
            Mail::to($email)->queue(new CentaurWelcomeEmail($email, $code));
        }

        // Assign User Roles
        foreach ($request->get('roles', []) as $slug => $id) {
            $role = Sentinel::findRoleBySlug($slug);
            if ($role) {
                $role->users()->attach($result->user);
            }
        }

        $result->setMessage("User {$request->get('email')} has been created.");
        return $result->dispatch(route('users.index'));
    }
1066190
public function store(Request $request)
    {
        $this->authorize('create', Ticket::class);
        $this->validate($request, [
            'email'   => 'required|exists:users,email|not_in:'.Auth::user()->email,
            'subject' => 'required|max:255',
            'message' => 'required|max:2500',
        ]);

        $user = User::where('email', $request->email)->first();

        $ticket = Ticket::create([
            'subject'  => $request->subject,
            'user_id'  => User::where('email', $request->email)->first()->id,
            'open'     => true,
            'admin_id' => Auth::id(),
        ]);

        if (Settings::first()->text_editor == 'markdown') {
            $msg = Markdown::convertToHtml($request->message);
        } elseif (Settings::first()->text_editor == 'wysiwyg') {
            $msg = $request->message;
        } else {
            $msg = htmlentities($request->message);
        }

        Message::create([
            'message'   => $msg,
            'ticket_id' => $ticket->id,
            'user_id'   => Auth::id(),
        ]);

        return redirect()->route('laralum::tickets.show', ['ticket' => $ticket->id])
            ->with('success', __('laralum_tickets::general.created'));
    }