Esempio n. 1
0
def user_quizarena_solve_view(request, quiz_id):
    """
    Attempt the quiz here. Setup for the player to attempt.
    Disallow repeated attempts.
    :param request:
    :param quiz_id:
    :return:
    """
    request, alert_type, alert_message = init_alerts(request=request)
    quiz_adapter = QuizAdapter()
    quiz_tools = QuizTools()

    quiz = quiz_adapter.exists(quiz_id)
    if not quiz:
        set_alert_session(session=request.session, message="No such quiz present", alert_type=DANGER)
        return HttpResponseRedirect(reverse(SERVICE_USER_QUIZARENA_HOME))
    content = quiz_tools.download_quiz_content(quiz_model=quiz)
    if not content:
        set_alert_session(session=request.session, message="This quiz is unavailable", alert_type=DANGER)
        return HttpResponseRedirect(reverse(SERVICE_USER_QUIZARENA_HOME))

    context = {
        REQUEST: request,
        USER: request.user,
        ALERT_MESSAGE: alert_message,
        ALERT_TYPE: alert_type,
        'quiz_form': content.quiz_form
    }
    request.session['quiz'] = content.quiz_model

    return render(request, USER_QUIZARENA_SOLVE_PAGE, context)
def get_password_confirmation(request, uidb64=None, token=None, *args, **kwargs):
    if request.method == 'GET':
        return render(request, RESET_PASSWORD_CONFIRM, {'uidb64': uidb64, 'token': token})

    # uidb64, token is for verification purpose
    new_password = request.POST.get('password')
    uidb64 = request.POST.get('uidb64')
    token = request.POST.get('token')
    user_adapter = UserAdapter()
    try:
        assert uidb64 is not None and token is not None
        uid = urlsafe_base64_decode(uidb64)
        user = user_adapter.get_user_from_django_pk(uid)
    except Exception:
        user = None

    if user is not None and default_token_generator.check_token(user, token):
        # Changing password
        user_adapter.user_change_password(user, new_password)

        success_alert = 'Password has been reset.'
        set_alert_session(session=request.session, message=success_alert, alert_type=SUCCESS)
        return HttpResponseRedirect(reverse(SERVICE_MAIN_HOME))
    else:
        failure_alert = 'Password reset has not been unsuccessful.'
        set_alert_session(session=request.session, message=failure_alert, alert_type=DANGER)
        return HttpResponseRedirect(reverse(SERVICE_MAIN_HOME))
Esempio n. 3
0
def login_check_view(request):
    """
    Checks login authentication result and gives failure alert if unsuccessful
    :param request: user request
    :return: renders a page with context
    """

    username = request.POST.get(USERNAME)
    password = request.POST.get(PASSWORD)

    # Authenticate the user with the provided username and password.
    # Django authentication is used here.
    user = authenticate(username=username, password=password)
    if user is not None:
        if user.is_active:
            # Authentication successful
            auth_login(request, user)
            return HttpResponseRedirect(reverse(SERVICE_USER_SETUP))

        else:
            # Authentication failure as user was disabled.
            # Creating respective alerts.
            set_alert_session(
                session=request.session,
                message="This account has been disabled. Contact the admin.",
                alert_type=DANGER)
            return HttpResponseRedirect(reverse(SERVICE_MAIN_HOME))

    else:
        # Authentication failure
        # the authentication system was unable to verify the username and password
        set_alert_session(session=request.session,
                          message="The username or password were incorrect.",
                          alert_type=DANGER)
        return HttpResponseRedirect(reverse(SERVICE_MAIN_HOME))
Esempio n. 4
0
def login_check_view(request):
    """
    Checks login authentication result and gives failure alert if unsuccessful
    :param request: user request
    :return: renders a page with context
    """

    username = request.POST.get(USERNAME)
    password = request.POST.get(PASSWORD)

    # Authenticate the user with the provided username and password.
    # Django authentication is used here.
    user = authenticate(username=username, password=password)
    if user is not None:
        if user.is_active:
            # Authentication successful
            auth_login(request, user)
            return HttpResponseRedirect(reverse(SERVICE_USER_SETUP))

        else:
            # Authentication failure as user was disabled.
            # Creating respective alerts.
            set_alert_session(session=request.session, message="This account has been disabled. Contact the admin.",
                              alert_type=DANGER)
            return HttpResponseRedirect(reverse(SERVICE_MAIN_HOME))

    else:
        # Authentication failure
        # the authentication system was unable to verify the username and password
        set_alert_session(session=request.session, message="The username or password were incorrect.",
                          alert_type=DANGER)
        return HttpResponseRedirect(reverse(SERVICE_MAIN_HOME))
Esempio n. 5
0
def user_quizarena_solve_view(request, quiz_id):
    """
    Attempt the quiz here. Setup for the player to attempt.
    Disallow repeated attempts.
    :param request:
    :param quiz_id:
    :return:
    """
    quiz_adapter = QuizAdapter()
    quiz_tools = QuizTools()
    quiz_storage_handler = QuizStorageHandler()

    quiz = quiz_adapter.exists(quiz_id)
    try:
        if not quiz:
            raise ValueError("No such quiz present")
        quiz_complete_model = quiz_storage_handler.download_quiz_content(quiz_model=quiz)
        if not quiz_complete_model:
            raise ValueError("This quiz is unavailable")

        quiz_tools.check_quiz_eligibility((request.session.get(USER_PROFILE_MODEL)), quiz_complete_model, quiz_id)

    except ValueError as err:
        set_alert_session(session=request.session,
                          message=str(err),
                          alert_type=DANGER)
        return ControllerModel(view=SERVICE_USER_QUIZARENA_HOME, redirect=True)
    context = {'quiz_form': quiz_complete_model.quiz_form}

    request.session['quiz'] = quiz_complete_model.quiz_model

    return ControllerModel(view=USER_QUIZARENA_SOLVE_PAGE, redirect=False, context=context)
