def on_disconnect(): """ Invoked when user disconnects and closes the room user was in. :return: None """ close_room(current_user.id) LOGGER.info('%s disconnected', str(current_user))
def test_get_registration(self): self.seed_static_data() registration_data = { 'registration_form_id': self.form_id, 'answers': [{ 'registration_question_id': self.question_id, 'value': 'Answer 1' }, { 'registration_question_id': self.question2_id, 'value': 'Hello world, this is the 2nd answer.' }, { 'registration_question_id': self.question3_id, 'value': 'Hello world, this is the 3rd answer.' }] } response = self.app.post('/api/v1/guest-registration', data=json.dumps(registration_data), content_type='application/json', headers=self.headers) LOGGER.debug("hi: {}".format(response.data)) response = self.app.get('/api/v1/guest-registration', content_type='application/json', headers=self.headers) self.assertEqual(response.status_code, 200)
def save_residents(region_id, residents): """Save residents to database""" session = SESSION() player_ids = [] new_residents = 0 for player_dict in residents: player = session.query(Player).get(player_dict['id']) if player is None: player = save_player(session, player_dict) player_ids.append(player.id) last_residency = player.residencies \ .filter(PlayerResidency.region_id == region_id) \ .filter(PlayerResidency.until_date_time == None) \ .first() if not last_residency: new_residents += 1 player_location = PlayerResidency() player_location.player_id = player.id player_location.region_id = region_id player_location.from_date_time = datetime.now().replace(second=0, minute=0) session.add(player_location) LOGGER.info('regio %6s: "%s" new residents', region_id, new_residents) session.commit() current_residents = session.query(PlayerResidency) \ .filter(PlayerResidency.region_id == region_id) \ .filter(PlayerResidency.until_date_time == None).all() for current_resident in current_residents: if current_resident.player_id not in player_ids: current_resident.until_date_time = datetime.now().replace(second=0, minute=0) session.commit() session.close()
def post(self): args = self.req_parser.parse_args() registration_id = args['registration_id'] user_id = g.current_user['id'] try: current_user = UserRepository.get_by_id(user_id) registration, offer = RegistrationRepository.get_by_id_with_offer( registration_id) if not current_user.is_registration_admin(offer.event_id): return errors.FORBIDDEN registration.confirm() registration_user = UserRepository.get_by_id(offer.user_id) registration_event = EventRepository.get_by_id(offer.event_id) if _send_registration_confirmation_mail(registration_user, registration_event): registration.confirmation_email_sent_at = datetime.now() db.session.commit() return 'Confirmed Registration for {} {}'.format( registration_user.firstname, registration_user.lastname), 200 except Exception as e: LOGGER.error( 'Error occured while confirming registration with id {}: {}'. format(registration_id, e)) return errors.DB_NOT_AVAILABLE
def run(self): LOGGER.info("Searching for flapping alerts") logged_alerts = self.db.get_log_count_interval() flapping_alerts = self.db.get_flapping_alerts() flaphash = [x[0] for x in flapping_alerts] logged_hash = [] for a in logged_alerts: logged_hash.append(a[0]) if a[3] > self.limit and a[0] not in flaphash: # Set flapping self.db.set_flapping(a[0], a[1], a[2], a[3]) self.notify(a[1], a[2], a[3]) elif a[3] > self.limit and a[0] in flaphash: # Send reminder every hour if alert is still flapping self.db.update_flapping(a[0], a[4]) flaptime = [x[2] for x in flapping_alerts if x[0] == a[0]] if 0 < (time.time() % 3600 - flaptime[0] % 3600) <= 60: self.notify(a[1], a[2], a[3], reminder=True) elif a[3] <= self.limit and a[0] in flaphash: # Too low count to be marked as flapping # Check that time now is bigger than # modified + quarantine interval quarantine = [x[3] + x[4] for x in flapping_alerts if x[0] == a[0]] if time.time() > quarantine[0]: self.db.unset_flapping(a[0], a[1]) # If alert is no longer in the log it is not flapping, unset for a in [(x[0], x[1]) for x in flapping_alerts if x[0] not in logged_hash]: self.db.unset_flapping(a[0], a[1])
def post(self): req_parser = reqparse.RequestParser() req_parser.add_argument('email', type=str, required=True) args = req_parser.parse_args() LOGGER.debug( "Requesting password reset for email {} and organisation {}". format(args['email'], g.organisation.name)) user = user_repository.get_by_email(args['email'], g.organisation.id) if not user: LOGGER.debug( "No user found for email {} and organisation {}".format( args['email'], g.organisation.name)) return USER_NOT_FOUND password_reset = PasswordReset(user=user) db.session.add(password_reset) db.session.commit() email_user( 'password-reset', template_parameters=dict(system=g.organisation.system_name, organisation=g.organisation.name, host=misc.get_baobab_host(), token=password_reset.code), subject_parameters=dict(system_name=g.organisation.system_name), user=user) return {}, 201
def get(self): args = self.req_parser.parse_args() event_id = args['event_id'] user_id = g.current_user['id'] try: offer = db.session.query(Offer).filter(Offer.event_id == event_id).filter(Offer.user_id == user_id).first() request_travel = db.session.query(Answer).join( Question, Question.id == Answer.question_id ).filter( Question.headline == 'Would you like to be considered for a travel award?' ).join(Response, Answer.response_id == Response.id).filter( Response.user_id == user_id, Response.is_submitted == True ).first() if not offer: return errors.OFFER_NOT_FOUND elif offer.is_expired(): return errors.OFFER_EXPIRED else: return offer_info(offer, request_travel), 200 except SQLAlchemyError as e: LOGGER.error("Database error encountered: {}".format(e)) return errors.DB_NOT_AVAILABLE except: LOGGER.error("Encountered unknown error: {}".format( traceback.format_exc())) return errors.DB_NOT_AVAILABLE
def delete(self): args = self.del_req_parser.parse_args() current_user_id = g.current_user['id'] response = response_repository.get_by_id(args['id']) if not response: return errors.RESPONSE_NOT_FOUND if response.user_id != current_user_id: return errors.UNAUTHORIZED response.withdraw() response_repository.save(response) try: user = user_repository.get_by_id(current_user_id) event = response.application_form.event organisation = event.organisation emailer.email_user( 'withdrawal', template_parameters=dict( organisation_name=organisation.name ), event=event, user=user ) except: LOGGER.error('Failed to send withdrawal confirmation email for response with ID : {id}, but the response was withdrawn succesfully'.format(id=args['id'])) return {}, 204
def test_get_attendance_list(self): self.seed_static_data() # Create an unconfirmed user attendee2 = AppUser('*****@*****.**', 'attendee2', 'attendee2', 'Ms', 1, 1, 'M', 'Wits', 'CS', 'NA', 1, datetime(1984, 12, 12), 'Eng', 'abc') self.attendee2 = attendee2 db.session.add(attendee2) db.session.commit() offer2 = Offer(user_id=attendee2.id, event_id=self.event.id, offer_date=datetime.now(), expiry_date=datetime.now() + timedelta(days=15), payment_required=False, accommodation_award=True, travel_award=True, accepted_accommodation_award=True, accepted_travel_award=True) db.session.add(offer2) db.session.commit() registration2 = Registration(offer_id=offer2.id, registration_form_id=self.form.id, confirmed=False) db.session.add(registration2) db.session.commit() header = self.get_auth_header_for('*****@*****.**') user_id = 1 params = {'event_id': 1} result = self.app.get('/api/v1/registration/confirmed', headers=header, data=params) data = json.loads(result.data) self.assertEqual(len(data), 2) self.assertEqual(data[0]['user_id'], user_id) params = {'user_id': user_id, 'event_id': 1} self.app.post('/api/v1/attendance', headers=header, data=params) # Exclude signed in params = {'event_id': 1, 'exclude_already_signed_in': True} result2 = self.app.get('/api/v1/registration/confirmed', headers=header, data=params) data2 = json.loads(result2.data) self.assertEqual(len(data2), 1) # Include signed in - possible to undo params = {'exclude_already_signed_in': 'false', 'event_id': 1} LOGGER.debug(params) result2 = self.app.get('/api/v1/registration/confirmed', headers=header, data=params) data2 = json.loads(result2.data) self.assertEqual(len(data2), 2)
def post(self): req_parser = reqparse.RequestParser() req_parser.add_argument('email', type=str, required=True) args = req_parser.parse_args() LOGGER.debug("Requesting password reset for email {}".format( args['email'])) user = db.session.query(AppUser).filter( AppUser.email == args['email']).first() if not user: LOGGER.debug("No user found for email {}".format(args['email'])) return USER_NOT_FOUND password_reset = PasswordReset(user=user) db.session.add(password_reset) db.session.commit() # send_mail(recipient=args['email'], # subject='Password Reset for Lytehouse portal', # body_text=RESET_EMAIL_BODY.format(user.firstname, user.lastname, # get_baobab_host(), password_reset.code)) return {}, 201
def get(self): args = self.req_parser.parse_args() try: event = db.session.query(Event).filter(Event.id == args['event_id']).first() if not event: LOGGER.warn("Event not found for event_id: {}".format(args['event_id'])) return errors.EVENT_NOT_FOUND form = db.session.query(ApplicationForm).filter(ApplicationForm.event_id == args['event_id']).first() if not form: LOGGER.warn("Form not found for event_id: {}".format(args['event_id'])) return errors.FORM_NOT_FOUND # Get the latest response (note there may be older withdrawn responses) response = db.session.query(Response).filter( Response.application_form_id == form.id, Response.user_id == g.current_user['id'] ).order_by(Response.started_timestamp.desc()).first() if not response: LOGGER.debug("Response not found for event_id: {}".format(args['event_id'])) return errors.RESPONSE_NOT_FOUND answers = db.session.query(Answer).filter(Answer.response_id == response.id).all() response.answers = list(answers) return response except SQLAlchemyError as e: LOGGER.error("Database error encountered: {}".format(e)) return errors.DB_NOT_AVAILABLE except: LOGGER.error("Encountered unknown error: {}".format(traceback.format_exc())) return errors.DB_NOT_AVAILABLE
def __init__(self, server, username, password, project_key, assignee): LOGGER.info("Initiating jira incident") self._server = server self._username = username self._password = password self._project_key = project_key self._assignee = assignee
def _serialize_tag(tag, language): tag_translation = tag.get_translation(language) if not tag_translation: LOGGER.warn('Could not find {} translation for tag id {}'.format( language, tag.id)) tag_translation = tag.get_translation('en') return {'id': tag.id, 'name': tag_translation.name}
def get(self): args = self.req_parser.parse_args() event_id = args['event_id'] user_id = g.current_user['id'] try: offer = db.session.query(Offer).filter(Offer.event_id == event_id).filter(Offer.user_id == user_id).first() response = response_repository.get_submitted_by_user_id_for_event(user_id, event_id) if not response: return errors.RESPONSE_NOT_FOUND request_travel = response_repository.get_answer_by_question_key_and_response_id('travel_grant', response.id) if not offer: return errors.OFFER_NOT_FOUND elif offer.is_expired(): return errors.OFFER_EXPIRED else: return offer_info(offer, request_travel), 200 except SQLAlchemyError as e: LOGGER.error("Database error encountered: {}".format(e)) return errors.DB_NOT_AVAILABLE except: LOGGER.error("Encountered unknown error: {}".format( traceback.format_exc())) return errors.DB_NOT_AVAILABLE
def post(self): args = self.req_parser.parse_args() LOGGER.debug("FileUpload args: {}".format(args)) bucket = _get_storage_bucket() unique_name = str(uuid.uuid4().hex) blob = bucket.blob(unique_name) file = args['file'] bytes_file = file.read() content_type = file.content_type file_size = len(bytes_file) if file_size > FILE_SIZE_LIMIT: LOGGER.debug('File size of {} exceeds limit of {}'.format( file_size, FILE_SIZE_EXCEEDED)) return FILE_SIZE_EXCEEDED blob.upload_from_string(bytes_file, content_type=content_type) return { 'file_id': unique_name, }, 201
def _get_registrations(event_id, user_id, confirmed, exclude_already_signed_in=False): try: current_user = UserRepository.get_by_id(user_id) if not current_user.is_registration_volunteer(event_id): return errors.FORBIDDEN if(exclude_already_signed_in == True): registrations = RegistrationRepository.get_unsigned_in_attendees( event_id, confirmed=confirmed) guest_registration = GuestRegistrationRepository.get_all_unsigned_guests( event_id) else: if confirmed is None: registrations = RegistrationRepository.get_all_for_event( event_id) else: registrations = RegistrationRepository.get_confirmed_for_event( event_id, confirmed=confirmed) guest_registration = GuestRegistrationRepository.get_all_guests( event_id) registrations = [map_registration_info(info) for info in registrations] guest_registrations = [map_registration_info_guests( info) for info in guest_registration] all_registrations = registrations + guest_registrations # remove duplicates all_registrations_no_duplicates = list() for name, group in itertools.groupby(sorted(all_registrations, key=lambda d : d['user_id']), key=lambda d : d['user_id']): all_registrations_no_duplicates.append(next(group)) return marshal(all_registrations_no_duplicates, registration_admin_fields) except Exception as e: LOGGER.error( 'Error occured while retrieving unconfirmed registrations: {}'.format(e)) return errors.DB_NOT_AVAILABLE
def post(self): args = self.req_parser.parse_args() user = user_repository.get_by_email(args['email'], g.organisation.id) LOGGER.debug("Authenticating user: {}".format(args['email'])) if user: if user.is_deleted: LOGGER.debug("Failed to authenticate, user {} deleted".format( args['email'])) return USER_DELETED if not user.verified_email: LOGGER.debug( "Failed to authenticate, email {} not verified".format( args['email'])) return EMAIL_NOT_VERIFIED if bcrypt.check_password_hash(user.password, args['password']): LOGGER.debug("Successful authentication for email: {}".format( args['email'])) roles = db.session.query(EventRole).filter( EventRole.user_id == user.id).all() return user_info(user, roles) else: LOGGER.debug("User not found for {}".format(args['email'])) return BAD_CREDENTIALS
def get(self): try: user_id = verify_token(request.headers.get('Authorization'))['id'] db_offer = db.session.query(Offer).filter( Offer.user_id == user_id).first() if db_offer is None: return errors.OFFER_NOT_FOUND registration = db.session.query(Registration).filter( Registration.offer_id == db_offer.id).first() if registration is None: return 'no Registration', 404 registration_form = db.session.query(RegistrationForm).filter(RegistrationForm.id == registration. registration_form_id).first() if registration_form is None: return errors.REGISTRATION_FORM_NOT_FOUND db_answers = db.session.query(RegistrationAnswer).filter(RegistrationAnswer.registration_id == registration.id).all() response = { 'registration_id': registration.id, 'offer_id': db_offer.id, 'registration_form_id': registration_form.id, 'answers': db_answers } return marshal(response, self.response_fields) except Exception as e: LOGGER.error("Database error encountered: {}".format(e)) return errors.DB_NOT_AVAILABLE
def put(self): # update existing offer args = self.req_parser.parse_args() offer_id = args['offer_id'] candidate_response = args['candidate_response'] accepted_accommodation_award = args['accepted_accommodation_award'] accepted_travel_award = args['accepted_travel_award'] rejected_reason = args['rejected_reason'] offer = db.session.query(Offer).filter(Offer.id == offer_id).first() LOGGER.info('Updating offer {} with values: candidate response: {}, Accepted accommodation: {}, ' 'Accepted travel: {}, Rejected Reason: {}'.format(offer_id, candidate_response, accepted_accommodation_award, accepted_travel_award, rejected_reason)) if not offer: return errors.OFFER_NOT_FOUND try: user_id = verify_token(request.headers.get('Authorization'))['id'] if offer and offer.user_id != user_id: return errors.FORBIDDEN offer.responded_at = datetime.now() offer.candidate_response = candidate_response offer.accepted_accommodation_award = accepted_accommodation_award offer.accepted_travel_award = accepted_travel_award offer.rejected_reason = rejected_reason db.session.commit() except Exception as e: LOGGER.error("Failed to update offer with id {} due to {}".format(args['offer_id'], e)) return errors.ADD_OFFER_FAILED return offer_update_info(offer), 201
def add_n_users(self, n, password='******', organisation_id=1, is_admin=False, post_create_fn=lambda x: None): firstnames, lastnames = self._get_names() users = [] for i in range(n): title = random.choice(titles) firstname = random.choice(firstnames) lastname = random.choice(lastnames) email = "{firstname}.{lastname}{num}@bestemail.com".format( firstname=firstname, lastname=lastname if lastname != "" else "x", num=len(self.test_users)) email = strip_accents(email) try: user = self.add_user(email, firstname, lastname, title, password, organisation_id, is_admin, post_create_fn) users.append(user) except ProgrammingError as err: LOGGER.debug("info not added for user: {} {} {} {}".format( email, firstname, lastname, title)) db.session.rollback() return users
def post(self): args = self.req_parser.parse_args() event_id = args['event_id'] event = db.session.query(Event).filter( Event.id == event_id).first() if not event: return errors.EVENT_NOT_FOUND registration_form = RegistrationForm( event_id=event_id ) db.session.add(registration_form) try: db.session.commit() except IntegrityError: LOGGER.error( "Failed to add registration form for event : {}".format(event_id)) return errors.ADD_REGISTRATION_FORM_FAILED return registration_form_info(registration_form), 201
def delete(self, route_id): LOGGER.info('DELETE route') route = self.get_or_abort(route_id) db.session.delete(route) db.session.commit() return '', 204
def __init__(self): super(SlackAlertSummary, self).__init__() LOGGER.info("Initiating SlackAlertSummary") self.alertctrl = AlertController() self.db = DBController() self.url = "http://" + \ app.config['SERVER_FQDN'] + "/kap/log?environment="
def delete(self, vehicle_id): LOGGER.info('DELETE vehicle') vehicle = self.get_or_abort(vehicle_id) db.session.delete(vehicle) db.session.commit() return '', 204
def conv_start(update, context): """Start conversion""" LOGGER.info('"@%s" start remove account conversation', update.message.from_user.username) update.message.reply_text( 'Starting removal conversation, use /cancel to stop.') return conv_ask_player(update, context)
def post(self): LOGGER.info('CREATE Route') args = self.parser.parse_args() stops = [] checkpoints = [] if args['stops']: stops = [RouteStopM(**p) for p in args['stops']] if args['checkpoints']: checkpoints = [RouteCheckpointM(**p) for p in args['checkpoints']] for p in stops + checkpoints: db.session.add(p) route = RouteM(args['name'], args['status']) if args['path_color']: route.path_color = args['path_color'] if args['path']: route.path = json.dumps(args['path']) if stops: route.stops = stops if checkpoints: route.checkpoints = checkpoints db.session.add(route) db.session.commit() # path = json.loads(args['path']) return route, 201
def save_work_permits(state_id, work_permits): """Save residents to database""" session = SESSION() player_ids = [] new_work_permits = 0 for player_dict in work_permits: player = session.query(Player).get(player_dict['id']) if player is None: player = save_player(session, player_dict) player_ids.append(player.id) last_work_permit = player.state_work_permits \ .filter(StateWorkPermit.state_id == state_id) \ .filter(StateWorkPermit.until_date_time == None) \ .first() if not last_work_permit: new_work_permits += 1 state_work_permit = StateWorkPermit() state_work_permit.player_id = player.id state_work_permit.state_id = state_id state_work_permit.from_date_time = player_dict['from'] session.add(state_work_permit) session.commit() LOGGER.info('state %6s: "%s" new work permits', state_id, new_work_permits) current_work_permits = session.query(StateWorkPermit) \ .filter(StateWorkPermit.state_id == state_id) \ .filter(StateWorkPermit.until_date_time == None).all() for current_work_permit in current_work_permits: if current_work_permit.player_id not in player_ids: current_work_permit.until_date_time = datetime.now().replace( second=0, minute=0) session.commit() session.close()
def put(self, route_id): LOGGER.info('UPDATE Route') args = self.parser.parse_args() stops = [] checkpoints = [] if args['stops']: stops = [RouteStopM(p['lat'], p['lng']) for p in args['stops']] if args['checkpoints']: checkpoints = [ RouteCheckpointM(p['lat'], p['lng']) for p in args['checkpoints'] ] route = self.get_or_abort(route_id) if args['name']: route.name = args['name'] if args['status']: route.status = args['status'] if args['path_color']: route.path_color = args['path_color'] if args['path']: route.path = json.dumps(args['path']) if stops: route.stops = stops if checkpoints: route.checkpoints = checkpoints db.session.commit() return route, 200
def get_auth_header_for(self, email): body = {'email': email, 'password': '******'} response = self.app.post('api/v1/authenticate', data=body) data = json.loads(response.data) LOGGER.debug("<<auth>> {}".format(data)) header = {'Authorization': data['token']} return header
def get(self): args = self.req_parser.parse_args() language = args['language'] try: form = application_form_repository.get_by_event_id( args['event_id']) if not form: return FORM_NOT_FOUND if not form.is_open: return APPLICATIONS_CLOSED if not form.sections: return SECTION_NOT_FOUND if not form.questions: return QUESTION_NOT_FOUND return get_form_fields(form, language) except SQLAlchemyError as e: LOGGER.error("Database error encountered: {}".format(e)) return DB_NOT_AVAILABLE except: LOGGER.error("Encountered unknown error: {}".format( traceback.format_exc())) return DB_NOT_AVAILABLE