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}'
def reset_password(self, email): if email: try: self.auth.send_password_reset_email(email) return 'Please check your email to reset your password.' except Exception as e: logger.error(e) return e
def is_authenticated(self, session): id_token = session.get('id_token') if id_token: try: return self.is_authenticated_and_email_verified(id_token) or \ self.is_authenticated_and_email_verified(self.refresh_id_token(id_token)) except Exception as e: logger.error(e) return False
def initialize_firebase_app(): if CURRENT_ENV == DEV_ENV: return pyrebase.initialize_app(credentials.dev_credentials) elif CURRENT_ENV == PROD_ENV: return pyrebase.initialize_app(credentials.prod_credentials) else: logger.error("Current env is not set.") FirebaseManager.get_instance()
def clear_session_quiz_data(self): cleared_keys = ('mock_id', 'current_quiz', 'start_time', 'time_limit', 'num_questions', 'quiz_state_id', 'current_question_number') for key in cleared_keys: try: del self.request.session[key] except Exception as e: logger.error(e)
def is_authenticated(self, id_token): if id_token: try: is_auth = FirebaseManager.get_instance().is_authenticated( id_token) return is_auth and self.auth.get_account_info( id_token)['users'][0]['emailVerified'] except Exception as e: logger.error(e) return False
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
def update_last_updated(self): try: timestamp = datetime.now() self.request.session['last_updated'] = utils.datetime_to_timestamp( timestamp) self.db.update_quiz_state(self.user_id, self.mock_id, self.quiz_state_id, {'lastUpdated': timestamp}) except Exception as e: logger.error( f"Error during updating the last updated timestamp. {e}")
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
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
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
def get_view(self): if self.request.method == 'POST': if 'add_mock' in self.request.POST: name = self.request.POST.get('name') prices = { 'india': self.request.POST.get('price_india'), 'uk': self.request.POST.get('price_uk') } message = self.validate_parameters(name=name, prices=prices) if message is not None: self.context['error'] = message else: mock_doc = self.db.create_mock_test(name, prices) if mock_doc: return redirect('admin:edit_mock', mock_doc.id) else: logger.error(f"Mock id = {mock_doc}") self.context['error'] = 'Error creating mock.' return self.render_view()
def create_mock_test(self, name, prices, index=None, max_duration=60): index = index if index is not None else self.get_largest_mock_test_index( ) + 1 response = self._db.collection('mockTests').add({ 'name': name, 'price': prices, 'index': index, 'numQuestions': 0, 'largestQuestionIndex': 0, 'duration': max_duration, # TODO: Add this max_duration from views }) if len(response) > 1: self.increment_num_mock_tests(1) return response[1] logger.error(f"Problem creating mock_test. {response}")
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
def __init__(self, message, *args, **kwargs): Exception.__init__(self, message, *args, **kwargs) logger.error(message)
def create_group(self, group_name, permissions=None): group = {'name': group_name, 'permissions': permissions} response = self._db.collection('groups').add(group) if len(response) == 2: return response[1] logger.error(f"problem creating group {group_name}. {response}")
def validate_response(self, response): if len(response) == 2 and isinstance(response[1], DocumentReference): return response[1] else: logger.error(f'Failed to add new quiz. {response}') return str(response)