Esempio n. 6
0
def user_setup_view(request):
    """
    Sets up the user profile and user models
    :param request:
    :return:
    """
    user_adapter = UserAdapter()

    # User Exists and nothing else required
    if user_adapter.exists(request.user):
        return HttpResponseRedirect(reverse(SERVICE_USER_HOME))

    # User does not exist but has email field in social authentication
    elif request.user.email and str(request.user.email).strip():
        # Creating username from email address
        username = "".join([str(request.user.pk), request.user.email])
        # username exists
        if user_adapter.exists(username):
            return HttpResponseRedirect(reverse(SERVICE_USER_HOME))
        # Create user
        else:
            if user_adapter.create_and_save_model(
                    username=username,
                    first_name=request.user.first_name,
                    last_name=request.user.last_name):
                return HttpResponseRedirect(reverse(SERVICE_USER_HOME))
            # This condition should never be encountered
            else:
                set_alert_session(
                    session=request.session,
                    message=
                    "Trouble signing in. Contact the support for help !",
                    alert_type=DANGER)
                return HttpResponseRedirect(reverse(SERVICE_MAIN_HOME))

    # User not present and no email field (facebook) so creating username from username and pk
    else:
        # Creating username from pk and username in auth
        username = "".join(
            [str(request.user.pk), request.user.username, "@bookturks.com"])
        if user_adapter.exists(username):
            return HttpResponseRedirect(reverse(SERVICE_USER_HOME))
        else:
            if user_adapter.create_and_save_model(
                    username=username,
                    first_name=request.user.first_name,
                    last_name=request.user.last_name):
                return HttpResponseRedirect(reverse(SERVICE_USER_HOME))
            else:
                set_alert_session(
                    session=request.session,
                    message=
                    "Trouble signing in. Contact the support for help !",
                    alert_type=DANGER)
                return HttpResponseRedirect(reverse(SERVICE_MAIN_HOME))
Esempio n. 7
0
def user_quiz_delete_view(request):
    """
    Deletes
    :param request:
    :return:
    """
    quiz_tools = QuizTools()
    user_adapter = UserAdapter()
    quiz_adapter = QuizAdapter()

    quiz_id = request.POST.get('quiz_id')
    quiz = quiz_adapter.exists(quiz_id)

    try:
        # Check whether user deleting this quiz is admin or owner or any other staff person
        if not request.user.is_staff and \
                not (user_adapter.get_user_instance_from_django_user(request.user) == quiz.quiz_owner):
            raise ValueError(
                "You do not have the permission to delete this quiz. This action will be reported"
            )
        if not quiz:
            raise ValueError("No such quiz.")

        # Unlink all tags from the quiz
        quiz_tools.unlink_all_tags_of_quiz(quiz)
        # Deletes from storage
        quiz_tools.delete_quiz_from_storage(quiz)
        # Deletes from database
        quiz_adapter.delete_model(quiz)
        # Deletes from the user profile
        UserProfileTools.remove_my_quiz_profile(session=request.session,
                                                quiz_model=quiz)

        # Save the profile
        user_profile_tools = UserProfileTools()
        future = user_profile_tools.save_profile(request.session)
        # Wait for asynchronous callback
        future.result()

    except ValueError as err:
        set_alert_session(session=request.session,
                          message=str(err),
                          alert_type=DANGER)
        return HttpResponseRedirect(reverse(SERVICE_USER_MYQUIZ_HOME))

    set_alert_session(session=request.session,
                      message="The quiz has been successfully deleted",
                      alert_type=SUCCESS)
    return HttpResponseRedirect(reverse(SERVICE_USER_MYQUIZ_HOME))
Esempio n. 8
0
def user_quizarena_result_view(request):
    """
    Result of the quiz attempt
    :param request:
    :return:
    """
    quiz = request.session.get('quiz')

    user_adapter = UserAdapter()
    quiz_storage_handler = QuizStorageHandler()
    user_profile_storage_handler = UserProfileStorageHandler()
    quiz_checker = QuizChecker()
    # Get the user model from the request.
    user = user_adapter.get_user_instance_from_django_user(request.user)

    try:
        if not quiz or not user:
            raise ValueError("Invalid quiz attempt.")

        content = quiz_storage_handler.download_quiz_content(quiz_model=quiz)

        if not content:
            raise ValueError("This quiz is unavailable")

        answer_key = content.answer_key
        user_answer_key = dict(request.POST)

        quiz_result_model = quiz_checker.get_quiz_result(quiz_model=quiz, answer_key=answer_key,
                                                         user_answer_key=user_answer_key)
    except ValueError as err:
        set_alert_session(session=request.session,
                          message=str(err),
                          alert_type=DANGER)
        return ControllerModel(view=SERVICE_USER_QUIZARENA_HOME, redirect=True)

    # Save result in model
    UserProfileTools.save_attempted_quiz_profile(session=request.session, quiz_result_model=quiz_result_model)
    # Save the profile
    future = user_profile_storage_handler.save_profile(request.session)

    context = {'result': quiz_result_model}

    # Clearing the session
    del request.session['quiz']

    # Wait for asynchronous callback
    future.result()
    return ControllerModel(view=USER_QUIZARENA_RESULT_PAGE, redirect=False, context=context)
