def put_role(role_id: int) -> ApiResponse: role = RoleModel.find_by_id(role_id) if not role: abort( 404, description=ERROR_404.format("Role", "id", role_id), ) role_json = request.get_json() role_by_name = RoleModel.find_by_name(role_json.get("role_name")) if role_by_name and role_by_name.id != role_id: abort( 409, description=ERROR_409.format( "Role", "role_name", role_json.get("role_name"), ), ) role.role_name = role_json.get("role_name") role.save_to_db() return ( jsonify( { "message": MODIFIED.format("Role"), "role": role_schema.dump(role), } ), 200, )
def post(cls): data = cls.parser.parse_args() role = RoleModel(**data) if role.find_by_name(role.name): return {"message": "Role already Exists"} role.save_to_db() return {"message": "Role Created Successfully"}, 201
def post(self, name): role = RoleModel.find_by_role_name(name) if role: return {"message": "Designation already there"} else: role = RoleModel(name) role.insert_role() return {"message": "Designation inserted successfully"}, 201
def get(self, id=None): queryData = request.args.to_dict() if id: role = RoleModel.find_by_id(id) if role: return role.json() else: return {'error': 'role not found'}, 404 roles = RoleModel.find(**queryData) return {'roles': list(map(lambda x: x.json(), roles))}, 200
def post(self): data = request.get_json() if RoleModel.find_by_role_name(data['role_name']): return {"message": "role already exists"}, 400 dt = datetime.datetime.utcnow().strftime("%d-%m-%Y %H:%M:%S.%f") role = RoleModel(role_name=data['role_name'], description=data['description'], created_at=dt, updated_at=dt, is_admin=data['is_admin']) role.save_to_db() return {"message": role.role_name + " is created"}, 201
def admin_new_role(): if request.method == 'POST': is_admin = False if request.form.get('is_admin', None) is None else True role_name = request.form.get('role_name', None) if role_name is None: return render_template('new_role.html') role = RoleModel(role_name=role_name, is_admin=is_admin) role.save() return redirect(url_for('admin_cp')) else: return render_template('new_role.html')
def post_role() -> ApiResponse: role_json = request.get_json() if RoleModel.find_by_name(role_json.get("role_name")): abort( 409, description=ERROR_409.format( "Role", "role_name", role_json.get("role_name"), ), ) role = role_schema.load(role_json) role.save_to_db() return ( jsonify( { "message": CREATED.format("Role"), "role": role_schema.dump(role), } ), 201, )
def delete(self, id): role = RoleModel.find_by_id(id) if role: role.delete_from_db() return {'success': 'role deleted'}, 202 return {'error': 'role not found'}, 404
def resetdb_command(): """Destroys and creates the database + tables.""" from models.user import UserModel from models.role import RoleModel import os from sqlalchemy_utils import database_exists, create_database, drop_database DB_URL = os.environ.get('DATABASE_URL', 'sqlite:///data.db') if database_exists(DB_URL): print('Deleting database.') drop_database(DB_URL) if not database_exists(DB_URL): print('Creating database.') create_database(DB_URL) print('Creating tables.') db.create_all() print('Adding role: Admin') admin_role = RoleModel('Administrador', True) db.session.add(admin_role) db.session.commit() print('Adding Admin user') admin = UserModel('*****@*****.**', 'adminpassword', '1') db.session.add(admin) db.session.commit() print('Done!')
def admin_role(): if request.method == 'POST': pass else: role_name = request.args.get('role_name') role = RoleModel.find_by_name(role_name) return render_template('role_mgmt.html', role=role)
def get(self, id): role = RoleModel.find_by_id(id) if role: return { 'permissions': list(map(lambda x: x.json(), role.permissions)) }, 200 return {'error': 'role not found'}, 404
def get_roles() -> ApiResponse: role_list = RoleModel.find_all() return ( jsonify({"roles": role_list_schema.dump(role_list)}), 200, )
def test_find_by_name(self): with self.app_context: role_1 = self.add_role_to_db(self.role_1) role = RoleModel.find_by_name(self.ROLE_NAME) self.assertEqual(role.id, role_1.id)
def admin_delete_role(): role = RoleModel.find_by_name(request.form.get('role_name', '')) if role is not None: role.delete() else: print('[DELETE ROLE] Could not delete role with name: %s' % request.form.get('role_name')) return redirect(url_for('admin_cp'))
def check_if_user_is_admin(cls, id): print("id: " + str(id)) user = cls.query.filter_by(id=id).first() print(user) role_id = user.role_id print("role id" + str(role_id)) role = RoleModel.find_by_role_id(role_id) if role: return role.is_admin
def create_tables(): db.init_app(app=app) db.create_all(app=app) doctor = RoleModel.find_by_name('doctor') if not doctor: role_doctor = RoleModel(name='doctor') role_doctor.save_to_db() patient = RoleModel.find_by_name('patient') if not patient: role_patient = RoleModel(name='patient') role_patient.save_to_db()
def __init__(self, pname, description, owner_id, roles=[]): self.pname = pname self.description = description self.owner_id = owner_id # print((roles) self.roleList = [] for role in roles: # print(type(eval(role))) role = eval(role) r = RoleModel(role['title'], role['description'], role['skills']) self.roleList += [r]
def setUp(self) -> None: """Create all db tables before each test""" self.client = app.test_client() self.app_context = app.app_context() with self.app_context: db.create_all() self.keynote_1 = KeynoteModel(**TEST_KEYNOTE_1) self.keynote_2 = KeynoteModel(**TEST_KEYNOTE_2) self.member_1 = MemberModel(**TEST_MEMBER_1) self.member_2 = MemberModel(**TEST_MEMBER_2) self.meeting_1 = MeetingModel(**TEST_MEETING_1) self.meeting_2 = MeetingModel(**TEST_MEETING_2) self.permission_1 = PermissionModel(**TEST_PERMISSION_1) self.permission_2 = PermissionModel(**TEST_PERMISSION_2) self.permission_3 = PermissionModel(**TEST_PERMISSION_3) self.permission_4 = PermissionModel(**TEST_PERMISSION_4) self.permission_5 = PermissionModel(**TEST_PERMISSION_5) self.permission_6 = PermissionModel(**TEST_PERMISSION_6) self.permission_7 = PermissionModel(**TEST_PERMISSION_7) self.permission_8 = PermissionModel(**TEST_PERMISSION_8) self.project_1 = ProjectModel(**TEST_PROJECT_1) self.project_2 = ProjectModel(**TEST_PROJECT_2) self.role_1 = RoleModel(**TEST_ROLE_1) self.role_2 = RoleModel(**TEST_ROLE_2) self.role_3 = RoleModel(**TEST_ROLE_3) self.role_4 = RoleModel(**TEST_ROLE_4) self.role_5 = RoleModel(**TEST_ROLE_5) self.speaker_1 = SpeakerModel(**TEST_SPEAKER_1) self.speaker_2 = SpeakerModel(**TEST_SPEAKER_2)
def put(self, id): data = json.loads(request.data) if 'permissions' not in data or data['permissions'] == '': return { 'error': "The role permissions is empty".format(data['name']) }, 400 role = RoleModel.find_by_id(id) if role: role.update(**data) return role.json(), 201 return {'error': 'role not found'}, 404
def get_role(role_id: int) -> ApiResponse: role = RoleModel.find_by_id(role_id) if not role: abort( 404, description=ERROR_404.format("Role", "id", role_id), ) return ( jsonify( { "role": role_schema.dump(role), } ), 200, )
def post(self): try: user = user_schema.load(request.get_json(), partial=("roles", "isActivated")) except ValidationError as err: return err.messages, 400 if UserModel.find_by_email(user.email): return {"message": "A user with that email already exists."}, 400 user.password = generate_password_hash(user.password) role = RoleModel.find_by_name("student") user.roles.append(role) user.save_to_db() return {"message": "User created successfully."}, 201
def delete_role(role_id: int) -> ApiResponse: role = RoleModel.find_by_id(role_id) if not role: abort( 404, description=ERROR_404.format("Role", "id", role_id), ) role.delete_from_db() return ( jsonify( { "message": DELETED.format("Role"), "role": role_schema.dump(role), } ), 200, )
def post(cls): data = cls.parser.parse_args() if not validate_email(data["email"]): return {"message": "Email is invalid"}, 400 if UserModel.find_by_email(data["email"]): return {"message": "User Already Exist"}, 400 if not RoleModel.find_by_id(data["role_id"]): return {"message": "There is no role Match"}, 400 captcha_token = data['captcha'] cap_url = 'https://www.google.com/recaptcha/api/siteverify' cap_secret = '6LdepUwaAAAAAMpgIoRBiwGUNCuXA26OS8hqDoYP' cap_data = {"secret": cap_secret, "response": captcha_token} cap_server_response = requests.post(url=cap_url, data=cap_data) cap_json = json.loads(cap_server_response.text) if cap_json['success'] == False: return {"message": "Some thing wrong "}, 404 user = UserModel(username=data['username'], email=data['email'], password=data['password'], role_id=data['role_id']) user.save_to_db() return {"message": "User Created Successfully"}, 201
def post(self): data = _user_parser.parse_args() data["lozinka"]= (encrypt(data["lozinka"])) if UserModel.find_by_email(data["email"]): return {"message":"Korisnik s tim emailom već postoji"},400 trajanje= datetime.timedelta(minutes=60) user = UserModel(data["email"], data["lozinka"], data["ime"], data["prezime"], data["mobitel"]) user.save_to_db() newuser= UserModel.find_by_email(data["email"]) access_token= create_access_token(identity=newuser.id, fresh=True, expires_delta=trajanje) refresh_token = create_refresh_token(newuser.id) rola= RoleModel.find_by_rolaID(3) return { "message":"Korisnički račun uspješno stvoren", "access_token": access_token, "refresh_token": refresh_token, "user":{"ime":user.ime, "role":rola.rola} }, 201
def post(self): trajanje= datetime.timedelta(minutes=60) data=_user_parser.parse_args() user = UserModel.find_by_email(data["email"]) if user!=None: rola= RoleModel.find_by_rolaID(user.roleID) enpass = user.lozinka if (data["admin_required"]==0) or (data["admin_required"]==None): if user and ( decrypt(enpass , data["lozinka"])==True): access_token=create_access_token(identity=user.id, fresh=True, expires_delta=trajanje) refresh_token=create_refresh_token(identity=user.id) return {"message":"Uspješna prijava.", "access_token": access_token, "refresh_token": refresh_token, "user": {"ime":user.ime, "role":rola.rola} },200 return {"message": "Pogrešan email ili lozinka"}, 401 if (data["admin_required"]==1): if user and decrypt(enpass, data["lozinka"])==True and (user.roleID!=1 and user.roleID!=2): return {"message":"Samo administratori imaju pristup!!!"}, 401 elif user and decrypt(enpass, data["lozinka"])==True and (user.roleID==1 or user.roleID==2): access_token=create_access_token(identity=user.id, fresh=True, expires_delta=trajanje) refresh_token=create_refresh_token(identity=user.id) return {"message":"Uspješna prijava.", "access_token": access_token, "refresh_token": refresh_token, "user": {"ime":user.ime, "role":rola.rola} },200
def post(self, name): data = Role.parser.parse_args() # role_name = data['role_name'] if RoleModel.find_by_name(name): return {'message', 'A role with this name already exists'}, 400 is_admin = data['is_admin'] if is_admin is None: is_admin = False role = RoleModel(name, is_admin) try: role.save() except: return {'message': 'Error saving the role'}, 500 return role.json(), 201
def post(self): data = json.loads(request.data) if 'permissions' not in data or len( data['permissions']) == 0 or data['permissions'] == '': return { 'error': "The role permissions is empty".format(data['name']) }, 400 if RoleModel.find_by_name(data["name"]): return { 'error': "A role with name '{}' already exists.".format(data["name"]) }, 400 role = RoleModel(**data) try: role.save_to_db() except: return {"error": "An error occurred creating the role."}, 500 return role.json(), 201
def get(self): roles = RoleModel.find_all_roles() if roles: return {'roles': [role.json() for role in roles]}, 200 return {'message': 'No roles found!'}, 404
class BaseTest(TestCase): """Base class which is inherited by all test classes""" @classmethod def setUpClass(cls) -> None: pass def setUp(self) -> None: """Create all db tables before each test""" self.client = app.test_client() self.app_context = app.app_context() with self.app_context: db.create_all() self.keynote_1 = KeynoteModel(**TEST_KEYNOTE_1) self.keynote_2 = KeynoteModel(**TEST_KEYNOTE_2) self.member_1 = MemberModel(**TEST_MEMBER_1) self.member_2 = MemberModel(**TEST_MEMBER_2) self.meeting_1 = MeetingModel(**TEST_MEETING_1) self.meeting_2 = MeetingModel(**TEST_MEETING_2) self.permission_1 = PermissionModel(**TEST_PERMISSION_1) self.permission_2 = PermissionModel(**TEST_PERMISSION_2) self.permission_3 = PermissionModel(**TEST_PERMISSION_3) self.permission_4 = PermissionModel(**TEST_PERMISSION_4) self.permission_5 = PermissionModel(**TEST_PERMISSION_5) self.permission_6 = PermissionModel(**TEST_PERMISSION_6) self.permission_7 = PermissionModel(**TEST_PERMISSION_7) self.permission_8 = PermissionModel(**TEST_PERMISSION_8) self.project_1 = ProjectModel(**TEST_PROJECT_1) self.project_2 = ProjectModel(**TEST_PROJECT_2) self.role_1 = RoleModel(**TEST_ROLE_1) self.role_2 = RoleModel(**TEST_ROLE_2) self.role_3 = RoleModel(**TEST_ROLE_3) self.role_4 = RoleModel(**TEST_ROLE_4) self.role_5 = RoleModel(**TEST_ROLE_5) self.speaker_1 = SpeakerModel(**TEST_SPEAKER_1) self.speaker_2 = SpeakerModel(**TEST_SPEAKER_2) def tearDown(self) -> None: """Clear db tables after each test""" with self.app_context: db.drop_all() def login( self, client: app.test_client, email: str, password: str ) -> LoginJSON: results = client.post( f"/members/login", data=json.dumps( { "email": email, "password": password, } ), headers={"Content-Type": "application/json"}, ) return json.loads(results.data) def add_permissions_to_admin(self): role_1 = self.role_1.save_to_db() permission_1 = self.permission_1.save_to_db() permission_2 = self.permission_2.save_to_db() permission_3 = self.permission_3.save_to_db() permission_4 = self.permission_4.save_to_db() permission_5 = self.permission_5.save_to_db() permission_6 = self.permission_6.save_to_db() permission_7 = self.permission_7.save_to_db() permission_8 = self.permission_8.save_to_db() role_1.permissions.append(permission_1) role_1.permissions.append(permission_2) role_1.permissions.append(permission_3) role_1.permissions.append(permission_4) role_1.permissions.append(permission_5) role_1.permissions.append(permission_6) role_1.permissions.append(permission_7) role_1.permissions.append(permission_8) return role_1 def add_keynote_to_db( self, keynote: KeynoteModel, role: RoleModel, member: MemberModel, speaker: SpeakerModel, meeting: MeetingModel, ) -> Tuple[ KeynoteModel, MemberModel, RoleModel, SpeakerModel, MeetingModel ]: speaker = self.add_speaker_to_db(speaker) meeting, member, role = self.add_meeting_to_db(meeting, member, role) keynote = keynote.save_to_db() return keynote, member, role, speaker, meeting def add_meeting_to_db( self, meeting: MeetingModel, member: MemberModel, role: RoleModel ) -> Tuple[MeetingModel, MemberModel, RoleModel]: member, role = self.add_member_to_db(member, role) meeting = meeting.save_to_db() return meeting, member, role def add_member_to_db( self, member: MemberModel, role: RoleModel ) -> Tuple[MemberModel, RoleModel]: role = self.add_role_to_db(role) member = member.save_to_db() return member, role def add_permission_to_db( self, permission: PermissionModel ) -> PermissionModel: return permission.save_to_db() def add_role_to_db(self, role: RoleModel) -> RoleModel: return role.save_to_db() def add_speaker_to_db(self, speaker: SpeakerModel) -> SpeakerModel: return speaker.save_to_db()
def add_role_to_db(self, role: RoleModel) -> RoleModel: return role.save_to_db()