Example #1
0
    def create_app():

        global db, bootstrap, mail, login_manager, moment, pagedown
        app = Flask(__name__)

        from main import main as main_blueprint
        from auth import auth as auth_blueprint
        from admin import admin as admin_blueprint

        app.config["SQLALCHEMY_DATABASE_URI"] = "mysql://flask:gf37888676@172.17.0.25/flask"
        app.config["SQLAlCHEMY_COMMIT_ON_TEARDOWN"] = True
        app.config["FLASK_ADMIN"] = "iamawar3player@163.com"
        app.config["FLASK_MAIL_SUBJECT_PREFIX"] = "[Flasky]"
        app.config["FLASK_MAIL_SENDER"] = "Flasky Admin <iamawar3player@163.com>"
        app.config["MAIL_SERVER"] = "smtp.163.com"
        app.config["MAIL_PORT"] = 25
        app.config["MAIL_USE_TLS"] = False
        app.config["MAIL_USERNAME"] = "iamawar3player@163.com"
        app.config["MAIL_PASSWORD"] = "fan86797121"
        app.config["DEBUG"] = True
        app.config["FLASKY_POSTS_PER_PAGE"] = 10
        app.config["SECRET_KEY"] = "gf37888676"
        app.register_blueprint(main_blueprint)
        app.register_blueprint(auth_blueprint, url_prefix="/auth")
        app.register_blueprint(admin_blueprint, url_prefix="/admin")

        db = db.init_app(app)
        mail = mail.init_app(app)
        bootstrap = bootstrap.init_app(app)
        login_manager = login_manager.init_app(app)
        moment = moment.init_app(app)
        pagedown = pagedown.init_app(app)

        return app
Example #2
0
def create_app():
    app = Flask(__name__)
    app.config.update(CELERY_BROKER_URL="redis://localhost:6379/0", CELERY_RESULT_BACKEND="redis://localhost:6379/0")
    app.config["MAIL_SERVER"] = "smtp.gmail.com"
    app.config["MAIL_PORT"] = 587
    app.config["MAIL_USE_TLS"] = True
    app.config["MAIL_USERNAME"] = admin_imap
    app.config["MAIL_PASSWORD"] = admin_pass
    app.config["MAIL_DEFAULT_SENDER"] = "server-error@example.com"

    return app
Example #3
0
try:
    from settings_local import MAIL_SERVER
    from settings_local import MAIL_PORT
    from settings_local import MAIL_USE_TLS
    from settings_local import MAIL_USERNAME
    from settings_local import MAIL_PASSWORD
    from settings_local import DEFAULT_MAIL_SENDER
except ImportError:
    MAIL_SERVER = "localhost"
    MAIL_PORT = 25
    MAIL_USE_TLS = False
    MAIL_USERNAME = MAIL_PASSWORD = DEFAULT_MAIL_SENDER = None

rsvp_app.config["MAIL_SERVER"] = MAIL_SERVER
rsvp_app.config["MAIL_PORT"] = MAIL_PORT
rsvp_app.config["MAIL_USE_TLS"] = MAIL_USE_TLS
rsvp_app.config["MAIL_USERNAME"] = MAIL_USERNAME
rsvp_app.config["MAIL_PASSWORD"] = MAIL_PASSWORD
rsvp_app.config["DEFAULT_MAIL_SENDER"] = DEFAULT_MAIL_SENDER

mail = Mail(rsvp_app)

basedir = os.path.abspath(os.path.dirname(__file__))
rsvp_app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///" + os.path.join(basedir, "rsvp.db")  # 'sqlite:////tmp/test.db'
rsvp_app.config["SQLALCHEMY_MIGRATE_REPO"] = os.path.join(basedir, "db_repository")

db = SQLAlchemy(rsvp_app)
# CORS(rsvp_app)  # allow all origins

# LOGGING
Example #4
0
ENCRYPTION_KEY = SettingsUtil.EncryptionKey.get(RUN_MODE == "development")

app = Flask(__name__)

app.secret_key = CryptoUtil.decrypt(config.ENCRYPTED_SESSION_KEY, ENCRYPTION_KEY)