Esempio n. 9
0
def user_quizarena_result_view(request):
    """
    Result of the quiz attempt
    :param request:
    :return:
    """
    request, alert_type, alert_message = init_alerts(request=request)
    quiz = request.session.get('quiz')

    user_adapter = UserAdapter()
    quiz_tools = QuizTools()
    # Get the user model from the request.
    user = user_adapter.get_user_instance_from_django_user(request.user)

    if not quiz or not user:
        set_alert_session(session=request.session, message="Invalid quiz attempt.", alert_type=DANGER)
        return HttpResponseRedirect(reverse(SERVICE_USER_QUIZARENA_HOME))

    content = quiz_tools.download_quiz_content(quiz_model=quiz)
    if not content:
        set_alert_session(session=request.session, message="This quiz is unavailable", alert_type=DANGER)
        return HttpResponseRedirect(reverse(SERVICE_USER_QUIZARENA_HOME))

    answer_key = content.answer_key
    user_answer_key = dict(request.POST)

    quiz_result_model = quiz_tools.get_quiz_result(quiz_model=quiz, answer_key=answer_key,
                                                   user_answer_key=user_answer_key)
    # Save result in model
    UserProfileTools.save_attempted_quiz_profile(session=request.session, quiz_result_model=quiz_result_model)
    # Save the profile
    user_profile_tools = UserProfileTools()
    future = user_profile_tools.save_profile(request.session)

    context = {
        REQUEST: request,
        USER: request.user,
        ALERT_MESSAGE: alert_message,
        ALERT_TYPE: alert_type,
        'result': quiz_result_model
    }

    # Clearing the session
    del request.session['quiz']

    # Wait for asynchronous callback
    future.result()
    return render(request, USER_QUIZARENA_RESULT_PAGE, context)
Esempio n. 10
0
def user_quizarena_result_view(request):
    """
    Result of the quiz attempt
    :param request:
    :return:
    """
    request, alert_type, alert_message = init_alerts(request=request)
    quiz = request.session.get('quiz')

    user_adapter = UserAdapter()
    quiz_tools = QuizTools()
    # Get the user model from the request.
    user = user_adapter.get_user_instance_from_django_user(request.user)

    if not quiz or not user:
        set_alert_session(session=request.session, message="Invalid quiz attempt.", alert_type=DANGER)
        return HttpResponseRedirect(reverse(SERVICE_USER_QUIZARENA_HOME))

    content = quiz_tools.download_quiz_content(quiz_model=quiz)
    if not content:
        set_alert_session(session=request.session, message="This quiz is unavailable", alert_type=DANGER)
        return HttpResponseRedirect(reverse(SERVICE_USER_QUIZARENA_HOME))

    answer_key = content.answer_key
    user_answer_key = dict(request.POST)

    quiz_result_model = quiz_tools.get_quiz_result(quiz_model=quiz, answer_key=answer_key,
                                                   user_answer_key=user_answer_key)
    # Save result in model
    UserProfileTools.save_attempted_quiz_profile(session=request.session, quiz_result_model=quiz_result_model)
    # Save the profile
    user_profile_tools = UserProfileTools()
    future = user_profile_tools.save_profile(request.session)

    context = {
        REQUEST: request,
        USER: request.user,
        ALERT_MESSAGE: alert_message,
        ALERT_TYPE: alert_type,
        'result': quiz_result_model
    }

    # Clearing the session
    del request.session['quiz']

    # Wait for asynchronous callback
    future.result()
    return render(request, USER_QUIZARENA_RESULT_PAGE, context)
Esempio n. 11
0
def user_quiz_delete_view(request):
    """
    Deletes
    :param request:
    :return:
    """
    quiz_tools = QuizTools()
    quiz_storage_handler = QuizStorageHandler()
    user_profile_storage_handler = UserProfileStorageHandler()

    user_adapter = UserAdapter()
    quiz_adapter = QuizAdapter()

    quiz_id = request.POST.get('quiz_id')
    quiz = quiz_adapter.exists(quiz_id)

    try:
        # Check whether user deleting this quiz is admin or owner or any other staff person
        if not request.user.is_staff and \
                not (user_adapter.get_user_instance_from_django_user(request.user) == quiz.quiz_owner):
            raise ValueError("You do not have the permission to delete this quiz. This action will be reported")
        if not quiz:
            raise ValueError("No such quiz.")

        # Unlink all tags from the quiz
        quiz_tools.unlink_all_tags_of_quiz(quiz)
        # Deletes from storage
        quiz_storage_handler.delete_quiz_from_storage(quiz)
        # Deletes from database
        quiz_adapter.delete_model(quiz)
        # Deletes from the user profile
        UserProfileTools.remove_my_quiz_profile(session=request.session, quiz_model=quiz)

        # Save the profile
        future = user_profile_storage_handler.save_profile(request.session)
        # Wait for asynchronous callback
        future.result()

    except ValueError as err:
        set_alert_session(session=request.session,
                          message=str(err),
                          alert_type=DANGER)
        return HttpResponseRedirect(reverse(SERVICE_USER_MYQUIZ_HOME))

    set_alert_session(session=request.session, message="The quiz has been successfully deleted", alert_type=SUCCESS)
    return HttpResponseRedirect(reverse(SERVICE_USER_MYQUIZ_HOME))
