Search code examples
pythonflaskflask-wtformsflask-loginmulti-user

flask multi user authentication with multiple table


I need your help please, I have in my models file, 3 tables of 3 different kinds of users (admins, clients, company) and each user can have an email and password for authentication. The problem is that when a user creates a count in 2 tables, say clients and company, with a same email, the program confuses between to count and gives an error :

 - class Admin(UserMixin, db.Model):   
 - class Client(UserMixin, db.Model): 
 - class Company(UserMixin, db.Model):

Do you have any idea about this problem?


Solution

  • Okay, so this is a design flaw with your database. Different types of users should not be stored in different places.

    You need to define a model where the type of user is defined within the database. You can then create methods within your model class to evaluate the user class and decide how to treat it.

    Example:

    class User(db.Model):
        id = db.Column(db.Integer, primary_key = True)
        username = db.Column(db.String(200), unique = True)
        password = db.Column(db.String(200))
        userType = db.Column(db.String(20), default = 'user') #can be user, client, admin or whatever your options are
    
        def isAdmin(self): #an example method - your admin view could use this method to check if a user should be given access
             if self.userType == 'admin':
                 return True
             else:
                 return False