Exemple #1
0
    def post(self, request, format=None):
        try:
            if not request.user.is_authenticated():
                raise UserNotAuthenticated()

            ts_id = request.data.get('ts_id')

            if ts_id is None:
                raise TestSeriesNotSelected()

            try:
                ts = TestSeries.objects.get(id=int(ts_id))
                request.session['test_series_id'] = ts.id
                request.session['question_no'] = 1
                return Response({'success': True})
            except TestSeries.DoesNotExist:
                raise ValidTestSeriesNotSelected()

        except ValidTestSeriesNotSelected:
            return APIErrorResponse.valid_test_series_not_selected()
        except TestSeriesNotSelected:
            return APIErrorResponse.test_series_not_selected()
        except UserNotAuthenticated:
            return APIErrorResponse.forbidden_action()
        except Exception as e:
            return APIErrorResponse.internal_server_error(e.message)
Exemple #2
0
    def post(self, request):
        lr_dto = _LoginRequestDTO(data=request.data)

        if not lr_dto.is_valid():
            return Response(lr_dto.errors, status.HTTP_400_BAD_REQUEST)

        lr_data = lr_dto.data
        user = authenticate(username=lr_data['username'],
                            password=lr_data['password'])
        if user and user.is_active:
            login(request, user)

            response = Response({
                'status': 'success',
                'msg': 'User logged in successfully',
                'userId': user.id,
                'email': user.email,
            })
            authenticated_user_cookie_map = {
                "userId": user.id,
                "email": user.email,
            }

            request.session['test_series_id'] = TestSeries.objects.order_by(
                '?').first().id
            request.session['question_no'] = 1

            response.set_cookie(
                'authenticated_user',
                urllib.quote(json.dumps(authenticated_user_cookie_map)))
            return response
        else:
            return APIErrorResponse.invalid_login_credentials(
                lr_data['username'])
Exemple #3
0
    def post(self, request):
        lr_dto = _LoginRequestDTO(data=request.data)

        if not lr_dto.is_valid():
            return Response(lr_dto.errors, status.HTTP_400_BAD_REQUEST)

        lr_data = lr_dto.data

        user = authenticate(username=lr_data['username'],
                            password=lr_data['password'])

        if user is None:
            try:
                user = get_user_model().objects.create_user(
                    username=lr_data['username'],
                    password=lr_data['username'],
                    email=lr_data['username'])
            except Exception as e:
                return APIErrorResponse.user_already_exist(lr_data['username'])
            if user is not None:
                user.is_staff = True
                # save user properties in sqlite auth_user table.
                user.save()
                login(request, user)

                response = Response({
                    'status': 'success',
                    'msg': 'User logged in successfully',
                    'userId': user.id,
                    'email': user.email,
                })
                authenticated_user_cookie_map = {
                    "userId": user.id,
                    "email": user.email,
                }

                # request.session['test_series_id'] = TestSeries.objects.order_by('?').first().id
                # request.session['question_no'] = 1

                response.set_cookie(
                    'authenticated_user',
                    urllib.quote(json.dumps(authenticated_user_cookie_map)))
                return response

        else:
            return APIErrorResponse.user_already_exist(lr_data['username'])
Exemple #4
0
    def get(self, request, format=None):
        try:
            if not request.user.is_authenticated():
                raise UserNotAuthenticated()

            test_series = TestSeries.objects.all()

            test_series_list = []
            for ts in test_series:
                test_series_list.append(dict(id=ts.id, name=ts.name))

            data = dict(test_series=test_series_list)
            return Response(data)
        except UserNotAuthenticated:
            return APIErrorResponse.forbidden_action()
Exemple #5
0
    def get(self, request, format=None):
        try:
            if not request.user.is_authenticated():
                raise UserNotAuthenticated()

            test_series_id = request.session['test_series_id']

            test_series = TestSeries.objects.get(id=test_series_id)

            questions = test_series.questions.all().values_list('id', flat=True)

            answered_choices = UserQuestionAnswer.objects.filter(user=request.user,
                                                                 question__id__in=questions,
                                                                 # session_end=False,
                                                                 ).order_by('-id')
            question_ans_mapping = dict()
            correct_choices = 0
            wrong_choices = 0

            for ac in answered_choices:
                if question_ans_mapping.get(ac.question.id) is None:
                    question_ans_mapping[ac.question.id] = ac.is_correct
                    if ac.is_correct:
                        correct_choices += 1
                    else:
                        wrong_choices += 1

            data = dict(
                total_question=len(questions),
                total_answered=len(question_ans_mapping.keys()),
                correct_choices=correct_choices,
                wrong_choices=wrong_choices
            )

            qs = UserQuestionAnswer.objects.filter(user=request.user)
            qs.update(session_end=True)

            # request.session['test_series_id'] = 0
            request.session['review_test_series_id'] = request.session['test_series_id']
            request.session['question_no'] = 1

            return Response(data)
        except UserNotAuthenticated:
            return APIErrorResponse.forbidden_action()