Esempio n. 12
0
def user_setup_view(request):
    """
    Sets up the user profile and user models
    :param request:
    :return:
    """
    user_adapter = UserAdapter()

    # User Exists and nothing else required
    if user_adapter.exists(request.user):
        return HttpResponseRedirect(reverse(SERVICE_USER_HOME))

    # User does not exist but has email field in social authentication
    elif request.user.email and str(request.user.email).strip():
        # Creating username from email address
        username = request.user.email
        # username exists
        if user_adapter.exists(username):
            return HttpResponseRedirect(reverse(SERVICE_USER_HOME))
        # Create user
        else:
            if user_adapter.create_and_save_model(username=username, first_name=request.user.first_name,
                                                  last_name=request.user.last_name):
                return HttpResponseRedirect(reverse(SERVICE_USER_HOME))
            # This condition should never be encountered
            else:
                set_alert_session(session=request.session, message="Trouble signing in. Contact the support for help !",
                                  alert_type=DANGER)
                return HttpResponseRedirect(reverse(SERVICE_MAIN_HOME))

    # User not present and no email field (facebook) so creating username from username and pk
    else:
        # Creating username from pk and username in auth
        username = "".join([request.user.username, "@bookturks.com"])
        if user_adapter.exists(username):
            return HttpResponseRedirect(reverse(SERVICE_USER_HOME))
        else:
            if user_adapter.create_and_save_model(username=username, first_name=request.user.first_name,
                                                  last_name=request.user.last_name):
                return HttpResponseRedirect(reverse(SERVICE_USER_HOME))
            else:
                set_alert_session(session=request.session, message="Trouble signing in. Contact the support for help !",
                                  alert_type=DANGER)
                return HttpResponseRedirect(reverse(SERVICE_MAIN_HOME))
Esempio n. 13
0
def user_quiz_verifier_view(request):
    """
    Verifies the form for errors
    Asks the user to prepare the answer key
    :param request: User request
    :return: Message depending on success or failure of quiz creation.
    """
    request, alert_type, alert_message = init_alerts(request=request)
    quiz_tools = QuizTools()

    # Quiz form is the HTML form which can be displayed and submitted by a user
    quiz_form = request.POST.get('quiz_form')
    # Quiz data is the template created by the form builder. This can be editted
    quiz_data = request.POST.get('quiz_data')

    try:
        # Do not allow empty forms to be submitted
        if not quiz_data or not quiz_form:
            raise ValueError("Quiz data was not provided")

        # Parse the form to remove irrelevant data.
        # It will be better and cleaner to change the javascript so this will not be required
        quiz_form = quiz_tools.parse_form(quiz_form=quiz_form)

    except ValueError as err:
        set_alert_session(session=request.session,
                          message=str(err),
                          alert_type=DANGER)
        return HttpResponseRedirect(reverse(SERVICE_USER_QUIZ_INIT))

    # Add this form so that it can be displayed in the next page
    context = {
        'quiz_form': quiz_form,
    }
    # Save to session to pass to the next view
    quiz_complete_model = request.session.get('quiz_complete_model')
    quiz_complete_model.quiz_form = quiz_form
    quiz_complete_model.quiz_data = quiz_data
    session_insert_keys(request.session,
                        quiz_complete_model=quiz_complete_model)

    return render(request, USER_QUIZ_VERIFIER_PAGE, context)
Esempio n. 14
0
def user_quiz_verifier_view(request):
    """
    Verifies the form for errors
    Asks the user to prepare the answer key
    :param request: User request
    :return: Message depending on success or failure of quiz creation.
    """
    request, alert_type, alert_message = init_alerts(request=request)
    quiz_tools = QuizTools()

    # Quiz form is the HTML form which can be displayed and submitted by a user
    quiz_form = request.POST.get('quiz_form')
    # Quiz data is the template created by the form builder. This can be editted
    quiz_data = request.POST.get('quiz_data')

    try:
        # Do not allow empty forms to be submitted
        if not quiz_data or not quiz_form:
            raise ValueError("Quiz data was not provided")

        # Parse the form to remove irrelevant data.
        # It will be better and cleaner to change the javascript so this will not be required
        quiz_form = quiz_tools.parse_form(quiz_form=quiz_form)

    except ValueError as err:
        set_alert_session(session=request.session,
                          message=str(err),
                          alert_type=DANGER)
        return HttpResponseRedirect(reverse(SERVICE_USER_QUIZ_INIT))

    # Add this form so that it can be displayed in the next page
    context = {
        'quiz_form': quiz_form,
    }
    # Save to session to pass to the next view
    quiz_complete_model = request.session.get('quiz_complete_model')
    quiz_complete_model.quiz_form = quiz_form
    quiz_complete_model.quiz_data = quiz_data
    session_insert_keys(request.session, quiz_complete_model=quiz_complete_model)

    return render(request, USER_QUIZ_VERIFIER_PAGE, context)
