Exemplo n.º 1
0
def resetToken(token):
    if current_user.is_authenticated:
        return redirect(url_for('home'))
    try:
        student = Student.verify_reset_token(token)
        if student is None:
            app.logger.info(
                'In resetToken, token was invalid for {}'.format(student))
            flash('Invalid or expired token!', 'danger')
            return redirect(url_for('resetRequest'))
        form = resetPasswordForm()
        if request.method == "POST":
            if form.validate_on_submit():
                hashed_password = bcrypt.generate_password_hash(
                    form.password.data).decode('utf-8')
                app.logger.info(
                    'In resetToken, commiting new password to DB for {}'.
                    format(student))
                database.updateStudent(student.id,
                                       {"password": hashed_password})
                flash('Your password has been updated successfully!',
                      'success')
                return redirect(url_for('login'))
            else:
                app.logger.info(
                    'In resetToken, form is NOT valid. form.errors:{}'.format(
                        form.errors))
                flash('There was an error, see details below.', 'danger')
        return render_template('resetToken.html',
                               title="Reset Password",
                               form=form)
    except Exception as e:
        app.logger.error('In resetToken, Error is: {}\n{}'.format(
            e, traceback.format_exc()))
        return redirect(url_for('errorPage'))
Exemplo n.º 2
0
def editLab():
    if not utils.check_user_lab():
        return redirect(url_for('login'))
    try:
        admin = utils.check_user_admin()
        lab = None if not utils.check_user_lab() else database.getLabByAcronym(flask_login.current_user.userId)
        form = editLabForm()

        if request.method == 'POST':
            if form.validate_on_submit():
                if lab.acronym != form.new_acronym.data:
                    labWithAcr = database.getLabByAcronym(form.new_acronym.data)
                    if labWithAcr:
                        flash('There is already a lab with the same acronym!', 'danger')
                        return redirect(url_for('editLab'))
                projectImage = lab.logo
                if form.new_logo.data:
                    app.logger.info('In manageProjects, in editForm, deleting old project image')
                    utils.delete_logo_image(projectImage)  # TODO CHANGE THIS FUNCTIONS
                    projectImage = utils.save_form_image(form.new_logo.data, "labs_logo")
                hashed_password = bcrypt.generate_password_hash(form.new_password.data).decode('utf-8')
                database.updateLab(lab.id, {
                    "name": form.new_name.data,
                    "acronym": form.new_acronym.data,
                    "password": hashed_password,
                    "description": form.description.data,
                    "website": form.website.data,
                    "logo": projectImage
                })
                flash('Lab was updated successfully!', 'success')
                return redirect(url_for('home'))
            else:
                app.logger.info('In Edit Account, form is NOT valid. form.errors:{}'.format(form.errors))
                if 'csrf_token' in form.errors:
                    flash('Error: csrf token expired, please re-enter your credentials.', 'danger')
                else:
                    flash('There was an error, see details below.', 'danger')
        elif request.method == 'GET':
            form.labId.data = lab.id
            form.new_name.data = lab.name
            form.new_acronym.data = lab.acronym
            form.new_password.data = lab.password
            form.new_logo.data = lab.logo
            form.website.data = lab.website
            form.description.data = lab.description
        return render_template('/admin/editLab.html', title="Edit Lab", form=form, admin=admin, lab=lab)
    except Exception as e:
        app.logger.error('In editAccount, Error is: {}\n{}'.format(e, traceback.format_exc()))
        return redirect(url_for('errorPage'))
Exemplo n.º 3
0
def createAdminAccount():
    if current_user.is_authenticated:
        app.logger.info('is_authenticated')
        return redirect(url_for('home'))
    try:
        totalAdmins = database.getAdminsCount()
        # allow **only one** admin to register

        if totalAdmins > 0:
            app.logger.info('totalAdmins > 0')
            return redirect(url_for('home'))

        form = createAdminForm()
        if request.method == "POST":
            if form.validate_on_submit():
                hashed_password = bcrypt.generate_password_hash(
                    form.password.data).decode('utf-8')
                # create admin
                database.addAdmin({
                    "adminId": form.id.data,
                    "password": hashed_password
                })
                flash('Admin account was created successfully!', 'success')
                return redirect(url_for('login'))
            else:
                app.logger.info(
                    'In Create Admin Account, form is NOT valid. form.errors:{}'
                    .format(form.errors))
                flash('There was an error, see details below.', 'danger')
        return render_template('/admin/createAdminAccount.html',
                               title="Create Admin Account",
                               form=form)
    except Exception as e:
        app.logger.error('In createAdminAccount, Error is: {}\n{}'.format(
            e, traceback.format_exc()))
        return redirect(url_for('errorPage'))
