def login(): """ Function that checks if a user has the right credentials. If the user has the right credentials, it will be given a JWT. """ json_data = request.get_json() if not json_validation.validate_json(json_data, ['email', 'password']): return Iresponse.create_response("Bad request", 400) user_email = request.json.get('email') password = request.json.get('password') user_info = User.query.filter_by(email=user_email).first() if not user_info: return Iresponse.create_response('No user found by this email', 404) # Check password hashedpsw = user_info.password if hashedpsw == bcrypt.hashpw(password.encode('utf-8'), hashedpsw): identity_wrapped = { 'user_id': user_info.id, 'in_lti': False, } acces_token = create_access_token(identity=identity_wrapped) return Iresponse.create_response( { 'status': 'success', 'user': user_info.serialize, 'access_token': acces_token }, 200) else: return Iresponse.create_response('Wrong password', 403)
def verify_ta_rights_in_course(*args, **kwargs): """ Function that verifies that an user has ta rights in the specified course. This function required that the course_id is specified in the decorator. Returns on failure: - Iresponse 400: if the user can not be extracted from the jwt. - Iresponse 404: if the course can not be found. - Iresponse 403: if the user is not a teaching assistant in the course. Returns on succes: - Calls the decorated function, with the following params: (course, user, *args, **kwargs). So the decorated function should always accept atleast two params, namely the course and user, in that order. Extra params, should come after the course and user. """ verify_jwt_in_request() curr_user = get_current_user() course = Course.Course.query.get(course_id) if curr_user is None: return Iresponse.create_response("", 400) if course is None: return Iresponse.create_response("Course not found", 404) if curr_user not in course.ta_courses: if curr_user not in course.supervisors: return Iresponse.create_response("", 403) return func(course, curr_user, *args, **kwargs)
def create_labels(course_id): """ Adds a label to a course. """ data = request.get_json() if data is None: return Iresponse.create_response("", 404) name = data["name"] labelid = uuid.uuid4() exist_label = Label.query.filter_by(label_name=name).all() if exist_label: return Iresponse.create_response("", 200) course = Course.query.get(course_id) if course is None: return Iresponse.create_response("", 404) new_label = Label() new_label.label_name = name new_label.label_id = labelid new_label.course = course if not database.addItemSafelyToDB(new_label): return Iresponse.internal_server_error() database.db.session.commit() return Iresponse.create_response("", 200)
def createEmailMessage(): ''' Add a message to an existing ticket. ''' formdata = request.get_json() # Check if the ticket and message have a valid JSON. if not json_validation.validate_json(formdata, ['ticketid']): somethingWentWrongMessage(formdata['subject'], formdata['email'], 'Message: validate json data.', formdata['message']) return Iresponse.create_response('Malformed request', 400) ticket = Ticket.query.get(formdata['ticketid']) # Check if the ticket related to the message is valid. if ticket is None: somethingWentWrongMessage( formdata['subject'], formdata['email'], 'Message: Could not find a ticket with that id.', formdata['message']) return Iresponse.create_response('Could not find ticket', 400) formdata['studentid'] = ticket.user_id msg = rp_message.create_request(formdata, formdata['ticketid']) # Send an email to the student to notify them of our failing in life. if (msg.status_code != 201): message = replyErrorEmail(ticket.title, [ticket.email], formdata['ticketid'], json_data['message']) if current_app.config['SEND_MAIL_ON_MESSAGE']: app = current_app._get_current_object() thr = Thread(target=sendAsyncEmail, args=[message, app]) thr.start() return msg
def retrieve_user(): """ Returns the user model of the current user. """ current_identity = get_current_user() if current_identity is None: return Iresponse.create_response("", 404) student, ta, supv, usr = {}, {}, {}, {} student = database.serialize_list(current_identity.student_courses) ta = database.serialize_list(current_identity.ta_courses) supv = database.serialize_list(current_identity.supervisor_courses) usr = current_identity.serialize usr['student'] = student usr['ta'] = ta usr['supervisor'] = supv usr['roles'] = [] if len(usr['student']) >= 1: usr['roles'].append('student') if len(usr['ta']) >= 1: usr['roles'].append('ta') if len(usr['supervisor']) >= 1: usr['roles'].append('supervisor') return Iresponse.create_response({'user': usr}, 200)
def add_ta_to_ticket(json_data): """ Add a teaching assistant to a ticket. """ ticket = Ticket.query.filter_by( id=uuid.UUID(json_data['ticketid'])).first() ta = User.query.filter_by(id=json_data['taid']).first() if ticket.status_id != TicketStatus.receiving_help: ticket.status_id = TicketStatus.receiving_help database.db.session.commit() # Check if the ta and ticket were found and add if not already there. if ticket and ta: if ta not in ticket.bound_tas: ticket.bound_tas.append(ta) level_up = levels.add_experience(levels.EXP_FOR_ASSING, ta.id) levels.notify_level_change(ta.id, ticket, level_up) return Iresponse.create_response( { 'ta': ta.serialize, 'status': "Receiving help" }, 200) return Iresponse.create_response({'status': "OK"}, 201) return Iresponse.create_response("Failure", 400)
def download_file(): """ Download a file from server. """ json_data = request.get_json() if 'address' in json_data: homefolder = expanduser("~") base = '/serverdata/' location = json_data['address'].rsplit('/', 1)[0] folder = homefolder + base + location file = json_data['address'].rsplit('/', 1)[1] full_path = folder + json_data['address'] fileType, fileEncoding = mimetypes.guess_type(full_path) if folder and file: fp = open(folder + '/' + file, 'br').read() encoded = base64.b64encode(fp).decode("utf-8") return Iresponse.create_response( { 'encstring': str(encoded), 'mimetype': fileType }, 200) else: return Iresponse.create_response("No address", 404)
def retrieveEmailSettings(course_id): ''' Retrieve the email settings of a course. ''' # Find the course in the database. course = Course.query.get(course_id) if course is None: return Iresponse.create_response('This course does no longer exists', 200) # Check if a thread exists. thread = MailThread.existThreadCourseID(course_id) running = False if (thread is not None): running = True object = { 'email': course.course_email, 'password': course.mail_password, 'port': course.mail_port, 'pop': course.mail_server_url, 'running': running } return Iresponse.create_response(object, 201)
def create_request(jsonData, ticket_id): """ Function that handles the create request from a ticket. """ user_id = escape(jsonData["studentid"]) text = escape(jsonData["message"]) response_body = {} if text == '': response_body['message'] = "empty message" ticket = Ticket.query.get(ticket_id) if ticket is None: response_body['ticket'] = "No ticket exists with this id" if len(response_body) != 0: return Iresponse.create_response(response_body, 400) try: if user_id != ticket.user_id: notification = notifications.notify(user_id, ticket, text, Message.NTFY_TYPE_MESSAGE) notification = notification # Add experience if its a teaching assistant who is commenting. user = User.query.get(user_id) course = Course.query.get(ticket.course_id) if user in course.ta_courses: level_up = levels.add_experience(levels.EXP_FOR_RESPONSE, user_id) levels.notify_level_change(user_id, ticket, level_up) except Exception as e: return Iresponse.create_response(str(e), 400) return Iresponse.create_response("", 201)
def get_user(user_id): """ Retrieve user credentials. """ user = get_current_user() if user is None: return Iresponse.create_response("", 404) return Iresponse.create_response(user.serialize, 200)
def create_request(json_data): """ Function that handles the create request for a ticket. """ name = escape(json_data["name"]) name = name # flake8 studentid = escape(json_data["studentid"]) email = escape(json_data["email"]) subject = escape(json_data["subject"]) message = escape(json_data["message"]) courseid = escape(json_data["courseid"]) labelid = escape(json_data["labelid"]) files = json_data['files'] response_body = {} bound_tas = list() label = None if labelid != "": label = Label.query.get(uuid.UUID(labelid)) bound_tas = get_label_tas(label, studentid) if len(bound_tas) < 1: status_id = TicketStatus.unassigned else: status_id = TicketStatus.waiting_for_help ticket = Ticket(id=uuid.uuid4(), user_id=studentid, course_id=courseid, status_id=status_id, title=subject, email=email, label=label, files=files, timestamp=datetime.now()) for ta in bound_tas: ticket.bound_tas.append(ta) level_up = levels.add_experience(levels.EXP_FOR_ASSING, ta.id) levels.notify_level_change(ta.id, ticket, level_up) if not database.addItemSafelyToDB(ticket): return Iresponse.internal_server_error() try: msg = notifications.notify(studentid, ticket, message, Message.NTFY_TYPE_MESSAGE) msg = msg except Exception as e: raise e return Iresponse.create_response(str(e), 400) response_body['ticketid'] = ticket.id response = Iresponse.create_response(response_body, 201) response.headers.add('Location', 'api/ticket/{0}'.format(ticket.id)) return response
def retrieve_all_request(ticket_id): """ Process the request to receive all notes of a certain ticket. """ notes = Note.query.filter_by(ticket_id=ticket_id).all() if len(notes) == 0: return Iresponse.create_response("", 404) return Iresponse.create_response(database.serialize_list(notes), 200)
def wrapper(*args, **kwargs): verify_jwt_in_request() curr_identity = get_jwt_identity() if curr_identity is None: return Iresponse.create_response("", 404) if not curr_identity['in_lti']: return Iresponse.create_response("", 412) return func(*args, **kwargs)
def get_course_tas(course_id): """ Return all the tas in a course. """ course = Course.query.get(course_id) if course is None: return Iresponse.create_response("", 404) tas = course.ta_courses return Iresponse.create_response(database.serialize_list(tas), 200)
def retreive_course(course_id): """ Function that returns information about a specific course. """ course = Course.query.get(course_id) if course: return Iresponse.create_response(course.serialize, 200) else: return Iresponse.create_response("Course not found", 404)
def get_courses_user_is_ta_in(): """ Retrieve the courses where user is a teaching assistant. """ curr_user = get_current_user() if curr_user is None: return Iresponse.create_response("", 404) courses = curr_user.ta_courses return Iresponse.create_response(database.serialize_list(courses), 200)
def email_retrieve_labels(course_id): """ Returns all labels of given course. """ course = Course.query.get(course_id) if course is None: return Iresponse.create_response("", 404) return Iresponse.create_response(database.serialize_list(course.labels), 200)
def remove_ta_from_ticket(json_data): ticket = Ticket.get(uuid.UUID(json_data['ticketid'])) ta = User.query.filter_by(id=json_data['taid']).first() if ticket and ta: if ta in ticket.bound_tas: ticket.bound_tas.remove(ta) return Iresponse.create_response("Success", 200) return Iresponse.create_response("Failure", 400)
def retrieve_single_userlevel(user_id): """ Retrieves the level of given user. """ user = User.query.get(user_id) if user: response = {} response['level'] = level = user.level return Iresponse.create_response(response, 200) return Iresponse.create_response("", 400)
def update_plugin_state(course_id, plugin_id): """ Change the active state of a plugin. """ course = Course.query.get_or_404(course_id) if plugin_id not in plugins.plugin_list(): return Iresponse.create_response({"error": "Plugin does not exist"}, 400) pids = [p.plugin for p in course.plugins] if plugin_id not in pids: cp = CoursePlugin(id=uuid.uuid4(), plugin=plugin_id, course_id=course_id, active=request.get_json()['active']) course.plugins.append(cp) try: db.session.add(course) db.session.commit() except Exception as e: db.session.rollback() print(e) return Iresponse.create_response( { "status": "could not process\ your request" }, 500) return Iresponse.create_response( { "status": "success", "active": cp.active }, 200) else: cp = next((p for p in course.plugins if p.plugin == plugin_id), None) cp.active = request.get_json()['active'] try: db.session.add(course) db.session.commit() except Exception as e: db.session.rollback() print(e) return Iresponse.create_response( { "status": "could not process\ your request" }, 500) return Iresponse.create_response( { "status": "success", "active": cp.active }, 200)
def get_course_students(course_id): """ Returns all the students in a course. """ course = Course.query.get(course_id) print(course_id) if course is None: return Iresponse.create_response("", 404) print(course.student_courses) return Iresponse.create_response( database.serialize_list(course.student_courses), 200)
def retrieve_course_tickets(curr_course, curr_user): """ Inner fucntion that gets wrapped in a decorator. Retrieves the tickets by course id and returns them if found. If no tickets are found we return a 404. """ tickets = Ticket.query.filter_by(course_id=curr_course.id).all() if tickets is None: return Iresponse.create_response("", 404) return Iresponse.create_response(database.serialize_list(tickets), 200)
def stopEmailFetching(): ''' Stop the fetching of emails. ''' # Find the thread and check if it's running. course_id = escape(request.json['course_id']) thread = MailThread.existThreadCourseID(course_id) if (thread is None): return Iresponse.create_response('No email thread running', 200) thread.stop() return Iresponse.create_response('Succes', 201)
def retrieve_single_ticket(ticket_id): """ Retrieve single ticket from database. """ current_identity = get_current_user() ticket = Ticket.query.get(ticket_id) if is_user_relevant_to_ticket(current_identity, ticket): ticketObj = Ticket.query.get(ticket_id) else: return Iresponse.create_response('Unauthorized', 403) if ticketObj is None: return Iresponse.create_response("", 404) return Iresponse.create_response(ticketObj.serialize, 200)
def remove_label(label_id): """ Function that removes a label. """ label = Label.query.get(label_id) print(label) if label is None: return Iresponse.create_response("", 404) if not database.deleteSafelyFromDB(label, remove_label): return Iresponse.internal_server_error() return Iresponse.create_response("", 202)
def labelSelected(label_id): """ Return a boolean for selected labels. """ json_data = request.get_json() if not validate_json(json_data, ["user_id"]): return Iresponse.create_response("", 404) user_id = json_data["user_id"] user = User.query.get(user_id) label = Label.query.get(label_id) return Iresponse.create_response({'bool': label in user.labels}, 200)
def get_all_courses_for_ta(user_id): """ Function that returns all the courses a user is a teaching assistant in. """ user = User.query.get(user_id) if user is None: return Iresponse.create_response("", 404) courses = user.ta_courses if len(courses) == 0: return Iresponse.create_response("", 404) return Iresponse.create_response(database.serialize_list(courses), 200)
def retrieve_tickets(user_id): """ Function that returns all the tickets of a teaching assistant. """ user = User.query.get(user_id) if user is None: return Iresponse.create_response("", 404) tickets = user.ta_tickets if len(tickets) == 0: return Iresponse.create_response("", 404) return Iresponse.create_response(database.serialize_list(tickets), 200)
def user_exists(): """ Function that checks if a user email already exists. """ json_data = request.get_json() if not validate_json(json_data, ["email"]): return Iresponse.empty_json_request() email = json_data["email"] user = User.query.filter_by(email=email).first() if user is None: return Iresponse.create_response({"status": False}, 200) return Iresponse.create_response({"status": True}, 200)
def userid_exists(): """ Function that checks if the id of a user already exists. """ json_data = request.get_json() if not validate_json(json_data, ["studentid"]): return Iresponse.empty_json_request() studentid = json_data["studentid"] user = User.query.filter_by(id=studentid).first() if user is None: return Iresponse.create_response({"status": False}, 200) return Iresponse.create_response({"status": True}, 200)