Exemple #1
0
def callback():
    # Get authorization code Google sent back to you
    code = request.args.get("code")
    google_provider_cfg = get_google_provider_cfg()
    token_endpoint = google_provider_cfg["token_endpoint"]
    token_url, headers, body = client.prepare_token_request(
        token_endpoint,
        authorization_response=request.url,
        redirect_url=request.base_url,
        code=code)
    token_response = requests.post(
        token_url,
        headers=headers,
        data=body,
        auth=(GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET),
    )

    # Parse the tokens!
    client.parse_request_body_response(json.dumps(token_response.json()))

    userinfo_endpoint = google_provider_cfg["userinfo_endpoint"]
    uri, headers, body = client.add_token(userinfo_endpoint)
    userinfo_response = requests.get(uri, headers=headers, data=body)

    if userinfo_response.json().get("email_verified"):
        unique_id = userinfo_response.json()["sub"]
        users_email = userinfo_response.json()["email"]
        picture = userinfo_response.json()["picture"]
        users_name = userinfo_response.json()["name"]
    else:
        return "User email not available or not verified by Google.", 400

    if users_email.split('@')[1] == 'std.sehir.edu.tr':
        student = Student(unique_id, users_name, users_email, picture)

        if not Student.get(unique_id):
            student.create()

        session['user_id'] = student.student_google_id
        return redirect(url_for('profile.profile'))

    elif users_email.split(
            '@')[1] == 'gmail.com':  # change this later to sehir.edu.tr
        instructor = Instructor(unique_id, users_name,
                                '*****@*****.**', picture)

        if not instructor.get():
            instructor.create()

        session['user_id'] = instructor.instructor_email
        return redirect(url_for('profile.profile'))

    else:
        return render_template('auth/error.html')
def rate_instructor():
    current_user = g.user
    student_object = Student.get(current_user[0])
    if request.method == 'POST':
        instructor_email = request.form['instructor_email_form']
        course_details = request.form['course_details']
        semester_year = request.form['semester_year']
        rating = request.form['rating']
        will_rec = request.form['will_rec']
        is_suitable = request.form['is_suitable']
        grading = request.form['grading_policy']
        explanation = request.form['explanation']
        take_again = request.form['take_again']
        student_object.save_instructor_rating(instructor_email, course_details,
                                              semester_year, rating, will_rec,
                                              is_suitable, grading,
                                              explanation, take_again)

    unrated_instructors = student_object.get_unrated_instructors()
    for i in range(len(unrated_instructors)):
        unrated_instructors[i] = list(unrated_instructors[i])
        unrated_instructors[i][0] = int(unrated_instructors[i][0]) + 1
        if unrated_instructors[i][6] == None:
            unrated_instructors[i][6] = "static/media/users/default.jpg"
    return render_template('profile/rate_instructor.html',
                           name=student_object.student_name,
                           profile_pic=student_object.student_profile_picture,
                           unrated_instructors=unrated_instructors)
def predict():
    current_user = g.user
    student = Student.get(current_user[0])
    subjects = []
    with open(os.getcwd() +
              '/Smart-Advisor/flaskr/data/subject_names.txt') as subject_names:
        for subject in subject_names:
            subjects.append(subject.strip())

    if request.method == 'GET':
        return render_template('profile/predict.html',
                               title='Predict',
                               name=student.student_name,
                               profile_pic=student.student_profile_picture,
                               subjects=subjects)
    else:
        subject_filters = request.form['subject_filters']
        min_grade = request.form['min-grade']
        predictions = get_predictions(subject_filters.strip().split(),
                                      min_grade, student)
        return render_template('profile/predict.html',
                               title='Predict',
                               name=student.student_name,
                               profile_pic=student.student_profile_picture,
                               subjects=subjects,
                               predictions=predictions)
def profile():
    current_user = g.user
    if '@' in current_user[0]:
        return redirect(url_for('profile.instructor_profile'))
    student = Student.get(current_user[0])
    block, radio, label = fetch_testifiers()
    details = student.get_details()
    department = student.get_department()
    graduation_progress = 100
    if department != None:
        graduation_progress = student.graduation_progress()
    incompleted_required_courses = student.get_incompleted_required_courses()
    time_table = student.get_timetable()
    return render_template('profile/profile.html',
                           title='Profile',
                           name=student.student_name,
                           email=student.student_email,
                           profile_pic=student.student_profile_picture,
                           testifiers=block,
                           radio_buttons=radio,
                           labels=label,
                           student_number=details[0],
                           semester_of_student=details[1],
                           advisor=details[2],
                           standing=details[3],
                           gpa=details[4],
                           completed_credits=details[5],
                           completed_ects=details[6],
                           department=department,
                           graduation_progress=graduation_progress,
                           time_table=time_table,
                           incompleted_courses=incompleted_required_courses)
def rate_course():
    current_user = g.user
    student_object = Student.get(current_user[0])
    if request.method == 'POST':
        course_details = request.form['course_details']
        semster_year = request.form['semester_year']
        rating = request.form['rating']
        will_rec = request.form['will_rec']
        did_enjoy = request.form['did_enjoy']
        take_sim = request.form['take_sim']
        good_content = request.form['good_content']
        was_helpful = request.form['was_helpful']
        student_object.save_course_rating(course_details, semster_year, rating,
                                          will_rec, did_enjoy, take_sim,
                                          good_content, was_helpful)

    unrated_courses = student_object.get_unrated_courses()
    for i in range(len(unrated_courses)):
        unrated_courses[i] = list(unrated_courses[i])
        unrated_courses[i][2] = int(unrated_courses[i][2]) + 1
        unrated_courses[i] = tuple(unrated_courses[i])

    return render_template('profile/rate_course.html',
                           name=student_object.student_name,
                           profile_pic=student_object.student_profile_picture,
                           unrated_courses=unrated_courses)