app.config["STRIPE_TOKEN"] = CryptoUtil.decrypt(config.ENCRYPTED_STRIPE_TOKEN, ENCRYPTION_KEY)
app.config["DATABASE_PASSWORD"] = CryptoUtil.decrypt(config.ENCRYPTED_DATABASE_PASSWORD, ENCRYPTION_KEY)
app.config["STRIPE_CACHE_REFRESH_MINUTES"] = config.STRIPE_CACHE_REFRESH_MINUTES
app.config["STRIPE_CACHE_REBUILD_MINUTES"] = config.STRIPE_CACHE_REBUILD_MINUTES
app.config["STRIPE_CACHE_REFRESH_BACKREACH_MIN"] = config.STRIPE_CACHE_REFRESH_BACKREACH_MIN
app.config["ACCESS_CONTROL_HOSTNAME"] = config.ACCESS_CONTROL_HOSTNAME
app.config["ACCESS_CONTROL_SSH_PORT"] = config.ACCESS_CONTROL_SSH_PORT

app.config["MAIL_SERVER"] = config.MAIL_SERVER
app.config["MAIL_PORT"] = config.MAIL_PORT
app.config["MAIL_USE_TLS"] = config.MAIL_USE_TLS
app.config["MAIL_USE_SSL"] = config.MAIL_USE_SSL
app.config["MAIL_USERNAME"] = CryptoUtil.decrypt(config.ENCRYPTED_MAIL_USERNAME, ENCRYPTION_KEY)
app.config["MAIL_PASSWORD"] = CryptoUtil.decrypt(config.ENCRYPTED_MAIL_PASSWORD, ENCRYPTION_KEY)
app.config["ADMIN_PASSPHRASE"] = CryptoUtil.decrypt(config.ENCRYPTED_ADMIN_PASSPHRASE, ENCRYPTION_KEY)
app.config["LOG_FILE"] = config.LOG_FILE

# Logging
file_handler = logging.FileHandler(app.config["LOG_FILE"])
file_handler.setFormatter(logging.Formatter("%(asctime)s - %(levelname)s: %(message)s"))
file_handler.setLevel(logging.INFO)
app.logger.setLevel(logging.INFO)
app.logger.addHandler(file_handler)

app.logger.info("------------------------------")
Example #5
0
# services
SERVICE_POD = "pod"
SERVICE_TLP = "tlp"
SERVICES = [SERVICE_POD, SERVICE_TLP]

# models
MODELS_POD_OCR = "ocr"
MODELS_POD_BAYES_SPAM = "bayes_spam"
MODELS_POD_FACE_DETECT = "face_detect"
MODELS = [MODELS_POD_OCR, MODELS_POD_BAYES_SPAM, MODELS_POD_FACE_DETECT]


# mail settings
PRAXYK_API_APP.config["MAIL_SERVER"] = "smtp.googlemail.com"
PRAXYK_API_APP.config["MAIL_PORT"] = 587
PRAXYK_API_APP.config["MAIL_USE_TLS"] = True
PRAXYK_API_APP.config["MAIL_USE_SSL"] = False
# gmail authentication
PRAXYK_API_APP.config["MAIL_USERNAME"] = apiconf["email"]
PRAXYK_API_APP.config["MAIL_PASSWORD"] = apiconf["emailpassword"]

mail = Mail(PRAXYK_API_APP)

# mail accounts
PRAXYK_API_APP.config["MAIL_DEFAULT_SENDER"] = "from@example.com"

# default access token expiration time (24 hours)
TOKEN_EXPIRATION = apiconf["token_expiration"]

Example #6
0
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
from flask_mail import Mail
from forms import LoginForm
from config import *


app = Flask(__name__)
app.config.from_object("config")

app.config["MAIL_SERVER"] = "192.168.1.223"
app.config["MAIL_PORT"] = "25"
app.config["MAIL_USERNAME"] = "s_int7"
app.config["MAIL_PASSWORD"] = "1234"
app.config["MAIL_USE_TLS"] = False
app.config["MAIL_USE_SSL"] = False
app.config["MAIL_DEBUG"] = True
app.config["DEFAULT_MAIL_SENDER"] = True

mail = Mail(app)
db = SQLAlchemy(app)

