Пример #1
0
def adminMail():
    if not utils.check_user_lab_admin():
        return redirect(url_for('home'))
    try:
        admin = utils.check_user_admin()
        lab = None if not utils.check_user_lab() else database.getLabByAcronym(flask_login.current_user.userId)
        form = adminMailForm()
        if request.method == "POST":
            if form.validate_on_submit():
                recipients = form.email.data.split(',')
                title = form.title.data
                content = form.content.data
                emailWasSent = sendMail(recipients,title,content)
                # emailWasSent = False
                if emailWasSent:
                    app.logger.info('Email was sent successfully')
                    flash('The email was sent successfully.', 'info')
                    return redirect(url_for('adminMail'))
            else:
                app.logger.info('In resetRequest, form is NOT valid. form.errors:{}'.format(form.errors))
                flash('There was an error, see details below.', 'danger')
        return render_template('/admin/adminMail.html', title="Mail", form=form, admin=admin, lab=lab)
    except Exception as e:
        app.logger.error('In resetRequest, Error is: {}\n{}'.format(e, traceback.format_exc()))
        return redirect(url_for('errorPage'))
Пример #2
0
def getProjectsTableData():
    if not utils.check_user_lab_admin():
        return redirect(url_for('login'))

    try:
        sort = request.args.get('sort')
        order = request.args.get('order') or "desc"
        limit = request.args.get('limit') or 10
        offset = request.args.get('offset') or 0
        filters = request.args.get('filter')
        lab = None if utils.check_user_admin() else database.getLabByAcronym(
            flask_login.current_user.userId).id

        totalResults, results = database.getProjectsTableData(
            sort, order, limit, offset, filters, lab)

        rows = []
        for result in results:
            supervisors = database.getProjectById(
                result.id).supervisorsFullNameEng
            lab = None
            if result.lab:
                lab = database.getLabById(result.lab).acronym

            rows.append({
                "image":
                f"<img style='width:80px;height:70px;' src='/static/images/projects/{result.image}' alt='{result.image}'"
                if result.image else "",
                "year":
                result.year,
                "semester":
                result.semester,
                "title":
                result.title,
                "status":
                result.status,
                "supervisorsNames":
                ",<br>".join(supervisors),
                "lab":
                lab,
                "btnEdit":
                f"<button type='button' onclick='getProjectData({result.id})' name='btnEdit' class='btn btn-primary' data-toggle='modal' data-target='#editProjectModal'><i class='fa fa-edit fa-fw'></i> Edit</button>",
                "btnDelete":
                f"<button type='button' onclick='deleteProject({result.id})' name='btnDelete' class='btn btn-danger' data-toggle='modal' data-target='#deleteProjectModal'><i class='fa fa-trash fa-fw'></i> Delete</button>"
            })

        # get filters options for the table
        filterOptions = database.getProjectsTableFilters()

        return jsonify(total=totalResults,
                       rows=rows,
                       filterOptions=filterOptions)

    except Exception as e:
        app.logger.error('In getProjectsTableData, error is: {}\n{}'.format(
            e, traceback.format_exc()))
        return jsonify(total=0, rows=[])
Пример #3
0
def getProjectsTableDataWithMails():
    if not utils.check_user_lab_admin():
        return redirect(url_for('login'))

    try:
        sort = request.args.get('sort')
        order = request.args.get('order') or "desc"
        limit = request.args.get('limit') or 10
        offset = request.args.get('offset') or 0
        filters = request.args.get('filter')
        lab = None if utils.check_user_admin() else database.getLabByAcronym(
            flask_login.current_user.userId).id

        totalResults, results = database.getProjectsTableData(
            sort, order, limit, offset, filters, lab)

        rows = []
        for result in results:

            project = database.getProjectById(result.id)
            supervisors = project.supervisorsFullNameEng
            studentsMail = [s.email for s in project.students]
            lab = None
            if result.lab:
                lab = database.getLabById(result.lab).acronym
            rows.append({
                "image":
                f"<img style='width:80px;height:70px;' src='/static/images/projects/{result.image}' alt='{result.image}'"
                if result.image else "",
                "year":
                result.year,
                "semester":
                result.semester,
                "title":
                result.title,
                "supervisorsNames":
                ",<br>".join(supervisors),
                "lab":
                lab,
                "id":
                result.id,
                "studentsMail":
                studentsMail
            })

        # get filters options for the table
        filterOptions = database.getProjectsTableFilters()

        return jsonify(total=totalResults,
                       rows=rows,
                       filterOptions=filterOptions)

    except Exception as e:
        app.logger.error('In getProjectsTableData, error is: {}\n{}'.format(
            e, traceback.format_exc()))
        return jsonify(total=0, rows=[])
