User Signup

@method POST
@url /v1/users

@return Response
2241
public function signup() : Response
    {
        $user = $this->userModel;

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

        if (empty($request)) {
            $request = $this->request->getJsonRawBody(true);
        }

        $user->email = $this->request->getPost('email', 'email');
        $user->firstname = ltrim(trim($this->request->getPost('firstname', 'string')));
        $user->lastname = ltrim(trim($this->request->getPost('lastname', 'string')));
        $user->password = ltrim(trim($this->request->getPost('password', 'string')));
        $userIp = !defined('API_TESTS') ? $this->request->getClientAddress() : '127.0.0.1'; //help getting the client ip on scrutinizer :(
        $user->displayname = ltrim(trim($this->request->getPost('displayname', 'string')));
        $user->defaultCompanyName = ltrim(trim($this->request->getPost('default_company', 'string')));

        //Ok let validate user password
        $validation = new Validation();
        $validation->add('password', new PresenceOf(['message' => _('The password is required.')]));
        $validation->add('firstname', new PresenceOf(['message' => _('The firstname is required.')]));
        $validation->add('email', new EmailValidator(['message' => _('The email is not valid.')]));

        $validation->add(
            'password',
            new StringLength([
                'min' => 8,
                'messageMinimum' => _('Password is too short. Minimum 8 characters.'),
            ])
        );

        $validation->add('password', new Confirmation([
            'message' => _('Password and confirmation do not match.'),
            'with' => 'verify_password',
        ]));

        //validate this form for password
        $messages = $validation->validate($this->request->getPost());
        if (count($messages)) {
            foreach ($messages as $message) {
                throw new Exception($message);
            }
        }

        //user registration
        try {
            $this->db->begin();

            $user->signup();

            $this->db->commit();
        } catch (Exception $e) {
            $this->db->rollback();

            throw new Exception($e->getMessage());
        }

        //login the user
        $random = new \Phalcon\Security\Random();

        $sessionId = $random->uuid();

        //save in user logs
        $payload = [
            'sessionId' => $sessionId,
            'email' => $user->getEmail(),
            'iat' => time(),
        ];

        $token = $this->auth->make($payload);

        //start session
        $session = new Sessions();
        $session->start($user, $sessionId, $token, $userIp, 1);

        $authSession = [
            'token' => $token,
            'time' => date('Y-m-d H:i:s'),
            'expires' => date('Y-m-d H:i:s', time() + $this->config->jwt->payload->exp),
            'id' => $user->getId(),
        ];

        $user->password = null;
        $this->sendEmail($user, 'signup');

        return $this->response([
            'user' => $user,
            'session' => $authSession
        ]);
    }
693902
public function RegisterForm()
    {

        // If back URL set, push to session
        if (isset($_REQUEST['BackURL'])) {
            Session::set('BackURL', $_REQUEST['BackURL']);
        }

        $config = Users::config();

        // Setup form fields
        $fields = FieldList::create(
            TextField::create("FirstName"),
            TextField::create("Surname"),
            EmailField::create("Email"),
            $password_field = ConfirmedPasswordField::create("Password")
        );

        $password_field->minLength = $config->get("password_min_length");
        $password_field->maxLength = $config->get("password_max_length");
        $password_field->requireStrongPassword = $config->get("password_require_strong");

        // Setup form actions
        $actions = new FieldList(
            FormAction::create("doRegister", "Register")
                ->addExtraClass("btn")
                ->addExtraClass("btn-green")
        );

        // Setup required fields
        $required = new RequiredFields(
            array(
            "FirstName",
            "Surname",
            "Email",
            "Password"
            )
        );

        $form = Form::create(
            $this,
            "RegisterForm",
            $fields,
            $actions,
            $required
        )->addExtraClass("forms")
        ->addExtraClass("forms-columnar");

        $this->extend("updateRegisterForm", $form);

        $session_data = Session::get("Form.{$form->FormName()}.data");

        if ($session_data && is_array($session_data)) {
            $form->loadDataFrom($session_data);
            Session::clear("Form.{$form->FormName()}.data");
        }

        return $form;
    }
584796
protected function userSetup()
    {
        $this->output->writeln(<<<STEP
<fg=yellow>
*-----------------------------------------------*
|                                               |
|            Configure Default User             |
|                                               |
*-----------------------------------------------*
</fg=yellow>
STEP
        );

        $first = $this->ask('Please enter the user first name');
        $last  = $this->ask('Please enter the user last name');
        $email = $this->ask('Please enter the user email');
        $pass  = $this->userSetupPassword();

        $headers = [
          'Setting',
          'Value'
        ];

        $data = [
          ['First Name', $first],
          ['Last Name', $last],
          ['Email', $email],
          ['Password', $pass],
        ];

        $this->table($headers, $data);

        if (!$this->confirm('Is the user information correct?')) {
            $this->userSetup();
        }

        $this->user = [
          'first' => $first,
          'last'  => $last,
          'email' => $email,
          'pass'  => $pass,
        ];

        $this->info('User configuration saved.');
    }
