def edit_user(user_id):
    """ (str) -> rendered_template

    Returns the rendered template of admin-users.html with data from user input
    into User Object, after the user makes a POST request to 'admin/user/<user_id>'
    """
    if request.form['submit'] == 'Save':
        user = UserModel.get(ObjectId(user_id))
        user.user_type = request.form['user-type'].lower()
        UserModel.update(user)
    elif request.form['submit'] == 'Delete':
        db.accounts.remove(ObjectId(user_id))
    return redirect(url_for('get_user_list'))
def edit_user(user_id):
    """ (str) -> rendered_template

    Returns the rendered template of admin-users.html with data from user input
    into User Object, after the user makes a POST request to 'admin/user/<user_id>'
    """
    if request.form['submit'] == 'Save':
        user = UserModel.get(ObjectId(user_id))
        user.user_type = request.form['user-type'].lower()
        UserModel.update(user)
    elif request.form['submit'] == 'Delete':
        db.accounts.remove(ObjectId(user_id))
    return redirect(url_for('get_user_list'))
def upload_page():
    """ () -> rendered_template

    Returns the rendered template of upload.html with User's first and last name
    """
    if 'logged_in' in session and 'username' in session:
        user = UserModel.get({'username': session['username']})
    return render_template('upload.html', name=user.first_name + " " + user.last_name)
def upload_page():
    """ () -> rendered_template

    Returns the rendered template of upload.html with User's first and last name
    """
    if 'logged_in' in session and 'username' in session:
        user = UserModel.get({'username': session['username']})
    return render_template('upload.html',
                           name=user.first_name + " " + user.last_name)
def view_user(user_id):
    """ (str(ObjectId()) -> rendered_template

    Returns the rendered template of admin-user.html with data from the User object
    associated with , after the user makes a GET request to 'admin/user/user_id'
    """
    user = UserModel.get(ObjectId(user_id))
    if not user:
        return 'User not found', 404

    return render_template('admin-user.html', user=user)
def view_user(user_id):
    """ (str(ObjectId()) -> rendered_template

    Returns the rendered template of admin-user.html with data from the User object
    associated with , after the user makes a GET request to 'admin/user/user_id'
    """
    user = UserModel.get(ObjectId(user_id))
    if not user:
        return 'User not found', 404

    return render_template('admin-user.html', user=user)
def oauth2_callback():
    error = request.args.get('error')
    if error:
        return '{error}: {error_description}'.format(error=error, error_description=request.args.get('error_description')), 401

    code = request.args.get('code')
    if not code:
        return 'No code given', 401

    credentials = FLOW.step2_exchange(code)
    http = httplib2.Http()
    http = credentials.authorize(http)
    response, content = http.request('https://umairidris.auth0.com/userinfo')

    if response.status != 200:
        return response.reason, response.status

    user_dict = json.loads(content.decode("utf-8"))

    for key in REQUIRED_RESPONSE_KEYS:
        if key not in user_dict:
            return 'Missing {key} in response'.format(key=key), 401

    user = UserModel.get({'email': user_dict['email']})

    if not user: # new user
        # username is email for now
        user = User(user_dict['email'], user_dict['nickname'], user_dict['email'])
        user = UserModel.create(user)

        if not user:
            return 'Failed to create user', 500

    session['username'] = user.username
    session['logged_in'] = True

    if user.user_type == 'admin':
        session['admin'] = True
        return redirect(url_for('get_admin'))

    return redirect('/')
def answer_question(question_id):
    """ (str) -> str

    Return success message if answer is correct,
    Otherwise return the failure message
    """
    session['try'] = session.get('try', 0) + 1

    question = GetQuestion(ObjectId(question_id)).get()

    if not question:
        return 'Question not found', 404

    given_order = json.loads(request.form.get('order', '[]'))
    given_indentation = json.loads(request.form.get('indentation', '[]'))

    user = UserModel.get({'username': session['username']})

    if ObjectId(question_id) not in user.completed:
        question.attempts += 1

    if check_answer(question, given_order, given_indentation):
        if ObjectId(question_id) not in user.completed:
            user.completed.append(ObjectId(question_id))
            if session["try"] > 10:
                user.xp += question.difficulty
            else:
                user.xp += ceil(int(question.difficulty) * 10 / int(session["try"]))
            user.level = ceil(user.xp / 25)
            question.success += 1
        UpdateQuestion(question).post()
        UserModel.update(user)
        session.pop("try", None)
        return RESPONSE_SUCCESS + "<br>Return to home for more challenges"
    else:
        return RESPONSE_FAILED + "<br>Failed Attempt: " + str(
            session["try"]) + "<br>More failed attempts results in less trophies"
def get_questions():
    """ () -> rendered_template

    Returns the rendered template of questions.html with data from list
    of Question objects, after the user makes a GET request to to home page
    """
    if not 'logged_in' in session or not 'username' in session:
        return 'Unauthorized', 403

    user = UserModel.get({'username': session['username']})
    if user is None:
        return 'User not found', 500

    print(user, file=sys.stderr)
    questions = db.questions.find()
    unattempted = questions.count() - len(user.completed)
    return render_template('questions.html',
                           questions=questions,
                           completed=user.completed,
                           unattempted=unattempted,
                           user=user)