Пример #4
0
def labOverview():
    if not utils.check_user_lab_admin():
        return redirect(url_for('login'))

    admin = utils.check_user_admin()
    lab = None if not utils.check_user_lab() else database.getLabByAcronym(
        current_user.userId)
    overview = database.getLabOverview(lab)
    return render_template("/admin/labOverview.html",
                           overview=overview,
                           admin=admin,
                           lab=lab)
Пример #5
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'))
Пример #6
0
def manageProjects():
    if not utils.check_user_lab_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)
        courses = database.getAllCourses()
        addForm = addProjectForm()
        editForm = editProjectForm()
        deleteForm = deleteProjectForm()
        addFormErrors = False
        editFormErrorProjectId = ''
        edit_studentForm = editStudentForm()

        currentSemester = utils.getRegistrationSemester()
        currentYear = utils.getRegistrationYear()
        semesterChoices = [("Winter", "Winter"), ("Spring", "Spring")]
        if currentSemester == "Spring":
            semesterChoices.reverse()
        addForm.new_title.choices = [
            (str(s.id), s.title) for s in database.getAllProposedProjects()
        ]
        addForm.new_year.choices = [
            (currentYear, currentYear),
            (str(int(currentYear) + 1), str(int(currentYear) + 1)),
            (str(int(currentYear) + 2), str(int(currentYear) + 2))
        ]
        addForm.new_semester.choices = semesterChoices

        allSupervisors = database.getAllSupervisors()
        supervisorsChoices = [(str(s.id), s.firstNameEng + " " + s.lastNameEng)
                              for s in allSupervisors]
        supervisorsChoices.insert(0, ('', ''))
        addForm.new_supervisor1.choices = supervisorsChoices
        addForm.new_supervisor2.choices = supervisorsChoices
        addForm.new_supervisor3.choices = supervisorsChoices

        editForm.year.choices = [
            (currentYear, currentYear),
            (str(int(currentYear) + 1), str(int(currentYear) + 1)),
            (str(int(currentYear) + 2), str(int(currentYear) + 2))
        ]
        editForm.semester.choices = semesterChoices
        editForm.supervisor1.choices = supervisorsChoices
        editForm.supervisor2.choices = supervisorsChoices
        editForm.supervisor3.choices = supervisorsChoices

        # get Labs
        allLabs = database.getAllLabs()
        allLabsChoices = [(str(l.id), l.acronym) for l in allLabs]
        editForm.lab.choices = allLabsChoices
        addForm.new_lab.choices = allLabsChoices

        if (request.method == 'POST'):
            formName = request.form['sentFormName']
            if formName == 'editProjectForm':
                project = database.getProjectById(editForm.projectId.data)

                if not project:
                    app.logger.error(
                        'In manageProjects, in editForm, tried to edit a project with id {} that does not exist in the db'
                        .format(editForm.projectId.data))
                    flash(
                        "Error: project with id {} is not in the db.".format(
                            editForm.projectId.data), 'danger')
                    return redirect(url_for('manageProjects'))

                app.logger.error("this is the students: {}".format(
                    request.form))
                if editForm.validate_on_submit():
                    studentsIds = request.form.getlist("students")
                    studentsCoursesIds = request.form.getlist(
                        "studentsCoursesIds")
                    if studentsIds and not studentsCoursesIds:
                        flash(
                            "Error: students can't be added to a project without a course number.",
                            'danger')
                        return redirect(url_for('manageProjects'))

                    projectImage = project.image
                    if editForm.image.data:
                        # delete old image if exists
                        app.logger.info(
                            'In manageProjects, in editForm, deleting old project image'
                        )
                        utils.delete_project_image(projectImage)
                        projectImage = utils.save_form_image(
                            editForm.image.data, "projects")

                    database.updateProject(
                        project.id, {
                            "title": editForm.title.data,
                            "year": editForm.year.data,
                            "semester": editForm.semester.data,
                            "comments": editForm.comments.data,
                            "grade": editForm.grade.data,
                            "image": projectImage,
                            "lab": editForm.lab.data
                        })

                    # update students in project
                    studentsInProject = []
                    for i in range(len(studentsIds)):
                        studentsInProject.append({
                            "id":
                            studentsIds[i],
                            "courseId":
                            studentsCoursesIds[i]
                        })
                    database.updateProjectStudents(project.id,
                                                   studentsInProject)

                    # update supervisors in project
                    supervisorsIds = set()
                    if editForm.supervisor1.data:
                        supervisorsIds.add(editForm.supervisor1.data)
                    if editForm.supervisor2.data:
                        supervisorsIds.add(editForm.supervisor2.data)
                    if editForm.supervisor3.data:
                        supervisorsIds.add(editForm.supervisor3.data)
                    database.updateProjectSupervisors(project.id,
                                                      supervisorsIds)

                    # update status
                    database.updateProjectStatus(
                        project.id, {
                            "requirementsDoc": editForm.requirementsDoc.data,
                            "firstMeeting": editForm.firstMeeting.data,
                            "halfwayPresentation":
                            editForm.halfwayPresentation.data,
                            "finalMeeting": editForm.finalMeeting.data,
                            "projectReport": editForm.projectReport.data,
                            "equipmentReturned":
                            editForm.equipmentReturned.data,
                            "projectDoc": editForm.projectDoc.data,
                            "gradeStatus": editForm.gradeStatus.data
                        })

                    flash('Project was updated successfully!', 'success')
                    if request.form.get('studentsReferrer'):
                        return redirect(url_for('manageStudents'))
                    else:
                        return redirect(url_for('manageProjects'))
                else:
                    app.logger.info(
                        'In manageProjects, editForm is NOT valid. editForm.errors: {}'
                        .format(editForm.errors))
                    editFormErrorProjectId = editForm.projectId.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')
                    if request.form.get('studentsReferrer'):
                        edit_StudentForm = editStudentForm()
                        delete_StudentForm = deleteStudentForm()
                        editFormErrorStudentId = ''

                        return render_template(
                            '/admin/students.html',
                            title="Manage Students",
                            editForm=edit_StudentForm,
                            editProjectForm=editForm,
                            courses=courses,
                            deleteForm=delete_StudentForm,
                            editFormErrorStudentId=editFormErrorStudentId,
                            editProjectErrorId=editFormErrorProjectId)

            elif formName == 'addProjectForm':
                if addForm.validate_on_submit():

                    studentsIds = request.form.getlist("students")
                    studentsCoursesIds = request.form.getlist(
                        "studentsCoursesIds")
                    if studentsIds and not studentsCoursesIds:
                        flash(
                            "Error: students can't be added to a project without a course number.",
                            'danger')
                        return redirect(url_for('manageProjects'))

                    # add new project
                    projectTitle = dict(addForm.new_title.choices).get(
                        addForm.new_title.data)
                    newImageName = None
                    # save project image
                    matchingProposedProject = database.getProposedProjectByTitle(
                        projectTitle)
                    if matchingProposedProject:
                        matchingImageName = matchingProposedProject.image
                        if matchingImageName:
                            newImageName = utils.copy_project_image_from_proposed_project(
                                matchingImageName)

                    newProject = {
                        "title": projectTitle,
                        "year": addForm.new_year.data,
                        "semester": addForm.new_semester.data,
                        "grade": addForm.new_grade.data,
                        "comments": addForm.new_comments.data,
                        "image": newImageName,
                        "requirementsDoc": addForm.new_requirementsDoc.data,
                        "firstMeeting": addForm.new_firstMeeting.data,
                        "halfwayPresentation":
                        addForm.new_halfwayPresentation.data,
                        "finalMeeting": addForm.new_finalMeeting.data,
                        "projectReport": addForm.new_projectReport.data,
                        "equipmentReturned":
                        addForm.new_equipmentReturned.data,
                        "projectDoc": addForm.new_projectDoc.data,
                        "gradeStatus": addForm.new_gradeStatus.data,
                        "status": "הרשמה",
                        "lab": addForm.new_lab.data
                    }

                    newProjectId = database.addProject(newProject)

                    # add students to project
                    studentsInProject = []
                    for i in range(len(studentsIds)):
                        studentsInProject.append({
                            "id":
                            studentsIds[i],
                            "courseId":
                            studentsCoursesIds[i]
                        })
                    database.updateProjectStudents(newProjectId,
                                                   studentsInProject)

                    # add supervisors to project
                    supervisorsIds = set()
                    if addForm.new_supervisor1.data:
                        supervisorsIds.add(addForm.new_supervisor1.data)
                    if addForm.new_supervisor2.data:
                        supervisorsIds.add(addForm.new_supervisor2.data)
                    if addForm.new_supervisor3.data:
                        supervisorsIds.add(addForm.new_supervisor3.data)
                    database.updateProjectSupervisors(newProjectId,
                                                      supervisorsIds)

                    flash('Project was created successfully!', 'success')
                    return redirect(url_for('manageProjects'))
                else:
                    addFormErrors = True
                    app.logger.info(
                        'In manageProjects, 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/projects.html',
                               title="Manage Projects",
                               courses=courses,
                               addForm=addForm,
                               editForm=editForm,
                               deleteForm=deleteForm,
                               addFormErrors=addFormErrors,
                               editFormErrorProjectId=editFormErrorProjectId,
                               editStudentForm=edit_studentForm,
                               admin=admin,
                               lab=lab)
    except Exception as e:
        app.logger.error('In manageProjects, Error is: {}\n{}'.format(
            e, traceback.format_exc()))
        return redirect(url_for('errorPage'))
