How can I register and login a user in my Controller? I have tried something like this:
$newUser = new User($userName, $userPassword, $userEmail); Craft::$app->elements->saveUser($newUser);
Put this at the top of the file:
Within your function use the following code:
$user = new User(); $user->pending = true; $user->username = $contact["login_email"]; $user->firstName = $contact["first_name"]; $user->lastName = $contact["last_name"]; $user->email = $contact["login_email"]; $user->passwordResetRequired = false; $user->validate(null, false); Craft::$app->getElements()->saveElement($user, false); Craft::$app->users->assignUserToGroups($user->id, ); Craft::$app->getUsers()->sendActivationEmail($user);
The sendActivationEmail is not a required step and can be removed but this code is working on a Craft 3 site I've been building and it creates user accounts.
This assumes that a $contacts array has been set with all of the correct values, just swap these out for your own values or omit them if you don't have any. From here you should be able to customise it though for what you need once the user account is created.
The final step for you to log in as that user would be to use something like this, this is untested however and may need some tweaking but has come from the docs:
$userLogin = new \Craft\web\User(); $userLogin->loginByUserId($user->id);