def add_application(self, user, data): """Add an applicant to the ticket :param user: The applicant :param data: The JSON format application """ if self.state != 'Open': raise BusinessException("The ticket cannot be applied now", 3) if Log.select().where( Log.model == "PreviewShowTicket", Log.log_type == 'apply', Log.model_refer == self.id, Log.user_affected == user).exists(): raise BusinessException("", 0) # send email to EVP mail_content = render_template( 'ticket_apply.html', ticket=self, member=user, data=data, time=str(datetime.now()) ) sq = Exco.select().where(Exco.position == "External Vice-President") send_email( ['*****@*****.**'] + [x.email for x in sq], [], "Ticket Application", mail_content )
def process_ask_for_ride( request, ride_response, ride_offer, ride_request ): ''' Processes a response YES/NO to a request for a ride from a particular RideOffer ''' offer_id = ride_offer request_id = ride_request response = ride_response profile = request.session.get("profile") # Do some error checking def fail( msg ): messages.add_message( request, messages.ERROR, msg ) return HttpResponseRedirect( reverse('user_landing') ) try: offer = RideOffer.objects.get( id=ObjectId(offer_id) ) req = RideRequest.objects.get( pk=ObjectId(request_id) ) rider = req.passenger # Offer or Passenger is not real except (RideOffer.DoesNotExist, RideRequest.DoesNotExist): return fail( "Rideoffer or request does not exist" ) # Invalid value for "response" field--- must accept or decline if response not in ('accept','decline'): return fail( "Not a valid accept or decline request link" ) # Accepting/declining someone who never asked for a ride if req not in offer.askers: return fail( "Not a valid accept or decline request link (no such user has asked you for a ride)" ) if profile != offer.driver: return fail( "Not a valid accept or decline request link (no ride request has been sent to this account)" ) # Update the RideOffer instance to accept/decline the request if response == 'accept': if len(offer.passengers) == 0: offer.passengers = [rider] else: offer.passengers.append( rider ) # Save this offer inside of the RideRequest req.ride_offer = offer req.save() # Email the driver, confirming the fact that they've decided to give a ride. # Also give them passenger's contact info. body_driver = render_message( "taxi/static/emails/driver_thankyou.txt", locals() ) send_email( email_to=request.user.username, email_body=body_driver, email_subject="Your ride from %s to %s"%(offer.start,offer.end) ) # Email the requester, telling them that they're request has been accepted, and # give them the driver's contact info. body_requester = render_message( "taxi/static/emails/process_ask_for_ride_confirm.txt", locals() ) send_email( email_to=rider.user.username, email_body=body_requester, email_subject="Your ride from %s to %s"%(offer.start,offer.end) ) offer.askers.remove( req ) offer.save() messages.add_message( request, messages.SUCCESS, "You have {} {}'s request".format('accepted' if response == 'accept' else 'declined', str(rider.user)) ) return HttpResponseRedirect( reverse('user_landing') )
def post(self): test_id = self.request.get( 'test_id' ) author_id = self.request.get( 'author_id' ) user = users.get_current_user() if user: test = Test.query( Test.id == test_id ).get() mark_query = Mark.query( ancestor = ndb.Key("Entity", user.user_id() ) ) mark_query = mark_query.filter( Mark.test.id == test.id ) this_mark = mark_query.get() if this_mark == None: print "IndexError" this_mark = Mark( parent = ndb.Key("Entity", user.user_id() ) ) this_mark.test = test this_mark.created = datetime.datetime.now() this_mark.mark = None this_mark.rated = False this_mark.rating = 0 test.times_taken += 1 test.put() this_mark.response = self.request.get( 'response' ) this_mark.complete = False this_mark.modified = datetime.datetime.now() this_mark.id = test_id + user.user_id() this_mark.marker_entity = Entity.query( Entity.id == author_id ).get() this_mark.taker_entity = Entity.query( Entity.id == user.user_id() ).get() send_email( this_mark.marker_entity.user.email() , test, "Test-Answer") this_mark.put() self.redirect( '/t/%s' % test_id ) return
def rider_feedback(request, request_id): # confirm correct user profile = request.session.get('profile') if profile != RideRequest.objects.get(pk=ObjectId(request_id)).passenger: raise PermissionDenied try: RideRequest.objects.get(pk=request_id) except (RideRequest.DoesNotExist): raise Http404 if request.method == 'POST': form = RiderFeedbackForm(request.POST) if form.is_valid(): data = form.cleaned_data feedback_msg = data['message'] request = RideRequest.objects.get(pk=ObjectId(data['request_id'])) driver = request.ride_offer.driver send_email(email_to=driver.user.username, email_subject="Trip Feedback", email_body=feedback_msg ) request.completed = True request.save() return HttpResponseRedirect( reverse('user_landing') ) form = RiderFeedbackForm(initial={'request_id':request_id}) return render_to_response('rider_feedback.html', locals(), context_instance=RequestContext(request))
def signup(): try: form = SignupForm() if form.validate_on_submit(): print "I am here" the_user = session.query(User).filter_by(mobilenumber = form.mobile.data).first() if the_user: flash("User with same mobile number already exist") else: user = User(name = form.name.data, email = form.email.data, password = generate_password_hash(form.password.data), mobilenumber = form.mobile.data) session.add(user) session.commit() token = generate_confirmation_token(user.email) confirm_url = url_for('confirm_email',token = token,_external = True) html = render_template('activate.html',confirm_url = confirm_url) subject = "Please confirm your email {}.".format(user.name) send_email(user.email,subject,html) flash("Thank you for Registering {}.".format(user.name)) flash("We have sent you a confirmation email to your registered email and its valid for 1 hour") flash("It may take 1 minute to arrive") flash("Please click on confirmation link sent in mail") return redirect(url_for('confirm')) return render_template('signup.html',form = form) except Exception as e: print e
def post( self, in_test_id ): path = urlparse.urlsplit(self.request.referrer).path author_id = self.request.get("author_id") test_id = self.request.get("test_id") mark_id = self.request.get("mark_id") address = self.request.get("mark_address") comment = self.request.get("comment") mark = self.request.get("mark") author_entity = Entity.query( Entity.id == author_id ).get() test_entity = Test.query( Test.id == test_id ).get() mark_entity = Mark.query( ancestor = ndb.Key("Entity", mark_id) ) mark_entity = mark_entity.filter( Mark.test.id == test_id ).get() mark_entity.marker_entity = author_entity mark_entity.test = test_entity mark_entity.comment = comment mark_entity.mark = int(mark) test_entity.total_score += mark_entity.mark test_entity.num_marked += 1 mark_entity.modified = datetime.datetime.now() mark_entity.complete = True mark_entity.put() send_email( address, test_entity, "Answer-Response") test_entity.put() self.redirect( path ) return
def process_offer_ride( request, ride_response, ride_offer, ride_request ): ''' Handles the 'accept' or 'decline' links sent to a passenger when a driver finds their RideRequest and submits an offer. ''' request_id = ride_request offer_id = ride_offer response = ride_response profile = request.session.get("profile") # Do some error checking def fail( msg ): messages.add_message( request, messages.ERROR, msg ) return HttpResponseRedirect( reverse('user_landing') ) try: req = RideRequest.objects.get( id=ObjectId(request_id) ) offer = RideOffer.objects.get( pk=ObjectId(offer_id) ) driver = offer.driver # Offer or Passenger is not real except (RideRequest.DoesNotExist, RideOffer.DoesNotExist): return fail( "Ride request or offer does not exist" ) # Invalid value for "response" field--- must accept or decline if response not in ('accept','decline'): return fail( "Not a valid accept or decline request link" ) # Accepting/declining someone who never asked for a ride if offer not in req.askers: return fail( "Not a valid accept or decline request link (no such user has offered you a ride)" ) if profile != req.passenger: return fail( "Not a valid accept or decline request link (no offer request has been sent to this account)" ) # Update the RideOffer instance to accept/decline the request if response == 'accept': req.ride_offer = offer if len(offer.passengers) == 0: offer.passengers = [profile] else: offer.passengers.append( profile ) offer.save() # Email the driver, confirming the fact that they've decided to give a ride. body_driver = render_message( "taxi/static/emails/driver_thankyou.txt", locals() ) send_email( email_to=driver.user.username, email_body=body_driver, email_subject="Your ride %s"%(offer) ) # Email the requester, telling them that they're request has been accepted, and # give them the driver's contact info. body_requester = render_message( "taxi/static/emails/process_offer_ride_confirm.txt", locals() ) send_email( email_to=profile.user.username, email_body=body_requester, email_subject="Your ride %s"%str(req) ) req.askers.remove( offer ) req.save() messages.add_message( request, messages.SUCCESS, "You have {} {}'s offer".format('accepted' if response == 'accept' else 'declined', str(driver)) ) return HttpResponseRedirect( reverse('user_landing') )
def ask_for_ride( request ): ''' Asks for a ride from a particular offer ''' data = request.POST profile = request.session.get("profile") offer = RideOffer.objects.get( pk=ObjectId(data['offer_id']) ) msg = data['msg'] request_id = data['request_choices'] if 'request_choices' in data else 'new' # See if the logged-in user has already asked for a ride from this person for asker in offer.askers: if asker.passenger == profile: messages.add_message( request, messages.ERROR, "You have already asked to join this ride." ) return render_to_response( 'ride_offer.html', locals(), context_instance=RequestContext(request) ) # Get or create the RideRequest if request_id == 'new': req = RideRequest.objects.create( passenger = profile, start = offer.start, end = offer.end, message = msg, date = offer.date ) request_id = req.id profile.requests.append( req ) profile.save() else: req = RideRequest.objects.get( pk=ObjectId(request_id) ) req.message = msg req.save() # Stuff that we append to the message accept_link = '%s%s'%( _hostname(), reverse( 'process_ask_for_ride', args=('accept', offer.id, request_id) ) ) decline_link = '%s%s'%( _hostname(), reverse( 'process_ask_for_ride', args=('decline', offer.id, request_id) ) ) appended = render_message( "taxi/static/emails/ask_for_ride_accept_or_decline.txt", locals() ) msg = "\r\n".join( (msg,30*'-',appended) ) # Save this asker in the offer's 'askers' field offer.askers.append( req ) offer.save() dest_email = offer.driver.user.username subject = "{} {} is asking you for a ride!".format( request.user.first_name, request.user.last_name ) send_email( email_to=dest_email, email_body=msg, email_subject=subject ) messages.add_message( request, messages.SUCCESS, "Your request has been sent successfully." ) return HttpResponseRedirect( reverse("browse") )
def offer_ride( request ): ''' Sends an offer for a ride to someone who has made a RideRequest ''' data = request.POST profile = request.session.get("profile") req = RideRequest.objects.get( pk=ObjectId(data['request_id']) ) msg = data['msg'] offer_choices = data['offer_choices'] if 'offer_choices' in data else 'new' # Can't offer twice for asker in req.askers: if asker.driver == profile: messages.add_message( request, messages.ERROR, "You have already offered a ride to this person" ) return render_to_response( 'ride_request.html', locals(), context_instance=RequestContext(request) ) # Get or create the offer that this request should be associated with if offer_choices == 'new': offer = RideOffer.objects.create( driver = profile, start = req.start, end = req.end, date = req.date, message = msg ) profile.offers.append( offer ) profile.save() else: offer = RideOffer.objects.get( pk=ObjectId(offer_choices) ) offer.message = msg offer.save() # Message to be sent to the passenger accept_link = '%s%s'%( _hostname(), reverse( 'process_offer_ride', args=('accept', offer.id, req.id) ) ) decline_link = '%s%s'%( _hostname(), reverse( 'process_offer_ride', args=('decline', offer.id, req.id) ) ) appended = render_message( 'taxi/static/emails/offer_ride_accept_or_decline.txt', locals() ) msg = "\r\n".join( (msg,30*'-',appended) ) # Save this asker in the offer's 'askers' field req.askers.append( offer ) req.save() dest_email = req.passenger.user.username subject = "{} can drive you to {}".format( profile, req.end ) send_email( email_to=dest_email, email_body=msg, email_subject=subject ) messages.add_message( request, messages.SUCCESS, "Your offer has been sent successfully." ) return HttpResponseRedirect( reverse("browse") )
def api_reserve(self, pk): """API to reserve a disk""" obj = get_object_or_404(self.get_query(), self.pk == pk) data = request.data or request.form.get('data') or '' new_log = Log(model='Disk', log_type='reserve', model_refer=obj.id) if request.method == 'POST': data = self.data_precheck(data, ReserveForm) # reserve the disk obj.reserve(g.user, data['form']) new_log.user_affected = g.user if data['form'] == 'Counter': new_log.content = ("member %s reserves disk" " %s (counter)") % \ (g.user.itsc, obj.get_callnumber()) elif data['form'] == 'Hall': new_log.content = ("member %s reserves disk" " %s (Hall %d %s). remarks: %s") %\ ( g.user.itsc, obj.get_callnumber(), data.get('hall', ''), data.get('room', ''), data.get('remarks', '') ) # send email to reminder exco to deliver disk mail_content = render_template( 'exco_reserve.html', disk=obj, member=g.user, data=data, time=str(datetime.now())) sq = Exco.select().where( Exco.hall_allocate % ("%%%d%%" % int(data.get('hall', '*')))) send_email( ['*****@*****.**'] + [x.email for x in sq], [], "Delivery Request", mail_content) elif request.method == 'DELETE': # clear reservation if not self.check_delete(obj): return self.response_forbidden() new_log.content = "clear reservation for disk %s" % obj.get_callnumber() new_log.admin_involved = g.user new_log.user_affected = obj.reserved_by obj.clear_reservation() obj.save() new_log.save() return self.object_detail(obj)
def contact_user(queriedUserID): cookie = bottle.request.get_cookie("session") userID, firstname = sessions.get_userID_firstname(cookie) if userID is None: bottle.redirect('/login'); return queriedUserID = cgi.escape(queriedUserID) queriedUser = users.get_user(queriedUserID) if queriedUser is None: bottle.redirect('/internal_error'); return subject = "You've received a message!" message = bottle.request.forms.get("message") error = {'e':''} if validate_message(message, error): email_sent = send_email(queriedUser['e'], subject, message) if email_sent: bottle.redirect('/message_sent?targetUserID=' + queriedUserID); return else: error['e'] = "Sorry, there was an internal error. It wasn't you. It was us." return bottle.template('user_profile', dict(userID = userID, firstname = firstname, mode = 'contact', message = message, queriedUser = queriedUser, error = error['e']))
def tell(medium, friend, msg): if medium not in VALID_MEDIUMS: return "Medium '%s' not recognized" % (medium,) config = CONFIG[friend] if medium == "cloakcast": # TODO: Add cloakcast support print "Clandestinely messaging %s via Cloakcast" % (friend,) elif medium == "email": return send_email(EMAIL_USERNAME, EMAIL_PASSWORD, [config[medium]], msg) elif medium == "gtalk": return send_im(EMAIL_USERNAME, EMAIL_PASSWORD, config[medium], msg) elif medium == "sms": return send_sms(config[medium], msg) elif medium == "twitter": tokens = twitter_tokens(creds["twitter_consumer_key"], creds["twitter_consumer_secret"]) if len(tokens) != 2: return "Problem getting twitter tokens: %s" % tokens # twitter_oauth_token, twitter_oauth_token_secret = tokens twitter_oauth_token = creds["twitter_oauth_token"] twitter_oauth_token_secret = creds["twitter_oauth_token_secret"] return send_tweet( creds["twitter_consumer_key"], creds["twitter_consumer_secret"], "https://api.twitter.com/1.1/statuses/update.json", twitter_oauth_token, twitter_oauth_token_secret, http_method="POST", post_body=urllib.urlencode({"status": msg}), ) return ""
def process_signup(): form_input = bottle.request.forms user_signup = build_user_signup_JSON(form_input) error = {'e':''} ## if it was a good signup if validate_signup(users, user_signup, error): # user inputs do not need to be escaped they have been validated by validate_signup() # however, for added security, we will escape anyway user = clean_and_format_user_signup(user_signup) # removed the second password; contains the raw password # insert signed-up user to database and obtain signup confirmation string (for email address verification) signup_conf_str = users.insert_user(user) if not signup_conf_str: # if there was error inserting signed-up user to database return bottle.redirect("/internal_error"); return else: # if user signup successfully inserted into db signup_conf_link = base_url + '/confirm_signup/' + signup_conf_str subject = "Signup Confirmation" message = "Thanks for signing up! You can confirm your signup by visiting this link: %s" % signup_conf_link email_sent = send_email(emailID, subject, message) if email_sent: bottle.redirect('/please_confirm_email'); return else: bottle.redirect('/internal_error'); return ## if it was a bad signup else: # firstname, lastname, emailID variables do not need to be escaped in the server side as they are escaped in the template engine; # in fact, if they were escaped in the server-side, the client-side would escape the escaped strings return bottle.template("signup", dict(user_signup = user_signup, error = error['e']))
def resend_confirmation(): try: form = ResendForm() if form.validate_on_submit(): user = session.query(User).filter_by(email = form.email.data).first() if user: token = generate_confirmation_token(form.email.data) confirm_url = url_for('confirm_email',token = token,_external = True) html = render_template('activate.html',confirm_url = confirm_url) subject = "Please confirm your email {}.".format(user.name) send_email(user.email,subject,html) flash("Confirmation link sent to your registered email\nPlease click on the link to confirm your email") return redirect(url_for('confirm')) else: flash("You are not registered.\nPlease Register") return render_template('unconfirmed.html') return render_template('resend.html',form = form) except Exception as e: print e
def post(self): test_id = self.request.get('test_id') author_id = self.request.get('author_id') user = users.get_current_user() if user: test = Test.query(Test.id == test_id).get() mark_query = Mark.query(ancestor=ndb.Key("Entity", user.user_id())) mark_query = mark_query.filter(Mark.test.id == test.id) this_mark = mark_query.get() if this_mark == None: print "IndexError" this_mark = Mark(parent=ndb.Key("Entity", user.user_id())) this_mark.test = test this_mark.created = datetime.datetime.now() this_mark.mark = None this_mark.rated = False this_mark.rating = 0 test.times_taken += 1 test.put() this_mark.response = self.request.get('response') this_mark.complete = False this_mark.modified = datetime.datetime.now() this_mark.id = test_id + user.user_id() this_mark.marker_entity = Entity.query( Entity.id == author_id).get() this_mark.taker_entity = Entity.query( Entity.id == user.user_id()).get() send_email(this_mark.marker_entity.user.email(), test, "Test-Answer") this_mark.put() self.redirect('/t/%s' % test_id) return
def root(): if request.method == 'GET': return 'ok', 200 elif request.method == 'POST': data = request.data values = json.loads(data) logging.info(values) data = None email = None template = None try: data = values['data'] email = values['email'] template = values['template'] except Exception as e: logging.debug(e) # Check that email is provided if email is None: return 'Missing email', 500 # Send email with data response = None if template is None: response = send_email(email=email, data=data) else: response = send_email(email=email, data=data, template=template) # Check the status code from sendgrid request if response.status_code < 400: return 'ok', 200 else: return 'Something went wrong, ' + response.status_code
def tell(medium, friend, msg): if medium not in VALID_MEDIUMS: return "Medium '%s' not recognized" % (medium,) config = CONFIG[friend] if medium == "cloakcast": # TODO: Add cloakcast support print "Clandestinely messaging %s via Cloakcast" % (friend,) elif medium == "email": return send_email(EMAIL_USERNAME, EMAIL_PASSWORD, [config[medium]], msg) elif medium == "gtalk": return send_im(EMAIL_USERNAME, EMAIL_PASSWORD, config[medium], msg) elif medium == "sms": return send_sms(config[medium], msg) return ""
def tell(medium, friend, msg): if medium not in VALID_MEDIUMS: return "Medium '%s' not recognized" % (medium, ) config = CONFIG[friend] if medium == "cloakcast": # TODO: Add cloakcast support print "Clandestinely messaging %s via Cloakcast" % (friend, ) elif medium == "email": return send_email(EMAIL_USERNAME, EMAIL_PASSWORD, [config[medium]], msg) elif medium == "gtalk": return send_im(EMAIL_USERNAME, EMAIL_PASSWORD, config[medium], msg) elif medium == "sms": return send_sms(config[medium], msg) return ""
def send_confirmation(self): ''' Helper that actually creates confirmation nonce and sends the email to associated email. Renders different templates depending on the result ''' log.debug('Sending confirmation') if self.confirm_sent: return {'code': Form.STATUS_CONFIRMATION_DUPLICATED} # the nonce for email confirmation will be the hash when it exists # (whenever the form was created from a simple submission) or # a concatenation of HASH(email, id) + ':' + random_like_string # (whenever the form was created from the dashboard) id = str(self.id) nonce = self.hash or '%s:%s' % (HASH( self.email, id), self.get_random_like_string()) link = url_for('confirm_email', nonce=nonce, _external=True) def render_content(type): return render_template('email/confirm.%s' % type, email=self.email, host=self.host, nonce_link=link) log.debug('Sending email') result = send_email(to=self.email, subject='Confirm email for %s' % settings.SERVICE_NAME, text=render_content('txt'), html=render_content('html'), sender=settings.DEFAULT_SENDER) log.debug('Sent') if not result[0]: return {'code': Form.STATUS_CONFIRMATION_FAILED} self.confirm_sent = True DB.session.add(self) DB.session.commit() return {'code': Form.STATUS_CONFIRMATION_SENT}
def send_email(self): # get selected lines selected_ids = self.get_selected_item_ids() # get data of each id if not selected_ids: messagebox.showinfo( title="Status Info", message="There is nothing to send.\n\nPlease refresh the page." ) return None email_details = self.prepare_email_details(selected_ids) # send email if send_email(**email_details): messagebox.showinfo( title="Status Info", message="Email has been sent!") # add trs into exceptions return self.add_to_exceptions() else: return None
def process_signup(): form_input = bottle.request.forms user_signup = build_user_signup_JSON(form_input) error = {'e': ''} ## if it was a good signup if validate_signup(users, user_signup, error): # user inputs do not need to be escaped they have been validated by validate_signup() # however, for added security, we will escape anyway user = clean_and_format_user_signup( user_signup ) # removed the second password; contains the raw password # insert signed-up user to database and obtain signup confirmation string (for email address verification) signup_conf_str = users.insert_user(user) if not signup_conf_str: # if there was error inserting signed-up user to database return bottle.redirect("/internal_error") return else: # if user signup successfully inserted into db signup_conf_link = base_url + '/confirm_signup/' + signup_conf_str subject = "Signup Confirmation" message = "Thanks for signing up! You can confirm your signup by visiting this link: %s" % signup_conf_link email_sent = send_email(emailID, subject, message) if email_sent: bottle.redirect('/please_confirm_email') return else: bottle.redirect('/internal_error') return ## if it was a bad signup else: # firstname, lastname, emailID variables do not need to be escaped in the server side as they are escaped in the template engine; # in fact, if they were escaped in the server-side, the client-side would escape the escaped strings return bottle.template("signup", dict(user_signup=user_signup, error=error['e']))
def confirm_tutors(): if request.method == "POST": decision = request.form.get("submit-btn") tutorID = request.form.get("tutorID") DB = Db() if decision == "Accept": status = 1 elif decision == "Move to Pending": status = 0 elif decision == "Reject": status = -1 elif decision == "Remove": status = -2 else: flash( Markup( f"ERROR: Invalid Status. Please report this incident <a href={ url_for('contact') }>here</a>." ), "error") return redirect(url_for("confirm_tutors")) # Remove tutor if status == -2: tutor = DB.execute("SELECT * from tutors WHERE tutorID = %s", (tutorID, ))[0] DB.execute( "INSERT INTO removedTutors (name, email, grade, image, hours, applyDate) VALUES (%s, %s, %s, %s, %s, %s)", (tutor['name'], tutor['email'], tutor['grade'], tutor['image'], tutor['hours'], tutor['applyDate'])) DB.execute("DELETE FROM answers WHERE tutorID = %s", (tutorID, )) DB.execute("DELETE FROM tutors WHERE tutorID = %s", (tutorID, )) # Change tutor status else: # If accepted, send acceptance email if status == 1: tutor = DB.execute( "SELECT name, email from tutors WHERE tutorID = %s", (tutorID, ))[0] first_name = tutor['name'].split()[0] send_email(tutor['email'], "Interact Tutors Acceptance", acceptance_email_default % (first_name), acceptance_email_html % (first_name)) DB.execute("UPDATE tutors SET status = %s WHERE tutorID = %s", (status, tutorID)) flash("Status updated!") DB.close_connection() return redirect(url_for("confirm_tutors")) DB = Db() query = ( "SELECT tutors.tutorID, name, email, grade, image, hours, applyDate, status, questionName, answerText " "FROM tutors JOIN answers ON tutors.tutorID = answers.tutorID JOIN questions on answers.questionID = questions.questionID;" ) tutors = DB.execute(query) for tutor in tutors: tutor[tutor["questionName"]] = tutor["answerText"] tutor.pop("questionName") tutor.pop("answerText") tutors = merge_list(tutors, "tutorID") tutors = sorted( tutors, key=lambda k: k['name'].lower() ) # https://stackoverflow.com/questions/72899/how-do-i-sort-a-list-of-dictionaries-by-a-value-of-the-dictionary # Define list of subjects subjects = subject_dict.keys() DB.close_connection() return render_template("confirmTutors.html", tutors=tutors, subjects=subjects)
def async_send_email(to_address, subject, content): print("async_send_email to %s" % to_address) helpers.send_email(to_address, subject, content)
def daily_summary(): """Daily Summary""" try: # Establish database Connection conn = hub_connect.get_connection() # Create cursor - needed for any database operation cur = hub_connect.get_cursor(conn) select_sql = 'SELECT * from "vwTodaysMaximums" ORDER BY "SensorID"' cur.execute(select_sql) msg_body = '' msg_tmplt = '* {0} {1} {2} at {3}\r\n' if cur.rowcount > 0: # Read results into python list maximums = cur.fetchall() HUB_LOGGER.info("Processing Daily Maxs") msg_body += ('The following highest values' ' have been recorded today:\r\n\r\n') for maximum in maximums: sensor_title = maximum.get('SensorTitle') val = float(maximum.get('Value')) units = maximum.get('TextUnits') date = datetime.datetime.strftime(maximum.get('Timestamp'), '%H:%M %d/%m/%Y') msg_body += msg_tmplt.format(sensor_title, val, units, date) msg_body += '\r\n' select_sql = "SELECT * from \"vwTodaysMinimums\" ORDER BY \"SensorID\"" cur.execute(select_sql) if cur.rowcount > 0: # Read results into python list minimums = cur.fetchall() HUB_LOGGER.info("Processing Daily Mins") msg_body += ('The following lowest values' ' have been recorded today:\r\n\r\n') for minimum in minimums: sensor_title = minimum.get('SensorTitle') val = float(minimum.get('Value')) units = minimum.get('TextUnits') date = datetime.datetime.strftime(minimum.get('Timestamp'), '%H:%M %d/%m/%Y') msg_body += msg_tmplt.format(sensor_title, val, units, date) if msg_body != '': HUB_LOGGER.info("Processing Daily Summary: %s", msg_body) # Send Email subject = ('Daily Highs and Lows from the Hub ' + datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d')) email_recip = helpers.get_user_setting('AdminRecipient') helpers.send_email(msg_body, subject, email_recip) except Exception: HUB_LOGGER.error("Unable to process daily summary statistics") HUB_LOGGER.error("%s %s %s", sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2].tb_lineno)
def settings(): # User reached route via post if request.method == "POST": # get the users from the database user = db.execute("SELECT * FROM users WHERE id = :user_id", user_id=session["user_id"])[0] changes = { "name": request.form.get("name"), "username": request.form.get("username"), "email": request.form.get("email"), } # append club IDs of selected clubs subscriptions = user["subscriptions"] if subscriptions != None and subscriptions != '': subscriptions = parse(subscriptions) else: subscriptions = [] new_subscriptions = request.form.getlist("subscriptions") if new_subscriptions: for club_name in new_subscriptions: club_id = db.execute( "SELECT club_id FROM clubs WHERE name=:name", name=club_name)[0]["club_id"] if club_id not in subscriptions: subscriptions.append(str(club_id)) # append name of selected preferences preferences = user["preferences"] if preferences == None or preferences == "": preferences = [] else: preferences = parse(preferences) new_preferences = request.form.getlist("preferences") if new_preferences: for pref in new_preferences: if pref not in preferences: preferences.append(pref) # send permissions email to clubs permissions_requests = request.form.getlist("permissions") emailList = [] if permissions_requests: for club_name in permissions_requests: email = db.execute("SELECT email FROM clubs WHERE name=:name", name=club_name)[0]["email"] emailList.append(email) send_email( emailList, "Verify Posting Permissions", "Hi! A student has requested to post events on behalf of your club. Please verify their club membership through this link: http://ide50-omidiran.cs50.io:8080/permissions" ) db.execute( "UPDATE users SET preferences = :preferences, subscriptions=:subscriptions WHERE id=:user_id", preferences=rejoin(preferences), subscriptions=rejoin(subscriptions), user_id=session["user_id"]) for change in changes: if changes[change] != '': db.execute( "UPDATE users SET :change = :value WHERE id=:user_id", change=change, value=changes[change], user_id=session["user_id"]) # Make sure user fills out all fields if they've filled out any if request.form.get("password") or request.form.get( "new-password") or request.form.get("confirmation"): if not request.form.get("password"): return render_template("error.html", message="Must provide password") elif not request.form.get("new-password"): return render_template("error.html", message="Must provide new password") elif not request.form.get("confirmation"): return render_template("error.html", message="Must confirm password") rows = db.execute("SELECT hash FROM users WHERE id = :user_id", user_id=session["user_id"]) if not check_password_hash(rows[0]["hash"], request.form.get("password")): return render_template("error.html", message="Invalid password") else: if request.form.get("new-password") == request.form.get( "confirmation"): db.execute( "UPDATE users SET hash = :hashedpass WHERE id = :user_id", hashedpass=generate_password_hash( request.form.get("new-password")), user_id=session["user_id"]) return redirect("/") else: return render_template( "error.html", message="New passwords do not match") flash("Settings successfully updated") return redirect("/settings") # User reached route via get else: # get relevant tables user = db.execute("SELECT * FROM users WHERE id = :user_id", user_id=session["user_id"])[0] clubs = db.execute("SELECT * FROM clubs") # error-checking for no preferences/subscriptions/permissions subscriptions = user["subscriptions"] if subscriptions != None and subscriptions != '': subscriptions = [int(x) for x in parse(user["subscriptions"])] else: subscriptions = [] permissions = user["permissions"] if permissions == None or permissions == '': permissions = [] else: permissions = parse(permissions) # initialize empty arrays not_subbed = [] subbed = [] preferences = [] not_preferences = [] # populate arrays based on if the user hasn't already indicated preference for club in clubs: if club["club_id"] in subscriptions: subbed.append(club["name"]) else: not_subbed.append(club["name"]) for preference in all_preferences: if user["preferences"] != None and user["preferences"] != '': if preference in parse(user["preferences"]): preferences.append(preference) else: not_preferences.append(preference) # if user has no preferences else: not_preferences.append(preference) return render_template("settings.html", user=user, clubs=clubs, subscriptions=subbed, not_subscribed=not_subbed, preferences=preferences, not_preferences=not_preferences, permissions=permissions)
def send(self, http_form, referrer): ''' Sends form to user's email. Assumes sender's email has been verified. ''' data, keys = http_form_to_dict(http_form) subject = data.get( '_subject', 'New submission from %s' % referrer_to_path(referrer)) reply_to = data.get('_replyto', data.get('email', data.get('Email', None))) cc = data.get('_cc', None) next = next_url(referrer, data.get('_next')) spam = data.get('_gotcha', None) # prevent submitting empty form if not any(data.values()): return {'code': Form.STATUS_EMAIL_EMPTY} # return a fake success for spam if spam: return {'code': Form.STATUS_EMAIL_SENT, 'next': next} # increase the monthly counter request_date = datetime.datetime.now() self.increase_monthly_counter(basedate=request_date) # increment the forms counter self.counter = Form.counter + 1 DB.session.add(self) # archive the form contents sub = Submission(self.id) sub.data = data DB.session.add(sub) # commit changes DB.session.commit() # delete all archived submissions over the limit records_to_keep = settings.ARCHIVED_SUBMISSIONS_LIMIT newest = self.submissions.with_entities( Submission.id).limit(records_to_keep) DB.engine.execute( delete('submissions'). \ where(Submission.form_id == self.id). \ where(~Submission.id.in_(newest)) ) # check if the forms are over the counter and the user is not upgraded overlimit = False if self.get_monthly_counter( basedate=request_date) > settings.MONTHLY_SUBMISSIONS_LIMIT: if not self.owner or not self.owner.upgraded: overlimit = True now = datetime.datetime.utcnow().strftime('%I:%M %p UTC - %d %B %Y') if not overlimit: text = render_template('email/form.txt', data=data, host=self.host, keys=keys, now=now) html = render_template('email/form.html', data=data, host=self.host, keys=keys, now=now) else: text = render_template('email/overlimit-notification.txt', host=self.host) html = render_template('email/overlimit-notification.html', host=self.host) result = send_email(to=self.email, subject=subject, text=text, html=html, sender=settings.DEFAULT_SENDER, reply_to=reply_to, cc=cc) if not result[0]: return {'code': Form.STATUS_EMAIL_FAILED} return {'code': Form.STATUS_EMAIL_SENT, 'next': next}
def main(): # Since the script is standalone, we need to first invoke the # Jinja template environment env = Environment(loader=PackageLoader('filmsoc', 'templates')) # Acquire essential templates tp_reminder = env.get_template("reminder.html") tp_renewed = env.get_template("renewed_reminder.html") tp_overdue = env.get_template("overdue.html") # Send reminders of disks due the next day neardue = Disk.select().where( Disk.avail_type == 'Borrowed', Disk.due_at == date.today() + timedelta(1) ) for disk in neardue: last_log = Log.select().where( Log.model == 'Disk', Log.model_refer == disk.id, Log.log_type == 'borrow', Log.user_affected == disk.hold_by ).order_by(Log.created_at.desc()).get() if 'renew' not in last_log.content: body = tp_reminder.render(disk=disk) send_email( [disk.hold_by.itsc + '@ust.hk'], ['*****@*****.**'], 'Reminder: Due Date of the VCD/DVD(s) You Borrowed', body) else: body = tp_renewed.render(disk=disk) send_email( [disk.hold_by.itsc + '@ust.hk'], ['*****@*****.**'], 'Reminder: Due Date of the VCD/DVD(s) You Renewed', body) # Send reminders of disks overdue # Sent every 3 days overdue = Disk.select().where( Disk.avail_type == 'Borrowed', Disk.due_at < date.today() ) for disk in overdue: passed = date.today() - disk.due_at if passed.days % 3 == 1: body = tp_overdue.render(disk=disk) send_email( [disk.hold_by.itsc + '@ust.hk'], ['*****@*****.**'], 'Reminder: Overdue of the VCD/DVD(s)', body) # Clear reservation of disks over 3 days # Only clear Counter Reservation reserved = Disk.select().where(Disk.avail_type == 'ReservedCounter') for disk in reserved: reserve_log = Log.select().where( Log.model == 'Disk', Log.model_refer == disk.id, Log.log_type == 'reserve', Log.user_affected == disk.reserved_by ).order_by(Log.created_at.desc()).get() if date.today() - reserve_log.created_at.date() > timedelta(2): disk.reserved_by = None disk.avail_type = 'Available' disk.save() Log.create( model="Disk", model_refer=disk.id, log_type="reserve", content="clear reservation for disk %s(automatically)" % disk.get_callnumber())
images.append(['images/swag_5_class.png', '<@swag_5_class>']) if winner['new_badge_levels'][5]: images.append(['images/swag_6_phylum.png', '<@swag_6_phylum>']) # if winner['new_badge_levels'][6]: # images.append(['images/swag_7_kingdom.png', '<@swag_7_kingdom>']) text_rendered = plain_template.render(winner) html_rendered = html_template.render(winner) to_addr = helpers.get_email_from_username(all_users, winner["username"]) to_addr_check = helpers.get_email_from_userid(all_users, winner["user_id"]) if to_addr != to_addr_check or to_addr == None: print "error with address " + to_addr + ".... continuing" continue #send the emails if test_mode: to_addr = '*****@*****.**' subject += ' Test' for index in range(0,len(winner['new_badge_levels'])): if winner['new_badge_levels'][index] != 0: print winner['date'].strftime("%x") + ', ' + winner["username"] + ', ' + to_addr + ',' + helpers.ANIMAL_CATEGORIES[index] helpers.send_email(to_addr, smtp_options['from_addr'], subject, text_rendered, html_rendered, smtp_options, images) elif to_addr != None: print "AsdFASDFASFASFSD" import pdb;pdb.set_trace() to_addr += ".rpost.org" for index in range(0,len(winner['new_badge_levels'])): if winner['new_badge_levels'][index] != 0: print winner['date'].strftime("%x") + ', ' + winner["username"] + ', ' + to_addr + ',' + helpers.ANIMAL_CATEGORIES[index] # helpers.send_email(to_addr, smtp_options['from_addr'], subject, text_rendered, html_rendered, smtp_options, images)
def createevent(): # Create the list of possible tags for events tagNames = all_preferences # user reached route via post if request.method == "POST": # Store user inputs and return relevant error is user didn't input a required variable # Store the event name title = request.form.get("eventname") # Return error if title was not provided if not title: return render_template("error.html", message="You must provide an event name") # Store the club club = request.form.get("club") # Return error if club was not provided if not club: return render_template("error.html", message="You must provide a club") # Store the clubid for the club input to put in database club_id = db.execute("SELECT club_id FROM clubs WHERE name=:club", club=club) # Store the description description = request.form.get("description") # Store whether or not a user wants to upload a photo pictureuploadcheck = request.form.get("pictureuploadcheck") # Return error if the picture upload preference was not provided if not pictureuploadcheck: return render_template( "error.html", message= "You must say whether or not you want to upload a picture") # If the user wants to upload a photo if pictureuploadcheck == "yes": # Try to store the picture from the form try: picture = request.files["picture"] # Either the user did not provide a photo or provided an invalid image except: return render_template( "error.html", message= "You did not provide an image and you stated you wanted to upload one, or you provided an invalid image" ) # Create the file # Get the title of the event for the filename nospaces = title.replace(" ", "") # Store the filename filename = nospaces + ".jpg" # Save the picture to the images folder picture.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) # Store the link to the picture picturelink = os.path.join(app.config['UPLOAD_FOLDER'], filename) # If the user does not want to upload a photo, store no path to a photo else: picturelink = "" # Store the location location = request.form.get("location") # Return error if no location is provided if not location: return render_template("error.html", message="You must provide a location") # Store the start month startmonth = request.form.get("startmonth") # Return error if no start month was provided if not startmonth: return render_template( "error.html", message="You must provide a starting date (month)") # Store the start day startday = request.form.get("startday") # Return error if no start day was provided if not startday: return render_template( "error.html", message="You must provide a starting date (day)") # Store the start year startyear = request.form.get("startyear") # Return error if no start year was provided if not startyear: return render_template( "error.html", message="You must provide a starting date (year)") # Store the end month endmonth = request.form.get("endmonth") # Return error if no end month was provided if not endmonth: return render_template( "error.html", message="You must provide an ending date (month)") # Store the end day endday = request.form.get("endday") # Return error if no end day was provided if not endday: return render_template( "error.html", message="You must provide an ending date (day)") # Store the end year endyear = request.form.get("endyear") # Return error if no end year was provided if not endyear: return render_template( "error.html", message="You must provide an ending date (year)") # Store the start hour starthour = request.form.get("starthour") # Return error if no start hour was provided if not starthour: return render_template( "error.html", message="You must provide a starting time (hour)") # Store the start minutes startminutes = request.form.get("startminutes") # Return error if no start minutes were provided if not startminutes: return render_template( "error.html", message="You must provide a starting time (minutes)") # Store the start am pm startampm = request.form.get("startampm") # Return error if no start am pm was provided if not startampm: return render_template( "error.html", message="You must provide a starting time (am/pm)") # Store the end hour endhour = request.form.get("endhour") # Return error if no end hour was provided if not endhour: return render_template( "error.html", message="You must provide an ending time (hour)") # Store the end minutes endminutes = request.form.get("endminutes") # Return error if no end minutes were provided if not endminutes: return render_template( "error.html", message="You must provide an ending time (minutes)") # Store the end am pm endampm = request.form.get("endampm") # Return error if no end am pm was provided if not endampm: return render_template( "error.html", message="You must provide an ending time (am/pm)") # verify that the user has permission to post for the club they are trying to post for permissions = db.execute( "SELECT permissions FROM users WHERE id = :user_id", user_id=session["user_id"]) for i in range(len(parse(permissions[0]["permissions"]))): # if the user has permission for the club allow them to post if parse(permissions[0]["permissions"])[i] == club: break # if the user does not have permission return an error if i == len(parse(permissions[0]["permissions"])) - 1: return render_template( "error.html", message= "Sorry, but you do not have permission to post events for this club. Request permissions on settings in order to be authorized to post events." ) # convert to military time to put into calendar if startampm == "pm" and int(starthour) != 12: # get the end hour in the proper format for the Google Calendar event starthourmilitary = int(starthour) + 12 starthourmilitary = str(starthourmilitary) else: starthourmilitary = starthour if endampm == "pm" and int(endhour) != 12: # get the end hour in the proper format for the Google Calendar event endhourmilitary = int(endhour) + 12 endhourmilitary = str(endhourmilitary) else: endhourmilitary = endhour # format the start date and time and end date and time for the Google Calendar event startdateandtime = startyear + "-" + startmonth + "-" + startday + "T" + starthourmilitary + ":" + startminutes + ":00-05:00" enddateandtime = endyear + "-" + endmonth + "-" + endday + "T" + endhourmilitary + ":" + endminutes + ":00-05:00" # initialize an empty list ot store tags in tags = [] # Go through all of the tags and check if the user selected that tag for the event for tag in tagNames: value = request.form.get(tag) # If the user did select the tag, add it to the list if value != None: tags.append(tag) # format the start date startdate = startmonth + "/" + startday + "/" + startyear # format the end date enddate = endmonth + "/" + endday + "/" + endyear # format the start date for comparison formattedstartdate = time.strptime(startdate, "%m/%d/%Y") # format the end date for comparison formattedenddate = time.strptime(enddate, "%m/%d/%Y") # if the start and end date are the same, store the event with one date if formattedstartdate == formattedenddate: eventdate = startdate else: # if the end date is before the start date, return an error if formattedenddate < formattedstartdate: return render_template( "error.html", message= "You must provide an end date that is the same day as or after the start date" ) # store the event date in the proper format eventdate = startdate + "-" + enddate # format the start time starttime = starthour + ":" + startminutes + startampm # format the end time endtime = endhour + ":" + endminutes + endampm # format the start time for comparison formattedstarttime = time.strptime(starttime, "%I:%M%p") # format the end time for comparison formattedendtime = time.strptime(endtime, "%I:%M%p") # if the start and end time are the same, store the event with one time if starttime == endtime: eventtime = starttime else: # if the event is on the same day, test the time if formattedstartdate == formattedenddate: # if the end time is before the start time, return an error if formattedendtime < formattedstarttime: return render_template( "error.html", message= "You must provide an end time that is equal to or after your start time" ) # store the event time in the proper format eventtime = starttime + "-" + endtime # add the event to the database db.execute( "INSERT INTO events (club_id, title, description, picture, tags, date, time, location) VALUES(:club_id, :title, :description, :picture, :tags, :date, :time, :location)", club_id=club_id[0]["club_id"], title=title, description=description, picture=picturelink, tags=rejoin(tags), date=eventdate, time=eventtime, location=location) # The file service.json stores the user's access and refresh tokens, and is # created automatically when the authorization flow completes for the first # time. SCOPES = ['https://www.googleapis.com/auth/calendar'] SERVICE_ACCOUNT_FILE = '/home/ubuntu/workspace/final-project/service.json' credentials = service_account.Credentials.from_service_account_file( SERVICE_ACCOUNT_FILE, scopes=SCOPES) service = googleapiclient.discovery.build('calendar', 'v3', credentials=credentials) # create event based on user input event = { 'summary': title, 'location': location, 'description': description, 'start': { 'dateTime': startdateandtime, 'timeZone': 'America/New_York', }, 'end': { 'dateTime': enddateandtime, 'timeZone': 'America/New_York', }, 'reminders': { 'useDefault': False, 'overrides': [ { 'method': 'email', 'minutes': 24 * 60 }, { 'method': 'popup', 'minutes': 10 }, ], }, } # add the event to the calendar event = service.events().insert(calendarId='*****@*****.**', body=event).execute() # get the email and subscriptions from users rows = db.execute( "SELECT email, subscriptions FROM users WHERE subscriptions IS NOT NULL" ) # create an empty list of recipients emailList = [] # loop through each each user for row in rows: # if the user has subscriptions if row["subscriptions"] != None and row["subscriptions"] != "": # get a list of subscriptions clubsList = parse(row["subscriptions"]) # if the club is in the list of clubs the user is subscribed to, add their email to the group to email if str(club_id[0]["club_id"]) in clubsList: emailList.append(row["email"]) # send the email send_email( emailList, "New event posted by one of your clubs", "One of the clubs you subscribe to just posted a new event. Check it out at http://ide50-omidiran.cs50.io:8080!" ) # redirect to index return redirect("/") # user reached route via get else: # get the permission for the user userpermissions = db.execute( "SELECT permissions FROM users WHERE id=:id", id=session["user_id"]) # if the user has no permissions, they can not access the page if userpermissions[0]["permissions"] == None or userpermissions[0][ "permissions"] == "": return render_template( "error.html", message= "You do not have permissions to post for any clubs. Please wait for your club to approve of your club membership" ) # store the club names clubs = db.execute("SELECT name FROM clubs") # store the months months = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ] # return the template for creating an event with relevant information return render_template("createevent.html", clubs=clubs, tags=tagNames, months=months)
def register(): """Register user""" # from our own implementation in problem set 8 - finance but with new features # user reached route via post if request.method == "POST": # Store inputs in variables for easier access username = request.form.get("username") password = request.form.get("password") confirmation = request.form.get("confirmation") email = request.form.get("email") name = request.form.get("name") preferences = request.form.getlist("preferences") permissions = request.form.getlist("permissions") # Return relevant error is user didn't input one variable if not username: return render_template("error.html", message="Missing username") if not password: return render_template("error.html", message="Missing password") if not confirmation: return render_template("error.html", message="Missing password confirmation") if password != confirmation: return render_template("error.html", message="Passwords do not match") # Sends permission email to club if permissions != None: emailList = [] for club in permissions: email = db.execute("SELECT email FROM clubs WHERE name=:name", name=club)[0]["email"] emailList.append(email) send_email( emailList, "Verify Posting Permissions", "Hi! A student has requested to post events on behalf of your club. Please verify their club membership through this link: http://ide50-carissawu.cs50.io:8080/permissions" ) # If insertion returns null, then username must be taken result = db.execute( "INSERT INTO users (username, hash, name, email, preferences, permissions) VALUES(:username, :hashed, :name, :email, :preferences, :permissions)", username=username, hashed=generate_password_hash(password), name=name, email=email, preferences=rejoin(preferences), permissions=None) # Return the relevant error if not result: return render_template("error.html", message="Username is taken") # get the user from the database rows = db.execute("SELECT * FROM users WHERE username = :username", username=username) # store the user id session["user_id"] = rows[0]["id"] # redirect to index return redirect("/") # user reached route via get else: # show the register form return render_template("register.html", clubs=db.execute("SELECT name FROM clubs"), preferences=all_preferences)
def register(): """Register user""" if request.method == "GET": session.clear() return render_template("auth/register.html") else: username = request.form.get("username") password = request.form.get("password") confirmation = request.form.get("confirmation") email = request.form.get("email") university = request.form.get("university") if not username or not password or not confirmation or password != confirmation: return apology("please fill the form correctly to register.") # Checking for username c = db.execute("SELECT username FROM users WHERE username ILIKE :username", { "username": username }).fetchall() if c: return apology("username already taken") # Specifications for password # password length if len(password) < 6: return apology(message="password must be longer than 6 characters") # password must contain numbers if password.isalpha(): return apology(message="password must contain numbers") # password must contain letters if password.isdigit(): return apology(message="password must contain letters") for c in username: if not c.isalpha() and not c.isdigit() and c != "_": return apology(message="Please enter a valid username.") if len(username) < 3: return apology("please enter a username with 3 or more characters") if len(username) > 50: return apology("username limit is 50 characters") hash_pw = generate_password_hash(password) try: if email: if len(email) > 70: return apology("email limit is 50 characters") q = db.execute("SELECT email FROM users WHERE email = :email", { "email": email }).fetchone() if q: return apology("this email already exists") if not email: email = None if university: if len(university) > 70: return apology("university limit is 70 characters") university = university.title() else: university = None db.execute( "INSERT INTO users(username, hash, email, date, university) VALUES(:username, :hash_pw, :email, CURRENT_DATE, :university)", { "username": username, "hash_pw": hash_pw, "email": email, "university": university }) db.commit() except: return apology("something went wrong with the database.") if email: try: send_email( email, username, "Registeration for Student Helper", "Congratulations!\n You're now registered on Student Helper!") except Exception as x: print(x) rows = db.execute( "SELECT id, username, email, university FROM users WHERE username = :username", { "username": username }).fetchone() session["user_id"] = rows["id"] session["username"] = rows["username"] session["email"] = rows["email"] session["uni"] = rows["university"] flash("You're now registered!") return redirect("/")
for winner in winner_list: #pick a random template for the thank you template_index = random.randint(0, len(plain_mail_templates)-1) plain_template = plain_mail_templates[template_index] html_template = html_mail_templates[template_index] text_rendered = plain_template.render(username = winner["username"]) html_rendered = html_template.render(username = winner["username"]) subject = "Thank you from the SciCast team" to_addr = helpers.get_email_from_username(all_users, winner["username"]) to_addr_check = helpers.get_email_from_userid(all_users, winner["user_id"]) if to_addr != to_addr_check: print "error with address " + to_addr + ".... continuing" continue from_addr = config["from"] if test_mode: to_addr = test_send_to_addrs[0] #just grab the first print "Sending email for " + winner["username"] + ' at address ' + to_addr + '.' if not test_mode and to_addr != None and False: helpers.send_email(to_addr, from_addr, subject, text_rendered, html_rendered, smtp_options, images) if test_mode and False: #now we want to send the tested emails through subject = "Test of Thank You Script" for addr in test_send_to_addrs: helpers.send_email(addr, config["from"], subject, text_rendered, html_rendered, smtp_options, images)
def driver_feedback( request, offer_id ): offer = get_mongo_or_404( RideOffer, pk=ObjectId(offer_id) ) # Submitting feedback if request.method == 'POST': profile = request.session.get("profile") def fail( msg ): ''' What to do when we get an error ''' messages.add_message( request, messages.ERROR, msg ) return HttpResponseRedirect( reverse('user_landing') ) # Must be the driver of this RideOffer if profile != offer.driver: return fail( "Cannot leave feedback on that trip." ) # Make sure no feedback has already been left for this trip if offer.completed: return fail( "You have already left feedback for that trip." ) form = DriverFeedbackForm( offer, request.POST ) if form.is_valid(): data = form.cleaned_data passengers = { p:data[p] for p in data if p.startswith("passenger_") } group_message = data['group_fb'] # Make sure these passengers were those on the trip form_ids = sorted([p.split('_')[1] for p in passengers.keys()]) actual_ids = sorted([str(p.id) for p in offer.passengers]) if form_ids != actual_ids: return fail( "Cannot leave feedback on that trip because the feedback left for one or more passengers was invalid." ) # Increment trust rating for all passengers, and send emails for name, val in passengers.iteritems(): passenger = UserProfile.objects.get( pk=ObjectId(name.split("_")[1]) ) trust = Trust(message=val, truster=profile, offer=offer) if len(passenger.trust) == 0: passenger.trust = [trust] else: passenger.trust.append(trust) passenger.save() if len(group_message) > 0 or len(val) > 0: if len(group_message) > 0 and len(val)>0: email_body = "%s\r\n\r\nAdditionally, your driver says:\r\n\r\n%s"%( group_message, val ) elif len(group_message) > 0: email_body = group_message elif len(val) > 0: email_body = val send_email( email_to=passenger.user.username, email_subject="Correspondence on your trip %s"%str(offer), email_body=email_body ) # Mark this trip as having been reviewed already offer.completed = True offer.save() messages.add_message( request, messages.SUCCESS, "Your correspondence has been recorded." ) return HttpResponseRedirect( reverse('user_landing') ) form = DriverFeedbackForm( offer, initial={'offer_id':str(offer.id)} ) return render_to_response("driver_feedback.html", locals(), context_instance=RequestContext(request) )
def cancel_ride(request, ride_id): ''' Render and process a RideRequest/RideOffer cancellation ''' try: ride_offer = RideOffer.objects.get(pk=ObjectId(ride_id)) driver = ride_offer.driver except (RideOffer.DoesNotExist): driver = None try: ride_request = RideRequest.objects.get(pk=ObjectId(ride_id)) rider = ride_request.passenger except (RideRequest.DoesNotExist): rider = None # confirm correct user profile = request.session.get('profile') if not profile in (driver,rider): raise PermissionDenied # Form has been submitted, else... if request.method == 'POST': form = CancellationForm(request.POST) # Check for valid form if form.is_valid(): data = form.cleaned_data try: req = RideRequest.objects.get(pk=ObjectId(ride_id)) except RideRequest.DoesNotExist: req = None try: offer = RideOffer.objects.get(pk=ObjectId(ride_id)) except RideOffer.DoesNotExist: offer = None if req is not None: reason_msg = data['reason'] email_message = render_message( "taxi/static/emails/passenger_cancelled.txt", locals() ) if req.offer: send_email( email_subject='Rider Cancellation', email_to=req.offer.driver.user.username, email_body=email_message ) #user_id = req. req.delete() elif offer is not None: reason_msg = data['reason'] for passenger in offer.passengers: email_message = render_message( "taxi/static/emails/driver_cancelled.txt", locals() ) send_email( email_subject='Ride Cancellation', email_to=passenger.user.username, email_body=email_message ) for each_ride in RideRequest.objects.filter(ride_offer=offer): each_ride.ride_offer = None each_ride.save() offer.delete() return HttpResponseRedirect( reverse('user_landing') ) return render_to_response('cancel_ride.html', locals(), context_instance=RequestContext(request)) if driver: if not ride_offer.passengers: ride_offer.delete() return HttpResponseRedirect( reverse('user_landing') ) elif rider: if not ride_request.ride_offer: ride_request.delete() return HttpResponseRedirect( reverse('user_landing') ) form = CancellationForm(initial={'ride_id':ride_id}) return render_to_response('cancel_ride.html', locals(), context_instance=RequestContext(request))
from database import Db from helpers import send_email from email_templates import mass_email_default, mass_email_html DB = Db() tutors = DB.execute("SELECT email FROM tutors WHERE status = 1") emails = [tutor["email"] for tutor in tutors] emails.append("*****@*****.**") for email in emails: send_email(email, "Interact Tutors Update", mass_email_default, mass_email_html) DB.close_connection()
def charge(): """Charges user account""" # User reached route via POST (as by submitting a form via POST) if request.method == "POST": # Ensure amount is int/float try: amount = float(request.form.get("amount")) except ValueError: return render_template("charge.html", wrong_amount=True, users=available_users) # Database queries for chargor and chargee rows_chargor = db.execute("SELECT * FROM users WHERE id = :id", id=session["user_id"]) rows_chargee = db.execute( "SELECT * FROM users WHERE username = :username", username=request.form.get("user")) # Get transaction currency ccy = request.form.get("ccy") # Get charge amount and home currency for chargor and chargee chargor_amount, chargor_rate = user_ccy(amount, ccy, rows_chargor[0]["ccy"]) chargee_amount, chargee_rate = user_ccy(amount, ccy, rows_chargee[0]["ccy"]) # Insert transaction into history (chargor side) db.execute( "INSERT INTO history (to_user, by_user, amount, ccy, user_amount, rate, notes) \ VALUES (:to_user, :by_user, :amount, :ccy, :user_amount, :rate, :notes)", to_user=rows_chargor[0]["username"], by_user=rows_chargee[0]["username"], amount=-round(amount, 2), ccy=ccy, user_amount=-round(chargor_amount, 2), rate=chargor_rate, notes=request.form.get("notes")) # Update chargor's balance db.execute( "UPDATE users SET balance = balance - :charge WHERE id = :id", charge=round(chargor_amount, 2), id=session["user_id"]) # If balance is over 50, send email if round(rows_chargor[0]["balance"] - chargor_amount, 2) < -50: # Generate notification message message = "Your current balance is: " + ccy_format(round(rows_chargor[0]["balance"] - chargor_amount, 2)) \ + " " + rows_chargor[0]["ccy"] + ". Note that your debt is over 50.00 " + rows_chargor[0]["ccy"] \ + ". Consider settling!" # Send notification email ##### Commented lines to be used once app goes live ##### # send_email(str.lower(rows_chargor[0]["username") + "@chathamfinancial.com", # "Settle your debt!", # message) ######################################################### send_email(placeholder_email, "Settle your debt!", message) # Insert transaction into history (chargee side) db.execute( "INSERT INTO history (to_user, by_user, amount, ccy, user_amount, rate, notes) \ VALUES (:to_user, :by_user, :amount, :ccy, :user_amount, :rate, :notes)", to_user=rows_chargee[0]["username"], by_user=rows_chargor[0]["username"], amount=round(amount, 2), ccy=ccy, user_amount=round(chargee_amount, 2), rate=chargee_rate, notes=request.form.get("notes")) db.execute( "UPDATE users SET balance = balance + :charge WHERE username = :username", charge=round(chargee_amount, 2), username=request.form.get("user")) # Generate notification message message = "User " + rows_chargor[0][ "username"] + " charged your account with " + ccy_format( round(amount, 2)) + " " + ccy # Add notes, if any if request.form.get("notes"): message += " (notes: " + request.form.get("notes") + ")" # Add balance info message += ". Your current balance is: " + ccy_format(round(rows_chargee[0]["balance"] + chargee_amount, 2)) \ + " " + rows_chargee[0]["ccy"] + "." # Add note if debt is over 50 if round(rows_chargee[0]["balance"] + chargee_amount, 2) < -50: message += " Note that your debt is over 50.00 " + rows_chargee[0][ "ccy"] + ". Consider settling!" # Send notification email ##### Commented lines to be used once app goes live ##### # send_email(str.lower(rows_chargee[0]["username") + "@chathamfinancial.com", # "New Charget charge", # message) ######################################################### send_email(placeholder_email, "New Charget charge", message) # Prepare dropdown list for users rows = db.execute("SELECT * FROM users") # List of available users available_users = [] for i in rows: if session["user_id"] != i["id"]: available_users.append(i["username"]) available_users.sort() return render_template("charge.html", charge_added=True, users=available_users) # User reached route via GET (as by clicking a link or via redirect) else: # get users list rows = db.execute("SELECT * FROM users") # List of available users available_users = [] for i in rows: if session["user_id"] != i["id"]: available_users.append(i["username"]) available_users.sort() return render_template("charge.html", users=available_users)
def form_valid(self, form): email_context = RequestContext(self.request, {'referer': self.request.user}) recipient = form.cleaned_data['referee'] subject = 'Un ami, %s, vous propose de devenir membre de Bbsitting sharing'%self.request.user.get_full_name() send_email([recipient], subject, 'refer_request', email_context) return super(ReferView, self).form_valid(form)
def worker(scan_tasker_queue, slack_client, log): """ Worker function to take items off the queue and process them. This worker gets scan tasks, starts the scan, monitors scan progress, and returns scan results. """ while True: try: # Get item off the queue, exit if nothing queued. item = scan_tasker_queue.get() log.debug('Worker started and got item from queue.') log.debug("Got {} targets from command.".format(len(item['target_list']))) if item is None: continue # Common vars target_set = set() site_set = set() no_scan_set = set() if not item['site_scan']: # Determine site for IDs. # List placeholder, parrallel function returns a list of outputs site_asset_set = [] log.info("Getting asset/site membership.") for ip in item['target_list']: site_names_and_ids = helpers.retrieve_site_names_and_site_ids_containing_an_ip(ip) for site in site_names_and_ids: site_asset_set.append((site['site_id'], site['target'])) log.debug('List returned from site membership: {}'.format(site_asset_set)) # Parse site and address to determine any assets that do not live # in InsightVM. # Get actual targets and site for site_asset_pair in site_asset_set: target_set.add(site_asset_pair[1]) site_set.add(site_asset_pair[0]) no_scan_set = set(item['target_list']) - target_set log.info('Site set: {}'.format(site_set)) log.info('Target set: {}'.format(target_set)) log.info('No-scan set: {}'.format(no_scan_set)) elif item['site_scan']: site_set.add(item['target_list'][0]) log.info('Site set: {}'.format(site_set)) # Check if assets reside in more than one site, prompt for additional # info if needed. All assets should/must reside in one common site. # Counting on InsightVM to handle different site errors. scan_id = None skip = False if len(site_set) > 1 and 'site id:' in item['command'].lower(): try: scan_id = helpers.adhoc_site_scan(target_set, int(item['command'].split(':')[1])) message = "<@{}> Scan ID: {} started".format(item['user'], scan_id) except SystemError as e: message = "<@{}> Scan produced an error".format(item['user']) message += str(e) skip = True # Assets in multiple sites but NO site ID provided. elif len(site_set) > 1: message = '<@{}> Assets exist in multiple sites ({}). ' message += 'Please re-run command with ' message += '`@nexpose_bot scan <IPs> site id:<ID>``' message = message.format(item['user'], site_set) skip = True # All assets do not exist in Nexpose elif len(site_set) == 0: message = '<@{}> scan for {} *failed*.' message += ' Device(s) do not exist in insightvm :confounded:' message += ' Device must have been scanned previously through a normal scan. ' message = message.format(item['user'], item['target_list']) skip = True # All assets live in one site else: try: if 'false_positive' in item: scan_id = helpers.adhoc_site_scan( target_set, site_set.pop(), SECRETS['insightvm']['fp_template_id'] ) else: scan_id = helpers.adhoc_site_scan(target_set, site_set.pop()) message = "<@{}> Scan ID: {} started. ".format(item['user'], scan_id) except SystemError as e: message = "<@{}> Scan produced an error ".format(item['user']) message += str(e) skip = True # Indicate if some assets were not scanned due to no existing in Nexpose. if no_scan_set: message += ' These hosts do not exist in InsightVM, unable to scan: `{}` '.format(', '.join(no_scan_set)) # Respond to Slack with result log.info(message) slack_client.api_call( "chat.postMessage", channel=item['channel'], text=message, as_user=True ) # Skip the rest if there will be no scan this run. if skip: continue # Monitor scan for completion, simply break if scan has failed or other # error. Only do this if a scan_id was returned indicating a scan started. while True and scan_id is not None: time.sleep(60) scan = helpers.retrieve_scan_status(scan_id) log.debug("Current statuts for Scan {}: {}".format(scan_id, scan['status'])) if scan['status'] in ['running', 'integrating', 'dispatched']: continue else: break # Gather scan details if scan_id is not None and scan['status'] == 'finished': try: duration = time.strptime(scan['duration'], 'PT%MM%S.%fS').tm_min except ValueError: duration = time.strptime(scan['duration'], 'PT%S.%fS').tm_min message = "<@{}> Scan ID: {} finished for `{}` at {} UTC\n" message += "*Scan Duration*: {} minutes\n {}\n" message += "Scan details available here: https://{}/scan.jsp?scanid={}" message = message.format(item['user'], scan_id, ', '.join(item['target_list']), time.asctime(), duration, scan['vulnerabilities'], SECRETS['insightvm']['host'], scan_id) if scan['vulnerabilities']['total'] == 0: message += helpers.get_gif() if 'false_positive' in item: xml_report = helpers.generate_xml2_report(scan_id) scan_log_data = helpers.get_scan_logs(scan_id) email_body = 'Please see attached logs related to a false positive for {} '.format(item['vuln_id']) email_body += "Attachments are XML2 Report and Scan Data Export " email_body += "including scan logs." attachments = {"XML-Report.xml": xml_report, "Scan-Logs.zip": scan_log_data} helpers.send_email(SECRETS['insightvm']['fp_email'], # This is expecting a comma separated string, not a list. subject='False Positive Report For {}'.format(item['vuln_id']), body=email_body, attachments=attachments, port=587) elif scan_id is not None: message = "<@{}> Scan ID: {} *failed* for" message += " {} at {} :sob:" message += "Please contact the Security team." message = message.format(item['user'], scan_id, item['target_list'], time.asctime()) # Respond in Slack with scan finished message. log.info(message) slack_client.api_call( "chat.postMessage", channel=item['channel'], text=message, as_user=True ) log.debug('Worker done.') scan_tasker_queue.task_done() except Exception as e: log.error(e) pass
def output_error(subj, msg): helpers.send_email(subj, msg) return
def post(self): to = self.request.get('to') subject = self.request.get('subject') body = self.request.get('body') html = self.request.get('html') helpers.send_email(to, subject, body, html)
def form_valid(self, form): email_context = RequestContext(self.request, {"referer": self.request.user}) recipient = form.cleaned_data["referee"] send_email([recipient], "hello", "refer_request", email_context) return super(ReferView, self).form_valid(form)
from helpers import configs, get_torrents, send_email all_torrents = {} for cat in configs["torrents"]["categories"]: all_torrents[cat] = [] for page in range(1, (int(configs["torrents"]["pages"]) + 1)): torrents = get_torrents(cat, page) if len(torrents) > 0: all_torrents[cat].extend(torrents) if len(all_torrents[cat]) < 1: del all_torrents[cat] if all_torrents: send_email({"torrents": all_torrents}) print("Email sent") else: print("No new torrents found!")
def index(): if request.method == "GET": au = makeActiveUsers() currentUser = session.get('b', None) userIsAdmin = session.get('userIsAdmin', None) return render_template("index.html", au=au, userIsAdmin=userIsAdmin, currentUser=currentUser) else: au = makeActiveUsers() # list of alerts to trigger events in frontend breakTaken = False displayCheck = False shortCheck = False workTimeAlert = False noRowAlert = False userIsAdmin = session.get('userIsAdmin', None) currentUser = session.get('b', None) # collect user input display = request.form.get("display") show = request.form.get("show") user = request.form.get("user") short = request.form.get("short") clear = request.form.get("clear") if userIsAdmin: if display == "displayClicked": displayCheck = True if short == "shortClicked": shortCheck = True if clear == "clearClicked": c.execute("DELETE FROM entrances") #extract needed data to display table c.execute( "SELECT time(start), time(stop), duration, username, status FROM entrances" ) time_val = c.fetchall() started = [z[0] for z in time_val] stopped = [z[1] for z in time_val] duration = [z[2] for z in time_val] username = [z[3] for z in time_val] status = [z[4] for z in time_val] # filter by username if show == "detailsClicked": displayCheck = True c.execute("SELECT username FROM entrances WHERE username=?", (user, )) time_val2 = c.fetchall() username = [z[0] for z in time_val2] conn.commit() # zip all data extracted from db timing = zip(started, stopped, duration, username, status) return render_template("index.html", shortCheck=shortCheck, currentUser=currentUser, au=au, timing=timing, userIsAdmin=userIsAdmin, displayCheck=displayCheck) else: # time limit prototype (default is 8 hours) limit = timedelta(seconds=5) durationDelta = limit # collect user input start = request.form.get("start") stop = request.form.get("stop") break15 = request.form.get("break15") # default break value to be inserted to database x = 0 # collect data from user input if start == "startClicked": c.execute( "INSERT INTO entrances (start, userId, username, status, break) VALUES (julianday('now'), ?, ?, ?, ?)", (currentUser, currentUser, 1, x)) # extract current row and current stop value c.execute( "SELECT rowid, stop FROM entrances WHERE userId=? ORDER BY rowid DESC LIMIT 1", (currentUser, )) last_row = c.fetchone() if last_row == None: noRowAlert = True return render_template("error.html", noRowAlert=noRowAlert) current_no = last_row[0] current_stop = last_row[1] # update db if break taken # default break time: 30 min, for testing purposes: 5 seconds if break15 == "break15Clicked": x = 5 c.execute("UPDATE entrances SET break=? WHERE rowid=?", (x, current_no)) breakTaken = True # use current_stop value to prevent double scan # support multiple users using system at once if (stop == "stopClicked" and current_stop == None): c.execute( "UPDATE entrances SET stop=julianday('now') WHERE rowid=?", (current_no, )) # collect data for table display c.execute( "SELECT datetime(start), datetime(stop), username, break FROM entrances WHERE username=?", (currentUser, )) time_val = c.fetchall() started = [z[0] for z in time_val] stopped = [z[1] for z in time_val] username = [z[2] for z in time_val] breaks = [z[3] for z in time_val] userRecordQty = len(stopped) if stop == "stopClicked" and current_stop == None: # count work time duration # support overnight shifts FMT = '%Y-%m-%d %H:%M:%S' durationDelta = ( datetime.strptime(stopped[userRecordQty - 1], FMT) - datetime.strptime(started[userRecordQty - 1], FMT) ) - timedelta(seconds=breaks[userRecordQty - 1]) c.execute("UPDATE entrances SET duration=? WHERE rowid=?", (str(durationDelta), current_no)) if durationDelta < timedelta(seconds=breaks[userRecordQty - 1]): workTimeAlert = True return render_template("error.html", workTimeAlert=workTimeAlert) # inform admin if work time < limit if durationDelta < limit: c.execute("UPDATE entrances SET status=? WHERE rowid=?", (2, current_no)) send_email() # save changes to database conn.commit() c.execute("SELECT duration FROM entrances WHERE userId=?", (currentUser, )) # extract duration time of current userId extractDuration = c.fetchall() duration = [z[0] for z in extractDuration] # zip all data related to timing timing = zip(started, stopped, username, duration) return render_template("index.html", breakTaken=breakTaken, currentUser=currentUser, au=au, timing=timing, userIsAdmin=userIsAdmin, displayCheck=displayCheck)