from app import views, models
Example #7
0
import os
from flask.ext.mail import Mail
from flask import Flask
from flask_script import Manager

app = Flask(__name__)
mail = Mail(app)
manager = Manager(app)

app.config["MAIL_SERVER"] = "smtp.googlemail.com"
app.config["MAIL_PORT"] = "587"
app.config["MAIL_USE_TLS"] = True
app.config["MAIL_USE_SSL"] = True
app.config["MAIL_USERNAME"] = os.environ.get("MAIL_USERNAME")
app.config["MAIL_PASSWORD"] = os.environ.get("MAIL_PASSWORD")


if __name__ == "__main__":
    manager.run()
Example #8
0
app.config["MONGODB_HOST"] = mongo_host
app.config["MONGODB_PORT"] = mongo_port

# Security Features
app.config["SECURITY_REGISTERABLE"] = user_enable_registration
app.config["SECURITY_TRACKABLE"] = user_enable_tracking
app.config["SECURITY_EMAIL_SENDER"] = user_from_email
app.config["SECURITY_PASSWORD_HASH"] = pwhash
app.config["SECURITY_PASSWORD_SALT"] = salt
app.config["SECURITY_CONFIRMABLE"] = True
app.config["SECURITY_EMAIL_SUBJECT_REGISTER"] = user_register_email_subject

# Email
app.config["MAIL_SERVER"] = mail_url
app.config["DEBUG"] = False
app.config["MAIL_PORT"] = mail_port
app.config["MAIL_USE_SSL"] = mail_SSL
app.config["MAIL_USE_TLS"] = mail_TLS
app.config["MAIL_USERNAME"] = mail_user
app.config["MAIL_PASSWORD"] = mail_pass
app.config["MAIL_SUPPRESS_SEND"] = False


# Create database connection object
db = MongoEngine(app)
# Bootstrap
Bootstrap(app)
# Setup Mail
mail = Mail(app)
mail.init_app(app)
Example #9
0
from werkzeug.security import generate_password_hash, check_password_hash

mail = Mail()

app = Flask(__name__)
app.config.from_object(__name__)

app.config["SQLALCHEMY_DATABASE_URI"] = settings.database_uri
db = SQLAlchemy(app)

app.secret_key = settings.app_secret_key

# Mail config

app.config["MAIL_SERVER"] = settings.mail["server"]
app.config["MAIL_PORT"] = settings.mail["port"]
app.config["MAIL_USE_SSL"] = settings.mail["use_ssl"]
app.config["MAIL_USERNAME"] = settings.mail["username"]
app.config["MAIL_PASSWORD"] = settings.mail["password"]

mail.init_app(app)


# Database Setup


class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    email = db.Column(db.String(120), unique=True)
    password = db.Column(db.String(100))
    is_active = db.Column(db.Boolean())
Example #10
0

# Instanciate config
config = Config()

# Instanciate FLASK
app = Flask(__name__)

# Flask settings
app.config["SESSION_TYPE"] = "memcached"
app.config["SECRET_KEY"] = config.secret_key
app.config["TAP"] = config

# Setup Mail
app.config["MAIL_SERVER"] = config.mail_host.split(":")[0]
app.config["MAIL_PORT"] = int(config.mail_host.split(":")[1])
app.config["MAIL_USERNAME"] = config.mail_user
app.config["MAIL_PASSWORD"] = config.mail_pass
app.config["MAIL_DEFAULT_SENDER"] = config.mail_from
app.config["MAIL_USE_TLS"] = True
app.config["MAIL_USE_SSL"] = False
mail = Mail(app)

# Setup Storage
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///database.db"
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
db = SQLAlchemy(app)

# Setup CORS
cors = CORS(app, resources={r".*/api/v1/.*": {"origins": "*"}})
Example #11
0
    def build_user(self, data):
        user = super(GitHugAuth, self).build_user(data)
        user.avatar_url = data["user"]["avatar_url"]
        user.email = data["user"].get("email", "").strip() or None
        return user


#
# Setup
#
import requests

