Exemplo n.º 1
0
if __name__ == '__main__':

    parser = argparse.ArgumentParser()
    parser.add_argument(
        dest=u'host',
        nargs=u'?',
        default=u'0.0.0.0:5000',
    )

    args = parser.parse_args(sys.argv[1:])

    if u':' in args.host:
        host, port = args.host.split(':', 1)
        port = int(port)
    else:
        url = urlparse.urlparse(settings.get('url'))
        if url.port:
            port = url.port
        else:
            port = 5000
        if url.hostname:
            host = url.hostname
        else:
            host = '0.0.0.0'

    settings.initialize(backend)
    app = get_app(settings)

    app.run(
        debug=settings.get('debug', False),
        host=host,
# -*- coding: utf-8 -*-
"""
Jinja Settings
"""

import os

from jinja2 import Environment
from ..utils import TemplateLoader

from quantifiedcode.backend.templates.filters import metricsuffix
from quantifiedcode.settings import settings

#we set up the jinja environment with the template directories
project_path = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
jinja_env = Environment(loader=TemplateLoader(
    paths=settings.get('backend.template_paths')))

#we add a metric suffix filter
jinja_env.filters['metricsuffix'] = metricsuffix
def runserver():

    app = get_app(settings)
    app.run(debug=settings.get('debug', False), host="0.0.0.0", threaded=False)
    def post(self):
        form = SignupForm(request.form)
        if form.validate():
            with backend.transaction():
                email_matches = backend.filter(User, {'email': form.email.data})
                if len(email_matches) > 0:
                    for user in email_matches:
                        if user.delete is True:
                            return ({'message': 'Your account is scheduled for deletion. Try again in a few minutes".'},
                                    403)
                    return {'message': "A user with this e-mail address already exists. "
                                       "Please try resetting your password.",
                            'resetPasswordLink': True}, 403

                try:
                    user = backend.get(User, {'name': form.name.data.lower()})
                    return {'errors': {'name': {'message': 'This login has already been chosen by another user'}},
                            'message': 'Login already in use.'}, 403
                except User.DoesNotExist:
                    pass
                except User.MultipleDocumentsReturned:
                    return {'errors': {'name': {'message': 'This login has already been chosen by another user'}},
                            'message': 'Login already in use.'}, 403
                user = User({
                    'email': form.email.data.lower(),
                    'name': form.name.data.lower(),
                    'email_validated': False,
                    'email_validation_code': uuid.uuid4().hex,
                    'terms_accepted': form.terms.data,
                    'terms_accepted_at': datetime.datetime.utcnow(),
                    'terms_accepted_from_ip': request.remote_addr,
                    'email_settings': {
                        'newsletter': True,
                        'notifications': True,
                    },
                })
                user.set_password(form.password.data)
                backend.save(user)
                access_token = AccessToken({'user': user,
                                            'token': uuid.uuid4().hex})
                backend.save(access_token)

                user_profile = UserProfile.export(user)

                response = self.make_response({
                    'access_token': access_token.token,
                    'message': 'Success!',
                    'user': user_profile,
                })

                response.set_cookie(
                    'access_token',
                    value=access_token.token,
                    expires=(datetime.datetime.utcnow() + datetime.timedelta(days=7)),
                )

                activation_url = u"{}{}/user/validate/{}".format(
                    settings.get('url'),
                    settings.get('frontend.url'),
                    user.email_validation_code,
                )

                # Activate email
                send_mail(
                    email_to=user.email,
                    template="verify_email",
                    template_context={
                        "user_name": user.name,
                        "activation_url": activation_url,
                    })

                logger.warning("Hooray, a new user has just signed up: %s" % user.name)

                return response
        return {'message': 'Invalid data', 'errors': form.errors}, 403
Exemplo n.º 5
0
from quantifiedcode.settings import settings
from quantifiedcode.backend.commands import commands

import click
import os
import logging


@click.group()
def qc():
    pass


for command in commands:
    qc.add_command(command)

if __name__ == '__main__':
    settings.initialize(initialize_logging=True)
    for plugin in settings.get('plugins', []):
        config = settings.load_plugin_config(plugin)
        if 'commands' in config:
            for command in config['commands']:
                qc.add_command(command)
    qc()
 def get(self):
     return {'settings' : settings.get('frontend.settings',{})}, 200
Exemplo n.º 7
0
from .utils import RegexConverter
from .utils.api import register_routes, handle_exception
from .api.v1 import routes as routes_v1


def get_app(settings):

    app = Flask(__name__,
                static_url_path="/static",
                static_folder="{}/static".format(BACKEND_PATH),
                template_folder="{}/templates".format(BACKEND_PATH))
    app.url_map.converters['regex'] = RegexConverter
    app.handle_exception = handle_exception
    configure(app, settings)

    return app


def configure(app, settings):
    register_routes(routes_v1, app)
    for name, api in settings.get_plugin_apis().items():
        register_routes(api['routes'],
                        app,
                        module=name,
                        version=api['version'])


if __name__ == "__main__":
    app = get_app(settings)
    app.run(debug=settings.get('debug', False), host="0.0.0.0", threaded=False)
Exemplo n.º 8
0
def setup():
    """
    Sets up the QuantifiedCode installation.

    Does the following things:

    * Sets up a database connection.
    * Migrates the database.
    * Generates server-side secrets and settings.
    """

    #we create a new Settings object without defaults & secrets (as we're gonna write it back to the file)
    with open(settings_source, 'r') as input_file:
        settings_dict = yaml.load(input_file)

    click.echo(
        "Hi! Let's get started with setting up your instance of QuantifiedCode."
    )
    click.echo(
        "I will modify your setting file {source} and will put a backup in {source}.backup"
        .format(source=settings_source))

    if settings.get('backend.db_url') is None:
        db_default_url = 'sqlite+pysqlite:///qc.sqlite'
        db_url = click.prompt(
            "\n\nLet's first set up your database. Please provide a SQLAlchemy-compatible URL\n(see here for more info: http://docs.sqlalchemy.org/en/latest/core/engines.html)",
            default=db_default_url)

        #we update the database URL
        settings.set('backend.db_url', db_url)

        #we also update the settings_dict value
        if not 'backend' in settings_dict:
            settings_dict['backend'] = {}
        settings_dict['backend']['db_url'] = db_url

    if settings.get('url') is None:
        default_url = 'http://localhost:5000'
        url = click.prompt(
            '\n\nWich address shall we use for your QuantifiedCode instance?',
            default=default_url)
        settings.get('url', url)
        settings_dict['url'] = url

    click.echo("\n\nTrying to connect to the database...")
    settings.initialize_backend()
    backend = settings.backend
    try:
        engine = backend.engine
        with engine.connect() as connection:
            connection.execute("SELECT 1")
        click.echo("Seems everything's working!")
    except:
        click.echo(
            "Cannot connect to the database. Please try to run setup again...")
        raise
    click.echo("\n\nOkay, now we'll run the database migrations...\n")
    try:
        _migrate_db(settings, None)
    except:
        click.echo("Failed running migrations, aborting...")
        raise
    click.echo("Done running migrations.")
    click.echo("\nNow we'll import issue classes from checkmate...\n")

    _import_issue_classes()

    click.echo("\n\nFinally, let's set up plugins...\n")
    #we call possible setup hooks from the plugins
    settings.hooks.call("setup", settings, settings_dict)

    click.echo("\n\nGreat, you're all set!")
def send_mail_async(email_to,
                    template,
                    template_context=None,
                    email_from=None,
                    name_from=None,
                    email_reply_to=None,
                    attachments=None):
    """ Sends an email based on the specified template.
    :param email_to: address or a list of email addresses
    :param template: name of the template to use for the email
    :param template_context: dict with template context, ie `template_context = {"diffs": aggregated_diffs}`
    :param email_from: sender of the email
    :param name_from: name of the sender
    :param email_reply_to: email address to set as the reply-to address
    :param attachments: list of attachments
    :return:
    """
    if isinstance(email_to, string_types):
        email_to = [email_to]

    if email_to is None or not isinstance(email_to, (list, tuple)):
        raise ValueError("email_to is None or incompatible type!")

    if template_context is None:
        template_context = {}

    email_from = email_from if email_from is not None else settings.get(
        'email.from_email')
    name_from = name_from if name_from is not None else settings.get(
        'email.from_name')
    email_reply_to = email_reply_to if email_reply_to is not None else email_from

    if attachments is None:
        attachments = []

    # render mail content
    template_context.update(settings.get('render_context', {}))
    template_path = "email/{0}.multipart".format(template)
    template = jinja_env.get_template(template_path)
    #we generate the module, which allows us the extract individual blocks from it
    #we capture those blocks of interest using the {% set ... %} syntax
    module = template.make_module(template_context)

    logger.info(
        "Sending an email to: {}\ntemplate: {}\ntemplate_context: {}\nsubject: {}"
        .format("".join(email_to), template, template_context, module.subject))

    message = {
        'from_email': email_from,
        'from_name': name_from,
        'reply_to': email_reply_to,
        'subject': module.subject,
        'html': module.html,
        'text': module.text if module.text else None,
        'to': email_to,
        'attachments': attachments,
    }

    if not settings.providers['email.send']:
        logger.warning("No e-mail providers defined, aborting...")
        return

    for params in settings.providers['email.send']:
        params['provider'](message)
        break
Exemplo n.º 10
0
def send_mail(*args, **kwargs):
    if settings.get('debug'):
        send_mail_async(*args, **kwargs)
    else:
        send_mail_async.delay(*args, **kwargs)