0

In my controller, I can add new users when a user with the right privileges is logged in via craft()->users->saveUser(), but this doesn't work when no user is logged in.

Is "users/saveUser" the only service method I can use? I would prefer to be able to use my custom one.

EDIT: code below works fine when I'm logged in as an admin user, otherwise it redirects me to login form, after form submission. Have I missed something in here?

public function actionAddPartner() 
{
        $content = craft()->request->getPost();
        $companyId = explode("@", $content['email']);
        $user = new UserModel();
        $user->username         = $content['email'];
        $user->email            = $content['email'];
        $user->unverifiedEmail  = $content['email'];
        $user->firstName        = $content['firstName'];
        $user->lastName         = $content['lastName'];
        $user->pending          = true;
        $success = craft()->users->saveUser($user);
        if ($success) {
            // Assign them to the Partner Admin user group
            craft()->userGroups->assignUserToGroups($user->id, 1);
            // Update the Element Index
            craft()->search->indexElementAttributes($user);
        }
}
2

Oh well, totally forgot to allow anonymous access at the top of the controller. I guess I can leave this answer here in case somebody is as forgetful as me:

protected $allowAnonymous = true;
  • Hah... funny thing is I've done that plenty of times. Glad you're sorted! – Brad Bell Nov 23 '16 at 21:46
  • yeah, one of those things that can drive you insane, especially if one, like me, is still learning. – Lukigi Nov 23 '16 at 21:52
0

UsersService->saveUser() (at craft()->users->saveUser()) doesn't do any sort of permissions checking or authentication checks because it assumes that all of that has been performed at the controller level.

You'll find this similar interactions between controllers and services elsewhere in Craft as well.

My guess is you're hitting some sort of validation error when trying to save a user with an authenticated session. Try checking the output of $user->getErrors().

You can, of course, in your plugin write your own service method that saves a user in a method that differs from Craft's implementation.

  • I appreciate your answer, but when I try to register a user while logged out I'm being redirected to a login form. I've updated the question with the actual code. This is the controller to which I direct the registration form. – Lukigi Nov 23 '16 at 21:24
  • Maybe the example code isn't complete? Where is $success being defined? – Brad Bell Nov 23 '16 at 21:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.