Esempio n. 15
0
def user_quiz_create_view(request):
    """
    Creates the quiz and uploads to storage.
    :param request: User request
    :return: Redirects to dashboard on successful quiz creation.
    """
    quiz_tools = QuizTools()
    quiz_adapter = QuizAdapter()
    quiz_tag_adapter = QuizTagAdapter()

    answer_key = request.POST
    quiz_complete_model = request.session.get('quiz_complete_model')

    try:
        # Create serialized content to be uploaded to storage
        content = quiz_tools.create_content(quiz_complete_model=quiz_complete_model, answer_key=answer_key)

        # Create filename for file in storage
        filename = quiz_tools.create_filename(quiz=quiz_complete_model.quiz_model)

        # Upload file to storage and get the return code (file id)
        quiz_tools.upload_quiz(content=content, filename=filename)

    except ValueError as err:
        set_alert_session(session=request.session,
                          message=str(err),
                          alert_type=DANGER)
        return HttpResponseRedirect(reverse(SERVICE_USER_QUIZ_INIT))
    except Exception:
        # Remove the quiz objects so that new form can be generated without mixing up old data
        session_remove_keys(request.session, "quiz_complete_model")

        set_alert_session(session=request.session, message="An error occurred creating the quiz.", alert_type=DANGER)
        return HttpResponseRedirect(reverse(SERVICE_USER_QUIZ_INIT))

    # Same model treated as 2 different objects if constructed again from string.
    # This is executed twice when someone edits the quiz. Redirected from myquiz_info
    if not quiz_adapter.exists(quiz_complete_model.quiz_model.quiz_id):
        quiz_complete_model.quiz_model.save()

    # Save the quiz tags and links
    for tag_name in quiz_complete_model.tags:
        if not quiz_tag_adapter.exists(tag_name):
            quiz_tag_adapter.create_and_save_model(tag_name)
        quiz_tag_adapter.link_quiz(tag_name=tag_name, quiz_id=quiz_complete_model.quiz_model.quiz_id)

    # Save quiz in model of user profile
    UserProfileTools.save_my_quiz_profile(session=request.session, quiz_model=quiz_complete_model.quiz_model)

    # Save the profile
    user_profile_tools = UserProfileTools()
    future = user_profile_tools.save_profile(request.session)
    # Wait for asynchronous callback
    future.result()

    # Remove the quiz objects
    session_remove_keys(request.session, "quiz_complete_model")

    set_alert_session(session=request.session, message="The quiz has been successfully saved", alert_type=SUCCESS)
    return HttpResponseRedirect(reverse(SERVICE_USER_HOME))
Esempio n. 16
0
def user_quizarena_solve_view(request, quiz_id):
    """
    Attempt the quiz here. Setup for the player to attempt.
    Disallow repeated attempts.
    :param request:
    :param quiz_id:
    :return:
    """
    request, alert_type, alert_message = init_alerts(request=request)
    quiz_adapter = QuizAdapter()
    quiz_tools = QuizTools()

    quiz = quiz_adapter.exists(quiz_id)
    try:
        if not quiz:
            raise ValueError("No such quiz present")
        quiz_complete_model = quiz_tools.download_quiz_content(quiz_model=quiz)
        if not quiz_complete_model:
            raise ValueError("This quiz is unavailable")

        quiz_tools.check_attempt_eligibility((request.session.get(USER_PROFILE_MODEL)), quiz_complete_model, quiz_id)

    except ValueError as err:
        set_alert_session(session=request.session,
                          message=str(err),
                          alert_type=DANGER)
        return HttpResponseRedirect(reverse(SERVICE_USER_QUIZARENA_HOME))
    context = {
        REQUEST: request,
        USER: request.user,
        ALERT_MESSAGE: alert_message,
        ALERT_TYPE: alert_type,
        'quiz_form': quiz_complete_model.quiz_form
    }
    request.session['quiz'] = quiz_complete_model.quiz_model

    return render(request, USER_QUIZARENA_SOLVE_PAGE, context)
Esempio n. 17
0
def user_myquiz_info_view(request, quiz_id):
    """
    Quiz related tasks
    :param request:
    :param quiz_id:
    :return:
    """
    user_adapter = UserAdapter()
    quiz_adapter = QuizAdapter()
    quiz_tools = QuizTools()

    user = user_adapter.get_user_instance_from_django_user(request.user)
    quiz = quiz_adapter.exists(quiz_id)
    if not quiz or not user:
        set_alert_session(session=request.session,
                          message="No such quiz exists",
                          alert_type=DANGER)
        return HttpResponseRedirect(reverse(SERVICE_USER_HOME))

    # Check if this user is the owner of this quiz
    if user != quiz.quiz_owner:
        set_alert_session(
            session=request.session,
            message=
            "You do not own this quiz. You are not allowed to edit this",
            alert_type=DANGER)
        return HttpResponseRedirect(reverse(SERVICE_USER_HOME))

    # Downloading the content from storage.
    content = quiz_tools.download_quiz_content(quiz_model=quiz)
    if not content:
        set_alert_session(session=request.session,
                          message="This quiz is unavailable",
                          alert_type=DANGER)
        return HttpResponseRedirect(reverse(SERVICE_USER_MYQUIZ_HOME))

    # Passing these session objects as this page submits the result to user_quiz_verifier view which checks for them.
    request.session['quiz_complete_model'] = content

    context = {'quiz_data': content.quiz_data}
    return render(request, USER_MYQUIZ_INFO_PAGE, context)
def get_username_password_reset_view(request):
    username = request.POST.get('username')

    user_adapter = UserAdapter()
    if validate_email_address(username) is True:
        try:
            user = user_adapter.get_user_from_django(username)
        except Exception:
            set_alert_session(session=request.session,
                              message=str("The user does not exist."),
                              alert_type=DANGER)
            return HttpResponseRedirect(reverse(SERVICE_MAIN_HOME))
        content = craft_email(request, user)
        send_email(content, user.email)
        success_alert = "An email has been sent to " + user.email +\
                        ". Please check the inbox to reset the password."
        set_alert_session(session=request.session,
                          message=success_alert,
                          alert_type=SUCCESS)
    else:
        set_alert_session(session=request.session,
                          message=str("The email address is not valid."),
                          alert_type=DANGER)
    return HttpResponseRedirect(reverse(SERVICE_MAIN_HOME))
