4

I am new to web2py. I want to make an application that has one admin (super user) account. I want to restrict 'only admin can register user'. So that once Admin logs into the app, he will see different menus like 'Home', 'Setting', and 'Register User'. I am done with other options but I am getting problems in 'Register User'.

In my application there is a 'Register' link – http://127.0.0.1:8000/filemanager2/default/user/register. But when I click on it, I get redirected to the profiles page. It's because the admin user is already logged in and therefore after clicking on the register link it shows the admin account's profile. What can I do to fix this?

1 Answer 1

6

If you want to take advantage of the built-in Auth register() function, you can hack it a bit as follows:

@auth.requires_membership('admin') def register() admin_auth = session.auth auth.is_logged_in = lambda: False def post_register(form): session.auth = admin_auth auth.user = session.auth.user auth.settings.register_onaccept = post_register return dict(form=auth.register()) 

Normally, Auth.register() checks if the user is logged in, and if so redirects to the profile page. The above replaces the auth.is_logged_in() method with a lambda that simply returns False, so no redirect will happen. Auth.register() also sets session.auth and auth.user to values associated with the newly registered user, so the above code saves the admin's values and uses the register_onaccept callback to restore session.auth and auth.user to the admin's values.

Another approach is simply to create your own registration form based on the db.auth_user table and use the Auth.get_or_create_user() method to add the new user:

@auth.requires_membership('admin') def register(): form = SQLFORM(db.auth_user) if form.validate(): admin_user = auth.user auth.get_or_create_user(form.vars) auth.user = admin_user return dict(form=form) 

However, in that case you won't get the password verification field that the built-in register() function automatically adds to the register form. As with the built-in register() method, get_or_create_user() also sets auth.user to the new user's record, so you have to re-set it back to the record for the admin user after the insert.

Note, both of the above methods will automatically create a new unique Auth group for the new user and assign the user to that group if auth.settings.create_user_groups is True (which is the default). Instead of the above methods, you could simply use a standard SQLFORM to add new users, but you would then have to handle creating and adding to the groups manually.

We should probably add an option to make this easier.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks to you both for the question and the answer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.