Add role to User table with a default value of “User”. The role attribute is set during the initialization of the User object. The is_admin method checks if the user has the role of an admin.
What this will do is differentiate between if a user that logs in will be granted regular user permissions, or will have admin permissions.
this will be put in model/users.py
class User(db.Model):
# ... (existing code)
_role = db.Column(db.String(20), default="User", nullable=False)
def __init__(self, name, uid, password="123qwerty", dob=date.today(), role="User"):
# ... (existing code)
self._role = role
@property
def role(self):
return self._role
@role.setter
def role(self, role):
self._role = role
def is_admin(self):
return self._role == "Admin"
# ... (existing code)
# CRUD read converts self to dictionary
# returns dictionary
def read(self):
return {
"id": self.id,
"name": self.name,
"uid": self.uid,
"dob": self.dob,
"age": self.age,
"role": self.role,
"posts": [post.read() for post in self.posts]
}
def initUsers():
with app.app_context():
"""Create database and tables"""
db.create_all()
"""Tester data for table"""
u1 = User(name='Thomas Edison', uid='toby', password='123toby', dob=date(1847, 2, 11), role="Admin")a
# ... (existing code)
this will go in api/users.py.
class _Security(Resource):
def post(self):
try:
body = request.get_json()
if not body:
return {
"message": "Please provide user details",
"data": None,
"error": "Bad request"
}, 400
''' Get Data '''
uid = body.get('uid')
if uid is None:
return {'message': f'User ID is missing'}, 400
password = body.get('password')
''' Find user '''
user = User.query.filter_by(_uid=uid).first()
if user is None or not user.is_password(password):
return {'message': f"Invalid user id or password"}, 400
if user:
try:
token_payload = {
"_uid": user._uid,
"role": user.role # Add the role information to the token
}
token = jwt.encode(
token_payload,
current_app.config["SECRET_KEY"],
algorithm="HS256"
)
# ... (existing code)