def fetch_sap():
    current_user = g.user
    student = Student.get(current_user[0])
    if request.method == 'GET':
        return render_template('profile/fetch_sap.html',
                               title='Fetch SAP',
                               name=student.student_name,
                               profile_pic=student.student_profile_picture)
    else:
        email = request.form['email']
        password = request.form['password']
        fetch_transcript(email, password, student)
        return redirect(url_for('profile.profile'))
def testify():
    current_user = g.user
    student_object = Student.get(current_user[0])
    if request.method == 'GET':
        return render_template(
            'profile/testimonial.html',
            title='Testimonial',
            name=student_object.student_name,
            profile_pic=student_object.student_profile_picture)
    else:
        headline = request.form['headline']
        testimony = request.form['testimony']
        save_testimony(testimony, headline, student_object.student_google_id)
        return redirect(url_for('profile.profile'))
    def confirm_email(self, token):
        """
        Activates users account on database, based on token sent by email.
        :param token: Token sent to user by email, used to identify himself.
        :return: A view of the login page showing the user that he was able
                to activate his/her account.
        """
        try:
            message = verify_token(
                secret_key=current_app.config["SECRET_KEY"],
                expiration=current_app.config["EMAIL_CONFIRMATION_EXPIRATION"],
                token=token)

        except Exception as e:
            self._log.exception("Could not verify token")
            raise abort(403)

        try:
            if message:
                # split message using token set in config
                (k_number, scheme_id) = message.split(
                    current_app.config["MESSAGE_SEPARATION_TOKEN"])

                user = Student(k_number=k_number, scheme_id=scheme_id)

                if user.email_confirmed:
                    flash("Account already active.")
                else:
                    user.activate()
                    flash("Account successfully activated.")
            else:
                flash("The token verification has failed")

        except Exception as e:
            self._log.exception("Could not activate account")
            raise abort(500)
        return redirect("/login")
def student_progress():
    current_inst = g.user
    instructor = Instructor(current_inst[1], current_inst[2], current_inst[0],
                            current_inst[3])
    department = instructor.get_department()
    advisees = instructor.get_advisees()
    advisees_details = {}
    for i in range(len(advisees)):
        advisees[i] = list(advisees[i])
        student = Student(advisees[i][0], advisees[i][2], advisees[i][3],
                          advisees[i][4])
        graduation_progress = student.graduation_progress()
        department = student.get_department()
        advisees[i].append(graduation_progress)
        advisees[i].append("width: {}%;".format(graduation_progress))
        completed_courses = student.get_completed_courses()
        incompleted_required_courses = student.get_incompleted_required_courses(
        )
        advisees_details[advisees[i][1]] = {
            'student_number': advisees[i][1],
            'student_name': advisees[i][2],
            'student_email': advisees[i][3],
            'profile_picture': advisees[i][4],
            'student_semester': str(advisees[i][5]),
            'standing': advisees[i][6],
            'completed_credit': str(advisees[i][7]),
            'completed_ects': str(advisees[i][8]),
            'gpa': str(advisees[i][9]),
            'department': department,
            'completed_courses': completed_courses,
            'incompleted_required_courses': incompleted_required_courses,
            'graduation_progress': str(graduation_progress)
        }
    return render_template('profile/student_progress.html',
                           name=instructor.instructor_name,
                           profile_pic=instructor.instructor_profile_pic,
                           advisees_details=json.dumps(advisees_details),
                           advisees=advisees)
    def login(self, request):
        """
        Logs the user into the system given a username and password.
        :param request: The request is passed through so we can access the form
                        contained inside it.
        :return: A view based on whether the login was sucessfull (redirecting
                to /dashboard or back to the login screen if the login was
                unsuccesful)
        """
        if current_user.is_authenticated:
            return redirect("/dashboard")

        # Try to load the available schemes
        try:
            scheme_options = self._get_scheme()
        except Exception as e:
            flash("Error logging in, please check the data that was entered")

        login_form = LoginForm(request.form)
        login_form.scheme_id.choices = scheme_options

        try:
            if request.method == "POST":  # If the user is trying to login
                if login_form.validate_on_submit():  # If the form is validated
                    scheme_id = login_form.scheme_id.data
                    k_number = login_form.k_number.data

                    if not self._student_handler.user_exist(
                            scheme_id, k_number):
                        flash(
                            "This k_number and password combination does not exist in our database."
                        )
                        return redirect("/login")

                    try:
                        user = Student(scheme_id, k_number)
                    except:
                        flash('You must first confirm your email address')
                        return redirect("/login")

                    # if user exists in db then a password hash was successfully retrieved
                    if user.password:
                        # check if he is authorised
                        if check_password_hash(user.password,
                                               login_form.password.data):
                            # redirect to profile page, where he must insert his preferences
                            login_user(user, remember=False)
                            return redirect("/dashboard")
                        else:
                            flash('The password you entered is incorrect')
                            return redirect("/login")
                    else:  # The user is loading the page
                        return redirect("/login")
                else:
                    flash(
                        "Error logging in, please check the data that was entered"
                    )
                    return render_template("login.html", login_form=login_form)

            return render_template("login.html", login_form=login_form)
        except Exception as e:
            self._log.exception(
                "Oops... Something went wrong. The data entered could not be valid, try again."
            )
            raise abort(500)