Exemplo n.º 4
0
def editAccount():
    if not utils.check_user_student():
        return redirect(url_for('login'))
    try:
        student = database.getStudentByStudentId(
            flask_login.current_user.userId)
        form = EditAccountForm()

        if request.method == 'POST':
            form.email.data = form.email.data.strip()
            if form.validate_on_submit():
                if student.studentId != form.studentId.data:
                    userWithSameId = database.getUserByUserId(
                        form.studentId.data)
                    if userWithSameId:
                        flash('There is already a user with the same ID!',
                              'danger')
                        return redirect(url_for('editAccount'))
                if student.email != form.email.data:
                    studentWithSameEmail = database.getStudentByEmail(
                        form.email.data)
                    if studentWithSameEmail:
                        flash('This email is already used by another student!',
                              'danger')
                        return redirect(url_for('editAccount'))

                profilePic = student.profilePic
                if form.profilePic.data:
                    # delete old profile image
                    utils.delete_profile_image(profilePic)
                    # save new profile image
                    profilePic = utils.save_form_image(form.profilePic.data,
                                                       "profile")
                hashed_password = bcrypt.generate_password_hash(
                    form.password.data).decode('utf-8')

                database.updateStudent(
                    student.id, {
                        "studentId": form.studentId.data,
                        "password": hashed_password,
                        "firstNameHeb": form.firstNameHeb.data,
                        "lastNameHeb": form.lastNameHeb.data,
                        "firstNameEng": form.firstNameEng.data.capitalize(),
                        "lastNameEng": form.lastNameEng.data.capitalize(),
                        "academicStatus": form.academicStatus.data,
                        "faculty": form.faculty.data,
                        "cellPhone": form.cellPhone.data,
                        "email": form.email.data,
                        "profilePic": profilePic
                    })
                # update userId in current session
                flask_login.current_user.userId = form.studentId.data
                app.logger.info(
                    'In Edit Account, commiting student changes. updated student will be: {}'
                    .format(student))
                flash('Your account was updated successfully!', 'success')
                return redirect(url_for('home'))
            else:
                app.logger.info(
                    'In Edit Account, form is NOT valid. form.errors:{}'.
                    format(form.errors))
                if 'csrf_token' in form.errors:
                    flash(
                        'Error: csrf token expired, please re-enter your credentials.',
                        'danger')
                else:
                    flash('There was an error, see details below.', 'danger')
        elif request.method == 'GET':
            form.studentId.data = student.studentId
            form.firstNameHeb.data = student.firstNameHeb
            form.lastNameHeb.data = student.lastNameHeb
            form.firstNameEng.data = student.firstNameEng
            form.lastNameEng.data = student.lastNameEng
            form.academicStatus.data = student.academicStatus
            form.faculty.data = student.faculty
            form.cellPhone.data = student.cellPhone
            form.email.data = student.email

        return render_template('editAccount.html',
                               title="Edit Account",
                               form=form,
                               student=student)
    except Exception as e:
        app.logger.error('In editAccount, Error is: {}\n{}'.format(
            e, traceback.format_exc()))
        return redirect(url_for('errorPage'))
Exemplo n.º 5
0
def register():
    if flask_login.current_user.is_authenticated:
        return redirect(url_for('home'))
    try:
        form = RegistrationForm()
        projectTitleChoices = [('', 'NOT CHOSEN')]
        form.projectTitle.choices = projectTitleChoices
        registrationSemester = utils.getRegistrationSemester()
        registrationYear = utils.getRegistrationYear()
        form.semester.choices = [(registrationSemester, registrationSemester)]
        form.year.choices = [(registrationYear, registrationYear)]
        if (request.method == 'POST'):
            form.email.data = form.email.data.strip()
            if form.validate_on_submit():
                picFile = None
                if form.profilePic.data:
                    picFile = utils.save_form_image(form.profilePic.data,
                                                    "profile")
                hashed_password = bcrypt.generate_password_hash(
                    form.password.data).decode('utf-8')
                database.registerStudent({
                    "studentId":
                    form.studentId.data,
                    "password":
                    hashed_password,
                    "firstNameHeb":
                    form.firstNameHeb.data,
                    "lastNameHeb":
                    form.lastNameHeb.data,
                    "firstNameEng":
                    form.firstNameEng.data.capitalize(),
                    "lastNameEng":
                    form.lastNameEng.data.capitalize(),
                    "academicStatus":
                    form.academicStatus.data,
                    "faculty":
                    form.faculty.data,
                    "cellPhone":
                    form.cellPhone.data,
                    "email":
                    form.email.data,
                    "semester":
                    registrationSemester,
                    "year":
                    registrationYear,
                    "profilePic":
                    picFile
                })

                flash('Account created successfully!', 'success')
                return redirect(url_for('login'))
            else:
                app.logger.info(
                    'In Register, form is NOT valid. form.errors:{}'.format(
                        form.errors))
                if 'csrf_token' in form.errors:
                    flash(
                        'Error: csrf token expired, please re-send the form.',
                        'danger')
                else:
                    flash('There was an error, see details below.', 'danger')
        return render_template('register.html',
                               title="Registration",
                               form=form)
    except Exception as e:
        app.logger.error('In register, Error is: {}\n{}'.format(
            e, traceback.format_exc()))
        return redirect(url_for('errorPage'))
