def create(self, request: Request, course_id: int): card: Card = ASerializer().from_dict(request.data, Card) card.creator = request.user card.course = Course.get_or_404(pk=course_id, user=request.user) card.save() return JsonResponse( {"data": ASerializer().to_dict(card, groups=['card_detailed'])})
def create(self, request: Request): course: Course = ASerializer().from_dict(request.data, Course) course.teacher = request.user course.save() return JsonResponse({ "data": ASerializer().to_dict(course, groups=['course_detailed']) })
def signup(request): user: User = ASerializer().from_dict(request.data, User) user.save() jwt_token = __construct_token(user) return JsonResponse( ASerializer().to_dict({ 'token': jwt_token, 'user': user }, groups=['user_detailed']), status=200, )
def __construct_token(user: User) -> str: payload = { 'expires_in': datetime.utcnow() + timedelta(days=365), 'user_id': user.id, } return jwt.encode(ASerializer().to_dict(payload), settings.JWT_SECRET_KEY).decode('utf-8')
def list(self, request: Request): courses = Course.get_user_courses(request.user) return JsonResponse({ "data": ASerializer().to_dict(list(courses), groups=['course_detailed', 'user_basic']) })
def login(request: Request): login_body: LoginBody = ASerializer().from_dict(request.data, LoginBody) try: jwt_token, user = login_from_params(login_body.email, login_body.password) return JsonResponse( ASerializer().to_dict({ 'token': jwt_token, 'user': user }, groups=['user_detailed']), status=200, ) except User.DoesNotExist: return JsonResponse({'Error': "Invalid username/password"}, status="400")
def request_json(self, method_name, url: str, body: dict = None, *args, **kwargs): valid_method_names = [ 'get', 'post', 'put', 'patch', ] if method_name in valid_method_names: method = getattr(self.client, method_name) else: raise LookupError("Cannot find the method {0}".format(method_name)) try: final_url = reverse(url, args=args, kwargs=kwargs) except NoReverseMatch: final_url = url if self.current_token is not None: kwargs['HTTP_AUTHORIZATION'] = 'Bearer ' + self.current_token self.last_response = method( final_url, None if method_name == 'get' else ASerializer().serialize(body), content_type="application/json", *args, **kwargs) self.context = self.last_response.context return self.last_response
def list(self, request: Request, course_id: int): students = Student.objects.filter(course__pk=course_id) return JsonResponse({ "data": ASerializer().to_dict(list(students), groups=['student_basic', 'user_basic']) })
def update(self, request: Request, course_id: int, pk: int): # make sure data has the right format card = ASerializer().from_dict(request.data, UpdateCard) card_data = ASerializer().to_dict(card, groups=["card_basic"]) card: Card = get_object_or_404(Card, pk=pk, user=request.user) for key, value in card_data.items(): setattr(card, key, value) card.course = Course.get_or_404(pk=request.data['course_id'], user=request.user) card.save() return JsonResponse( {"data": ASerializer().to_dict(card, groups=['card_detailed'])})
def upload_photo(request: Request, file): user = request.user _, ext = os.path.splitext(file.name) path = f'static/users/photo_id_{uuid.uuid4()}_{user.id}{ext}' save_in_memory_file(file, path) user.photo_path = path user.save() return JsonResponse( {"data": ASerializer().to_dict(user, groups=['user_detailed'])})
def retrieve(self, request: Request, pk: str): user: User = request.user course: Course = Course.get_or_404(pk=request.data['course_id'], user=user) return JsonResponse({ "data": ASerializer().to_dict(course, groups=['course_detailed', 'user_detailed']) })
def retrieve(self, request: Request, course_id: int, pk: int): student: Student = get_object_or_404(Student, course__pk=course_id, id=pk) return JsonResponse({ "data": ASerializer().to_dict(student, groups=['student_detailed', 'user_detailed']) })
def students(self, request: Request, pk=None): if request.method == 'GET': students = Student.objects.filter(course__pk=pk) return JsonResponse({ "data": ASerializer().to_dict(list(students), groups=['student_basic', 'user_basic']) }) else: user = User.objects.get(id=request.data['user_id']) course = Course.objects.get(id=pk) student = Student() student.user = user student.course = course student.save() return JsonResponse({ "data": ASerializer().to_dict(student, groups=['student_basic', 'user_basic']) })
def upload_card_sentence_sound(request: Request, file, course_id: int, pk: int): # todo add security here card: Card = get_object_or_404(Card, pk=pk, creator=request.user) _, ext = os.path.splitext(file.name) path = f'static/cards/sentence_sound_id_{uuid.uuid4()}_{pk}{ext}' card.sentence_sound_path = path save_in_memory_file(file, path) card.save() return JsonResponse( {"data": ASerializer().to_dict(card, groups=['card_detailed'])})
def create(self, request: Request, course_id: int): user = User.objects.get(id=request.data['user_id']) course = Course.objects.get(id=course_id) student = Student() student.user = user student.course = course student.save() return JsonResponse({ "data": ASerializer().to_dict(student, groups=['student_basic', 'user_basic']) })
def authenticate(self, request): authorization = request.META.get('HTTP_AUTHORIZATION', '').replace('Bearer ', "", 1) if authorization == '': return None decoded_token = jwt.decode(authorization, settings.JWT_SECRET_KEY) token: DecodedToken = ASerializer().from_dict(decoded_token, DecodedToken) if token.expires_in <= datetime.utcnow(): raise jwt.exceptions.ExpiredSignatureError() user = User.objects.get(id=token.user_id) if user is None: raise jwt.exceptions.ImmatureSignatureError() return user, token
def get_content_json(self, response=None, _class: Optional[Type] = None): if response is None: response = self.last_response return ASerializer().unserialize(response.content, _class=_class)
def expires_in(self) -> datetime: return ASerializer().from_dict(self._decode_token(), DecodedToken).expires_in
def user_id(self) -> int: return ASerializer().from_dict(self._decode_token(), DecodedToken).user_id
def retrieve(self, request: Request, course_id: int, pk: int): card: Card = get_object_or_404(Card, pk=pk, user=request.user) return JsonResponse( {"data": ASerializer().to_dict(card, groups=['card_detailed'])})
def list(self, request: Request, course_id: int): cards = Card.get_user_cards(request.user).filter(course__pk=course_id) return JsonResponse({ "data": ASerializer().to_dict(list(cards), groups=['card_basic']) })