def update_officer(officer_id): auth.check_login() name = request.form['name'] year = request.form['year'] major = request.form['major'] position = request.form['position'] quote = request.form['quote'] description = request.form['description'] href = '#' + request.form['name'] if helpers.check_file_in_request(request): try: image_url = helpers.save_request_file(request, OFFICER_IMAGE_FOLDER) except ValueError as e: flash('Exception: ' + str(e)) return redirect(url_for('admin_panel')) query = ( 'update officers ' 'set name=?, year=?, major=?, position=?, quote=?, description=?, href=?, image_url=? ' 'where id=?' ) query_db(query, [name, year, major, position, quote, description, href, image_url, officer_id]) else: query = ( 'update officers ' 'set name=?, year=?, major=?, position=?, quote=?, description=?, href=? ' 'where id=?' ) query_db(query, [name, year, major, position, quote, description, href, officer_id]) flash('Updated ' + name) # TODO: think about doing all of these redirects javascript-side return redirect(url_for('admin_panel'))
def edit_family(family_id): auth.check_login() family_name = request.form['family_name'] family_head1 = request.form['family_head1'] family_head2 = request.form['family_head2'] description = request.form['description'] if helpers.check_file_in_request(request): try: image_url = helpers.save_request_file(request, FAMILY_IMAGE_FOLDER) except ValueError as e: flash('Exception: ' + str(e)) return redirect(url_for('admin_panel')) query = ( 'update families ' 'set family_name=?, family_head1=?, family_head2=?, description=?, image_url=? ' 'where id=?' ) query_db(query, [family_name, family_head1, family_head2, description, image_url, family_id]) else: query = ( 'update families ' 'set family_name=?, family_head1=?, family_head2=?, description=?' 'where id=?' ) query_db(query, [family_name, family_head1, family_head2, description, family_id]) flash('Updated ' + family_name) return redirect(url_for('admin_panel'))
def admin_panel(): auth.check_login() events = query_db('select * from events order by unix_time desc') officers = query_db('select * from officers order by id') families = query_db('select * from families order by id') files = query_db('select * from files order by id') return render_template('admin.html', events=events, officers=officers, families=families, files=files)
def add_officer(): auth.check_login() try: image = helpers.file_from_request(request) except ValueError as e: flash('Exception: ' + str(e)) return redirect(url_for('admin_panel')) image_url = helpers.save_request_file(request, OFFICER_IMAGE_FOLDER) name = request.form['name'] year = request.form['year'] major = request.form['major'] position = request.form['position'] quote = request.form['quote'] description = request.form['description'] # TODO: this doesn't need to be part of the model href = '#' + request.form['name'] query = 'insert into officers (name, year, major, quote, description, image_url, position, href)'\ 'values (?, ?, ?, ?, ?, ?, ?, ?)' query_db(query, [name, year, major, quote, description, image_url, position, href]) flash('New officer successfully posted') return redirect(url_for('admin_panel'))
def add_file(): auth.check_login() name = request.form['name'] file_url = request.form['file_url'] query = 'insert into files (name, file_url)'\ 'values (?, ?)' query_db(query, [name, file_url]) flash('New file successfully posted') return redirect(url_for('admin_panel'))
def query(request): if not auth.check_login(request): return HttpResponse("error: access denied", content_type="application/json") #request_data = request.REQUEST.get('request') request_data = request.POST['request'] print request_data response = "error" if None != request_data: try: request = json.loads(request_data) return_count = vornone(request, 'return_count') return_count = False if None == return_count else return_count response = json.dumps(data.query(vornone(request, 'input_src'), vornone(request, 'input_sport'), vornone(request, 'input_dst'), vornone(request, 'input_dport'), vornone(request, 'tech_syn_flood'), vornone(request, 'tech_ack_flood'), vornone(request, 'tech_udp_flood'), vornone(request, 'tech_icmp_flood'), vornone(request, 'tech_connection_flood'), vornone(request, 'tech_stream_flood'), vornone(request, 'tech_content_drop'), vornone(request, 'tech_udp_dns_flood'), vornone(request, 'flag'), vornone(request, 'start_time'), vornone(request, 'end_time'), vornone(request, 'page'), return_count)) except Exception , e: response = "error:" + "search error"
def add_family(): auth.check_login() try: image = helpers.file_from_request(request) except ValueError as e: flash('Exception: ' + str(e)) return redirect(url_for('admin_panel')) image_url = helpers.save_request_file(request, FAMILY_IMAGE_FOLDER) family_name = request.form['family_name'] family_head1 = request.form['family_head1'] family_head2 = request.form['family_head2'] description = request.form['description'] query = 'insert into families (family_name, family_head1, family_head2, description, image_url)'\ 'values (?, ?, ?, ?, ?)' query_db(query, [family_name, family_head1, family_head2, description, image_url]) flash('New family successfully posted') return redirect(url_for('admin_panel'))
def add_event(): auth.check_login() try: url = request.form['link'] # Facebook event url example: # https://www.facebook.com/events/1201801539835081/ # Match the numbers between /s fb_event_id = re.match(r'.*/([0-9]+)/?$', url) if fb_event_id: fb_event_id = fb_event_id.group(1) else: raise Exception('Bad URL') res = fb_events.get_event(fb_event_id) title = res['name'] location = res.get('place', {'name': ''})['name'] time_str, unix_time = helpers.convert_time(res['start_time']) # another GET to get the cover photo image = fb_events.get_cover_photo(fb_event_id) # just resave it as a jpg image_ext = '.jpg' file_name = helpers.generate_random_filename(image_ext) image_url, image_path = helpers.create_file_paths(IMAGE_FOLDER, file_name) image.save(image_path, format='JPEG', quality=95, optimize=True, progressive=True) query = 'insert into events (title, time, location, link, image_url, unix_time)'\ 'values (?, ?, ?, ?, ?, ?)' query_db(query, [title, time_str, location, url, image_url, unix_time]) flash('New event was successfully posted') return redirect(url_for('admin_panel')) except Exception as e: flash('Exception: ' + str(e)) return redirect(url_for('admin_panel'))
def photo(request): if not auth.check_login(request): return HttpResponse("error") sid = request.REQUEST.get('id') if None == sid: return HttpResponseNotFound("not found") file_path = data.photo_path(sid) if not os.path.exists(file_path): return HttpResponseNotFound('not found') response = FileResponse(open(file_path, 'rb')) response['Content-Type'] = 'image/jpeg' return response
def photo(request): if not auth.check_login(request): return HttpResponse("error") sid = request.REQUEST.get('id') if None == sid: return HttpResponseNotFound("not found") file_path = data.photo_path(sid) if not os.path.exists(file_path): return HttpResponseNotFound('not found') response = FileResponse(open(file_path, 'rb')) response['Content-Type'] = 'image/jpeg' return response
def query(request): if not auth.check_login(request): return HttpResponse("error: access denied", content_type = "application/json") request_data = request.REQUEST.get('request') response = "error" if None != request_data: try: print request_data request = json.loads(request_data) return_count = vornone(request, 'return_count') return_count = False if None == return_count else return_count response = json.dumps(data.query(vornone(request, 'name'), vornone(request, 'sid'), vornone(request, 'idcard'), vornone(request, 'page'), return_count)) except Exception, e: response = "error:" + str(e) print e
def test_login(self): ValidLogin1 = 'aaddfs.-dfgd43qqw' ValidLogin2 = 'aaddfs.-dfgd43q22' WrongLogin1 = '2addfs.-dfgd43q22' WrongLogin2 = 'Addfs.-dfgd43q22' LongLogin2 = 'Addfs.-dfgd43q22aalalalllalal' MissedSymbol = 'aaddfs3dfgd43qa' self.assertTrue(check_login(ValidLogin1)) self.assertTrue(check_login(ValidLogin2)) self.assertFalse(check_login(WrongLogin1)) self.assertFalse(check_login(WrongLogin2)) self.assertFalse(check_login(LongLogin2)) self.assertFalse(check_login(MissedSymbol))
def report(request): if not auth.check_login(request): return HttpResponse("error: access denied", content_type="application/json") #request_data = request.REQUEST.get('request') request_data = request.POST['request'] print request_data response = "error" if None != request_data: try: request = json.loads(request_data) report_type = vornone(request, 'report_type') report_start_date = vornone(request, 'report_start_date') report_end_date = vornone(request, 'report_end_date') report_icon = vornone(request, 'report_icon') if report_type is None or report_start_date is None or report_end_date is None or report_icon is None: return HttpResponse("error:args error") if report_icon == "1": report_data1 = data.report_query1(report_type, report_start_date, report_end_date) response = json.dumps(report_data1) if report_icon == "2": report_data2 = data.report_query2(report_type, report_start_date, report_end_date) response = json.dumps(report_data2) if report_icon == "3": report_data3 = data.report_query3(report_type, report_start_date, report_end_date) response = json.dumps(report_data3) print response except: pass #print response return HttpResponse(response, content_type="application/json")
def search(): """ Searches for teacher meeting ids """ email, firstname, lastname = auth.check_login(request) if email and firstname and lastname: query = request.args.get('search') # ScheduleManager().createSchedule(email, firstname, lastname, check_teacher(email)) user_schedule = ScheduleManager().getSchedule(email, firstname, lastname, check_teacher(email)) user_schedule.init_db_connection() search_results = user_schedule.search_teacher(query) cards = "" for result in search_results: desc = result.get('office_desc') if desc is None: desc = "" result["office_desc"] = Markup( str(escape(desc)).replace("\n", "<br>")) cards += render_template("teacher_card.html", **result) commit = get_commit() calendar_token = auth.get_token(request) user_schedule.end_db_connection() return render_template("index.html", cards=Markup(cards), card_js="", commit=commit, calendar_token=calendar_token, email=email, firstname=firstname, lastname=lastname) else: return redirect("/")
def _post_api(path, query, session, *, send_json, send_error): if path == '/login': if 'username' not in query: return send_json({'error': 'No username'}) if 'password' not in query: return send_json({'error': 'No password'}) success, reason = check_login(query['username'], query['password']) if not success: return send_json({'error': reason}) session.activate_login(query['username'], query.get('handshake')) return send_json({'ok': reason}) elif path == '/register': if 'username' not in query: return send_json({'error': 'No username'}) if 'password' not in query: return send_json({'error': 'No password'}) success, reason = register_user(query['username'], query['password']) if not success: return send_json({'error': reason}) # also login session.activate_login(query['username'], query.get('handshake')) return send_json({'ok': reason}) elif path == '/post_message': if not session or not session.privileged: return send_json({'error': 'Not logged in with privileges'}) if 'message' not in query: return send_json({'error': 'No message'}) try: message = json.loads(query['message']) except: logger.warning('Message load threw a JSON err', exc_info=True) logger.info(f'Message was: {query["message"]}') return send_json({'error': 'Bad message format'}) message_keys = ['encrypted', 'message'] if not set(message_keys) <= set(message): return send_json({'error': 'Bad message format'}) rs = message.get('recipients', []) if not isinstance(rs, list): return send_json({'error': 'Bad message format'}) if len(rs) > 2: return send_json({'error': 'Too many recipients'}) for r in rs: if not check_username(r): return send_json({'error': 'Bad recipient username'}) if not check_user_exists(r): return send_json({'error': f'User {r} does not exist'}) message = {k: message[k] for k in message_keys} message['recipients'] = rs if message['encrypted']: message_bytes = bytes.fromhex(message['message']) message_bytes = encrypt_message(message_bytes, author=session.user, recipients=rs) message['message'] = message_bytes.hex() message['encrypted'] = bool(message['encrypted']) message['author'] = session.get('username') message['timestamp'] = time.time() token = save_message(message) return send_json({'ok': 'Message published', 'token': token}) elif path == '/set_status': if 'status' not in query: return send_json({'error': 'No status'}) if not session: return send_json({'error': 'Login first'}) if not session.set_persist('status', query['status']): return send_json({'error': 'Status write failed'}) return send_json({'ok': 'Status updated'}) else: return send_error(404, 'Not Found')
def update(): """ Gets the Zoom meeting ids """ course = request.form.get('course') section = request.form.get('section') meeting_id = str(request.form.get('meeting_id')) if course == "Office Hours" and section == "DESC": email, firstname, lastname = auth.check_login(request) if email and firstname and lastname: if meeting_id is None: meeting_id = '' user_schedule = ScheduleManager().getSchedule( email, firstname, lastname, check_teacher(email)) user_schedule.init_db_connection() user_schedule.update_teacher_database_office_description( email, escape(meeting_id)) return "Success" return "Error" if not (course and section and meeting_id): return "Error" lines = meeting_id.split("\n") id_num = -1 for l in lines: id = str(re.sub(r"\D", "", l)) if len(id) > 8 and len(id) < 12: id_num = int(id) if (id_num == -1): return "Error" # with urllib.request.urlopen('https://zoom.us/j/' + str(id_num)) as response: # html = response.read() # if "Invalid meeting ID." in str(html): # return "Error" email, firstname, lastname = auth.check_login(request) if course and meeting_id and email and firstname and lastname: user_schedule = ScheduleManager().getSchedule(email, firstname, lastname, check_teacher(email)) user_schedule.init_db_connection() if course == "Office Hours": if section == "ID": user_schedule.update_teacher_database_office_id(email, id_num) if section == "DESC": user_schedule.update_teacher_database_office_description( email, id_num) elif email: user_schedule.update_schedule(course, section, id_num) user_schedule.end_db_connection() return str(id_num) return "Error"
def index(): """ Will contain the default views for faculty, students, and teachers """ # if email := get_email(): email, firstname, lastname = auth.check_login(request) if email and firstname and lastname: # ScheduleManager().createSchedule(email, firstname, lastname, check_teacher(email)) user_schedule = ScheduleManager().getSchedule(email, firstname, lastname, check_teacher(email)) user_schedule.init_db_connection() # render_template here # log.info(Schedule().search_teacher_exact("Guelakis Patrick")) user_schedule.fetch_schedule() card_script = "" cards = "" toc = {'A': '', 'B': '', 'C': '', 'D': '', 'E': '', 'F': '', 'G': ''} # log.info(block_iter()) # if check_teacher(email): # uuid = secrets.token_hex(8) # cards += render_template("class_card.html") # card_script += render_template("card.js") top_label = "Today's Classes:" bottom_label = "Not Today" for block, start_time in block_iter(is_teacher=check_teacher(email)): if block == "Not Today": top_label = start_time + "'s Classes" bottom_label = "Not On " + start_time continue if block == "Break": cards += "<br><br><hr><br><h4>" + bottom_label + "</h4><br>" continue uuid = secrets.token_hex(8) schedule = None if block == "Office Hours": try: teacher = user_schedule.search_teacher_email_with_creation( user_schedule.email, user_schedule.lastname, user_schedule.firstname) schedule = { "block": "Office", "course": "Office Hours", "course_name": "Office Hours", "teacher_name": str(user_schedule.firstname).title() + " " + str(user_schedule.lastname).title(), "meeting_id": teacher['office_id'], "teacher_email": 'placeholder', "office_desc": teacher.get('office_desc') } if schedule['office_desc'] is None: schedule['office_desc'] = '' except TypeError as e: log_error( "Unable to create teacher schedule due to failed query" ) else: schedule = user_schedule.schedule[block] if schedule is None: continue elif not check_teacher(email): teacher = user_schedule.search_teacher_email( schedule["teacher_email"]) schedule["office_meeting_id"] = teacher.get('office_id') desc = teacher.get('office_desc') if desc is None: desc = "" schedule["office_desc"] = Markup( str(escape(desc)).replace("\n", "<br>")) schedule["user_can_change"] = not bool( teacher.get(schedule.get('block') + "_id")) else: schedule["user_can_change"] = True if len(block) == 1: # toc[block] = '<br><li><a href="#' + block + '-block">' + block + ' Block</a></li>' toc[block] = render_template("toc.html", block=block) schedule["uuid"] = uuid schedule["time"] = start_time if block == "Office Hours": schedule['office_desc'] = str( escape(str(schedule['office_desc']).replace( '\\', '\\\\'))).replace('\n', '\\n') cards += render_template("office_hours_card.html", **schedule) card_script += render_template("office_hours.js", **schedule) else: cards += render_template("class_card.html", **schedule) card_script += render_template("card.js", **schedule) commit = get_commit() calendar_token = auth.get_token(request) user_schedule.end_db_connection() response = make_response( render_template( "index.html", cards=Markup(cards), card_js=Markup(card_script), toc=Markup(toc['A'] + toc['B'] + toc['C'] + toc['D'] + toc['E'] + toc['F'] + toc['G']), top_label=top_label, calendar_token=calendar_token, email=email, firstname=str(firstname).title(), lastname=str(lastname).title(), refresh=True, commit=commit)) return auth.set_login(response, request) else: button = render_template("login.html") commit = get_commit() return render_template("landing.html", button=Markup(button), commit=commit)
def delete_event(event_id): auth.check_login() query = 'delete from events where id = ?' query_db(query, (event_id,)) return 'Deleted event'
def check_login_app(): return auth.check_login()
def delete_file(file_id): auth.check_login() query = 'delete from files where id = ?' query_db(query, (file_id,)) return 'Deleted file'
def delete_officer(officer_id): auth.check_login() query = 'delete from officers where id = ?' query_db(query, (officer_id,)) return 'Deleted officer'
def delete_family(family_id): auth.check_login() query = 'delete from families where id = ?' query_db(query, (family_id,)) return 'Deleted family'