def get_current_professor( db: Session = Depends(get_db), user: models.User = Depends(get_current_user) ) -> models.Professor: if user.type == "professor": if professor := crud.professor.get(db, id=user.id): return professor raise NotFoundException(detail="Professor object not found")
def update_todo(todo_id): validate_json(request.json) todo = database.update_todo(g.user, todo_id, request.json) if todo is None: raise NotFoundException('Todo %s not found' % todo_id) else: return jsonify(todo), 201
def remove_student_from_term( *, db: Session = Depends(deps.get_db), division_id: str, student_id: str, current_admin: models.Admin = Depends( deps.get_current_admin_with_permission("term")), ) -> Any: if division := crud.division.get(db, division_id): if student := crud.student.get(db, student_id): if student in division.students: logging.info( f"Admin {current_admin.user_id} ({current_admin.user.email}) " f"is deleting Student {student_id} ({student.user.email}) " f"from Division {division_id} ({division.course.name} {division.division_code})" ) division.students.remove(student) try: db.commit() except exc.IntegrityError as e: logging.error(e) db.rollback() raise ConflictException(detail=e.__str__()) except Exception as e: logging.error(e) db.rollback() raise BadRequestException(detail=e.__str__()) return student raise NotFoundException( detail= f"Student with id {student_id} not found in Division with if {division_id}" )
def read_user_by_id( user_id: str, current_user: models.User = Depends(deps.get_current_user), db: Session = Depends(deps.get_db), ) -> Any: """ Get a specific user by id. """ # Fetch User with the corresponding id from db user = crud.user.get(db, id=user_id) # Return the fetched object without checking perms if current_user is trying to fetch itself if user == current_user: return user # Raise exception if fetched User is not the current_user and the current_user is not a superuser if current_user.is_admin: if admin := crud.admin.get(db, current_user.id): if schemas.AdminPermissions(admin.permissions).is_allowed("admin"): if user: return user raise NotFoundException( detail="The user with this ID does not exist in the system", )
def read_school_by_id( school_id: str, current_user: models.User = Depends(deps.get_current_user), db: Session = Depends(deps.get_db), ) -> Any: """ Get a specific school by id. """ # Fetch School with the corresponding id from db school = crud.school.get(db, id=school_id) # Raise exception if the current_user doesn't belong to the fetched School and the current_user doesn't have perms if current_user.school_id == school_id: return school if current_user.is_admin: if admin := crud.admin.get(db, current_user.id): if schemas.AdminPermissions( admin.permissions).is_allowed("school"): if school: return school raise NotFoundException( detail= "The school with this ID does not exist in the system", )
def get_emp(emp_id): connection = happybase.Connection('localhost', transport='framed', protocol='compact') table = connection.table('emp_data') row = table.row(emp_id) if row is None: raise NotFoundException('Emp %s not found' % emp_id) else: return jsonify(row)
def request(self, method, url: str, **kwargs): rs = self.http.request(method=method, url=url, **kwargs) exception = AmazonExceptionElement( content=rs.content, site_config_entity=self.site_config_entity) if exception.error_500(): raise CrawlErrorException('{} 500+ error'.format(url)) if exception.not_found(): raise NotFoundException('{} not_found'.format(url)) self.need_captcha_flag = exception.need_validate() if self.need_captcha_flag: Captcha(self.site.domain, http=self.http, html=rs.text) rs = self.http.request(method=method, url=url, **kwargs) return rs
def read_student_by_id( student_id: str, current_user: models.User = Depends(deps.get_current_user), db: Session = Depends(deps.get_db) ) -> Any: """ Get a specific student by ID. """ # Fetch student with the corresponding ID from DB student = crud.student.get(db, id=student_id) # Return the fetched object without checking perms if current_student is trying to fetch itself if current_user.id == student_id: return student # check perms and return if student exists, else 404 if (admin := crud.admin.get(db, id=current_user.id)) and AdminPermissions( admin.permissions).is_allowed("student"): if student: return student raise NotFoundException( detail="The student with this ID does not exist in the system", )
def update_school( *, db: Session = Depends(deps.get_db), school_id: str, school_in: schemas.SchoolUpdate, current_admin: models.Admin = Depends( deps.get_current_admin_with_permission("school")), ) -> Any: """ Update a school. """ # Fetch existing school object from db school = crud.school.get(db, id=school_id) if not school: raise NotFoundException( detail="The school with this ID does not exist in the system", ) logging.info( f"Admin {current_admin.user_id} ({current_admin.user.email}) is updating School {school.id} " f"({school.name}) to {school_in.__dict__}") # Save updated object based on given SchoolUpdate object in db return crud.school.update(db, db_obj=school, obj_in=school_in)
def read_admin_by_id( admin_id: str, current_admin: models.Admin = Depends(deps.get_current_admin), db: Session = Depends(deps.get_db) ) -> Any: """ Get a specific admin by ID. """ # Fetch Admin with the corresponding ID from DB admin = crud.admin.get(db, id=admin_id) # Return the fetched object without checking perms if current_admin is trying to fetch itself if admin == current_admin: return admin # check perms and return if admin exists, else 404 if schemas.AdminPermissions(current_admin.permissions).is_allowed("admin"): if admin: return admin raise NotFoundException( detail="The admin with this ID does not exist in the system", ) raise ForbiddenException(detail="The user doesn't have enough privileges")
""" Get a specific student's divisions by ID. """ # Fetch student with the corresponding ID from DB if student := crud.student.get(db, id=student_id): # Return the fetched divisions if current_user is trying to fetch itself # or is an admin with the required perms if current_user.id == student_id or ( (admin := crud.admin.get(db, id=current_user.id)) and AdminPermissions(admin.permissions).is_allowed("student")): return list(student.divisions) raise ForbiddenException( detail="The user doesn't have enough privileges") raise NotFoundException( detail="The student with this ID does not exist in the system", ) @router.put("/{student_id}", response_model=schemas.Student) def update_student( *, db: Session = Depends(deps.get_db), student_id: str, student_in: schemas.StudentUpdate, current_admin: models.Admin = Depends( deps.get_current_admin_with_permission("student")), ) -> Any: """ Update student. """
elif user.type == "professor" and (professor := crud.professor.get( db, id=user.id)): return generate_timetable(db, professor.divisions) else: raise BadRequestException( detail= f"No timetable can be generated for user type {user.type}") raise BadRequestException(detail="User object not found!") @router.get("/{division_id}", response_model=dict[str, list[Lecture]]) def get_timetable_division( *, db: Session = Depends(deps.get_db), _: models.User = Depends(deps.get_current_admin_with_permission("course")), division_id: str, ) -> Any: if division := crud.division.get(db, id=division_id): return generate_timetable(db, [division]) raise NotFoundException(detail=f"Division with id {division_id} not found") def generate_timetable(db: Session, divisions: list[Division]) -> Dict: response: Dict = defaultdict(lambda: []) for day in calendar.day_name: for division in divisions: if lectures := crud.lecture.get_by_day_division( db, day=day, division_id=division.id): response[day] += lectures return response
""" return current_user @router.post("/password-recovery/{email}", response_model=schemas.Msg) def recover_password(email: str, db: Session = Depends(deps.get_db)) -> Any: """ Password Recovery """ if user := crud.user.get_by_email(db, email=email): password_reset_token = generate_password_reset_token(email=email) send_reset_password_email(email_to=user.email, email=email, token=password_reset_token) return {"msg": "Password recovery email sent"} raise NotFoundException( detail="The user with this username does not exist in the system.", ) @router.post("/reset-password/", response_model=schemas.Msg) def reset_password( token: str = Body(...), new_password: str = Body(...), db: Session = Depends(deps.get_db), ) -> Any: """ Reset password """ if email := verify_password_reset_token(token): if user := crud.user.get_by_email(db, email=email): if crud.user.is_active(user): hashed_password = get_password_hash(new_password)
limit: int = 100, _: models.Admin = Depends(deps.get_current_admin_with_permission("course")), ) -> Any: return crud.course.get_multi(db, skip=skip, limit=limit) @router.get("/{course_id}", response_model=schemas.Course) def read_course_by_id( *, db: Session = Depends(deps.get_db), course_id: str, _: models.Admin = Depends(deps.get_current_admin_with_permission("course")), ) -> Any: if course := crud.course.get(db, id=course_id): return course raise NotFoundException(detail="The course with this ID does not exist!") @router.post("/", response_model=schemas.Course) def create_course( *, db: Session = Depends(deps.get_db), course_in: schemas.CourseCreate, current_admin: models.Admin = Depends(deps.get_current_admin_with_permission("course")), ) -> Any: if crud.course.get_by_details( db, name=course_in.name, course_code=course_in.course_code, term_id=course_in.term_id,
limit: int = 100, _: models.Admin = Depends(deps.get_current_admin_with_permission("school")), ) -> Any: return crud.lecture.get_multi(db, skip=skip, limit=limit) @router.get("/{lecture_id}", response_model=schemas.Lecture) def read_lecture_by_id( *, db: Session = Depends(deps.get_db), lecture_id: str, _: models.Admin = Depends(deps.get_current_admin_with_permission("school")), ) -> Any: if lecture := crud.lecture.get(db, id=lecture_id): return lecture raise NotFoundException(detail="A lecture with this ID does not exist!") @router.get("/division/{division_id}", response_model=list[schemas.Lecture]) def get_lectures_for_division( *, db: Session = Depends(deps.get_db), division_id: str, _: models.User = Depends(deps.get_current_user) ) -> Any: if crud.division.get(db, id=division_id): return crud.lecture.get_by_division(db, division_id=division_id) raise NotFoundException(detail="A division with this ID does not exist!") @router.post("/", response_model=schemas.Lecture) def create_lecture( *, db: Session = Depends(deps.get_db),
if token_data.type != token_type: raise BadRequestException( detail="Invalid token", ) except ExpiredSignatureError: raise ForbiddenException(detail="Token has expired") except (jwt.JWTError, ValidationError) as e: logging.error(e.__str__()) raise ForbiddenException( detail="Could not validate credentials", ) if user := crud.user.get(db, id=token_data.sub): if user.is_active: return user raise ConflictException("User account is disabled") raise NotFoundException(detail="User not found") def get_current_user(db: Session = Depends(get_db), token: str = Depends(reusable_oauth2)) -> models.User: return get_user_from_token(token, "access", db) def get_current_user_refresh(db: Session = Depends(get_db), token: str = Depends(reusable_oauth2)) -> models.User: return get_user_from_token(token, "refresh", db) def get_current_admin(db: Session = Depends(get_db), user: models.User = Depends(get_current_user)) -> models.Admin: if user.is_admin: if admin := crud.admin.get(db, id=user.id): return admin raise NotFoundException(detail="Admin object not found")
deps.get_current_admin_with_permission("school")), ) -> Any: return crud.timeslot.get_multi(db, skip=skip, limit=limit) @router.get("/{timeslot_id}", response_model=schemas.TimeSlot) def read_timeslot_by_id( *, db: Session = Depends(deps.get_db), timeslot_id: str, _: models.Admin = Depends( deps.get_current_admin_with_permission("school")), ) -> Any: if timeslot := crud.timeslot.get(db, id=timeslot_id): return timeslot raise NotFoundException(detail="The timeslot with this ID does not exist!") @router.post("/", response_model=schemas.TimeSlot) def create_timeslot( *, db: Session = Depends(deps.get_db), timeslot_in: schemas.TimeSlotCreate, current_admin: models.Admin = Depends( deps.get_current_admin_with_permission("school")), ) -> Any: if crud.timeslot.get_by_details(db, start_time=timeslot_in.start_time, end_time=timeslot_in.end_time, school_id=timeslot_in.school_id):
def __try_find_document(job_id: str): try: return JobDocument.get_by_id(job_id) except DoesNotExist as mongo_exception: raise NotFoundException("Job with id %s not found" % job_id) from mongo_exception
@router.get("/submission/{submission_id}", response_model=list[schemas.File]) def get_file_by_submission( *, db: Session = Depends(deps.get_db), current_professor: models.Professor = Depends(deps.get_current_professor), submission_id: str, ) -> Any: """ Retrieve a file by id """ if file := crud.file.get(db, id=submission_id): if file.course_id in {division.course_id for division in current_professor.divisions}: return crud.file.get_by_submission(db, submission_id=submission_id) raise NotFoundException(detail=f"Assignment with id {submission_id} not found or you don't have access to it") @router.post("/{course_id}", response_model=schemas.File) def upload_file( *, db: Session = Depends(deps.get_db), file: UploadFile = File(...), current_user: models.User = Depends(deps.get_current_non_admin_user), course_id: str, file_type: str, description: str, submission_id: Optional[str] = None, ) -> Any: """ Update a user's profile picture
deps.get_current_admin_with_permission("course")), ) -> Any: return crud.division.get_multi(db, skip=skip, limit=limit) @router.get("/{division_id}", response_model=schemas.Division) def read_division_by_id( *, db: Session = Depends(deps.get_db), division_id: str, _: models.Admin = Depends( deps.get_current_admin_with_permission("course")), ) -> Any: if division := crud.division.get(db, id=division_id): return division raise NotFoundException(detail="The division with this ID does not exist!") @router.get("/{division_id}/students", response_model=list[schemas.Student]) def read_division_students_by_id( division_id: str, current_user: models.User = Depends(deps.get_current_user), db: Session = Depends(deps.get_db) ) -> Any: """ Get all students for a specific division by ID. """ # Fetch division with the corresponding ID from DB if division := crud.division.get(db, id=division_id): # Return the fetched object if current_user is the professor for the division # or admin with required perms
_: models.Admin = Depends(deps.get_current_admin_with_permission("term")), ) -> Any: terms = crud.term.get_multi(db, skip=skip, limit=limit) return terms @router.get("/{term_id}", response_model=schemas.Term) def read_term_by_id( *, db: Session = Depends(deps.get_db), term_id: str, _: models.Admin = Depends(deps.get_current_admin_with_permission("term")), ) -> Any: if term := crud.term.get(db, term_id): return term raise NotFoundException(detail="The term with this ID does not exist!") @router.get("/{term_id}/students", response_model=list[schemas.Student]) def read_term_students_by_id( *, db: Session = Depends(deps.get_db), term_id: str, _: models.Admin = Depends(deps.get_current_admin_with_permission("term")), ) -> Any: if term := crud.term.get(db, term_id): return term.students raise NotFoundException(detail="The term with this ID does not exist!") @router.post("/{term_id}/students",
def get_lectures_for_division( *, db: Session = Depends(deps.get_db), division_id: str, _: models.User = Depends(deps.get_current_user) ) -> Any: if crud.division.get(db, id=division_id): return crud.lecture.get_by_division(db, division_id=division_id) raise NotFoundException(detail="A division with this ID does not exist!")
def get_current_student(db: Session = Depends(get_db), user: models.User = Depends(get_current_user)) -> models.Student: if user.type == "student": if student := crud.student.get(db, id=user.id): return student raise NotFoundException(detail="Student object not found")
# Fetch professor with the corresponding ID from DB if professor := crud.professor.get(db, id=professor_id): # Return the fetched object without checking perms if current_professor is trying to fetch itself if current_user.id == professor_id: return professor # check perms and return if professor exists, else 404 if (admin := crud.admin.get( db, id=current_user.id)) and AdminPermissions( admin.permissions).is_allowed("professor"): return professor raise ForbiddenException( detail="The user doesn't have enough privileges") raise NotFoundException( detail="The professor with this ID does not exist in the system", ) @router.get("/{professor_id}/divisions", response_model=list[schemas.Division]) def read_professor_divisions_by_id( professor_id: str, current_user: models.User = Depends(deps.get_current_user), db: Session = Depends(deps.get_db) ) -> Any: """ Get all divisions for a specific professor by ID. """ # Fetch professor with the corresponding ID from DB if professor := crud.professor.get(db, id=professor_id): # Return the fetched object without checking perms if current_professor is trying to fetch itself
def route_not_found_exception(): raise NotFoundException()
def test_not_found_exception_should_be_code_404_and_msg_is_default_value( self): ex = NotFoundException() self.assertEqual(ex.code, 404) self.assertEqual(ex.description, 'Not Found Exception')
def get_current_admin(db: Session = Depends(get_db), user: models.User = Depends(get_current_user)) -> models.Admin: if user.is_admin: if admin := crud.admin.get(db, id=user.id): return admin raise NotFoundException(detail="Admin object not found")
def delete_todo(todo_id): todo = database.delete_todo(g.user, todo_id) if todo is None: raise NotFoundException('Todo %s not found' % todo_id) else: return jsonify(todo), 201
@router.get("/{school_id}/timeslots", response_model=list[schemas.TimeSlot]) def get_timeslots( *, db: Session = Depends(deps.get_db), school_id: str, _: models.Admin = Depends( deps.get_current_admin_with_permission("school")), ) -> Any: """ Get all timeslots in a school """ return crud.timeslot.get_by_school(db, school_id=school_id) @router.delete("/{school_id}") def delete_school( *, db: Session = Depends(deps.get_db), school_id: str, current_admin: models.Admin = Depends( deps.get_current_admin_with_permission("school")), ) -> Any: if school := crud.school.get(db, school_id): logging.info( f"Admin {current_admin.user_id} ({current_admin.user.email}) is deleting School {school.id} ({school.name})" ) return crud.school.remove(db, id=school_id) raise NotFoundException( detail="The school with this ID does not exist in the system!")
# check perms and return if admin exists, else 404 if schemas.AdminPermissions(current_admin.permissions).is_allowed("admin"): if admin: return admin raise NotFoundException( detail="The admin with this ID does not exist in the system", ) raise ForbiddenException(detail="The user doesn't have enough privileges") @router.put("/", response_model=schemas.Admin) def update_admin( *, db: Session = Depends(deps.get_db), admin_in: schemas.AdminUpdate, current_admin: models.Admin = Depends( deps.get_current_admin_with_permission("admin")), ) -> Any: """ Update admin. """ if admin := crud.admin.get(db, admin_in.user_id): logging.info( f"Admin {current_admin.user_id} ({current_admin.user.email}) is updating Admin {admin.user_id}" f"({admin.user.email}) to {admin_in.__dict__}") return crud.admin.update(db, db_obj=admin, obj_in=admin_in) raise NotFoundException(detail="This admin does not exist!", )