Ejemplo n.º 1
0
def configure(config):
    directory = os.path.dirname(os.path.realpath(__file__))

    app = Flask(
        "wikilabels",
        static_url_path="/BASE_STATIC",  # No conflict with blueprint
        template_folder=os.path.join(directory, 'templates'))
    app.config["APPLICATION_ROOT"] = config['wsgi']['application_root']
    bp = Blueprint('wikilabels',
                   __name__,
                   static_folder=os.path.join(directory, 'static'))

    db = DB.from_config(config)

    form_directory = config['wikilabels']['form_directory']
    form_filenames = (os.path.join(form_directory, fn)
                      for fn in os.listdir(form_directory))
    form_map = {
        d['name']: d
        for d in (yaml.load(open(fn)) for fn in form_filenames)
    }

    app = sessions.configure(app)

    oauth_config = yaml.load(open(config['oauth']['creds']))

    consumer_token = mwoauth.ConsumerToken(oauth_config['key'],
                                           oauth_config['secret'])

    oauth = mwoauth.Handshaker(config['oauth']['mw_uri'], consumer_token)

    bp = routes.configure(config, bp, db, oauth, form_map)
    app.register_blueprint(bp, url_prefix=config['wsgi']['url_prefix'])

    return app
Ejemplo n.º 2
0
def configure(config):
    directory = os.path.dirname(os.path.realpath(__file__))

    app = Flask("wikilabels",
                static_url_path="/static",
                static_folder=os.path.join(directory, 'static'),
                template_folder=os.path.join(directory, 'templates'))
    app.config["APPLICATION_ROOT"] = config['wsgi']['application_root']
    bp = Blueprint('wikilabels', __name__)

    db = DB.from_config(config)

    form_directory = config['wikilabels']['form_directory']
    form_i18n_directory = config['wikilabels']['form_i18n_directory']
    form_filenames = (os.path.join(form_directory, fn)
                      for fn in os.listdir(form_directory))
    form_map = {}
    for fn in form_filenames:
        form_name = os.path.splitext(os.path.basename(fn))[0]
        form_map[form_name] = yaml.load(open(fn))
    for form_name in form_map:
        i18n_dir = os.path.join(form_i18n_directory, form_name)
        form_map[form_name]['i18n'] = (
            {lang[:-5]: json.load(open(os.path.join(i18n_dir, lang)))
                for lang in os.listdir(i18n_dir)}
        )
    app = sessions.configure(app)

    # Set up oauth
    consumer_token = mwoauth.ConsumerToken(config['oauth']['key'],
                                           config['oauth']['secret'])
    oauth = mwoauth.Handshaker(config['oauth']['mw_uri'], consumer_token)

    # Register basic routes
    bp = routes.configure(config, bp, db, oauth, form_map)
    CORS(bp, origins=config['wsgi'].get('cors_allowed', '*'),
         supports_credentials=True)
    app.register_blueprint(bp, url_prefix=config['wsgi']['url_prefix'])

    # Bundle and minify static assests
    app = assets.configure(app)

    # Configure OOJS-UI routes
    oojsui_bp = flask_oojsui.build_static_blueprint(
        'wikilabels-oojsui', __name__,
        url_prefix=config['wsgi']['url_prefix'])
    app.register_blueprint(oojsui_bp)
    return app
Ejemplo n.º 3
0
    def login(self, retry=False, force=False):
        """
        Attempt to log into the server.

        @see: U{https://www.mediawiki.org/wiki/API:Login}

        @param retry: infinitely retry if exception occurs during
            authentication.
        @type retry: bool
        @param force: force to re-authenticate
        @type force: bool
        """
        if self.access_token is None or force:
            pywikibot.output(
                'Logging in to %(site)s via OAuth consumer %(key)s' % {
                    'key': self.consumer_token[0],
                    'site': self.site
                })
            consumer_token = mwoauth.ConsumerToken(self.consumer_token[0],
                                                   self.consumer_token[1])
            handshaker = mwoauth.Handshaker(
                self.site.base_url(self.site.path()), consumer_token)
            try:
                redirect, request_token = handshaker.initiate()
                pywikibot.stdout('Authenticate via web browser..')
                webbrowser.open(redirect)
                pywikibot.stdout('If your web browser does not open '
                                 'automatically, please point it to: %s' %
                                 redirect)
                request_qs = pywikibot.input('Response query string: ')
                access_token = handshaker.complete(request_token, request_qs)
                self._access_token = (access_token.key, access_token.secret)
            except Exception as e:
                pywikibot.error(e)
                if retry:
                    self.login(retry=True, force=force)
        else:
            pywikibot.output('Logged in to %(site)s via consumer %(key)s' % {
                'key': self.consumer_token[0],
                'site': self.site
            })
