def new_person(user_id, password): """ Person is added to the DB with the data retrieved from LDAP :param user_id: student number or employee identification :param password: the user password :return: None if nothing found, else the new User """ # Make a search request to LDAP person = search_person(user_id, password) if person is None: return None if 'student' in person['distinguishedName'].value.lower(): # Make new student name = person['displayName'].value student = Student(name, user_id) StudentDataAccess(get_db()).add_student(student) return User(user_id, name, 'student', False) else: # Make new employee name = person['displayName'].value email = person['mail'].value office = person['physicalDeliveryOfficeName'].value picture = get_random_picture_location() employee = Employee(user_id, name, email, office, None, picture, None, None, False, False, True) EmployeeDataAccess(get_db()).add_employee(employee) return User(user_id, name, 'employee', True)
def get_user(user_id: str, password: str = None): """ Returns the User with the given user_id First it's checked in the DB (doesn't check the password) If not found there, a query to the ldap is used to gather the information. If the password is correct, the data will be retrieved and added to the DB. :param user_id: student number or employee identification :param password: the user password :return: User object """ # Check if it's an employee employee_access = EmployeeDataAccess(get_db()) try: employee = employee_access.get_employee(user_id) return User(user_id, employee.name, 'admin' if employee.is_admin else 'employee', False) except: pass # Check if it's a student student_access = StudentDataAccess(get_db()) try: student = student_access.get_student(user_id) return User(user_id, student.name, 'student', False) except: pass if password is None: return None return new_person(user_id, password)
def add_research_group(data): """ Handles addition of research group. :param data: data object to be added :return: Json with success/failure status and error message """ try: doc = Document(None, data["description"], data["description"]) doc = DocumentDataAccess(get_db()).add_document(doc) dao = ResearchGroupDataAccess(get_db()) group = ResearchGroup(data["name"], data["abbreviation"], None, doc.document_id, data["address"], data["telephone_number"], True) dao.add_research_group(group) return jsonify({'success': True}), 200, { 'ContentType': 'application/json' } except Exception as e: return jsonify({ 'success': False, "message": str(e) }), 400, { 'ContentType': 'application/json' }
def make_tags_for_employee(e_id): cnt_bigrams = Counter() employee_projects = GuideDataAccess( get_db()).get_projects_for_employee(e_id) project_access = ProjectDataAccess(get_db()) for project in employee_projects: tags = project_access.get_project_tags(project['project_id']) for tag in tags: cnt_bigrams[tag] += 1 return cnt_bigrams
def active(receiver, is_student): if is_student: return '' projects = GuideDataAccess(get_db()).get_projects_for_employee( receiver.e_id) access = ProjectDataAccess(get_db()) projects = [access.get_project(x['project_id'], True) for x in projects] if not projects: return '' text = '\n\nACTIVE' for project in projects: text += project_link(project) return text
def add_employee(project, guidance, name): """ Adds an employee in the database. :param project: project id :param guidance: guidance type :param name: employee name """ try: employee_access = EmployeeDataAccess(get_db()) employee = employee_access.get_employee_by_name(name) guide = Guide(employee.e_id, project, guidance) GuideDataAccess(get_db()).add_guide(guide) except: pass
def add_tag(project, tag): """ Adds a tag in the database. :param project: project id :param tag: tag name """ try: TagDataAccess(get_db()).add_tag(tag) except: pass try: ProjectDataAccess(get_db()).add_project_tag(project, tag) except: pass
def archived_old(receiver, is_student): if is_student: return '' projects = GuideDataAccess(get_db()).get_projects_for_employee( receiver.e_id) access = ProjectDataAccess(get_db()) projects = [access.get_project(x['project_id'], False) for x in projects] projects = [project for project in projects if not project.is_active] if not projects: return '' text = '\n\nARCHIVED OLD:' for project in projects: text += project_link(project) return text
def add_registration(): """ Handles the POST request to '/project-editor'. :return: Json with success/failure status. """ if current_user.is_authenticated and current_user.role == "student": try: project_id = request.form['data'] type = request.form['type'] registration = Registration(current_user.user_id, project_id, type, "Pending") RegistrationDataAccess(get_db()).add_registration(registration) project = ProjectDataAccess(get_db()).get_project( project_id, False) if not project.is_active: raise Exception() msg = f"You registered for project {project.title}!\n" \ f"You'll be notified when one of the supervisors changes your registration status.\n" \ f"Best of luck!" send_mail(current_user.user_id + "@ad.ua.ac.be", "ESP Registration", msg) msg_employees = f"Student {current_user.name} ({current_user.user_id}) has registered for your project {project.title}.\n" \ f"To change the registration status please visit the ESP site." \ guides = GuideDataAccess( get_db()).get_guides_for_project(project_id) employee_access = EmployeeDataAccess(get_db()) guides_with_info = [ employee_access.get_employee(x.employee) for x in guides ] for guide in guides_with_info: if guide.email: send_mail(guide.email, "ESP Registration", msg_employees) return jsonify({'success': True}), 200, { 'ContentType': 'application/json' } except Exception as e: return jsonify({ 'success': False, "message": "Failed to add a new registration!" }), 400, { 'ContentType': 'application/json' }
def employee_authorized_for_project(employee_name, project_id): """ Checks if an employee has authorisation over a certain project. :param employee_name: employee name :param project_id: project id :return: Boolean """ employee = EmployeeDataAccess(get_db()).get_employee_by_name(employee_name) guides = GuideDataAccess(get_db()).get_guides_for_project(project_id) for guide in guides: if guide.employee == employee.e_id: return True project = ProjectDataAccess(get_db()).get_project(project_id, False) return employee.research_group == project.research_group
def activation(data): """ Handles activation of objects. :param data: data object with to be activated data :return: Json with success/failure status and error message """ activate = data.get("activate") obj_type = data.get("object") if obj_type == "employees": dao = EmployeeDataAccess(get_db()) elif obj_type == "groups": dao = ResearchGroupDataAccess(get_db()) elif obj_type == "tags": dao = TagDataAccess(get_db()) elif obj_type == "types": dao = TypeDataAccess(get_db()) else: return jsonify({ 'success': False, "message": "Object type incorrect" }), 400, { 'ContentType': 'application/json' } try: for elem in data["items"]: if obj_type == "tags": dao.remove_tag(elem) else: dao.set_active(elem, activate) return jsonify({'success': True}), 200, { 'ContentType': 'application/json' } except Exception as e: return jsonify({ 'success': False, "message": str(e) }), 400, { 'ContentType': 'application/json' }
def load_logged_in_user(): user_id = session.get('user_id') data_object = BlogModels(db_conn=get_db()) if user_id is None: g.user = None else: g.user = data_object.get_logged_user(user_id)
def add_employee(data): """ Handles addition of employee. :param data: data object to be added :return: Json with success/failure status and error message """ try: if not data['research_group']: data['research_group'] = None dao = EmployeeDataAccess(get_db()) picture = get_random_picture_location() employee = Employee(data["name"], data["name"], data["email"], data["office"], data.get("extra_info"), picture, data["research_group"], data["title"] if data.get("title") else None, data["is_external"], False, True) dao.add_employee(employee) return jsonify({'success': True}), 200, { 'ContentType': 'application/json' } except Exception as e: return jsonify({ 'success': False, "message": str(e) }), 400, { 'ContentType': 'application/json' }
def get_user_based_recommendations(favorite_projects): """ Fetches all user-specific recommendations, based on liked projects. :param favorite_projects: list of liked projects :return: dictionary containing a recommendation percentage for each project link """ link_access = LinkDataAccess(get_db()) # Get all links of the favorite projects all_links = [] for project in favorite_projects: links = link_access.get_links_for_project(project) all_links.extend(links) # Edge case, no links so can't do anything if not all_links: return dict() max_match_percent = max(all_links, key=lambda link: link.match_percent).match_percent recommendations = dict() for link in all_links: recommendations[ link.project_2] = link.match_percent / max_match_percent return recommendations
def get_csv_data(): """ Handles the POST request to '/csv-data', which retrieves data about all project registrations for certain years. :return: Json with success/failure status / data """ if not current_user.is_authenticated or (current_user.role != "admin" and current_user.role != "employee"): return '<div class="title">Er ging iets mis bij het genereren van het rapport</div>' else: years = request.args['years'] years = years.split() data = RegistrationDataAccess(get_db()).get_csv_data(years) file = os.path.join(config_data['file-storage'], 'Registrations.xlsx') workbook = xlsxwriter.Workbook(file) worksheet = workbook.add_worksheet() row = 0 for registration in data: worksheet.write(row, 0, registration['student_name']) worksheet.write(row, 1, registration['status']) worksheet.write(row, 2, registration['date']) worksheet.write(row, 3, registration['type']) worksheet.write(row, 4, registration['title']) worksheet.write(row, 5, registration['employee_name']) row += 1 workbook.close() filename = 'Registrations_' + datetime.today().strftime( '%d-%m-%Y') + '.xlsx' return send_file(file, attachment_filename=filename, as_attachment=True)
def update_employee(data): """ Handles update of employee. :param data: data object with new data :return: Json with success/failure status and error message """ try: if "is_admin" not in data: data[ "is_admin"] = "TRUE" if current_user.role == "admin" else "FALSE" if not data['research_group']: data['research_group'] = None dao = EmployeeDataAccess(get_db()) employee = Employee(data["key"], data["name"], data["email"], data["office"], data["extra_info"], data["picture_location"], data["research_group"], data["title"] if data["title"] else None, data["is_external"], data['is_admin'], data['is_active']) dao.update_employee(employee) return jsonify({'success': True}), 200, { 'ContentType': 'application/json' } except Exception as e: return jsonify({ 'success': False, "message": str(e) }), 400, { 'ContentType': 'application/json' }
def get_all_project_data(p_id): """ Handles the GET request to '/get-all-project-data/<int:p_id>'. :param p_id: project id :return: Json with all project data, the research group and links. """ active_only = not session["archive"] project_access = ProjectDataAccess(get_db()) p_data = project_access.get_project(p_id, active_only) if current_user.is_authenticated and current_user.role == "student": p_data.liked = LikeDataAccess(get_db()).is_liked( p_data.project_id, current_user.user_id) # Add linked projects linked_projects = LinkDataAccess(get_db()).get_links_for_project(p_id) linked_projects_data = set() for link in linked_projects: linked_project = project_access.get_project(link.project_2, active_only) if len(linked_projects_data) >= 4: break if not linked_project.is_active: continue linked_projects_data.add(linked_project) # Fill linked projects list with most viewed projects if len(linked_projects_data) < 4: projects_most_views = project_access.get_most_viewed_projects( 8, active_only) i = 0 while len(linked_projects_data) < 4: if not projects_most_views[i].project_id == p_id: linked_projects_data.add(projects_most_views[i]) i += 1 try: research_group = ResearchGroupDataAccess(get_db()).get_research_group( p_data.research_group).to_dict() except: research_group = None return jsonify({ "project_data": p_data.to_dict(), "research_group": research_group, "links": [obj.to_dict() for obj in linked_projects_data] })
def get_employee_data(name): """ Fetches all data of a certain employee. :param name: employee name :return: Json containing employee data """ employee = EmployeeDataAccess(get_db()).get_employee_by_name(name) return jsonify(employee.to_dict())
def give_random_pictures(): employeedata = EmployeeDataAccess(get_db()) all_employees = employeedata.get_employees(False) for f in all_employees: if f.picture_location is None: f.picture_location = get_random_picture_location() employeedata.update_employee(f) return
def get_edit_profile_data(name): try: employee = EmployeeDataAccess(get_db()).get_employee_by_name(name) research_groups = ResearchGroupDataAccess( get_db()).get_research_groups(False) return jsonify({ "employee": employee.to_dict(), "groups": [obj.to_dict() for obj in research_groups] }) except: return jsonify({ 'success': False, "message": "Employee name from LDAP not found in database" }), 400, { 'ContentType': 'application/json' }
def project_page(): """ Increases link strength upon a click. :return: render project page """ if "from" in request.args and "project_id" in request.args: LinkDataAccess(get_db()).update_match_percent( request.args["from"], request.args["project_id"], 0.05) return render_template('project.html')
def add_type(project, p_type): """ Adds a type in the database. :param project: project id :param p_type: type name """ try: ProjectDataAccess(get_db()).add_type(project, p_type) except: pass
def search(search_query): """ Handles the GET request to '/search/<search_query>'. :param search_query: search query :return: Json with results """ project_access = ProjectDataAccess(get_db()) active_only = not session.get("archive") results = project_access.search(search_query, active_only) return jsonify(results)
def new_query(): query_access = QueryDataAccess(get_db()) query = request.form['search_terms'] current_session = request.form['session_id'] dt = datetime.now() obj = Query(session_id=current_session, time_of_query=dt, search_terms=query) query_access.add_query(obj) return "true"
def archived_recent(receiver, is_student): if is_student: return '' projects = GuideDataAccess(get_db()).get_projects_for_employee( receiver.e_id) access = ProjectDataAccess(get_db()) projects = [access.get_project(x['project_id'], True) for x in projects] projects = [x for x in projects if x.is_active] if not projects: return '' text = '\n\nARCHIVED RECENT:' roll_over_performed = False for project in projects: if project_is_full(project): access.set_active(project.project_id, False) text += project_link(project) roll_over_performed = True if not roll_over_performed: return '' return text
def projects_pending(receiver, is_student): if is_student: return '' projects = GuideDataAccess(get_db()).get_projects_for_employee( receiver.e_id) proj_access = ProjectDataAccess(get_db()) projects = [ proj_access.get_project(x['project_id'], False) for x in projects ] projects = filter(lambda p: p.is_active, projects) reg_access = RegistrationDataAccess(get_db()) pending_projects = [ x for x in projects if reg_access.get_pending_registrations(x.project_id) ] if not pending_projects: return '' text = "\n\nPROJECTS WITH PENDING REGISTRATIONS:" for project in pending_projects: text += project_link(project) return text
def new_session(): if not current_user.is_authenticated or current_user.role != "student": return "false" session_access = SessionDataAccess(get_db()) dt = datetime.now() obj = Session(session_id=None, student=current_user.user_id, start_of_session=dt) s_id = session_access.add_session(obj).session_id session['session_id'] = s_id return str(obj.session_id)
def handle_registration(): """ Handles the POST request to '/handle-registration'. :return: Json with success/failure status. / redirects to login """ if current_user.is_authenticated and current_user.role != "student": try: data = request.json RegistrationDataAccess(get_db()).update_registration( student_id=data['student_id'], project_id=data['project_id'], new_status=data['status'], new_type=data['type']) project_title = ProjectDataAccess(get_db()).get_project( data['project_id'], False).title if data['status']: msg = f"Your registration for project {project_title} has changed to {data['status']}.\n" \ f"For questions or remarks please contact the supervisors of the project." send_mail(data['student_id'] + "@ad.ua.ac.be", "ESP Registration Update", msg) except: return jsonify({ 'success': False, "message": "Failed to update registration!" }), 400, { 'ContentType': 'application/json' } return jsonify({'success': True}), 200, { 'ContentType': 'application/json' } else: return jsonify({ 'success': False, "message": "Failed to update registration!" }), 400, { 'ContentType': 'application/json' }
def get_guides_project_info(e_name): try: info = GuideDataAccess(get_db()).get_guides_project_info(e_name) return jsonify(info) except: return jsonify({ 'success': False, "message": "Employee name from LDAP not found in database" }), 404, { 'ContentType': 'application/json' }
def post_admin_mail(): if not current_user.is_authenticated or current_user.role != 'admin': return jsonify({'success': False}), 400, { 'ContentType': 'application/json' } data = request.get_json() subject = data['subject'] content = data['content'] receiver = data['receiver'] lists = data['additions'] is_student = receiver == 'students' if is_student: possible_receivers = StudentDataAccess(get_db()).get_students() else: possible_receivers = EmployeeDataAccess(get_db()).get_employees(False) sent = 0 for person in possible_receivers: mail_content = f'Beste {person.name},\n\n{content}' personal_lists = mail_lists(person, is_student, lists) mail_content += personal_lists # Don't send mail if not one list is relevant for this person if lists and not personal_lists: continue receiver_mail = person.student_id + "@ad.ua.ac.be" if is_student else person.email if receiver_mail is not None: send_mail(receiver_mail, subject, mail_content) sent += 1 return jsonify({ 'success': True, 'sent': sent }), 200, { 'ContentType': 'application/json' }