Exemplo n.º 6
0
def manageLabs():
    if not flask_login.current_user.is_authenticated or flask_login.current_user.userType != "admin":
        return redirect(url_for('login'))
    try:
        admin = utils.check_user_admin()
        lab = None if not utils.check_user_lab() else database.getLabByAcronym(flask_login.current_user.userId)
        addForm = addLabForm()
        editForm = editLabForm()
        deleteForm = deleteLabForm()
        addFormErrors = False
        editFormErrorLabId = ''
        if (request.method=='POST'):
            formName = request.form['sentFormName']
            if formName == 'editLabForm':
                lab = database.getLabById(editForm.labId.data)
                if not lab:
                    app.logger.error('In manageLabs, in editForm, tried to edit a lab with id {} that does not exist in the db'.format(editForm.labId.data))
                    flash("Error: Lab with id {} is not in the db.".format(editForm.labId.data), 'danger')
                    return redirect(url_for('manageLabs'))
                if editForm.validate_on_submit():
                    if lab.acronym != editForm.new_acronym.data:
                        labWithAcr = database.getLabByAcronym(editForm.new_acronym.data)
                        if labWithAcr:
                            flash('There is already a lab with the same acronym!', 'danger')
                            return redirect(url_for('editAccount'))
                    projectImage = lab.logo
                    if editForm.new_logo.data:
                        app.logger.info('In manageProjects, in editForm, deleting old project image')
                        utils.delete_logo_image(projectImage) # TODO CHANGE THIS FUNCTIONS
                        projectImage = utils.save_form_image(editForm.new_logo.data, "labs_logo")
                    hashed_password = bcrypt.generate_password_hash(editForm.new_password.data).decode('utf-8')
                    database.updateLab(lab.id,{
                        "name": editForm.new_name.data,
                        "acronym": editForm.new_acronym.data,
                        "password": hashed_password,
                        "description": editForm.description.data,
                        "website": editForm.website.data,
                        "logo": projectImage
                    })
                    flash('Lab was updated successfully!', 'success')
                    return redirect(url_for('manageLabs'))
                else:
                    app.logger.info(
                        'In managelabs, editForm is NOT valid. editForm.errors: {}'.format(editForm.errors))
                    editFormErrorLabId = editForm.labId.data
                    if 'csrf_token' in editForm.errors:
                        flash('Error: csrf token expired, please re-send the form.', 'danger')
                    else:
                        flash('There was an error, see details below.', 'danger')

            elif formName == 'addLabForm':
                if addForm.validate_on_submit():
                    picFile = None
                    if addForm.logo.data:
                        app.logger.info('In manageLabs, saving image of new lab logo')
                        picFile = utils.save_form_image(addForm.logo.data, "labs_logo")
                    hashed_password = bcrypt.generate_password_hash(addForm.new_password.data).decode('utf-8')
                    newLab = {
                        "name": addForm.new_name.data,
                        "acronym": addForm.new_acronym.data,
                        "password": hashed_password,
                        "description": addForm.description.data,
                        "website": addForm.website.data,
                        "logo": picFile
                    }
                    database.addLab(newLab)

                    flash('Lab was created successfully!', 'success')
                    return redirect(url_for('manageLabs'))
                else:
                    addFormErrors = True
                    app.logger.info('In manageLabs, addForm is NOT valid. addForm.errors:{}'.format(addForm.errors))
                    if 'csrf_token' in addForm.errors:
                        flash('Error: csrf token expired, please re-send the form.', 'danger')
                    else:
                        flash('There was an error, see details below.', 'danger')

        return render_template('/admin/labs.html', title="Manage Labs", addForm=addForm,
                               editForm=editForm, deleteForm=deleteForm, addFormErrors=addFormErrors,
                               editFormErrorLabId=editFormErrorLabId, admin=admin, lab=lab)
    except Exception as e:
        app.logger.error('In manageLabs, Error is: {}\n{}'.format(e, traceback.format_exc()))
        return redirect(url_for('errorPage'))