Ejemplo n.º 4
0
def configure(config):
    directory = os.path.dirname(os.path.realpath(__file__))

    app = Flask(
        "wikilabels",
        static_url_path="/BASE_STATIC",  # No conflict with blueprint
        template_folder=os.path.join(directory, 'templates'))
    app.config["APPLICATION_ROOT"] = config['wsgi']['application_root']
    bp = Blueprint('wikilabels',
                   __name__,
                   static_folder=os.path.join(directory, 'static'))

    db = DB.from_config(config)

    form_directory = config['wikilabels']['form_directory']
    form_i18n_directory = config['wikilabels']['form_i18n_directory']
    form_filenames = (os.path.join(form_directory, fn)
                      for fn in os.listdir(form_directory))
    form_map = {}
    for fn in form_filenames:
        form_name = os.path.splitext(os.path.basename(fn))[0]
        form_map[form_name] = yaml.load(open(fn))
    for form_name in form_map:
        i18n_dir = os.path.join(form_i18n_directory, form_name)
        form_map[form_name]['i18n'] = ({
            lang[:-5]: json.load(open(os.path.join(i18n_dir, lang)))
            for lang in os.listdir(i18n_dir)
        })
    app = sessions.configure(app)

    consumer_token = mwoauth.ConsumerToken(config['oauth']['key'],
                                           config['oauth']['secret'])

    oauth = mwoauth.Handshaker(config['oauth']['mw_uri'], consumer_token)

    bp = routes.configure(config, bp, db, oauth, form_map)
    app.register_blueprint(bp, url_prefix=config['wsgi']['url_prefix'])

    return app
Ejemplo n.º 5
0
    def login(self, retry: bool = False, force: bool = False) -> bool:
        """
        Attempt to log into the server.

        :see: https://www.mediawiki.org/wiki/API:Login

        :param retry: infinitely retry if exception occurs during
            authentication.
        :param force: force to re-authenticate
        """
        if self.access_token is None or force:
            pywikibot.output(
                'Logging in to {site} via OAuth consumer {key}'.format(
                    key=self.consumer_token[0], site=self.site))
            consumer_token = mwoauth.ConsumerToken(*self.consumer_token)
            handshaker = mwoauth.Handshaker(
                self.site.base_url(self.site.path()), consumer_token)
            try:
                redirect, request_token = handshaker.initiate()
                pywikibot.stdout('Authenticate via web browser..')
                webbrowser.open(redirect)
                pywikibot.stdout(
                    'If your web browser does not open '
                    'automatically, please point it to: {}'.format(redirect))
                request_qs = pywikibot.input('Response query string: ')
                access_token = handshaker.complete(request_token, request_qs)
                self._access_token = (access_token.key, access_token.secret)
                return True
            except Exception as e:
                pywikibot.error(e)
                if retry:
                    return self.login(retry=True, force=force)
                else:
                    return False
        else:
            pywikibot.output('Logged in to {site} via consumer {key}'.format(
                key=self.consumer_token[0], site=self.site))
            return True
Ejemplo n.º 6
0
    else:
        app.logger.warning(
            'No FROM_EMAIL/CONTACT_EMAIL/SMTP_HOST set in config.yaml!')

# Add databse credentials to config
if app.config.get('DBCONFIG_FILE') is not None:
    app.config['SQLALCHEMY_DATABASE_URI'] = app.config.get(
        'DB_URI') + '?read_default_file={cfile}'.format(
            cfile=app.config.get('DBCONFIG_FILE'))

locales = Locales(app)
_ = locales.get_message

consumer_token = mwoauth.ConsumerToken(app.config.get('CONSUMER_KEY'),
                                       app.config.get('CONSUMER_SECRET'))
handshaker = mwoauth.Handshaker(
    app.config.get('OAUTH_MWURI') + '/index.php', consumer_token)

contactEmail = app.config.get('CONTACT_EMAIL')
if not contactEmail:
    print("No CONTACT_EMAIL has been set in config.yaml!")
    print(
        "Wikimedia policy dictates that you should provide a way for system administrators to contact you."
    )
    print("You risk being IP-blocked if you do not comply.")
    contactEmail = "no contact provided"
useragent = "Watch-Translations-Bot/" + getVersionNumber(
) + " (" + contactEmail + ")"


class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
Ejemplo n.º 7
0
                "http://127.0.0.1:3000"
            ]
        }
    }
)