app = Flask(__name__)
app.secret_key = os.environ["SECRET"]
app.config["MAIL_SERVER"] = os.environ.get("MAIL_SERVER", "localhost")
app.config["MAIL_PORT"] = int(os.environ.get("MAIL_PORT", 25))
app.config["MAIL_USE_TLS"] = bool(os.environ.get("MAIL_USE_TLS", False))
app.config["MAIL_USE_SSL"] = bool(os.environ.get("MAIL_USE_SSL", False))
app.config["MAIL_USERNAME"] = os.environ.get("MAIL_USERNAME", None)
app.config["MAIL_PASSWORD"] = os.environ.get("MAIL_PASSWORD", None)
app.config["DEFAULT_MAIL_SENDER"] = "hugs@githugs.org"
app.local = os.environ.get("LOCAL", None) is not None
app.debug = bool(app.local)
heroku = Heroku(app)
if app.config.get("SENTRY_DSN"):
    sentry = Sentry(app)
db = connect(
    app.config["MONGODB_DB"],
    host=app.config["MONGODB_HOST"],
    port=app.config["MONGODB_PORT"],
    username=app.config["MONGODB_USER"],
Example #12
0
########################################################################
app = Flask(__name__)

manager = Manager(app)
mail = Mail(app)
login_manager.init_app(app)
bootstrap = Bootstrap(app)
app.config["SECRET_KEY"] = cfg.get("Secret", "wtf_secret_key")

# app.config['SERVER_NAME'] = "www.circl.lu:443"
# app.config['APPLICATION_ROOT'] = '/cve-portal'
# app.config['WTF_CSRF_ENABLED'] = True

# SMTP email config #
app.config["MAIL_SERVER"] = cfg.get("SMTP", "server")
app.config["MAIL_PORT"] = cfg.get("SMTP", "port")
app.config["MAIL_USE_TLS"] = cfg.get("SMTP", "tls")
app.config["DEFAULT_MAIL_SENDER"] = cfg.get("SMTP", "sender")

# Super Admin #
app.config["PORTAL_ADMIN"] = cfg.get("ADMIN", "mail")

#  REDIS CONNECTION  #
r = redis.StrictRedis(host=cfg.get("REDIS", "host"), port=cfg.get("REDIS", "port"), db=cfg.get("REDIS", "db"))

#  MONGO  #
app.config["MONGO_DBNAME"] = cfg.get("MONGO", "dbname")
m = PyMongo(app)

# GPG #
gpg = gnupg.GPG(homedir=cfg.get("GPG", "directory"))
Example #13
0
    with open(".secret", "r") as f:
        key = f.read()

except IOError:
    with open(".secret", "w") as w:
        key = os.urandom(23)
        pickle.dump(key, w)


db = DatabaseCreate(os.path.join(os.path.dirname(os.path.realpath(__file__))), "login.db")
access = dict(db.fetch_all("select * from stubhub_login"))

app = Flask(__name__)

app.config["MAIL_SERVER"] = "smtp.gmail.com"
app.config["MAIL_PORT"] = gmail["mail_port"]
app.config["MAIL_USE_SSL"] = True
app.config["MAIL_USERNAME"] = gmail["username"]
app.config["MAIL_PASSWORD"] = gmail["password"]

mail = Mail(app)
app.secret_key = key


@app.route("/")
def home():
    return render_template("home_skeleton.html", title="Home")


def login_required(f):
    @wraps(f)
Example #14
0
lm.init_app(app)
lm.login_view = "login"
oid = OpenID(app, os.path.join(settings.BASE_DIR, "tmp"))

# Configure database
app.config["SQLALCHEMY_DATABASE_URI"] = settings.DATABASE_URI
db = SQLAlchemy(app)
migrate = Migrate(app, db)

# Configure Flask-Script
manager = Manager(app)
manager.add_command("db", MigrateCommand)

# Configure Flask-Mail
app.config["MAIL_SERVER"] = settings.MAIL_SERVER
app.config["MAIL_PORT"] = settings.MAIL_PORT
app.config["MAIL_USE_TLS"] = settings.MAIL_USE_TLS
app.config["MAIL_USERNAME"] = settings.MAIL_USERNAME
app.config["MAIL_PASSWORD"] = settings.MAIL_PASSWORD
mail = Mail(app)

# Configure Flask-Cache
app.config["CACHE_TYPE"] = settings.CACHE_BACKEND
cache = Cache(app)

# Configure Babel
babel = Babel(app)


# Configure Flask-Assets
assets = Environment(app)
Example #15
0
from sqlalchemy.event import listens_for
from jinja2 import Markup
from flask.ext.security import current_user, login_required, RoleMixin, Security, SQLAlchemyUserDatastore, UserMixin
from flask_mail import Mail
from flask_admin import Admin, form, AdminIndexView, BaseView, helpers as admin_helpers
from flask_admin.form import rules
from flask_admin.contrib import sqla
from werkzeug import secure_filename

# Create application
app = Flask(__name__)
app.config["SECRET_KEY"] = "COfwEzLtXbxwuIxkTNBcG0"

# Mail
app.config["MAIL_SERVER"] = "smtp.gmail.com"
app.config["MAIL_PORT"] = "465"
app.config["MAIL_USE_SSL"] = True
app.config["MAIL_USERNAME"] = "botflasktest@gmail.com"
app.config["MAIL_PASSWORD"] = "medabots"
app.config["MAIL_DEFAULT_SENDER"] = "naoresponder"
mail = Mail(app)


# Create dummy secrety key so we can use sessions
app.config["SECURITY_PASSWORD_SALT"] = "COfwEzLtXbxwuIxkTNBcG0"
app.config["SECURITY_PASSWORD_HASH"] = "bcrypt"
app.config["SECURITY_RECOVERABLE"] = True

# Create in-memory database
app.config["DATABASE_FILE"] = "sample_db.sqlite"
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///" + app.config["DATABASE_FILE"]
Example #16
0
def create_app(configfile=None):
    app = Flask(__name__)
    handler = RotatingFileHandler("urlabuse.log", maxBytes=10000, backupCount=5)
    handler.setFormatter(Formatter("%(asctime)s %(message)s"))
    app.wsgi_app = ReverseProxied(app.wsgi_app)
    app.logger.addHandler(handler)
    app.logger.setLevel(logging.INFO)
    Bootstrap(app)
    q = Queue(connection=conn)

    # Mail Config
    app.config["MAIL_SERVER"] = "localhost"
    app.config["MAIL_PORT"] = 25
    mail = Mail(app)

    app.config["SECRET_KEY"] = "devkey"
    app.config["BOOTSTRAP_SERVE_LOCAL"] = True
    app.config["configfile"] = config_path

    parser = configparser.SafeConfigParser()
    parser.read(app.config["configfile"])

    replacelist = make_dict(parser, "replacelist")
    auth_users = prepare_auth()
    ignorelist = [i.strip() for i in parser.get("abuse", "ignore").split("\n") if len(i.strip()) > 0]
    autosend_threshold = 5

    def _get_user_ip(request):
        ip = request.headers.get("X-Forwarded-For")
        if ip is None:
            ip = request.remote_addr
        return ip

    @app.route("/", methods=["GET", "POST"])
    def index():
        form = URLForm()
        return render_template("index.html", form=form)

    @app.route("/urlreport", methods=["GET"])
    def url_report():
        return render_template("url-report.html")

    @app.errorhandler(404)
    def page_not_found(e):
        ip = request.headers.get("X-Forwarded-For")
        if ip is None:
            ip = request.remote_addr
        if request.path != "/_result/":
            app.logger.info("404 of {} on {}".format(ip, request.path))
        return render_template("404.html"), 404

    def authenticate():
        """Sends a 401 response that enables basic auth"""
        return Response(
            "Could not verify your access level for that URL.\n" "You have to login with proper credentials",
            401,
            {"WWW-Authenticate": 'Basic realm="Login Required"'},
        )

    def check_auth(username, password):
        """This function is called to check if a username /
        password combination is valid.
        """
        if auth_users is None:
            return False
        else:
            db_pass = auth_users.get(username)
            return db_pass == password

    @app.route("/login", methods=["GET", "POST"])
    def login():
        auth = request.authorization
        if not auth or not check_auth(auth.username, auth.password):
            return authenticate()
        return redirect(url_for("index"))

    @app.route("/_result/<job_key>", methods=["GET"])
    def check_valid(job_key):
        if job_key is None:
            return json.dumps(None), 200
        job = Job.fetch(job_key, connection=conn)
        if job.is_finished:
            return json.dumps(job.result), 200
        else:
            return json.dumps("Nay!"), 202

    @app.route("/start", methods=["POST"])
    def run_query():
        data = json.loads(request.data)
        url = data["url"]
        ip = _get_user_ip(request)
        app.logger.info("{} {}".format(ip, url))
        if get_submissions(url) >= autosend_threshold:
            send(url, "", True)
        is_valid = q.enqueue_call(func=is_valid_url, args=(url,), result_ttl=500)
        return is_valid.get_id()

    @app.route("/urls", methods=["POST"])
    def urls():
        data = json.loads(request.data)
        url = data["url"]
        u = q.enqueue_call(func=url_list, args=(url,), result_ttl=500)
        return u.get_id()

    @app.route("/resolve", methods=["POST"])
    def resolve():
        data = json.loads(request.data)
        url = data["url"]
        u = q.enqueue_call(func=dns_resolve, args=(url,), result_ttl=500)
        return u.get_id()

    @app.route("/phishtank", methods=["POST"])
    def phishtank():
        data = json.loads(request.data)
        if not os.path.exists("phishtank.key"):
            return None
        url = parser.get("PHISHTANK", "url")
        key = open("phishtank.key", "r").readline().strip()
        query = data["query"]
        u = q.enqueue_call(func=phish_query, args=(url, key, query), result_ttl=500)
        return u.get_id()

    @app.route("/virustotal_report", methods=["POST"])
    def vt():
        data = json.loads(request.data)
        if not os.path.exists("virustotal.key"):
            return None
        url = parser.get("VIRUSTOTAL", "url_report")
        url_up = parser.get("VIRUSTOTAL", "url_upload")
        key = open("virustotal.key", "r").readline().strip()
        query = data["query"]
        u = q.enqueue_call(func=vt_query_url, args=(url, url_up, key, query), result_ttl=500)
        return u.get_id()

    @app.route("/googlesafebrowsing", methods=["POST"])
    def gsb():
        data = json.loads(request.data)
        if not os.path.exists("googlesafebrowsing.key"):
            return None
        url = parser.get("GOOGLESAFEBROWSING", "url")
        key = open("googlesafebrowsing.key", "r").readline().strip()
        url = url.format(key)
        query = data["query"]
        u = q.enqueue_call(func=gsb_query, args=(url, query), result_ttl=500)
        return u.get_id()

    @app.route("/urlquery", methods=["POST"])
    def urlquery():
        data = json.loads(request.data)
        if not os.path.exists("urlquery.key"):
            return None
        url = parser.get("URLQUERY", "url")
        key = open("urlquery.key", "r").readline().strip()
        query = data["query"]
        u = q.enqueue_call(func=urlquery_query, args=(url, key, query), result_ttl=500)
        return u.get_id()

    @app.route("/ticket", methods=["POST"])
    def ticket():
        if not request.authorization:
            return ""
        data = json.loads(request.data)
        server = parser.get("SPHINX", "server")
        port = int(parser.get("SPHINX", "port"))
        url = parser.get("ITS", "url")
        query = data["query"]
        u = q.enqueue_call(func=sphinxsearch, args=(server, port, url, query), result_ttl=500)
        return u.get_id()

    @app.route("/whois", methods=["POST"])
    def whoismail():
        if not request.authorization:
            return ""
        server = parser.get("WHOIS", "server")
        port = parser.getint("WHOIS", "port")
        data = json.loads(request.data)
        query = data["query"]
        u = q.enqueue_call(func=whois, args=(server, port, query, ignorelist, replacelist), result_ttl=500)
        return u.get_id()

    @app.route("/eupi", methods=["POST"])
    def eu():
        data = json.loads(request.data)
        if not os.path.exists("eupi.key"):
            return None
        url = parser.get("EUPI", "url")
        key = open("eupi.key", "r").readline().strip()
        query = data["query"]
        u = q.enqueue_call(func=eupi, args=(url, key, query), result_ttl=500)
        return u.get_id()

    @app.route("/pdnscircl", methods=["POST"])
    def dnscircl():
        url = parser.get("PDNS_CIRCL", "url")
        user, password = open("pdnscircl.key", "r").readlines()
        data = json.loads(request.data)
        query = data["query"]
        u = q.enqueue_call(func=pdnscircl, args=(url, user.strip(), password.strip(), query), result_ttl=500)
        return u.get_id()

    @app.route("/bgpranking", methods=["POST"])
    def bgpr():
        data = json.loads(request.data)
        query = data["query"]
        u = q.enqueue_call(func=bgpranking, args=(query,), result_ttl=500)
        return u.get_id()

    @app.route("/psslcircl", methods=["POST"])
    def sslcircl():
        url = parser.get("PSSL_CIRCL", "url")
        user, password = open("psslcircl.key", "r").readlines()
        data = json.loads(request.data)
        query = data["query"]
        u = q.enqueue_call(func=psslcircl, args=(url, user.strip(), password.strip(), query), result_ttl=500)
        return u.get_id()

    @app.route("/get_cache", methods=["POST"])
    def get_cache():
        data = json.loads(request.data)
        url = data["query"]
        data = cached(url)
        dumped = json.dumps(data, sort_keys=True, indent=4, separators=(",", ": "))
        return dumped

    def digest(data):
        to_return = ""
        all_mails = set()
        for entry in data:
            for url, info in list(entry.items()):
                to_return += "\n{}\n".format(url)
                if info.get("whois"):
                    all_mails.update(info.get("whois"))
                    to_return += "\tContacts: {}\n".format(", ".join(info.get("whois")))
                if info.get("vt") and len(info.get("vt")) == 4:
                    vtstuff = info.get("vt")
                    to_return += "\t{} out of {} positive detections in VT - {}\n".format(
                        vtstuff[2], vtstuff[3], vtstuff[1]
                    )
                if info.get("gsb"):
                    to_return += "\tKnown as malicious on Google Safe Browsing: {}\n".format(info.get("gsb"))
                if info.get("phishtank"):
                    to_return += "\tKnown as malicious on PhishTank\n"
                if info.get("dns"):
                    ipv4, ipv6 = info.get("dns")
                    if ipv4 is not None:
                        for ip in ipv4:
                            to_return += "\t" + ip + "\n"
                            data = info[ip]
                            if data.get("bgp"):
                                to_return += "\t\t(PTR: {}) is announced by {} ({}).\n".format(*(data.get("bgp")[:3]))
                            if data.get("whois"):
                                all_mails.update(data.get("whois"))
                                to_return += "\t\tContacts: {}\n".format(", ".join(data.get("whois")))
                    if ipv6 is not None:
                        for ip in ipv6:
                            to_return += "\t" + ip + "\n"
                            data = info[ip]
                            if data.get("whois"):
                                all_mails.update(data.get("whois"))
                                to_return += "\t\tContacts: {}\n".format(", ".join(data.get("whois")))
            to_return += "\tAll contacts: {}\n".format(", ".join(all_mails))
        return to_return

    def send(url, ip="", autosend=False):
        if not get_mail_sent(url):
            set_mail_sent(url)
            data = cached(url)
            if not autosend:
                subject = "URL Abuse report from " + ip
            else:
                subject = "URL Abuse report sent automatically"
            msg = Message(subject, sender="urlabuse@circl.lu", recipients=["info@circl.lu"])
            msg.body = digest(data)
            msg.body += "\n\n"
            msg.body += json.dumps(data, sort_keys=True, indent=4, separators=(",", ": "))
            mail.send(msg)

    @app.route("/submit", methods=["POST"])
    def send_mail():
        data = json.loads(request.data)
        url = data["url"]
        if not get_mail_sent(url):
            ip = _get_user_ip(request)
            send(url, ip)
        return redirect(url_for("index"))

    return app
Example #17
0
app.config["SECRET_KEY"] = "todo-app-secret-key"

# for postgresql
# app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://postgres:ID@localhost/flask_example'
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///appdata.db"

# Config values for Flask-Security.
# We're using PBKDF2 with salt.
app.config["SECURITY_PASSWORD_HASH"] = "pbkdf2_sha512"
# Replace this with your own salt.
app.config["SECURITY_PASSWORD_SALT"] = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"

app.config["SECURITY_EMAIL_SENDER"] = "no-reply@example.com"
# SMTP Server settings (using https://github.com/ThiefMaster/maildump)
app.config["MAIL_SERVER"] = "localhost"
app.config["MAIL_PORT"] = 1025
app.config["MAIL_USE_SSL"] = False
app.config["MAIL_USERNAME"] = ""
app.config["MAIL_PASSWORD"] = ""

# for app registration, confirmation by email
app.config["SECURITY_REGISTERABLE"] = True
app.config["SECURITY_CONFIRMABLE"] = True
app.config["SECURITY_RECOVERABLE"] = True


# Flask-Mail and SQLAlchemy initialization
mail = Mail(app)
db = SQLAlchemy(app)

# Users and Roles table
Example #18
0
File: app.py Project: Fize/cvpn
db = SQLAlchemy(app)
migrate = Migrate(app, db)


def parser(field, key):
    a = Parser(os.path.join(basedir, "config.ini"))
    return a.get(field, key)


# config
app.config["SECRET_KEY"] = parser("secret", "key")
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite://" + parser("cvpn", "data_path")
app.config["SQLALCHEMY_COMMIT_ON_TEARDOWN"] = True
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = True
app.config["MAIL_SERVER"] = parser("mail", "smtp_server")
app.config["MAIL_PORT"] = int(parser("mail", "smtp_port"))
app.config["MAIL_USE_TLS"] = parser("mail", "mail_tls")
app.config["MAIL_USE_SSL"] = parser("mail", "mail_ssl")
app.config["MAIL_USERNAME"] = parser("mail", "mail_user")
app.config["MAIL_PASSWORD"] = parser("mail", "mail_password")
app.config["FLASK_MAIL_SUBJECT_PREFIX"] = parser("mail", "prefix")
app.config["FLASK_MAIL_SENDER"] = "cvpn admin<%s>" % app.config["MAIL_USERNAME"]


mail = Mail(app)


def send_email(to, subject, template, **kwargs):
    msg = Message(
        app.config["FLASK_MAIL_SUBJECT_PREFIX"] + subject, sender=app.config["FLASK_MAIL_SENDER"], recipients=[to]
    )
Example #19
0
import os, sys, hashlib, math

sys.path.append(os.path.dirname(__name__))

from flask import Flask
from flask import current_app
from flask.ext.mail import Mail
from flask.ext.mail import Message
from threading import Thread

app = Flask(__name__)
app.config.from_object(__name__)

# these configs must be set before creating mail instance
app.config["MAIL_SERVER"] = "smtp.qq.com"
app.config["MAIL_PORT"] = 25
app.config["MAIL_USE_TLS"] = True
app.config["MAIL_USE_SSL"] = False
app.config["MAIL_USERNAME"] = "36838082@qq.com"
app.config["MAIL_PASSWORD"] = "xx"
mail = Mail(app)


def send_async_email(app, msg):
    with app.app_context():
        mail.send(msg)


@app.route("/mail")
def SendMail():
    msg = Message("test", sender="36838082@qq.com", recipients=["hermasTang@hotmail.com"])
Example #20
0
from flask_sqlalchemy import SQLAlchemy
from wtforms import StringField, SubmitField
from wtforms.validators import Required


app = Flask(__name__)

# smtplib mail
import sys

sys.path.append("/data/python/")
import data

# mail headers
app.config["MAIL_SERVER"] = data.MAIL_SERVER
app.config["MAIL_PORT"] = data.MAIL_PORT
app.config["MAIL_USE_TLS"] = False
app.config["MAIL_USE_SSL"] = True
app.config["MAIL_USERNAME"] = data.MAIL_USERNAME
app.config["MAIL_PASSWORD"] = data.MAIL_PASSWD
# mail message
app.config["MAIL_SUBJECT"] = "[bamboo web]"
app.config["MAIL_SENDER"] = data.MAIL_USERNAME
app.config["MAIL_ADMIN"] = data.MAIL_ADMIN

# sqlite db
basedir = os.path.abspath(os.path.dirname(__file__))
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///" + os.path.join(basedir, "data.sqlite")
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = True
app.config["SQLALCHEMY_COMMIT_ON_TEARDOWN"] = True