def email_config(): # Modify the email_signup parameter cluster_desc = get_cluster_desc() new_value = flask.request.form.get("esup_value") == 'true' if new_value != cluster_desc['email_signup']: set_email_signup(new_value) # Modify the SMTP configuration config = load_config() new_config = config['mail'] new_server = flask.request.form.get('smtp_server') new_port = flask.request.form.get('smtp_port') new_user = flask.request.form.get('smtp_user') new_password = flask.request.form.get('smtp_pwd') smtp_change = False if len(new_server) > 0 and config['mail']['smtp_address'] != new_server: smtp_change = True new_config['smtp_address'] = new_server if len(new_port) > 0 and config['mail']['smtp_port'] != new_port: smtp_change = True new_config['smtp_port'] = new_port if len(new_user) > 0 and config['mail']['account'] != new_user: smtp_change = True new_config['account'] = new_user if len(new_password) > 0 and config['mail']['password'] != new_password: smtp_change = True new_config['password'] = new_password if smtp_change: save_mail_config(new_config) return flask.redirect(flask.url_for("app.admin"))
def users(): cluster_desc = get_cluster_desc() config = load_config() session = open_session() db_user = session.query(User).filter(User.email == current_user.id).first() authorized = [] admin = [] pending = [] if db_user.is_admin: for user in session.query(User).all(): if user.is_admin: category = admin elif user.user_authorized: category = authorized else: category = pending category.append({ 'id': user.id, 'email': user.email, 'firstname': user.firstname, 'lastname': user.lastname, 'email_confirmed': user.email_confirmed }) return json.dumps({ "status": "ok", "user_info": { 'filters': cluster_desc['email_filters'], 'admin': admin, 'authorized': authorized, 'pending': pending, 'smtp_config': config['mail'], 'email_signup': cluster_desc['email_signup'] } })
def get_email_configuration(): email_config = load_config().get("mail", {}) return { "smtp_server_url": email_config.get("smtp_address", "no_config"), "smtp_server_port": email_config.get("smtp_port", 587), "email": email_config.get("account","no_config"), "password": email_config.get("password", "no_config"), }
def send_confirmation_request(email, firstname): # Save the token to the database token = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(TOKEN_LENGTH)) db_session = open_session() user = db_session.query(User).filter_by(email = email).first() user.email_confirmation_token = token close_session(db_session) # Send the configuration email email_configuration = get_email_configuration() frontend_public_address = load_config().get("frontend", {}).get("public_address", "localhost:5000") fromaddr = email_configuration.get("email") toaddr = email msg = MIMEMultipart() msg['From'] = email_configuration.get("email") msg['To'] = toaddr msg['Subject'] = "Please confirm your email" body = """Hello %s, Thanks for creating an account on the Seduce system. In order to proceed with your account creation, please confirm your email by browsing on the following link: https://%s/confirm_email/token/%s Best Regards, Seduce administrators """ % (firstname, frontend_public_address, token) msg.attach(MIMEText(body, 'plain')) # Configure the smtp server smtp_server = smtplib.SMTP(email_configuration.get("smtp_server_url"), email_configuration.get("smtp_server_port")) smtp_server.ehlo() smtp_server.starttls() smtp_server.ehlo() smtp_server.login(fromaddr, email_configuration.get("password")) text = msg.as_string() smtp_server.sendmail(fromaddr, toaddr, text) smtp_server.quit() return { "success": True, "token": token }
def send_authorization_confirmation(email, firstname): email_configuration = get_email_configuration() frontend_public_address = load_config().get("frontend", {}).get("public_address", "localhost:5000") fromaddr = email_configuration.get("email") toaddr = user.email msg = MIMEMultipart() msg['From'] = email_configuration.get("email") msg['To'] = toaddr msg['Subject'] = "You account has been approved" body = """Hello %s, You account has been approved by an admin, in consequence you can now log in: https://%s/login Best Regards, Seduce system """ % (firstname, frontend_public_address) msg.attach(MIMEText(body, 'plain')) smtp_server = smtplib.SMTP(email_configuration.get("smtp_server_url"), email_configuration.get("smtp_server_port")) smtp_server.ehlo() smtp_server.starttls() smtp_server.ehlo() smtp_server.login(fromaddr, email_configuration.get("password")) text = msg.as_string() smtp_server.sendmail(fromaddr, toaddr, text) smtp_server.quit() return { "success": True, }
# Load the configuration file import sys from lib.config_loader import load_config, get_config if len(sys.argv) != 2: print("The configuration file is required in parameter.") print("For example, 'python3 %s config.json'" % sys.argv[0]) sys.exit(2) load_config(sys.argv[1]) from database.base import DB_URL from database.connector import create_tables import logging logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)-8s %(message)s', datefmt='%Y-%m-%d %H:%M:%S') logging.info("Create the tables from the URL '%s'" % DB_URL) if create_tables(): logging.info("Database initialization complete") else: logging.error("Fail to initialize the database")
from lib.config_loader import load_config from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker DB_URL = load_config()["db_url"] engine = create_engine(DB_URL, connect_args={"check_same_thread": False}) SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) Base = declarative_base()
""" Returns string representing "time since" e.g. 3 days ago, 5 hours ago etc. """ now = datetime.now() diff = now - dt periods = ( (diff.days / 365, "year", "years"), (diff.days / 30, "month", "months"), (diff.days / 7, "week", "weeks"), (diff.days, "day", "days"), (diff.seconds / 3600, "hour", "hours"), (diff.seconds / 60, "minute", "minutes"), (diff.seconds, "second", "seconds"), ) for period, singular, plural in periods: if period: return "%d %s ago" % (period, singular if period == 1 else plural) return default if __name__ == '__main__': try: logging_config() port_number = load_config().get('frontend', {'port': 9000}).get('port') logger = logging.getLogger('APP') logger.info('Running on port %s' % port_number) app.run(debug=True, port=port_number, host="0.0.0.0") except: logger.exception('The frontend is crashed:')
from database.connector import open_session, close_session from database.tables import User from datetime import datetime from flask import Flask, render_template from flask_login import LoginManager, UserMixin from lib.config_loader import load_config from api.admin import b_admin from api.login import b_login from api.user import b_user import jinja2, logging, os, sys # Create the application webui = Flask(__name__) webui.secret_key = load_config()["pwd_secret_key"] # Maximum size in bytes of the uploads (the size of the 64-bit piseduce image) webui.config['MAX_CONTENT_PATH'] = 3000000000 # Add routes from blueprints webui.register_blueprint(b_login) webui.register_blueprint(b_admin, url_prefix="/admin/") webui.register_blueprint(b_user, url_prefix="/user/") # Jinja filters to render templates @webui.template_filter() def timestamp_to_date(timestamp): return datetime.fromtimestamp(timestamp) # Flask_login configuration (session manager) class LoginUser(UserMixin): pass
from lib.config_loader import load_config from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker db_url = load_config().get("db").get("connection_url") db_name = db_url.split('/')[-1] engine = create_engine(db_url) Session = sessionmaker(bind=engine) Base = declarative_base()