示例#1
0
 def is_user_admin(self, uid):
     logger.info(f"Checking whether user {uid} is an admin or not.")
     admin_doc = self.get_admin_document()
     user_docs = self._db.collection(f'{admin_doc.path}/users').where(
         'uid', '==', uid)
     user_docs = [user_doc for user_doc in user_docs.stream()]
     return len(user_docs) > 0
示例#2
0
 def add_question_to_mock_test(self,
                               mock_id,
                               question_text,
                               index=None,
                               explanation=None,
                               choices=None,
                               is_update=False):
     question_dict = {'text': question_text}
     if index:
         if is_update or not self.is_mock_question_present(mock_id, index):
             question_dict['index'] = index
         else:
             message = f"Mock question with index {index} already exists"
             logger.error(message)
             return message
     else:
         question_dict['index'] = self.get_largest_mock_question_index(
             mock_id) + 1
     if explanation:
         question_dict['explanation'] = explanation
     response = self._db.collection(f'mockTests/{mock_id}/questions').add(
         question_dict)
     logger.info(
         f"Response for adding a question {question_dict} is \n{response}")
     self.increment_mock_num_questions(mock_id, 1)
     if len(response) == 2:
         if choices:
             choices_response = self.add_choices_to_mock_question(
                 choices, mock_id, response[1].id)
             if len(choices_response) < 2:
                 return choices_response
         return response[1]
     else:
         logger.error(f"Failed to add question. Response = {response}")
         return f'{response}'
示例#3
0
 def auth_with_email(self, email, password):
     try:
         self.user = self.auth.sign_in_with_email_and_password(
             email, password)
         return True
     except:
         logger.info(f"Login failed for email {email}")
         return False
示例#4
0
 def handle_delete_mock(self):
     response = self.db.delete_mock_test(self.mock_id)
     if isinstance(response, Exception):
         self.context['error'] = response
         self.load_data()
         return self.render_view()
     logger.info(f'{response}')
     return redirect('admin:home')
示例#5
0
 def validate_parameters(name, prices):
     logger.info(f"Validating. name {name} and prices {prices}")
     if not name:
         return "Name of the mock test is invalid"
     try:
         for key in prices:
             prices[key] = float(prices[key])
     except ValueError:
         return "Prices are not proper."
示例#6
0
 def get_questions(self):
     questions = self.db.get_mock_questions(self.mock_id)
     questions_list = []
     for question in questions:
         question_dict = question.to_dict()
         question_dict['id'] = question.id
         questions_list.append(dict_to_object(question_dict))
         logger.info(f"Question obtained = {question_dict}")
     return questions_list
示例#7
0
 def get_admin_document(self):
     admin_docs = self._db.collection('groups').where('name', '==', 'admin')
     groups = [doc for doc in admin_docs.stream()]
     if len(groups) == 0:
         group = self.create_group(group_name='admin')
         if group is None:
             logger.error(f"Failed to create group admin")
             return None
         return group
     logger.info(f"Group = {groups[0].__dict__}")
     return groups[0].reference
示例#8
0
 def create_user(self, email, password):
     if email and password:
         try:
             self.user = self.auth.create_user_with_email_and_password(
                 email, password)
             self.auth.send_email_verification(self.user['idToken'])
             logger.info(f'{self.user}')
             return 'Successful. Verify your email id.'
         except Exception as e:
             logger.error(e)
             return e
示例#9
0
 def handle_post_request(self):
     logger.info("Handling post request")
     if 'save_mock_quiz_attributes' in self.request.POST:
         return self.handle_save_attributes()
     if 'add_new_question' in self.request.POST:
         return self.handle_new_question()
     if 'delete_mock' in self.request.POST:
         return self.handle_delete_mock()
     if 'delete_mock_question' in self.request.POST:
         return self.handle_delete_mock_question()
     self.load_data()
     return self.render_view()
 def has_played_new_quizzes(self, user_mock_tests):
     try:
         size_of_cached_quizzes = len(user_mock_tests)
         real_attempts_size = self.db.get_user_total_num_attempts(
             self.user_id)
         logger.info(
             f"size_of_cached: {size_of_cached_quizzes}, real = {real_attempts_size}, condition = {size_of_cached_quizzes < int(real_attempts_size)}"
         )
         return size_of_cached_quizzes < int(real_attempts_size)
     except Exception as e:
         logger.exception(e)
         if 'user_mock_tests' in self.request.session:
             del self.request.session['user_mock_tests']
         return True