Esempio n. 19
0
def user_myquiz_info_view(request, quiz_id):
    """
    Quiz related tasks
    :param request:
    :param quiz_id:
    :return:
    """
    user_adapter = UserAdapter()
    quiz_adapter = QuizAdapter()
    quiz_tools = QuizTools()

    user = user_adapter.get_user_instance_from_django_user(request.user)
    quiz = quiz_adapter.exists(quiz_id)
    if not quiz or not user:
        set_alert_session(session=request.session,
                          message="No such quiz exists",
                          alert_type=DANGER)
        return HttpResponseRedirect(reverse(SERVICE_USER_HOME))

    # Check if this user is the owner of this quiz
    if user != quiz.quiz_owner:
        set_alert_session(session=request.session, message="You do not own this quiz. You are not allowed to edit this",
                          alert_type=DANGER)
        return HttpResponseRedirect(reverse(SERVICE_USER_HOME))

    # Downloading the content from storage.
    content = quiz_tools.download_quiz_content(quiz_model=quiz)
    if not content:
        set_alert_session(session=request.session, message="This quiz is unavailable", alert_type=DANGER)
        return HttpResponseRedirect(reverse(SERVICE_USER_MYQUIZ_HOME))

    # Passing these session objects as this page submits the result to user_quiz_verifier view which checks for them.
    request.session['quiz_complete_model'] = content

    context = {'quiz_data': content.quiz_data}
    return render(request, USER_MYQUIZ_INFO_PAGE, context)
Esempio n. 20
0
def user_quiz_maker_view(request):
    """
    Quiz creation page for user
    :param request: User request
    :return: Renders quiz page
    """
    # Get the post variables from the quiz init view.
    quiz_name = request.POST.get('quiz_name')
    quiz_description = request.POST.get('quiz_description')
    start_date_time = request.POST.get('start_date_time')
    end_date_time = request.POST.get('end_date_time')
    attempts = request.POST.get('attempts')
    pass_percentage = request.POST.get('pass_percentage')
    tag_names = request.POST.get('quiz_tags')

    local = timezone.get_current_timezone()
    event_model = None
    # TODO: Remove this from here and put it in a function.
    if start_date_time and end_date_time:
        event_start_date_time = (local.localize(parse(start_date_time),
                                                is_dst=None)).astimezone(
                                                    timezone.utc)
        event_end_date_time = (local.localize(parse(end_date_time),
                                              is_dst=None)).astimezone(
                                                  timezone.utc)
        event_model = EventModel(start_time=event_start_date_time,
                                 end_time=event_end_date_time)

    request, alert_type, alert_message = init_alerts(request=request)

    # Initialize the adapters.
    user_adapter = UserAdapter()
    quiz_adapter = QuizAdapter()
    quiz_tag_adapter = QuizTagAdapter()
    quiz_tools = QuizTools()

    context = {
        REQUEST: request,
        USER: request.user,
        ALERT_MESSAGE: alert_message,
        ALERT_TYPE: alert_type
    }

    try:

        # Get the user model from the request.
        user = user_adapter.get_user_instance_from_django_user(request.user)

        if not user:
            raise ValueError("User not recognized")

        # quiz_name could be None if there were errors in creating the model
        # Check if quiz_id is not set after creating the id. (This will mostly be true as we already have this check in
        # the javascript)
        quiz_id = quiz_tools.get_quiz_id(username=user.username,
                                         quiz_name=quiz_name)

        # Quiz ID is duplicate
        if quiz_adapter.exists(quiz_id):
            raise ValueError("Quiz ID already present")

        # Create the quiz model
        quiz = quiz_adapter.create_model(quiz_id=quiz_id,
                                         quiz_name=quiz_name,
                                         quiz_description=quiz_description,
                                         quiz_owner=user)

        quiz_complete_model = QuizCompleteModel(
            quiz_model=quiz,
            attempts=attempts,
            pass_percentage=pass_percentage,
            event_model=event_model,
            tags=list())

        # Create the tag names and put them into the quiz_complete_model
        tag_names_list = quiz_tag_adapter.split_and_verify_tag_names(tag_names)
        if tag_names_list:
            for tag_name in tag_names_list:
                quiz_complete_model.tags.append(tag_name)

    except ValueError as err:
        set_alert_session(session=request.session,
                          message=str(err),
                          alert_type=DANGER)
        return HttpResponseRedirect(reverse(SERVICE_USER_QUIZ_INIT))

    session_insert_keys(session=request.session,
                        quiz_complete_model=quiz_complete_model)

    return render(request, USER_QUIZ_MAKER_PAGE, context)
Esempio n. 21
0
def user_quiz_maker_view(request):
    """
    Quiz creation page for user
    :param request: User request
    :return: Renders quiz page
    """
    # Get the post variables from the quiz init view.
    quiz_name = request.POST.get('quiz_name')
    quiz_description = request.POST.get('quiz_description')
    start_date_time = request.POST.get('start_date_time')
    end_date_time = request.POST.get('end_date_time')
    attempts = request.POST.get('attempts')
    pass_percentage = request.POST.get('pass_percentage')
    tag_names = request.POST.get('quiz_tags')

    # Initialize the adapters.
    user_adapter = UserAdapter()
    quiz_adapter = QuizAdapter()
    quiz_tag_adapter = QuizTagAdapter()

    try:

        # Get the user model from the request.
        user = user_adapter.get_user_instance_from_django_user(request.user)

        if not user:
            raise ValueError("User not recognized")

        if not quiz_name.rstrip():
            raise ValueError("Quiz Name cannot be blank")

        if not re.match("^[A-Za-z0-9_ -]*$", quiz_name):
            raise ValueError("The quiz Name can contain ony alphanumeric characters, spaces, '-', '?' and '_'")

        # quiz_name could be None if there were errors in creating the model
        # Check if quiz_id is not set after creating the id. (This will mostly be true as we already have this check in
        # the javascript)
        quiz = quiz_adapter.get_quiz_for_owner(user, quiz_name)
        if quiz:
            raise ValueError("Quiz already present")

        # Create the quiz model
        quiz = quiz_adapter.create_model(quiz_name=quiz_name,
                                         quiz_description=quiz_description,
                                         quiz_owner=user,
                                         start_time=QuizParser.get_timezone_aware_datetime(start_date_time),
                                         end_time=QuizParser.get_timezone_aware_datetime(end_date_time))

        quiz_complete_model = QuizCompleteModel(quiz_model=quiz,
                                                attempts=attempts,
                                                pass_percentage=pass_percentage,
                                                event_model=QuizParser.get_event_model(start_date_time, end_date_time),
                                                tags=list())

        # Create the tag names and put them into the quiz_complete_model
        tag_names_list = quiz_tag_adapter.split_and_verify_tag_names(tag_names)
        if tag_names_list:
            for tag_name in tag_names_list:
                quiz_complete_model.tags.append(tag_name)

    except ValueError as err:
        set_alert_session(session=request.session,
                          message=str(err),
                          alert_type=DANGER)
        return ControllerModel(view=SERVICE_USER_QUIZ_INIT, redirect=True)

    session_insert_keys(session=request.session, quiz_complete_model=quiz_complete_model)

    return ControllerModel(view=USER_QUIZ_MAKER_PAGE, redirect=False)
