Setting a default role in flask-security
Asked Answered
E

2

2

I am trying to set a default role when a user registers with my site, currently no roles are set when the user registers.

I have created the roles I need, so I just need to define it somehow. Not sure how though.

The code I have is pretty much copy paste from the quick start guide. Anyway, here it is:

# Define models
roles_users = db.Table('roles_users',
        db.Column('user_id', db.Integer(), db.ForeignKey('user.id')),
        db.Column('role_id', db.Integer(), db.ForeignKey('role.id')))

class Role(db.Model, RoleMixin):
    id = db.Column(db.Integer(), primary_key=True)
    name = db.Column(db.String(80), unique=True)
    description = db.Column(db.String(255))

class User(db.Model, UserMixin):
    id = db.Column(db.Integer, primary_key=True)
    email = db.Column(db.String(255), unique=True)
    password = db.Column(db.String(255))
    active = db.Column(db.Boolean())
    confirmed_at = db.Column(db.DateTime())
    roles = db.relationship('Role', secondary=roles_users, backref=db.backref('users', lazy='dynamic'))

# Setup Flask-Security
user_datastore = SQLAlchemyUserDatastore(db, User, Role)
security = Security(app, user_datastore)


import users.getUser as getUser

#@app.before_first_request
def create_user():
    db.create_all()
    user_datastore.create_user(email='[email protected]', password='password')
    db.session.commit()

@flask_sijax.route(app, '/')
def test():
    print user_datastore.create_role(name='User', description='Generic user role')
    db.session.commit()
    return render_template('test.html')
Entrammel answered 17/6, 2013 at 11:44 Comment(0)
E
10

I fixed it using information from this git issue with this:

@user_registered.connect_via(app)
def user_registered_sighandler(app, user, confirm_token):
    default_role = user_datastore.find_role("User")
    user_datastore.add_role_to_user(user, default_role)
    db.session.commit()
Entrammel answered 17/6, 2013 at 15:7 Comment(1)
I add to use user_registered.connect(user_registered_sighandler) instead of the decorator in order to make this work.Silvasilvain
V
-1

If you have already created a role "User", You can add that role to the user when you create/register the user.

def create_user():
    db.create_all()
    user = user_datastore.create_user(email='[email protected]', password='password')
    default_role = user_datastore.find_role(name="User")
    user_datastore.add_role_to_user(user, default_role)
    db.session.commit()
Vite answered 17/6, 2013 at 13:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.