def send_email_message(self, recipient, subject, html_message, text_message, sender_email, sender_name): """ Send email message via sendgrid-python. Args: recipient: Email address or tuple of (Name, Email-address). subject: Subject line. html_message: The message body in HTML. text_message: The message body in plain text. """ if not current_app.testing: # pragma: no cover try: # Prepare Sendgrid helper objects from sendgrid.helpers.mail import Email, Content, Substitution, Mail from_email = Email(sender_email, sender_name) to_email = Email(recipient) text_content = Content('text/plain', text_message) html_content = Content('text/html', html_message) # Prepare Sendgrid Mail object # Note: RFC 1341: text must be first, followed by html mail = Mail(from_email, subject, to_email, text_content) mail.add_content(html_content) # Send mail via the Sendgrid API response = self.sg.client.mail.send.post(request_body=mail.get()) print(response.status_code) print(response.body) print(response.headers) except ImportError: raise ConfigError(SENDGRID_IMPORT_ERROR_MESSAGE) except Exception as e: print(e) print(e.body) raise
def __init__(self, app): """Check config settings and initialize the Fernet encryption cypher. Fernet is basically AES128 in CBC mode, with a timestamp and a signature. Args: app(Flask): The Flask application instance. """ self.app = app # Use the applications's SECRET_KEY if flask_secret_key is not specified. flask_secret_key = app.config.get('SECRET_KEY', None) if not flask_secret_key: raise ConfigError('Config setting SECRET_KEY is missing.') # Print a warning if SECRET_KEY is too short key = flask_secret_key.encode() if len(key) < 32: print( 'WARNING: Flask-User TokenManager: SECRET_KEY is shorter than 32 bytes.' ) key = key + b' ' * 32 # Make sure the key is at least 32 bytes long key32 = key[:32] base64_key32 = base64.urlsafe_b64encode(key32) # Create a Fernet cypher to encrypt data -- basically AES128 in CBC mode, # Encrypt, timestamp, sign, and base64-encode from cryptography.fernet import Fernet self.fernet = Fernet(base64_key32)
def __init__(self, app): """ Args: app(Flask): The Flask application instance. """ self.app = app self.user_manager = app.user_manager self.sender_name = self.user_manager.USER_EMAIL_SENDER_NAME self.sender_email = self.user_manager.USER_EMAIL_SENDER_EMAIL # Ensure that USER_EMAIL_SENDER_EMAIL is set if not self.sender_email: raise ConfigError('Config setting USER_EMAIL_SENDER_EMAIL is missing.') # Simplistic email address verification if '@' not in self.sender_email: raise ConfigError('Config setting USER_EMAIL_SENDER_EMAIL is not a valid email address.')
def __init__(self, app, db, UserClass, UserEmailClass=None, UserInvitationClass=None, RoleClass=None): """Initialize the appropriate DbAdapter, based on the ``db`` parameter type. Args: app(Flask): The Flask application instance. db: The Object-Database Mapper instance. UserClass: The User class. UserEmailClass: Optional UserEmail class for multiple-emails-per-user feature. UserInvitationClass: Optional UserInvitation class for user-invitation feature. RoleClass: For testing purposes only. """ self.app = app self.db = db self.UserClass = UserClass self.UserEmailClass = UserEmailClass self.UserInvitationClass = UserInvitationClass self.RoleClass = RoleClass self.user_manager = app.user_manager self.db_adapter = None # Check if db is a SQLAlchemy instance if self.db_adapter is None: try: from flask_sqlalchemy import SQLAlchemy if isinstance(db, SQLAlchemy): self.db_adapter = SQLDbAdapter(app, db) except ImportError: pass # Ignore ImportErrors # Check if db is a MongoEngine instance if self.db_adapter is None: try: from flask_mongoengine import MongoEngine if isinstance(db, MongoEngine): self.db_adapter = MongoDbAdapter(app, db) except ImportError: pass # Ignore ImportErrors # Check if db is a Flywheel instance if self.db_adapter is None: # pragma: no cover try: from flask_flywheel import Flywheel if isinstance(db, Flywheel): self.db_adapter = DynamoDbAdapter(app, db) except ImportError: pass # Ignore ImportErrors # Check self.db_adapter if self.db_adapter is None: raise ConfigError( 'No Flask-SQLAlchemy, Flask-MongoEngine or Flask-Flywheel installed.'\ ' You must install one of these Flask extensions.')
def __init__(self, app): """Check config settings and setup SendGrid Web API v3. Args: app(Flask): The Flask application instance. """ super(SendgridEmailAdapter, self).__init__(app) sendgrid_api_key = app.config.get('SENDGRID_API_KEY') if not sendgrid_api_key: raise ConfigError( "The SENDGRID_API_KEY setting is missing. Set SENDGRID_API_KEY in your app config.") # Setup sendgrid-python try: from sendgrid import SendGridAPIClient self.sg = SendGridAPIClient(apikey=sendgrid_api_key) except ImportError: raise ConfigError(SENDGRID_IMPORT_ERROR_MESSAGE)
def add_user(username, roles=[]): roles = list(roles) print(f'Adding user={username}; roles={roles}') if not User.query.filter(User.username == username).first(): user = User( username=username, password=user_manager.hash_password( input(f"Insert password for {username}: ")), ) for role in roles: user.roles.append(Role(name=role)) db.session.add(user) db.session.commit() print(f"User {username} successfully added!") else: raise ConfigError(f"Username {username} already exists!")
def __init__(self, app, sender_email=None, sender_name=None): """Check config settings and setup Flask-Sendemail. Args: app(Flask): The Flask application instance. """ super(SendmailEmailAdapter, self).__init__(app) # Setup Flask-Mail try: from flask_sendmail import Mail except ImportError: raise ConfigError( "The Flask-Sendmail package is missing. Install Flask-Sendmail with 'pip install Flask-Sendmail'." ) self.mail = Mail(app)
def __init__(self, app, db, UserClass, UserEmailClass=None, UserInvitationClass=None, RoleClass=None, UserRolesClass=None, PositionClass=None, UserHasEducationClass=None, PIClass = None, InstitutionClass = None, InstitutionHasGroupClass = None, EducationClass = None, ExperienceClass = None,CityClass = None, CountryClass = None, RequestsClass= None, PreferenceClass = None, FieldClass= None, MessageClass= None, DegreeClass = None ,DegreeFieldClass= None, RequirementClass=None): """Initialize the appropriate DbAdapter, based on the ``db`` parameter type. Args: app(Flask): The Flask application instance. db: The Object-Database Mapper instance. UserClass: The User class. UserEmailClass: Optional UserEmail class for multiple-emails-per-user feature. UserInvitationClass: Optional UserInvitation class for user-invitation feature. RoleClass: For testing purposes only. """ self.app = app self.db = db self.UserClass = UserClass self.UserEmailClass = UserEmailClass self.UserInvitationClass = UserInvitationClass self.RoleClass = RoleClass self.RequirementClass = RequirementClass self.UserRolesClass = UserRolesClass self.InstitutionClass = InstitutionClass self.InstitutionHasGroupClass = InstitutionHasGroupClass self.PIClass = PIClass self.EducationClass = EducationClass self.ExperienceClass = ExperienceClass self.PositionClass = PositionClass self.PreferenceClass = PreferenceClass self.FieldClass = FieldClass self.MessageClass = MessageClass self.RequestsClass = RequestsClass self.UserHasEducationClass = UserHasEducationClass self.CityClass = CityClass self.CountryClass = CountryClass self.DegreeFieldClass = DegreeFieldClass self.DegreeClass = DegreeClass self.user_manager = app.user_manager self.db_adapter = None # Check if db is a SQLAlchemy instance if self.db_adapter is None: try: from flask_sqlalchemy import SQLAlchemy if isinstance(db, SQLAlchemy): self.db_adapter = SQLDbAdapter(app, db) except ImportError: pass # Ignore ImportErrors # Check if db is a MongoEngine instance if self.db_adapter is None: try: from flask_mongoengine import MongoEngine if isinstance(db, MongoEngine): self.db_adapter = MongoDbAdapter(app, db) except ImportError: pass # Ignore ImportErrors # Check if db is a Flywheel instance if self.db_adapter is None: # pragma: no cover try: from flask_flywheel import Flywheel if isinstance(db, Flywheel): self.db_adapter = DynamoDbAdapter(app, db) except ImportError: pass # Ignore ImportErrors # Check if the UserClass is a Pynamo Model if self.db_adapter is None: try: from pynamodb.models import Model if issubclass(UserClass, Model): self.db_adapter = PynamoDbAdapter(app) except ImportError: pass # Ignore ImportErrors # Check self.db_adapter if self.db_adapter is None: raise ConfigError( 'No Flask-SQLAlchemy, Flask-MongoEngine or Flask-Flywheel installed and no Pynamo Model in use.'\ ' You must install one of these Flask extensions.')