示例#11
0
 def delete_mock_question(self, mock_id, question_id):
     """
     1. get all the choices and delete each
     2. delete question.
     """
     result = []
     try:
         response = self._db.document(
             f'mockTests/{mock_id}/questions/{question_id}').delete()
         result.append(response)
         self.increment_mock_num_questions(mock_id, -1)
     except Exception as e:
         logger.error(e)
         logger.info(f'Result of deletion = {result}')
         return e
     logger.info(f'Result of deletion = {result}')
     return result
示例#12
0
 def initialize_user_auth_details(self, id_token):
     """
     :param id_token: id_token
     :return: dict : {'localId': 'LIaDqg1YISPR0Qg22ibq9g5TAgH3', 'email': '*****@*****.**',
          'passwordHash': 'UkVEQUNURUQ=', 'emailVerified': True, 'passwordUpdatedAt': 1558621724112,
          'providerUserInfo': [
              {'providerId': 'password', 'federatedId': '*****@*****.**', 'email': '*****@*****.**',
               'rawId': '*****@*****.**'}], 'validSince': '1558621724', 'lastLoginAt': '1558682989858',
          'createdAt': '1558621724112'}
     """
     try:
         logger.info(f'user = {self.user}')
         if self.user is None:
             self.user = self.auth.get_account_info(id_token)['users'][0]
             logger.info(f'new user details = {self.user}')
     except Exception as e:
         logger.error(e)
     return self.user
示例#13
0
 def auth_with_email(self, email, password):
     try:
         logger.info(f'User before login = {self.user}')
         self.auth_details = self.auth.sign_in_with_email_and_password(
             email, password)
         logger.info(f"Login response = {self.auth_details}")
         self.initialize_user_auth_details(self.auth_details['idToken'])
         logger.info(f'User after login = {self.user}')
         return True
     except Exception as e:
         logger.info(f"Login failed for email {email}. {e}")
         return False
示例#14
0
 def get_choices_from_html(self):
     choice_ids = []
     for key in self.request.POST:
         if 'choice-' in key:
             choice_ids.append(key[7:])
     logger.info(f"Choice Ids found = {choice_ids}")
     choices = []
     for choice_id in choice_ids:
         choice_text = self.request.POST.get(f'choice-{choice_id}')
         if len(choice_text) == 0:
             continue
         choices.append({
             'index':
             int(self.request.POST.get(f'choiceIndex-{choice_id}', 0)),
             'text':
             choice_text,
             'isCorrect':
             bool(self.request.POST.get(f'is_correct_{choice_id}', False)),
         })
     return choices
示例#15
0
def master_validate(request, specs):
    """
    Returns a master validity status dict
    :param request: The HttpRequest object.
    :param specs: Should be of form: {'post': True, 'id_token': False}
    :return: Format: {'is_valid': True, 'master_status': [
            {'check_type': 'post', 'is_valid': True, 'considered': True, 'data': data, 'message': message}]}
    """
    master_status = []
    for validation_check in specs:
        status = validate_from_key(validation_check, request)
        status['check_type'] = validation_check
        status['considered'] = specs[validation_check]
        master_status.append(status)
        if status['considered'] and not status['is_valid']:
            break

    is_valid = all([
        status['is_valid'] for status in master_status if status['considered']
    ])
    result_status = {'is_valid': is_valid, 'master_status': master_status}
    logger.info("result_status = %s" % result_status)
    return result_status
示例#16
0
 def delete_mock_test(self, mock_id):
     """
     1. Get all documents in mockId/questions
     2. for each question, get all choices
         a. delete each choice
         b. delete question.
     3. delete mockId document.
     :param mock_id: String
     :return: response
     """
     questions_deleted = []
     try:
         questions_stream = self._db.collection(
             f'mockTests/{mock_id}/questions').stream()
         for question in questions_stream:
             question.reference.delete()
             questions_deleted.append(question.id)
         self._db.document(f'mockTests/{mock_id}').delete()
         self.increment_num_mock_tests(-1)
     except Exception as e:
         logger.error(f"Error while deleting mock test {mock_id}. {e}")
         return e
     logger.info(f'Questions deleted = {questions_deleted}')
     return questions_deleted
示例#17
0
def handle_logout(request):
    from django.contrib import auth as django_auth
    django_auth.logout(request)
    logger.info(FirebaseAuth.get_instance().user)
    return redirect('/')
示例#18
0
def home(request):
    details = FirebaseAuth.get_instance().auth.get_account_info(
        request.session['id_token'])
    logger.info(str(details))
    return render_to_response(template_name='app/index.html', context={})