app.config['CORS_HEADERS'] = 'Content-Type'
app.config['SESSION_COOKIE_SECURE'] = True
app.config['SESSION_COOKIE_SAMESITE'] = 'None'
app.config.from_object( os.environ['APP_SETTINGS'] )
app.secret_key = os.urandom(50)
consumer_token = mwoauth.ConsumerToken(
    app.config["CONSUMER_KEY"],
    app.config["CONSUMER_SECRET"]
)
handshaker = mwoauth.Handshaker(app.config["OAUTH_MWURI"], consumer_token)
API_URL = app.config["OAUTH_MWURI"] + "api.php"


@app.route('/')
def index():
    user = get_current_user()
    return render_template('index.html', user=user)

#############################
# ------ API Part -----------
#############################


@app.route('/api/createform', methods=['POST'])
def createform():
Ejemplo n.º 8
0
import mwapi
import mwoauth
from requests_oauthlib import OAuth1

# Consruct a "consumer" from the key/secret provided by MediaWiki
import config  # You'll need to provide this
from six.moves import input  # For compatibility between python 2 and 3

consumer_token = mwoauth.ConsumerToken(config.consumer_key,
                                       config.consumer_secret)

# Construct handshaker with wiki URI and consumer
handshaker = mwoauth.Handshaker("https://en.wikipedia.org/w/index.php",
                                consumer_token)

# Step 1: Initialize -- ask MediaWiki for a temporary key/secret for user
redirect, request_token = handshaker.initiate()

# Step 2: Authorize -- send user to MediaWiki to confirm authorization
print("Point your browser to: %s" % redirect)  #
response_qs = input("Response query string: ")

# Step 3: Complete -- obtain authorized key/secret for "resource owner"
access_token = handshaker.complete(request_token, response_qs)

# Construct an auth object with the consumer and access tokens
auth1 = OAuth1(consumer_token.key,
               client_secret=consumer_token.secret,
               resource_owner_key=access_token.key,
               resource_owner_secret=access_token.secret)
Ejemplo n.º 9
0
    def __init__(self,
                 base_url='https://www.mediawiki.org/w',
                 clean_url="Deprecated",
                 default_return_to='index',
                 consumer_key=None, consumer_secret=None,
                 return_json=False,
                 name="Deprecated"):
        if consumer_key is None:
            raise TypeError(
                "MWOAuth() missing 1 required argument: 'consumer_key'")
        if consumer_secret is None:
            raise TypeError(
                "MWOAuth() missing 1 required argument: 'consumer_secret'")
        consumer_token = mwoauth.ConsumerToken(consumer_key, consumer_secret)
        self.default_return_to = default_return_to
        self.return_json = return_json
        self.script_url = base_url + "/index.php"
        self.api_url = base_url + "/api.php"

        self.handshaker = mwoauth.Handshaker(self.script_url, consumer_token)

        self.bp = Blueprint('mwoauth', __name__)

        @self.bp.route('/logout')
        def logout():
            session['mwoauth_access_token'] = None
            session['mwoauth_username'] = None
            if 'next' in request.args:
                return redirect(request.args['next'])
            return redirect(self.default_return_to)

        @self.bp.route('/login')
        def login():
            redirect_to, request_token = self.handshaker.initiate()
            keyed_token_name = _str(request_token.key) + '_request_token'
            keyed_next_name = _str(request_token.key) + '_next'
            session[keyed_token_name] = \
                dict(zip(request_token._fields, request_token))

            if 'next' in request.args:
                session[keyed_next_name] = request.args.get('next')
            else:
                session[keyed_next_name] = self.default_return_to

            return redirect(redirect_to)

        @self.bp.route('/oauth-callback')
        def oauth_authorized():
            request_token_key = request.args.get('oauth_token', 'None')
            keyed_token_name = _str(request_token_key) + '_request_token'
            keyed_next_name = _str(request_token_key) + '_next'

            if keyed_token_name not in session:
                raise Exception("OAuth callback failed.  " +
                                "Can't find keyed token in session.  " +
                                "Are cookies disabled?")

            access_token = self.handshaker.complete(
                mwoauth.RequestToken(**session[keyed_token_name]),
                request.query_string)
            session['mwoauth_access_token'] = \
                dict(zip(access_token._fields, access_token))

            next_url = url_for(session[keyed_next_name])
            del session[keyed_next_name]
            del session[keyed_token_name]

            username = self.get_current_user(False)
            flash(u'You were signed in, %s!' % username)

            return redirect(next_url)