Пример #7
0
def manageStudents():
    if not utils.check_user_lab_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)
        totalStudents = database.getStudentsCount()
        editForm = editStudentForm()
        edit_ProjectForm = editProjectForm()
        courses = database.getAllCourses()
        deleteForm = deleteStudentForm()
        editFormErrorStudentId = ''
        editProjectErrorId = ''
        currentSemester = utils.getRegistrationSemester()
        currentYear = utils.getRegistrationYear()
        semesterChoices = [("Winter", "Winter"), ("Spring", "Spring")]
        if currentSemester == "Spring":
            semesterChoices.reverse()

        allSupervisors = database.getAllSupervisors()
        supervisorsChoices = [(str(s.id), s.firstNameEng + " " + s.lastNameEng)
                              for s in allSupervisors]
        supervisorsChoices.insert(0, ('', ''))

        edit_ProjectForm.year.choices = [
            (currentYear, currentYear),
            (str(int(currentYear) + 1), str(int(currentYear) + 1)),
            (str(int(currentYear) + 2), str(int(currentYear) + 2))
        ]
        edit_ProjectForm.semester.choices = semesterChoices
        edit_ProjectForm.supervisor1.choices = supervisorsChoices
        edit_ProjectForm.supervisor2.choices = supervisorsChoices
        edit_ProjectForm.supervisor3.choices = supervisorsChoices

        if (request.method == 'POST'):
            formName = request.form['sentFormName']
            if formName == 'editStudentForm':
                student = database.getStudentById(editForm.id.data)
                if not student:
                    app.logger.error(
                        'In manageStudents, in editForm, tried to edit a student with id {} that does not exist in the db'
                        .format(editForm.id.data))
                    flash(
                        "Error: student with id {} doesn't exist in the db.".
                        format(editForm.id.data), 'danger')
                    return redirect(url_for('manageStudents'))
                if editForm.validate_on_submit():
                    database.updateStudent(
                        student.id, {
                            "studentId": editForm.studentId.data,
                            "firstNameEng":
                            editForm.firstNameEng.data.capitalize(),
                            "lastNameEng":
                            editForm.lastNameEng.data.capitalize(),
                            "firstNameHeb": editForm.firstNameHeb.data,
                            "lastNameHeb": editForm.lastNameHeb.data,
                            "email": editForm.email.data
                        })

                    app.logger.info(
                        'In manageStudents, commiting student {} changes'.
                        format(student))
                    flash('Student was updated successfully!', 'success')
                    return redirect(url_for('manageStudents'))
                else:
                    app.logger.info(
                        'In manageStudents, editForm is NOT valid. editForm.errors: {}'
                        .format(editForm.errors))
                    editFormErrorStudentId = editForm.id.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')

        return render_template('/admin/students.html',
                               title="Manage Students",
                               editForm=editForm,
                               editProjectForm=edit_ProjectForm,
                               courses=courses,
                               deleteForm=deleteForm,
                               editFormErrorStudentId=editFormErrorStudentId,
                               totalStudents=totalStudents,
                               admin=admin,
                               lab=lab)
    except Exception as e:
        app.logger.error('In manageStudents, Error is: {}'.format(e))
        return redirect(url_for('errorPage'))
