lingthio / Flask-User

Customizable User Authorization & User Management: Register, Confirm, Login, Change username/password, Forgot password and more.
http://flask-user.readthedocs.io/
MIT License
1.06k stars 292 forks source link

Roles #173

Closed dann254 closed 7 years ago

dann254 commented 7 years ago

I'm creating a web app that uses Flask-user and i would like a role to be created when a user signs up.

i have read through the Roles required app. but in that, adding roles is done within the view.

is there a way to add roles when the register form is submitted?

carrete commented 7 years ago

Sounds like you want to use the user_registered signal. https://pythonhosted.org/Flask-User/signals.html

dann254 commented 7 years ago

Thanks @carrete this worked.

from flask_user import user_registered
from app.models import Role

@user_registered.connect_via(app)
def _after_register_hook(sender, user, **extra):
    identity= user.id
    role = "account_owner"
    if User.query.filter_by(id = identity).first():
        update = User.query.filter_by(id = identity).first()
        update.roles.append(Role(name = role))
        db.session.commit()
        return redirect(url_for('home.index'))
dann254 commented 7 years ago

Adding roles Has another Issue according to Roles required app.
When adding two Users with the same role, it raises an IntegrityError for unique values in the role.name.

I added this lines of code after line 92 in the Roles required app:

    # Create 'user008' user with 'secret' and 'agent' roles
    if not User.query.filter(User.username=='user008').first():
        user2 = User(username='user008', email='user008@exmple.com', active=True,
                password=user_manager.hash_password('Password1'))
        user2.roles.append(Role(name='secret'))
        user2.roles.append(Role(name='agent'))
        db.session.add(user2)
        db.session.commit()

And i got the error:

sqlalchemy.exc.IntegrityError: (sqlite3.IntegrityError) UNIQUE constraint failed: role.name

dann254 commented 7 years ago

Dont mind, i found a fix for that. i can now add many users with the same role.

from app.models import User, Role, UserRoles
from flask_user import user_registered

@user_registered.connect_via(app)
def after_register_hook(sender, user, **extra):

    role = Role.query.filter_by(name="account_owner").first()

    if role is None:
        role = Role(name="account_owner")
        db.session.add(role)
        db.session.commit()

    user_role = UserRoles(user_id=user.id, role_id=role.id)
    db.session.add(user_role)
    db.session.commit()

    flash("role added.")
    return redirect(url_for("home.index"))