Setting a default role in flask-security

2019-04-01 19:00发布

问题:

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='my@email.com', 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')

回答1:

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()


回答2:

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='my@email.com', password='password')
    default_role = user_datastore.find_role(name="User")
    user_datastore.add_role_to_user(user, default_role)
    db.session.commit()