Пример #8
0
def manageProposedProjects():
    if not utils.check_user_lab_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 = addProposedProjectForm()
        editForm = editProposedProjectForm()
        deleteForm = deleteProposedProjectForm()
        addFormErrors = False
        editFormErrorProposedProjectId = ''

        # get supervisors
        allSupervisors = database.getAllSupervisors()
        activeSupervisors = database.getActiveSupervisors()
        allSupervisorsChoices = [(str(s.id), s.firstNameEng + " " + s.lastNameEng) for s in allSupervisors]
        activeSupervisorsChoices = [(str(s.id), s.firstNameEng + " " + s.lastNameEng) for s in activeSupervisors]
        allSupervisorsChoices.insert(0, ('', ''))
        activeSupervisorsChoices.insert(0, ('', ''))

        editForm.supervisor1.choices = allSupervisorsChoices
        editForm.supervisor2.choices = allSupervisorsChoices
        editForm.supervisor3.choices = allSupervisorsChoices

        addForm.newSupervisor1.choices = activeSupervisorsChoices
        addForm.newSupervisor2.choices = activeSupervisorsChoices
        addForm.newSupervisor3.choices = activeSupervisorsChoices

        # get Labs
        allLabs = database.getAllLabs()
        allLabsChoices = [(str(l.id), l.acronym) for l in allLabs]
        editForm.lab.choices = allLabsChoices
        addForm.newLab.choices = allLabsChoices

        if (request.method == 'POST'):
            formName = request.form['pageForm']
            if formName == 'addProposedProjectForm':
                if addForm.validate_on_submit():
                    picFile = None
                    if addForm.newImage.data:
                        app.logger.info('In manageProposedProjects, saving image of new proposed project')
                        picFile = utils.save_form_image(addForm.newImage.data, "proposed_projects")

                    # create new proposed project
                    newProposedProjectId = database.addProposedProject({
                        "title": addForm.newTitle.data,
                        "description": addForm.newDescription.data,
                        "lab": addForm.newLab.data,
                        "image": picFile
                    })

                    # save the supervisors for this proposed project
                    supervisorsIds = set()
                    if addForm.newSupervisor1.data:
                        supervisorsIds.add(int(addForm.newSupervisor1.data))
                    if addForm.newSupervisor2.data:
                        supervisorsIds.add(int(addForm.newSupervisor2.data))
                    if addForm.newSupervisor3.data:
                        supervisorsIds.add(int(addForm.newSupervisor3.data))
                    database.updateProposedProjectSupervisors(newProposedProjectId, supervisorsIds)

                    flash('Proposed project created successfully!', 'success')
                    return redirect(url_for('manageProposedProjects'))
                else:
                    app.logger.info(
                        'In manageProposedProjects, 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')
                    addFormErrors = True
            elif formName == 'editProposedProjectForm':
                proposedProject = database.getProposedProjectById(editForm.proposedProjectId.data)

                if not proposedProject:
                    app.logger.error(
                        'In manageProposedProjects, in editForm, tried to edit a proposed project with id {} that does not exist in the db'.format(
                            editForm.proposedProjectId.data))
                    flash("Error: project with id {} is not in the db.".format(editForm.proposedProjectId.data),
                          'danger')
                    return redirect(url_for('manageProposedProjects'))

                if editForm.validate_on_submit():
                    picFile = proposedProject.image
                    if editForm.image.data:
                        # delete old image if exists
                        if picFile is not None:
                            utils.delete_proposed_project_image(picFile)
                        picFile = utils.save_form_image(editForm.image.data, "proposed_projects")

                    database.updateProposedProject(proposedProject.id, {
                        "title": editForm.title.data,
                        "description": editForm.description.data,
                        "image": picFile,
                        "lab": editForm.lab.data
                    })

                    newSupervisorsIds = set()
                    if editForm.supervisor1.data:
                        newSupervisorsIds.add(int(editForm.supervisor1.data))
                    if editForm.supervisor2.data:
                        newSupervisorsIds.add(int(editForm.supervisor2.data))
                    if editForm.supervisor3.data:
                        newSupervisorsIds.add(int(editForm.supervisor3.data))
                    database.updateProposedProjectSupervisors(proposedProject.id, newSupervisorsIds)

                    flash('Proposed project was updated successfully!', 'success')
                    return redirect(url_for('manageProposedProjects'))
                else:
                    app.logger.info(
                        'In manageProposedProjects, editForm is NOT valid. editForm.errors:{}'.format(editForm.errors))
                    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')
                    editFormErrorProposedProjectId = editForm.proposedProjectId.data

        return render_template('/admin/proposedProjects.html', title="Manage Proposed Projects", addForm=addForm,
                               editForm=editForm, deleteForm=deleteForm, addFormErrors=addFormErrors,
                               editFormErrorProposedProjectId=editFormErrorProposedProjectId,
                               admin=admin, lab=lab)
    except Exception as e:
        app.logger.error('In manageProposedProjects, Error is: {}\n{}'.format(e, traceback.format_exc()))
        return redirect(url_for('errorPage'))