Exemple #6
0
    def post(self, request, format=None):
        try:
            if not request.user.is_authenticated():
                raise UserNotAuthenticated()

            test_series_id = request.session['test_series_id']
            question_no = request.session['question_no']
            answer = request.data.get('answer')

            test_series = TestSeries.objects.get(id=test_series_id)

            questions = test_series.questions.all()

            if answer:
                answered_q_no = question_no
                answered_q = questions[answered_q_no - 1]

                correct_answer = answered_q.options.get(is_choice_correct=True)
                choice = Choice.objects.get(id=int(answer))
                user_answers, created = UserQuestionAnswer.objects.get_or_create(
                    user=request.user, question=answered_q, session_end=False)
                user_answers.is_correct = correct_answer.id == choice.id
                user_answers.choice = choice

                user_answers.save()

            if request.data.get('action') == "next":
                question_no += 1
            elif request.data.get('action') == "prev":
                question_no -= 1

            request.session['question_no'] = question_no

            try:
                selected_q = questions[question_no - 1]
            except Exception as e:
                logger.info("No question available. Error {error}".format(
                    error=e.message))
                return APIResponse.no_content()

            options = selected_q.options.all().values('id', 'choice', 'type')

            options_list = []

            try:
                answered_choice = UserQuestionAnswer.objects.filter(
                    user=request.user,
                    question=selected_q,
                    session_end=False,
                ).latest('id')
            except:
                answered_choice = None

            for option in options:
                tmp = {
                    'id': option['id'],
                    'choice': option['choice'],
                    'answered': False,
                    'type': option['type']
                }
                if option['type'] == "Image":
                    tmp['choice'] = tmp['choice'].replace(
                        "s3.us-east-2.amazonaws.com/edtech-ameltus",
                        "cdn-imgix-open.ameltus.com")
                if answered_choice and option[
                        'id'] == answered_choice.choice.id:
                    tmp['answered'] = True
                options_list.append(tmp)

            data = {
                "question_no": question_no,
                "topic": selected_q.topic.name,
                "question": selected_q.description,
                "options": options_list,
                "image": selected_q.diagram
            }
            return Response(data)
        except UserNotAuthenticated:
            return APIErrorResponse.forbidden_action()

        except Exception as e:
            logger.exception(e.message)
            return APIErrorResponse.internal_server_error(e.message)
Exemple #7
0
    def post(self, request, format=None):
        try:
            if not request.user.is_authenticated():
                raise UserNotAuthenticated()

            test_series_id = request.session.get('review_test_series_id')
            if test_series_id is None:
                return APIResponse.no_last_test_done()
            question_no = request.session['question_no']

            test_series = TestSeries.objects.get(id=test_series_id)
            questions = test_series.questions.all()

            if request.data.get('action') == "next":
                question_no += 1
            elif request.data.get('action') == "prev":
                question_no -= 1

            request.session['question_no'] = question_no

            try:
                selected_q = questions[question_no - 1]
            except Exception as e:
                logger.info("No question available. Error {error}".format(
                    error=e.message))
                return APIResponse.no_content()

            options = selected_q.options.all().values('id', 'choice', 'type',
                                                      'is_choice_correct')

            options_list = []

            try:
                answered_choice = UserQuestionAnswer.objects.filter(
                    user=request.user,
                    question=selected_q,
                    session_end=True,
                ).latest('id')
            except:
                answered_choice = None

            for option in options:
                tmp = {
                    'id': option['id'],
                    'choice': option['choice'],
                    'answered': False,
                    'type': option['type'],
                    'is_choice_correct': option['is_choice_correct']
                }
                if answered_choice and option[
                        'id'] == answered_choice.choice.id:
                    tmp['answered'] = True
                options_list.append(tmp)

            data = {
                "question_no": question_no,
                "topic": selected_q.topic.name,
                "question": selected_q.description,
                "options": options_list,
                "image": selected_q.diagram
            }
            return Response(data)
        except UserNotAuthenticated:
            return APIErrorResponse.forbidden_action()

        except Exception as e:
            logger.exception(e.message)
            return APIErrorResponse.internal_server_error(e.message)
Exemple #8
0
 def options(self, request, *args, **kwargs):
     return APIErrorResponse.method_not_allowed()