def get_user_groups(db_session, user): try: user = User.get_by_name_or_id(user) except orm_exceptions.NoResultFound: raise HTTPRequestError(404, "No user found with this username or ID") else: return user.groups
def add_user_group(db_session, user, group, requester): try: user = User.get_by_name_or_id(user) except orm_exceptions.NoResultFound: raise HTTPRequestError(404, f"No user found with this ID or name: {user}") try: group = Group.get_by_name_or_id(group) except orm_exceptions.NoResultFound: raise HTTPRequestError( 404, f"No group found with this ID or name: {group}") if db_session.query(UserGroup).filter_by(user_id=user.id, group_id=group.id).one_or_none(): raise HTTPRequestError(409, "User is already a member of the group") r = UserGroup(user_id=user.id, group_id=group.id) db_session.add(r) cache.delete_key(userid=user.id) user.reset_token() db_session.add(user) log().info( f"user {user.username} added to group {group.name} by {requester['username']}" ) db_session.commit()
def update_user(db_session, user: str, updated_info, requester) -> (dict, str): """ Updates all the information about a particular user. :param db_session: The postgres session to be used. :param user: The user ID to be updated. :param updated_info: The new data. :param requester: Who is requiring this update. :return: The old information (a dictionary containing the old information about the user and the old service. :raises HTTPRequestError: If the username is different from the original (this field cannot be updated). """ # Drop invalid fields updated_info = { k: updated_info[k] for k in updated_info if k in User.fillable } user = User.get_by_name_or_id(user) old_user = user.safe_dict() old_service = user.service if 'username' in updated_info.keys() \ and updated_info['username'] != user.username: raise HTTPRequestError(400, "usernames can't be updated") # check_user function needs username. updated_info['username'] = user.username check_user(updated_info) # Verify if the email is in use by another user if 'email' in updated_info.keys() and updated_info['email'] != user.email: if db_session.query(User).filter_by( email=updated_info['email']).one_or_none(): raise HTTPRequestError(400, "email already in use") log().info(f"user {user.username} updated by {requester['username']}") log().info({'oldUser': user.safe_dict(), 'newUser': updated_info}) # Update all new data. if 'name' in updated_info.keys(): user.name = updated_info['name'] if 'service' in updated_info.keys(): user.service = updated_info['service'] if 'email' in updated_info.keys(): user.email = updated_info['email'] db_session.add(user) db_session.commit() # Publish messages related to service creation/deletion if count_tenant_users(db_session, old_service) == 0: log().info(f"will emit tenant lifecycle event {old_service} - DELETE") Publisher.send_notification({"type": 'DELETE', 'tenant': old_service}) if count_tenant_users(db_session, user.service) == 1: log().info(f"will emit tenant lifecycle event {user.service} - CREATE") Publisher.send_notification({"type": 'CREATE', 'tenant': user.service}) return old_user, old_service
def delete_user(db_session, username: str, requester): """ Deletes an user from the system :param db_session: The postgres session to be used :param username: String The user to be removed :param requester: Who is creating this user. This is a dictionary with two keys: "userid" and "username" :return: The removed user :raises HTTPRequestError: If the user tries to remove itself. :raises HTTPRequestError: Can't delete the admin user. :raises HTTPRequestError: If the user is not in the database. """ try: user = User.get_by_name_or_id(username) if user.id == requester['userid']: raise HTTPRequestError(400, "a user can't remove himself") elif user.username == 'admin': raise HTTPRequestError(405, "Can't delete the admin user") db_session.execute( UserPermission.__table__.delete(UserPermission.user_id == user.id)) db_session.execute( UserGroup.__table__.delete(UserGroup.user_id == user.id)) cache.delete_key(userid=user.id) # The user is not hardDeleted. # it should be copied to inactiveUser table inactiveTables.PasswdInactive.createInactiveFromUser( db_session, user, ) inactiveTables.UserInactive.createInactiveFromUser( db_session, user, requester['userid']) password.expire_password_reset_requests(db_session, user.id) db_session.delete(user) LOGGER.info(f"user {user.username} deleted by {requester['username']}") LOGGER.info(user.safe_dict()) kongUtils.remove_from_kong(user.username) MVUserPermission.refresh() MVGroupPermission.refresh() db_session.commit() if count_tenant_users(db_session, user.service) == 0: LOGGER.info( f"will emit tenant lifecycle event {user.service} - DELETE") Publisher.send_notification({ "type": 'DELETE', 'tenant': user.service }) return user except orm_exceptions.NoResultFound: raise HTTPRequestError(404, "No user found with this ID")
def get_all_user_permissions(db_session, user): try: user = User.get_by_name_or_id(user) except orm_exceptions.NoResultFound: raise HTTPRequestError(404, "No user found with this username or ID") permissions = user.permissions permissions += [ perm for group in user.groups for perm in group.permissions ] # drop possible duplicates return list({v.id: v for v in permissions}.values())
def add_user_groups(): predef_user_group = [ { "name": "testadm", "groups": ["testadm"] }, ] for user in predef_user_group: user_id = User.get_by_name_or_id(user['name']).id for group_name in user['groups']: r = UserGroup(user_id=user_id, group_id=Group.get_by_name_or_id(group_name).id) db.session.add(r) db.session.commit()
def remove_user_group(db_session, user, group, requester): try: user = User.get_by_name_or_id(user) except orm_exceptions.NoResultFound: raise HTTPRequestError(404, "No user found with this ID or name") try: group = Group.get_by_name_or_id(group) except orm_exceptions.NoResultFound: raise HTTPRequestError(404, "No group found with this ID or name") try: relation = db_session.query(UserGroup) \ .filter_by(user_id=user.id, group_id=group.id).one() db_session.delete(relation) cache.delete_key(userid=user.id) log().info(f"user {user.username} removed from {group.name} by {requester['username']}") db_session.commit() except orm_exceptions.NoResultFound: raise HTTPRequestError(404, "User is not a member of the group")
def reset_password(db_session, link, reset_data): if 'passwd' not in reset_data.keys(): raise HTTPRequestError(400, 'missing password') try: reset_request = db_session.query(PasswordRequest). \ filter_by(link=link).one() if check_request_validity(db_session, reset_request): user = User.get_by_name_or_id(reset_request.user_id) user.salt, user.hash = update(db_session, user, reset_data['passwd']) # remove this used reset request PasswordRequestInactive.createInactiveFromRequest(db_session, reset_request) db_session.delete(reset_request) return user else: raise HTTPRequestError(404, 'Page not found or expired') except orm_exceptions.NoResultFound: raise HTTPRequestError(404, 'Page not found or expired')
def remove_user_permission(db_session, user, permission, requester): try: user = User.get_by_name_or_id(user) except orm_exceptions.NoResultFound: raise HTTPRequestError(404, "No user found with this ID or name") try: perm = Permission.get_by_name_or_id(permission) except orm_exceptions.NoResultFound: raise HTTPRequestError(404, "No permission found with this ID") try: relation = db_session.query(UserPermission) \ .filter_by(user_id=user.id, permission_id=perm.id).one() db_session.delete(relation) cache.delete_key(userid=user.id, action=perm.method, resource=perm.path) log().info(f"permission {perm.name} for user {user.username} was revoked by {requester['username']}") MVUserPermission.refresh() db_session.commit() except orm_exceptions.NoResultFound: raise HTTPRequestError(404, "User does not have this permission")
def add_user_permission(db_session, user, permission, requester): try: user = User.get_by_name_or_id(user) except orm_exceptions.NoResultFound: raise HTTPRequestError(404, "No user found with this ID or name") try: perm = Permission.get_by_name_or_id(permission) except orm_exceptions.NoResultFound: raise HTTPRequestError(404, "No permission found with this ID") if db_session.query(UserPermission) \ .filter_by(user_id=user.id, permission_id=perm.id).one_or_none(): raise HTTPRequestError(409, "User already have this permission") r = UserPermission(user_id=user.id, permission_id=perm.id) db_session.add(r) cache.delete_key(userid=user.id, action=perm.method, resource=perm.path) MVUserPermission.refresh() db_session.commit() log().info( f"user {user.username} received permission {perm.name} by {requester['username']}" )
def get_user(db_session, user): try: user = User.get_by_name_or_id(user) return user except (orm_exceptions.NoResultFound, ValueError): raise HTTPRequestError(404, "No user found with this ID")