Пример #9
0
def manageSupervisors():
    if not utils.check_user_lab_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 = addSupervisorForm()
        editForm = editSupervisorForm()
        deleteForm = deleteSupervisorForm()
        addFormErrors = False
        editFormErrorSupervisorId = ''
        if (request.method == 'POST'):
            formName = request.form['sentFormName']
            if formName == 'editSupervisorForm':
                supervisor = database.getSupervisorById(editForm.id.data)
                if not supervisor:
                    app.logger.error(
                        'In manageSupervisors, in editForm, tried to edit a supervisor with id {} that does not exist in the db'
                        .format(editForm.id.data))
                    flash(
                        "Error: supervisor with id {} is not in the db.".
                        format(editForm.id.data), 'danger')
                    return redirect(url_for('manageSupervisors'))
                if editForm.validate_on_submit():
                    database.updateSupervisor(
                        supervisor.id, {
                            "supervisorId": editForm.supervisorId.data,
                            "firstNameEng":
                            editForm.firstNameEng.data.capitalize(),
                            "lastNameEng":
                            editForm.lastNameEng.data.capitalize(),
                            "firstNameHeb": editForm.firstNameHeb.data,
                            "lastNameHeb": editForm.lastNameHeb.data,
                            "email": editForm.email.data.strip(),
                            "phone": editForm.phone.data,
                            "status": editForm.status.data,
                        })
                    app.logger.info(
                        'In manageSupervisors, in editForm, commiting supervisor {} changes'
                        .format(supervisor))
                    flash('Supervisor was updated successfully!', 'success')
                    return redirect(url_for('manageSupervisors'))
                else:
                    app.logger.info(
                        'In manageSupervisors, editForm is NOT valid. editForm.errors: {}'
                        .format(editForm.errors))
                    editFormErrorSupervisorId = editForm.id.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')
            if formName == 'addSupervisorForm':
                if addForm.validate_on_submit():
                    database.addSupervisor({
                        "supervisorId":
                        addForm.newSupervisorId.data,
                        "firstNameEng":
                        addForm.newFirstNameEng.data.capitalize(),
                        "lastNameEng":
                        addForm.newLastNameEng.data.capitalize(),
                        "firstNameHeb":
                        addForm.newFirstNameHeb.data,
                        "lastNameHeb":
                        addForm.newLastNameHeb.data,
                        "email":
                        addForm.newEmail.data.strip(),
                        "phone":
                        addForm.newPhone.data,
                        "status":
                        addForm.newStatus.data
                    })
                    flash('Supervisor created successfully!', 'success')
                    return redirect(url_for('manageSupervisors'))
                else:
                    app.logger.info(
                        'In manageSupervisors, addForm is NOT valid. addForm.errors: {}'
                        .format(addForm.errors))
                    addFormErrors = True
                    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/supervisors.html',
            title="Manage Supervisors",
            editForm=editForm,
            deleteForm=deleteForm,
            addForm=addForm,
            editFormErrorSupervisorId=editFormErrorSupervisorId,
            addFormErrors=addFormErrors,
            admin=admin,
            lab=lab)
    except Exception as e:
        app.logger.error('In manageSupervisors, Error is: {}\n{}'.format(
            e, traceback.format_exc()))
        return redirect(url_for('errorPage'))