Esempio n. 22
0
def user_quiz_maker_view(request):
    """
    Quiz creation page for user
    :param request: User request
    :return: Renders quiz page
    """
    # Get the post variables from the quiz init view.
    quiz_name = request.POST.get('quiz_name')
    quiz_description = request.POST.get('quiz_description')
    start_date_time = request.POST.get('start_date_time')
    end_date_time = request.POST.get('end_date_time')
    attempts = request.POST.get('attempts')
    pass_percentage = request.POST.get('pass_percentage')
    tag_names = request.POST.get('quiz_tags')

    local = timezone.get_current_timezone()
    event_model = None
    # TODO: Remove this from here and put it in a function.
    event_start_date_time = None
    event_end_date_time = None
    if start_date_time and end_date_time:
        event_start_date_time = (local.localize(parse(start_date_time), is_dst=None)).astimezone(timezone.utc)
        event_end_date_time = (local.localize(parse(end_date_time), is_dst=None)).astimezone(timezone.utc)
        event_model = EventModel(start_time=event_start_date_time, end_time=event_end_date_time)

    request, alert_type, alert_message = init_alerts(request=request)

    # Initialize the adapters.
    user_adapter = UserAdapter()
    quiz_adapter = QuizAdapter()
    quiz_tag_adapter = QuizTagAdapter()

    context = {
        REQUEST: request,
        USER: request.user,
        ALERT_MESSAGE: alert_message,
        ALERT_TYPE: alert_type
    }

    try:

        # Get the user model from the request.
        user = user_adapter.get_user_instance_from_django_user(request.user)

        if not user:
            raise ValueError("User not recognized")

        if not quiz_name.rstrip():
            raise ValueError("Quiz Name cannot be blank")

        if not re.match("^[A-Za-z0-9_ -]*$", quiz_name):
            raise ValueError("The quiz Name can contain ony alphanumeric characters, spaces, '-', '?' and '_'")

        # quiz_name could be None if there were errors in creating the model
        # Check if quiz_id is not set after creating the id. (This will mostly be true as we already have this check in
        # the javascript)
        quiz = quiz_adapter.get_quiz_for_owner(user, quiz_name)
        if quiz:
            raise ValueError("Quiz already present")

        # Create the quiz model
        quiz = quiz_adapter.create_model(quiz_name=quiz_name,
                                         quiz_description=quiz_description,
                                         quiz_owner=user,
                                         start_time=event_start_date_time,
                                         end_time=event_end_date_time)

        quiz_complete_model = QuizCompleteModel(quiz_model=quiz,
                                                attempts=attempts,
                                                pass_percentage=pass_percentage,
                                                event_model=event_model,
                                                tags=list())

        # Create the tag names and put them into the quiz_complete_model
        tag_names_list = quiz_tag_adapter.split_and_verify_tag_names(tag_names)
        if tag_names_list:
            for tag_name in tag_names_list:
                quiz_complete_model.tags.append(tag_name)

    except ValueError as err:
        set_alert_session(session=request.session,
                          message=str(err),
                          alert_type=DANGER)
        return HttpResponseRedirect(reverse(SERVICE_USER_QUIZ_INIT))

    session_insert_keys(session=request.session, quiz_complete_model=quiz_complete_model)

    return render(request, USER_QUIZ_MAKER_PAGE, context)
