def reset_password_post(): try: email = request.json['data']['email'] except TypeError: return BadRequestError({'source': ''}, 'Bad Request Error').respond() try: user = User.query.filter_by(email=email).one() except NoResultFound: logger.info('Tried to reset password not existing email %s', email) else: link = make_frontend_url('/reset-password', {'token': user.reset_password}) if user.was_registered_with_order: send_email_with_action(user, PASSWORD_RESET_AND_VERIFY, app_name=get_settings()['app_name'], link=link) else: send_email_with_action(user, PASSWORD_RESET, app_name=get_settings()['app_name'], link=link, token=user.reset_password) return make_response( jsonify(message="If your email was registered with us, you'll get an \ email with reset link shortly", email=email), 200)
def change_password(): old_password = request.json['data']['old-password'] new_password = request.json['data']['new-password'] try: user = User.query.filter_by(id=current_user.id).one() except NoResultFound: return abort( make_response(jsonify(error="User not found"), 404) ) else: if user.is_correct_password(old_password): user.password = new_password save_to_db(user) send_email_with_action(user, PASSWORD_CHANGE, app_name=get_settings()['app_name']) send_notification_with_action(user, PASSWORD_CHANGE_NOTIF, app_name=get_settings()['app_name']) else: return abort( make_response(jsonify(error="Wrong Password"), 400) ) return jsonify({ "id": user.id, "email": user.email, "name": user.fullname if user.fullname else None, "password-changed": True })
def send_email_to_attendees(order, purchaser_id, attachments=None): for holder in order.ticket_holders: if holder.user and holder.user.id == purchaser_id: # Ticket holder is the purchaser send_email(to=holder.email, action=TICKET_PURCHASED, subject=MAILS[TICKET_PURCHASED]['subject'].format( event_name=order.event.name, invoice_id=order.invoice_number, frontend_url=get_settings()['frontend_url']), html=MAILS[TICKET_PURCHASED]['message'].format( pdf_url=holder.pdf_url, event_name=order.event.name, frontend_url=get_settings()['frontend_url']), attachments=attachments) else: # The Ticket holder is not the purchaser send_email( to=holder.email, action=TICKET_PURCHASED_ATTENDEE, subject=MAILS[TICKET_PURCHASED_ATTENDEE]['subject'].format( event_name=order.event.name, invoice_id=order.invoice_number), html=MAILS[TICKET_PURCHASED_ATTENDEE]['message'].format( pdf_url=holder.pdf_url, event_name=order.event.name), attachments=attachments)
def change_password(): old_password = request.json['data']['old-password'] new_password = request.json['data']['new-password'] try: user = User.query.filter_by(id=current_user.id).one() except NoResultFound: return NotFoundError({'source': ''}, 'User Not Found').respond() else: if user.is_correct_password(old_password): if user.is_correct_password(new_password): return BadRequestError({'source': ''}, 'Old and New passwords must be different').respond() if len(new_password) < 8: return BadRequestError({'source': ''}, 'Password should have minimum 8 characters').respond() user.password = new_password save_to_db(user) send_email_with_action(user, PASSWORD_CHANGE, app_name=get_settings()['app_name']) send_notification_with_action(user, PASSWORD_CHANGE_NOTIF, app_name=get_settings()['app_name']) else: return BadRequestError({'source': ''}, 'Wrong Password. Please enter correct current password.').respond() return jsonify({ "id": user.id, "email": user.email, "name": user.fullname if user.fullname else None, "password-changed": True })
def send_order_cancel_email(order): send_email(to=order.user.email, action=TICKET_CANCELLED, subject=MAILS[TICKET_CANCELLED]['subject'].format( event_name=order.event.name, invoice_id=order.invoice_number, frontend_url=get_settings()['frontend_url']), html=MAILS[TICKET_CANCELLED]['message'].format( event_name=order.event.name, order_url=make_frontend_url('/orders/{identifier}'.format( identifier=order.identifier)), cancel_note=order.cancel_note, frontend_url=get_settings()['frontend_url']))
def validate_complex_fields_json(self, data, original_data): if data.get('complex_field_values'): if any(((not isinstance(i, (str, bool, int, float))) and i is not None) for i in data['complex_field_values'].values()): raise UnprocessableEntity( {'pointer': '/data/attributes/complex_field_values'}, "Only flattened JSON of form {key: value} where value is a string, " "integer, float, bool or null is permitted for this field") if len(data['complex_field_values']) > get_settings( )['max_complex_custom_fields']: raise UnprocessableEntity( {'pointer': '/data/attributes/complex_field_values'}, "A maximum of {} complex custom form fields are currently supported" .format(get_settings()['max_complex_custom_fields']))
def check_smtp_config(smtp_encryption): """ Checks config of SMTP """ config = { 'host': get_settings()['smtp_host'], 'username': get_settings()['smtp_username'], 'password': get_settings()['smtp_password'], 'encryption': smtp_encryption, 'port': get_settings()['smtp_port'], } for field in config: if field is None: return False return True
def export_event_task(self, email, event_id, settings): event = safe_query(db, Event, 'id', event_id, 'event_id') user = db.session.query(User).filter_by(email=email).first() smtp_encryption = get_settings()['smtp_encryption'] try: logging.info('Exporting started') path = event_export_task_base(event_id, settings) # task_id = self.request.id.__str__() # str(async result) download_url = path result = {'download_url': download_url} logging.info('Exporting done.. sending email') if check_smtp_config(smtp_encryption): send_export_mail(email=email, event_name=event.name, download_url=download_url) else: logging.warning('Error in sending export success email') send_notif_after_export(user=user, event_name=event.name, download_url=download_url) except Exception as e: result = {'__error': True, 'result': str(e)} logging.warning('Error in exporting.. sending email') if check_smtp_config(smtp_encryption): send_export_mail(email=email, event_name=event.name, error_text=str(e)) else: logging.warning('Error in sending export error email') send_notif_after_export(user=user, event_name=event.name, error_text=str(e)) return result
def send_email_task_sendgrid(payload, headers, smtp_config): try: message = Mail(from_email=From(payload['from'], payload['fromname']), to_emails=payload['to'], subject=payload['subject'], html_content=payload["html"]) if payload['attachments'] is not None: for attachment in payload['attachments']: with open(attachment, 'rb') as f: file_data = f.read() f.close() encoded = base64.b64encode(file_data).decode() attachment = Attachment() attachment.file_content = FileContent(encoded) attachment.file_type = FileType('application/pdf') attachment.file_name = FileName(payload['to']) attachment.disposition = Disposition('attachment') message.add_attachment(attachment) sendgrid_client = SendGridAPIClient(get_settings()['sendgrid_key']) logging.info('Sending an email regarding {} on behalf of {}'.format( payload["subject"], payload["from"])) sendgrid_client.send(message) logging.info('Email sent successfully') except urllib.error.HTTPError as e: if e.code == 429: logging.warning("Sendgrid quota has exceeded") send_email_task_smtp.delay(payload=payload, headers=None, smtp_config=smtp_config) elif e.code == 554: empty_attachments_send(sendgrid_client, message) else: logging.exception( "The following error has occurred with sendgrid-{}".format( str(e)))
def after_create_object(self, user, data, view_kwargs): """ method to send- email notification mail link for register verification add image urls :param user: :param data: :param view_kwargs: :return: """ s = get_serializer() hash = str(base64.b64encode(str(s.dumps([user.email, str_generator()])).encode()), 'utf-8') link = make_frontend_url('/verify'.format(id=user.id), {'token': hash}) send_email_with_action(user, USER_REGISTER_WITH_PASSWORD, app_name=get_settings()['app_name'], email=user.email) send_email_confirmation(user.email, link) if data.get('original_image_url'): try: uploaded_images = create_save_image_sizes(data['original_image_url'], 'speaker-image', user.id) except (urllib.error.HTTPError, urllib.error.URLError): raise UnprocessableEntity( {'source': 'attributes/original-image-url'}, 'Invalid Image URL' ) uploaded_images['small_image_url'] = uploaded_images['thumbnail_image_url'] del uploaded_images['large_image_url'] self.session.query(User).filter_by(id=user.id).update(uploaded_images)
def after_create_object(self, user, data, view_kwargs): """ method to send- email notification mail link for register verification add image urls :param user: :param data: :param view_kwargs: :return: """ s = get_serializer() hash = str( base64.b64encode( str(s.dumps([user.email, str_generator()])).encode()), 'utf-8') link = make_frontend_url('/verify'.format(id=user.id), {'token': hash}) send_email_with_action(user, USER_REGISTER_WITH_PASSWORD, app_name=get_settings()['app_name'], email=user.email) send_email_confirmation(user.email, link) if data.get('original_image_url'): try: uploaded_images = create_save_image_sizes( data['original_image_url'], 'speaker-image', user.id) except (urllib.error.HTTPError, urllib.error.URLError): raise UnprocessableEntity( {'source': 'attributes/original-image-url'}, 'Invalid Image URL') uploaded_images['small_image_url'] = uploaded_images[ 'thumbnail_image_url'] del uploaded_images['large_image_url'] self.session.query(User).filter_by( id=user.id).update(uploaded_images)
def after_create_object(self, user, data, view_kwargs): """ method to send- email notification mail link for register verification add image urls :param user: :param data: :param view_kwargs: :return: """ if user.was_registered_with_order: link = make_frontend_url('/reset-password', {'token': user.reset_password}) send_email_with_action(user, PASSWORD_RESET_AND_VERIFY, app_name=get_settings()['app_name'], email=user.email, link=link) else: s = get_serializer() hash = str( base64.b64encode( str(s.dumps([user.email, str_generator()])).encode()), 'utf-8') link = make_frontend_url('/verify'.format(id=user.id), {'token': hash}) send_email_with_action(user, USER_REGISTER_WITH_PASSWORD, app_name=get_settings()['app_name'], email=user.email) send_email_confirmation(user.email, link) # TODO Handle in a celery task # if data.get('original_image_url'): # try: # uploaded_images = create_save_image_sizes(data['original_image_url'], 'speaker-image', user.id) # except (urllib.error.HTTPError, urllib.error.URLError): # raise UnprocessableEntity( # {'source': 'attributes/original-image-url'}, 'Invalid Image URL' # ) # uploaded_images['small_image_url'] = uploaded_images['thumbnail_image_url'] # del uploaded_images['large_image_url'] # self.session.query(User).filter_by(id=user.id).update(uploaded_images) if data.get('avatar_url'): start_image_resizing_tasks(user, data['avatar_url'])
def send_order_cancel_email(order): cancel_msg = '' if order.cancel_note: cancel_msg = u"<br/>Message from the organizer: {cancel_note}".format( cancel_note=order.cancel_note) send_email(to=order.user.email, action=TICKET_CANCELLED, subject=MAILS[TICKET_CANCELLED]['subject'].format( event_name=order.event.name, invoice_id=order.invoice_number, ), html=MAILS[TICKET_CANCELLED]['message'].format( event_name=order.event.name, frontend_url=get_settings()['frontend_url'], cancel_msg=cancel_msg, app_name=get_settings()['app_name']))
def reset_password_post(): try: email = request.json['data']['email'] except TypeError: return BadRequestError({'source': ''}, 'Bad Request Error').respond() try: user = User.query.filter_by(email=email).one() except NoResultFound: return NotFoundError({'source': ''}, 'User not found').respond() else: link = make_frontend_url('/reset-password', {'token': user.reset_password}) if user.was_registered_with_order: send_email_with_action(user, PASSWORD_RESET_AND_VERIFY, app_name=get_settings()['app_name'], link=link) else: send_email_with_action(user, PASSWORD_RESET, app_name=get_settings()['app_name'], link=link) return make_response(jsonify(message="Email Sent"), 200)
def make_frontend_url(path, parameters=None): """ Create URL for frontend """ settings = get_settings() frontend_url = urllib.parse.urlparse(settings.get('frontend_url') or '') full_path = '/'.join( x.strip('/') for x in (frontend_url.path, str(path)) if x) return urllib.parse.urlunparse( (frontend_url.scheme, frontend_url.netloc, full_path, '', str(urllib.parse.urlencode(parameters) if parameters else ''), ''))
def proceed_order(event_id, order_identifier): order = TicketingManager.get_order_by_identifier(order_identifier) if order: if order.status == 'completed': return redirect(url_for('ticketing.view_order_after_payment', order_identifier=order_identifier)) return render_template('gentelella/guest/ticketing/order_pre_payment.html', order=order, event=order.event, countries=list(pycountry.countries), from_organizer=True, pay_via=order.paid_via, stripe_publishable_key=get_settings()['stripe_publishable_key']) else: abort(404) return redirect(url_for('.display_ticket_stats', event_id=event_id))
def make_frontend_url(path, parameters=None): """ Create URL for frontend """ settings = get_settings() frontend_url = urlparse.urlparse(settings['frontend_url'] if settings['frontend_url'] else '') return urlparse.urlunparse(( frontend_url.scheme, frontend_url.netloc, path, '', urllib.urlencode(parameters) if parameters else '', '' ))
def reset_password_post(): email = request.json['data']['email'] try: user = User.query.filter_by(email=email).one() except NoResultFound: return abort( make_response(jsonify(error="User not found"), 404) ) else: link = make_frontend_url('/reset-password', {'token': user.reset_password}) send_email_with_action(user, PASSWORD_RESET, app_name=get_settings()['app_name'], link=link) return make_response(jsonify(message="Email Sent"), 200)
def stripe_callback(): code = request.args.get('code') if code and code != "": data = { 'client_secret': get_settings()['stripe_secret_key'], 'code': code, 'grant_type': 'authorization_code' } response = requests.post('https://connect.stripe.com/oauth/token', data=data) if response.status_code == 200: response_json = response.json() stripe.api_key = response_json['access_token'] account = stripe.Account.retrieve(response_json['stripe_user_id']) return render_template('gentelella/guest/ticketing/stripe_oauth_callback.html', response=response_json, account=account) return "Error"
def make_frontend_url(path, parameters=None): """ Create URL for frontend """ settings = get_settings() frontend_url = urllib.parse.urlparse(settings.get('frontend_url') or '') full_path = '/'.join(x.strip('/') for x in (frontend_url.path, str(path)) if x) return urllib.parse.urlunparse(( frontend_url.scheme, frontend_url.netloc, full_path, '', str(urllib.parse.urlencode(parameters) if parameters else ''), '' ))
def reset_password_post(): try: email = request.json['data']['email'] except TypeError: return make_response(jsonify(error="Bad Request Error"), 400) try: user = User.query.filter_by(email=email).one() except NoResultFound: return abort( make_response(jsonify(error="User not found"), 404) ) else: link = make_frontend_url('/reset-password', {'token': user.reset_password}) send_email_with_action(user, PASSWORD_RESET, app_name=get_settings()['app_name'], link=link) return make_response(jsonify(message="Email Sent"), 200)
def after_create_object(self, user, data, view_kwargs): """ method to send- email notification mail link for register verification add image urls :param user: :param data: :param view_kwargs: :return: """ s = get_serializer() hash = base64.b64encode(s.dumps([user.email, str_generator()])) link = make_frontend_url('/email/verify'.format(id=user.id), {'token': hash}) send_email_with_action(user, USER_REGISTER_WITH_PASSWORD, app_name=get_settings()['app_name'], email=user.email) send_email_confirmation(user.email, link) if data.get('original_image_url'): uploaded_images = create_save_image_sizes(data['original_image_url'], 'user', user.id) uploaded_images['small_image_url'] = uploaded_images['thumbnail_image_url'] del uploaded_images['large_image_url'] self.session.query(User).filter_by(id=user.id).update(uploaded_images)
def send_email(to, action, subject, html, attachments=None): """ Sends email and records it in DB """ from .tasks import send_email_task_sendgrid, send_email_task_smtp if not string_empty(to): email_service = get_settings()['email_service'] email_from_name = get_settings()['email_from_name'] if email_service == 'smtp': email_from = email_from_name + '<' + get_settings( )['email_from'] + '>' else: email_from = get_settings()['email_from'] payload = { 'to': to, 'from': email_from, 'subject': subject, 'html': html, 'attachments': attachments } if not current_app.config['TESTING']: smtp_encryption = get_settings()['smtp_encryption'] if smtp_encryption == 'tls': smtp_encryption = 'required' elif smtp_encryption == 'ssl': smtp_encryption = 'ssl' elif smtp_encryption == 'tls_optional': smtp_encryption = 'optional' else: smtp_encryption = 'none' smtp_config = { 'host': get_settings()['smtp_host'], 'username': get_settings()['smtp_username'], 'password': get_settings()['smtp_password'], 'encryption': smtp_encryption, 'port': get_settings()['smtp_port'], } smtp_status = check_smtp_config(smtp_encryption) if smtp_status: if email_service == 'smtp': send_email_task_smtp.delay(payload=payload, headers=None, smtp_config=smtp_config) else: key = get_settings().get('sendgrid_key') if key: headers = { "Authorization": ("Bearer " + key), "Content-Type": "application/json" } payload['fromname'] = email_from_name send_email_task_sendgrid.delay(payload=payload, headers=headers, smtp_config=smtp_config) else: logging.exception( 'SMTP & sendgrid have not been configured properly' ) else: logging.exception( 'SMTP is not configured properly. Cannot send email.') # record_mail(to, action, subject, html) mail = Mail(recipient=to, action=action, subject=subject, message=html, time=datetime.utcnow()) save_to_db(mail, 'Mail Recorded') record_activity('mail_event', email=to, action=action, subject=subject) return True
def send_email(to, action, subject, html): """ Sends email and records it in DB """ if not string_empty(to): email_service = get_settings()['email_service'] email_from_name = get_settings()['email_from_name'] if email_service == 'smtp': email_from = email_from_name + '<' + get_settings()['email_from'] + '>' else: email_from = get_settings()['email_from'] payload = { 'to': to, 'from': email_from, 'subject': subject, 'html': html } if not current_app.config['TESTING']: if email_service == 'smtp': smtp_encryption = get_settings()['smtp_encryption'] if smtp_encryption == 'tls': smtp_encryption = 'required' elif smtp_encryption == 'ssl': smtp_encryption = 'ssl' elif smtp_encryption == 'tls_optional': smtp_encryption = 'optional' else: smtp_encryption = 'none' config = { 'host': get_settings()['smtp_host'], 'username': get_settings()['smtp_username'], 'password': get_settings()['smtp_password'], 'encryption': smtp_encryption, 'port': get_settings()['smtp_port'], } from .tasks import send_mail_via_smtp_task send_mail_via_smtp_task.delay(config, payload) else: payload['fromname'] = email_from_name key = get_settings()['sendgrid_key'] if not key: print('Sendgrid key not defined') return headers = { "Authorization": ("Bearer " + key), "Content-Type": "application/json" } from .tasks import send_email_task send_email_task.delay(payload, headers) # record_mail(to, action, subject, html) mail = Mail( recipient=to, action=action, subject=subject, message=html, time=datetime.utcnow() ) save_to_db(mail, 'Mail Recorded') record_activity('mail_event', email=to, action=action, subject=subject) return True
def send_email(to, action, subject, html): """ Sends email and records it in DB """ if not string_empty(to): email_service = get_settings()['email_service'] email_from_name = get_settings()['email_from_name'] if email_service == 'smtp': email_from = email_from_name + '<' + get_settings( )['email_from'] + '>' else: email_from = get_settings()['email_from'] payload = { 'to': to, 'from': email_from, 'subject': subject, 'html': html } if not current_app.config['TESTING']: if email_service == 'smtp': smtp_encryption = get_settings()['smtp_encryption'] if smtp_encryption == 'tls': smtp_encryption = 'required' elif smtp_encryption == 'ssl': smtp_encryption = 'ssl' elif smtp_encryption == 'tls_optional': smtp_encryption = 'optional' else: smtp_encryption = 'none' config = { 'host': get_settings()['smtp_host'], 'username': get_settings()['smtp_username'], 'password': get_settings()['smtp_password'], 'encryption': smtp_encryption, 'port': get_settings()['smtp_port'], } from .tasks import send_mail_via_smtp_task send_mail_via_smtp_task.delay(config, payload) else: payload['fromname'] = email_from_name key = get_settings()['sendgrid_key'] if not key: print('Sendgrid key not defined') return headers = { "Authorization": ("Bearer " + key), "Content-Type": "application/json" } from .tasks import send_email_task send_email_task.delay(payload, headers) # record_mail(to, action, subject, html) mail = Mail(recipient=to, action=action, subject=subject, message=html, time=datetime.utcnow()) save_to_db(mail, 'Mail Recorded') record_activity('mail_event', email=to, action=action, subject=subject) return True