Пример #10
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'))
Пример #11
0
def manageCourses():
    if not utils.check_user_lab_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 = addCourseForm()
        editForm = editCourseForm()
        deleteForm = deleteCourseForm()
        addFormErrors = False
        editFormErrorCourseId = ''

        # get Labs
        allLabs = database.getAllLabs()
        allLabsChoices = [(str(l.id), l.acronym) for l in allLabs]
        editForm.new_lab.choices = allLabsChoices
        addForm.new_lab.choices = allLabsChoices

        if (request.method == 'POST'):
            formName = request.form['sentFormName']
            if formName == 'editCourseForm':
                course = database.getCourseById(editForm.courseId.data)

                if not course:
                    app.logger.error(
                        'In manageCourses, in editForm, tried to edit a course with id {} that does not exist in the db'
                        .format(editForm.courseId.data))
                    flash(
                        "Error: Course with id {} is not in the db.".format(
                            editForm.courseId.data), 'danger')
                    return redirect(url_for('manageCourses'))

                if editForm.validate_on_submit():
                    database.updateCourse(
                        course.id, {
                            "number": editForm.new_number.data,
                            "name": editForm.new_name.data,
                            "lab": editForm.new_lab.data
                        })

                    flash('Course was updated successfully!', 'success')
                    return redirect(url_for('manageCourses'))
                else:
                    app.logger.info(
                        'In managecourses, editForm is NOT valid. editForm.errors: {}'
                        .format(editForm.errors))
                    editFormErrorCourseId = editForm.courseId.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 == 'addCourseForm':
                if addForm.validate_on_submit():
                    newCourse = {
                        "name": addForm.new_name.data,
                        "number": addForm.new_number.data,
                        "lab": addForm.new_lab.data
                    }
                    database.addCourse(newCourse)

                    flash('Course was created successfully!', 'success')
                    return redirect(url_for('manageCourses'))
                else:
                    addFormErrors = True
                    app.logger.info(
                        'In manageCourses, 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/courses.html',
                               title="Manage Courses",
                               addForm=addForm,
                               editForm=editForm,
                               deleteForm=deleteForm,
                               addFormErrors=addFormErrors,
                               editFormErrorCourseId=editFormErrorCourseId,
                               admin=admin,
                               lab=lab)
    except Exception as e:
        app.logger.error('In manageCourses, Error is: {}\n{}'.format(
            e, traceback.format_exc()))
        return redirect(url_for('errorPage'))