Esempio n. 23
0
def user_quiz_create_view(request):
    """
    Creates the quiz and uploads to storage.
    :param request: User request
    :return: Redirects to dashboard on successful quiz creation.
    """
    quiz_tools = QuizTools()
    quiz_adapter = QuizAdapter()
    quiz_tag_adapter = QuizTagAdapter()

    answer_key = request.POST
    quiz_complete_model = request.session.get('quiz_complete_model')

    try:
        # Create serialized content to be uploaded to storage
        content = quiz_tools.create_content(
            quiz_complete_model=quiz_complete_model, answer_key=answer_key)

        # Create filename for file in storage
        filename = quiz_tools.create_filename(
            quiz=quiz_complete_model.quiz_model)

        # Upload file to storage and get the return code (file id)
        quiz_tools.upload_quiz(content=content, filename=filename)

    except ValueError as err:
        set_alert_session(session=request.session,
                          message=str(err),
                          alert_type=DANGER)
        return HttpResponseRedirect(reverse(SERVICE_USER_QUIZ_INIT))
    except Exception:
        # Remove the quiz objects so that new form can be generated without mixing up old data
        session_remove_keys(request.session, "quiz_complete_model")

        set_alert_session(session=request.session,
                          message="An error occurred creating the quiz.",
                          alert_type=DANGER)
        return HttpResponseRedirect(reverse(SERVICE_USER_QUIZ_INIT))

    # Same model treated as 2 different objects if constructed again from string.
    # This is executed twice when someone edits the quiz. Redirected from myquiz_info
    if not quiz_adapter.exists(quiz_complete_model.quiz_model.quiz_id):
        quiz_complete_model.quiz_model.save()

    # Save the quiz tags and links
    for tag_name in quiz_complete_model.tags:
        if not quiz_tag_adapter.exists(tag_name):
            quiz_tag_adapter.create_and_save_model(tag_name)
        quiz_tag_adapter.link_quiz(
            tag_name=tag_name, quiz_id=quiz_complete_model.quiz_model.quiz_id)

    # Save quiz in model of user profile
    UserProfileTools.save_my_quiz_profile(
        session=request.session, quiz_model=quiz_complete_model.quiz_model)

    # Save the profile
    user_profile_tools = UserProfileTools()
    future = user_profile_tools.save_profile(request.session)
    # Wait for asynchronous callback
    future.result()

    # Remove the quiz objects
    session_remove_keys(request.session, "quiz_complete_model")

    set_alert_session(session=request.session,
                      message="The quiz has been successfully saved",
                      alert_type=SUCCESS)
    return HttpResponseRedirect(reverse(SERVICE_USER_HOME))
Esempio n. 24
0
def register_check_view(request):
    """
    Register validation
    Validates the input by the user and checks for duplicates or invalid inputs.
    :param request: User request
    :return: redirects depending on result of authentication.
    """
    # Get all the inputs from the POST method
    username = request.POST.get(USERNAME)
    user_first_name = request.POST.get(USER_FIRST_NAME)
    user_last_name = request.POST.get(USER_LAST_NAME)
    user_phone = request.POST.get(USER_PHONE)
    user_dob = request.POST.get(USER_DOB)
    password = request.POST.get(PASSWORD)
    repassword = request.POST.get(REPASSWORD)

    try:
        # Check if none of these are None
        if not username or \
                not user_first_name or \
                not user_last_name or \
                not user_phone or \
                not user_dob or \
                not password or \
                not repassword:
            # Set the alerts in the session field of the request and redirect back to register
            raise ValueError("Please fill in all the values")

        # Check if passwords are entered properly
        if password != repassword:
            raise ValueError("The password should be same in both the fields")

        user_adapter = UserAdapter()

        # Check if username already registered. If yes redirect with warning
        if user_adapter.exists(username):
            raise ValueError("User ID already present")

        # Creating user in django authentication in database
        auth_user = User.objects.create_user(username=username,
                                             email=username,
                                             password=password)

        # Set the name in the django authentication
        auth_user.first_name = user_first_name
        auth_user.last_name = user_last_name
        auth_user.save()

        # Creates model and saves to the database.
        user_adapter.create_and_save_model(username=username,
                                           first_name=user_first_name,
                                           last_name=user_last_name,
                                           phone=user_phone,
                                           dob=user_dob)
    except ValueError as err:
        set_alert_session(session=request.session,
                          message=str(err),
                          alert_type=DANGER)
        return HttpResponseRedirect(reverse(SERVICE_REGISTER))

    set_alert_session(session=request.session,
                      message=" ".join([
                          user_first_name, user_last_name,
                          "registered successfully"
                      ]),
                      alert_type=SUCCESS)
    return HttpResponseRedirect(reverse(SERVICE_MAIN_HOME))
Esempio n. 25
0
def register_check_view(request):
    """
    Register validation
    Validates the input by the user and checks for duplicates or invalid inputs.
    :param request: User request
    :return: redirects depending on result of authentication.
    """
    # Get all the inputs from the POST method
    username = request.POST.get(USERNAME)
    user_first_name = request.POST.get(USER_FIRST_NAME)
    user_last_name = request.POST.get(USER_LAST_NAME)
    user_phone = request.POST.get(USER_PHONE)
    user_dob = request.POST.get(USER_DOB)
    password = request.POST.get(PASSWORD)
    repassword = request.POST.get(REPASSWORD)

    try:
        # Check if none of these are None
        if not username or \
                not user_first_name or \
                not user_last_name or \
                not user_phone or \
                not user_dob or \
                not password or \
                not repassword:
            # Set the alerts in the session field of the request and redirect back to register
            raise ValueError("Please fill in all the values")

        # Check if passwords are entered properly
        if password != repassword:
            raise ValueError("The password should be same in both the fields")

        user_adapter = UserAdapter()

        # Check if username already registered. If yes redirect with warning
        if user_adapter.exists(username):
            raise ValueError("User ID already present")

        # Creating user in django authentication in database
        auth_user = User.objects.create_user(username=username, email=username, password=password)

        # Set the name in the django authentication
        auth_user.first_name = user_first_name
        auth_user.last_name = user_last_name
        auth_user.save()

        # Creates model and saves to the database.
        user_adapter.create_and_save_model(username=username,
                                           first_name=user_first_name,
                                           last_name=user_last_name,
                                           phone=user_phone,
                                           dob=user_dob)
    except ValueError as err:
        set_alert_session(session=request.session,
                          message=str(err),
                          alert_type=DANGER)
        return HttpResponseRedirect(reverse(SERVICE_REGISTER))

    set_alert_session(session=request.session,
                      message=" ".join([user_first_name, user_last_name, "registered successfully"]),
                      alert_type=SUCCESS)
    return HttpResponseRedirect(reverse(SERVICE_MAIN_HOME))