0

I want to have a custom key for the field id, for example, id_user, I've tried the following

class UserModel(db.model, UserMixin)
...
        @property
        def id(self):
            return self.id_user

But couldn't make it work. When I try to login it sends me this message:

{
"message": "You don't have the permission to access the requested resource. It is either read-protected or not readable by the server."
}
Hugo Pablo
  • 81
  • 1
  • 9
  • Need more info - what version of flask-security and flask are you using. That error message I don't think comes from Flask-Security - if login fails - assuming you are using forms - you should get a form back (from POST /login). – jwag Jan 31 '20 at 01:38

2 Answers2

0

I ended up with a nasty solution. I cloned the UserModel object, added a duplicated field for id, with the custom key I needed and told Flask-Security to use that object as the UserModel This is the function code I used:

def clone_model(model):
data = model
attr = getattr(model, "id_user")
setattr(data, "id", attr)
return data

cUserModel = clone_model(UserModel)
user_datastore = SQLAlchemyUserDatastore(db, cUserModel, Roles)

security = Security(app, user_datastore)

Hope someone find it useful

Hugo Pablo
  • 81
  • 1
  • 9
0

For anybody who is using Flask-Security-Too looking to change the default id column, here is my solution.

Define the User and Role Tables as usual and just define the id column depending on your preference.


class Role(db.Model, FsRoleMixin):
    __tablename__ = 'role'

    id = Column(String, primary_key=True)


class Users(db.Model, FsUserMixin):
    __tablename__ = 'users'

    id = Column(String, primary_key=True)

For me, I need to use String primary_key Column. For that to I needed to change the many-to-many relationship table (roles_users). Below is the code snippet for the same.

# Initialize the db object
db = SQLAlchemy()


# import this Class
from flask_security.models.fsqla_v2 import FsModels

# call this after creating the db object
FsModels.db = db
FsModels.user_table_name = 'users' # If you want a different table name than the default
FsModels.role_table_name = 'role'

# Create the relationship table as per your preferences
FsModels.roles_users = db.Table(
    "roles_users",
    Column("user_id", String, ForeignKey("users.id")),
    Column("role_id", String, ForeignKey("role.id")),
)

Dharman
  • 30,962
  • 25
  • 85
  • 135