225980
function user_signup($user, $notify=true) {
        global $CFG, $DB, $PAGE, $OUTPUT;

        require_once($CFG->dirroot.'/user/profile/lib.php');
        require_once($CFG->dirroot.'/user/lib.php');

        if ($this->user_exists($user->username)) {
            print_error('auth_ldap_user_exists', 'auth_ldap');
        }

        $plainslashedpassword = $user->password;
        unset($user->password);

        if (! $this->user_create($user, $plainslashedpassword)) {
            print_error('auth_ldap_create_error', 'auth_ldap');
        }

        $user->id = user_create_user($user, false, false);

        user_add_password_history($user->id, $plainslashedpassword);

        // Save any custom profile field information
        profile_save_data($user);

        $userinfo = $this->get_userinfo($user->username);
        $this->update_user_record($user->username, false, false, $this->is_user_suspended((object) $userinfo));

        // This will also update the stored hash to the latest algorithm
        // if the existing hash is using an out-of-date algorithm (or the
        // legacy md5 algorithm).
        update_internal_user_password($user, $plainslashedpassword);

        $user = $DB->get_record('user', array('id'=>$user->id));

        \core\event\user_created::create_from_userid($user->id)->trigger();

        if (! send_confirmation_email($user)) {
            print_error('noemail', 'auth_ldap');
        }

        if ($notify) {
            $emailconfirm = get_string('emailconfirm');
            $PAGE->set_url('/auth/ldap/auth.php');
            $PAGE->navbar->add($emailconfirm);
            $PAGE->set_title($emailconfirm);
            $PAGE->set_heading($emailconfirm);
            echo $OUTPUT->header();
            notice(get_string('emailconfirmsent', '', $user->email), "{$CFG->wwwroot}/index.php");
        } else {
            return true;
        }
    }
246993
public function post($url, $data=array(), $join=TRUE, $users=TRUE, $mixed=FALSE)
    {
      if ($join && $users)
        $url = $this->join($url);
      if ($join && !$users)
        $url = $this->join($url, FALSE);

      $this->setOption('auth', TRUE);
      $this->setOption('headers', TRUE);

      if ($mixed)
        return $this->request(API::API_METHOD_POST, $url, $data, $mixed);

      return $this->request(API::API_METHOD_POST, $url, json_encode($data), $mixed);

    }
794717
public function add()
    {
        $user = $this->Users->newEntity();

        if ($this->request->is('post')) {
            $user = $this->Users->patchEntity($user, $this->request->getData());

            if ($this->Users->save($user)) {
                $this->Flash->success(I18N_OPERATION_OK);

                return $this->redirect(['action' => 'index']);
            }

            $this->Flash->error(I18N_OPERATION_NOT_OK);
        }

        $this->set(compact('user'));
    }
227307
public function callbackSubmit()
    {
        // Get values from the submitted form
        $name       = $this->form->value("name");
        $email       = $this->form->value("email");
        $question       = $this->form->value("question");
        $password      = $this->form->value("password");
        $passwordAgain = $this->form->value("password-again");

        // Check password matches
        if ($password !== $passwordAgain) {
            $this->form->rememberValues();
            $this->form->addOutput("Password did not match.");
            return false;
        }

        if (preg_match("/[^-a-z0-9_]/i", $name)) {
            $this->form->addOutput("Ogiltigt användarnamn, vänligen försök igen.");
            return false;
        }

         $user = new User();
         $user->setDb($this->di->get("db"));

        if ($user->userExists($name)) {
             $this->form->addOutput("User already exists");
             return false;
        }

          $user->name = $name;
          $user->email = $email;
          $user->question = $question;
          $user->setPassword($password);
          $user->save();

          $this->di->get('session')->set("user", $name); # set user in session
          $this->di->get("response")->redirect("user/profile");
    }
1132139
protected function webLogin()
    {
        $response = $this->webclient->get("/en/auth", array(
            'cookies' => $this->cookiejar,
        ));

        $csrf = $this->getBetween((string)$response->getBody(), "document.write('", "');");
        $csrf = str_replace("' + '", "", $csrf);
        $name = $this->getBetween($csrf, 'name="', '"');
        $value = $this->getBetween($csrf, 'value="', '"');

        $response = $this->webclient->post("/en/auth", array(
            'body' => array(
                'submit' => 'Login',
                'email' => $this->username,
                'password' => $this->password,
                $name => $value,
            ),
        ));

        if($response->getStatusCode() == 200){
            throw new YouHostingException($this->getBetween((string) $response->getBody(), '<div class="notification info">', '</div>'));
        }
    }
107223
def user_create(self, data, **kwargs):
        ""
        api_path = "/api/v2/users.json"
        return self.call(api_path, method="POST", data=data, **kwargs)
731244
async function signupUser(form) {
  await client.connect();
  try {
    await api.signup(
      {
        credentials: {
          login: form.login.value,
          password: form.password.value
        },
        profile: {
          email: form.email.value
        }
      },
      'user'
    );
    displayMessage(
      'Account created',
      'Your account has been created, please check your emails to confirm your account',
      'is-success'
    );
    goTo('login');
  } catch (e) {
    displayMessage('Account not created', `Your account could not been created. Cause: ${e.message}`, 'is-danger');
  }
}
283004
def register
      @user = User.new(require_params)
      if @user.save
        render json: {message: @user, success: true}, status: 201
      else
        render json: {message: @user.errors.full_messages, success: false}, status: :ok
      end
    end
608910
public function indexAction()
    {
        if($this->identity()) {
            return $this->redirect()->toRoute($this->getOptions()->getLoginRedirectRoute());
        }
        
        $user = new User;
        $form = $this->getUserFormHelper()->createUserForm($user, 'SignUp');
        if($this->getRequest()->isPost()) {
            $form->setValidationGroup('username', 'email', 'firstName', 'lastName', 'password', 'passwordVerify', 'question', 'answer', 'csrf', 'captcha');
            $form->setData($this->getRequest()->getPost());    
            if($form->isValid()) {
                $entityManager = $this->getEntityManager();
                $user->setState($entityManager->find('CsnUser\Entity\State', 1));
                $user->setRole($entityManager->find('CsnUser\Entity\Role', 2));
                $user->setEmailConfirmed(false);
                $user->setLanguage($entityManager->find('CsnUser\Entity\Language', 1));
                $user->setRegistrationDate(new \DateTime());
                $user->setRegistrationToken(md5(uniqid(mt_rand(), true)));
                $user->setPassword(UserCredentialsService::encryptPassword($user->getPassword()));
                
    		    try {
    		        $fullLink = $this->getBaseUrl() . $this->url()->fromRoute('user-register', array('action' => 'confirm-email', 'id' => $user->getRegistrationToken()));
    		        $this->sendEmail(
    		            $user->getEmail(),
    		            $this->getTranslatorHelper()->translate('Please, confirm your registration!'),
    		            sprintf($this->getTranslatorHelper()->translate('Please, click the link to confirm your registration => %s'), $fullLink)
    		        );
    		        $entityManager->persist($user);
                    $entityManager->flush();

                    $viewModel = new ViewModel(array(
                        'email' => $user->getEmail(),
                        'navMenu' => $this->getOptions()->getNavMenu()
                    ));
                    $viewModel->setTemplate('csn-user/registration/registration-success');
                    return $viewModel;
    		    } catch (\Exception $e) {
                    return $this->getServiceLocator()->get('csnuser_error_view')->createErrorView(
    				    $this->getTranslatorHelper()->translate('Something went wrong when trying to send activation email! Please, try again later.'),
    					$e,
    					$this->getOptions()->getDisplayExceptions(),
    					$this->getOptions()->getNavMenu()
    				);
    			}
            }
        }   

        $viewModel = new ViewModel(array(
            'form' => $form,
            'navMenu' => $this->getOptions()->getNavMenu()
        ));
        $viewModel->setTemplate('csn-user/registration/registration');
        return $viewModel;
    }
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'));
    }
23625
public function getUsers()
    {
        // get the user list
        return $this->apiCall('users.list')->then(function (Payload $response) {
            $users = [];
            foreach ($response['members'] as $member) {
                $users[] = new User($this, $member);
            }
            return $users;
        });
    }
751277
public function register()
    {
        $this->loadModel('User.Users');
        $this->Users->fieldable(false);
        $user = $this->Users->newEntity();
        $registered = false;
        $languages = LocaleToolbox::languagesList();

        if ($this->request->data()) {
            $user->set('status', 0);
            $user->accessible(['id', 'token', 'status', 'last_login', 'created', 'roles'], false);
            $user = $this->Users->patchEntity($user, $this->request->data);

            if ($this->Users->save($user)) {
                NotificationManager::welcome($user)->send();
                $this->Flash->success(__d('user', 'Account successfully created, further instructions have been sent to your e-mail address.', ['key' => 'register']));
                $registered = true;
            } else {
                $this->Flash->danger(__d('user', 'Account could not be created, please check your information.'), ['key' => 'register']);
            }
        }

        $this->title(__d('user', 'Registration'));
        $this->set(compact('registered', 'user', 'languages'));
    }
1233123
public function formAction()
    {
        $user = new User();
        $form = $this->createForm(new UserRegistrationType(), $user);

        return array(
            'user' => $user,
            'form' => $form->createView(),
            'form_name' => $form->getName());
    }
1173592
def post(self, user_ids=None, usernames=None, status=None):
        
        return self.connection.post('user/array',
                                    data=dict(user_ids=user_ids,
                                              usernames=usernames,
                                              status=status))