Пример #1
0
def oauth_callback():
    if "request_token" not in flask.session:
        flask.flash(u"OAuth callback failed. Are cookies disabled?")
        return flask.redirect(flask.url_for("index"))

    consumer_token = mwoauth.ConsumerToken(app.config["CONSUMER_KEY"],
                                           app.config["CONSUMER_SECRET"])

    try:
        access_token = mwoauth.complete(
            app.config["OAUTH_MWURI"], consumer_token,
            mwoauth.RequestToken(**flask.session["request_token"]),
            flask.request.query_string)

        identity = mwoauth.identify(app.config["OAUTH_MWURI"], consumer_token,
                                    access_token)
    except Exception:
        app.logger.exception("OAuth authentication failed")

    else:
        flask.session["access_token"] = dict(
            zip(access_token._fields, access_token))
        flask.session["username"] = identity["username"]

    return flask.redirect(flask.url_for("index"))
def oauth_callback():
    """OAuth handshake callback."""
    if 'request_token' not in flask.session:
        flask.flash(u'OAuth callback failed. Are cookies disabled?')
        return flask.redirect(flask.url_for('index'))
    consumer_token = mwoauth.ConsumerToken(app.config['CONSUMER_KEY'],
                                           app.config['CONSUMER_SECRET'])

    try:
        access_token = mwoauth.complete(
            app.config['OAUTH_MWURI'], consumer_token,
            mwoauth.RequestToken(**flask.session['request_token']),
            flask.request.query_string)
        identity = mwoauth.identify(app.config['OAUTH_MWURI'], consumer_token,
                                    access_token)
    except Exception:
        app.logger.exception('OAuth authentication failed')
    else:
        flask.session['request_token_secret'] = dict(
            zip(access_token._fields, access_token))['secret']
        flask.session['request_token_key'] = dict(
            zip(access_token._fields, access_token))['key']
        flask.session['username'] = identity['username']

    return flask.redirect(flask.url_for('index'))
Пример #3
0
def oauth_callback():
    """OAuth handshake callback."""
    if 'request_token' not in flask.session:
        flask.flash(u'OAuth callback failed. Are cookies disabled?')
        return flask.redirect(flask.url_for('index'))

    consumer_token = mwoauth.ConsumerToken(app.config['CONSUMER_KEY'],
                                           app.config['CONSUMER_SECRET'])

    try:
        access_token = mwoauth.complete(
            app.config['OAUTH_MWURI'], consumer_token,
            mwoauth.RequestToken(**flask.session['request_token']),
            flask.request.query_string)

        identity = mwoauth.identify(app.config['OAUTH_MWURI'], consumer_token,
                                    access_token)
    except Exception as e:
        app.logger.exception('OAuth authentication failed')

    else:
        flask.session['access_token'] = dict(
            zip(access_token._fields, access_token))
        print('//////// ACCESS_TOKEN')
        print(access_token)
        flask.session['username'] = identity['username']

    next_url = flask.request.args.get('next_url') or flask.url_for(
        'get_random_edit')
    return flask.redirect(next_url)
Пример #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_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
def oauth_callback():
    """OAuth handshake callback."""
    if 'request_token' not in flask.session:
        flask.flash(u'OAuth callback failed. Are cookies disabled?')
        return flask.redirect(flask.url_for('index'))
    consumer_token = mwoauth.ConsumerToken(app.config['CONSUMER_KEY'],
                                           app.config['CONSUMER_SECRET'])

    try:
        access_token = mwoauth.complete(
            app.config['OAUTH_MWURI'], consumer_token,
            mwoauth.RequestToken(**flask.session['request_token']),
            flask.request.query_string)
        identity = mwoauth.identify(app.config['OAUTH_MWURI'], consumer_token,
                                    access_token)
    except Exception:
        app.logger.exception('OAuth authentication failed')
    else:
        flask.session['request_token_secret'] = dict(
            zip(access_token._fields, access_token))['secret']
        flask.session['request_token_key'] = dict(
            zip(access_token._fields, access_token))['key']
        flask.session['username'] = identity['username']
        tconn = tconnect()
        with tconn.cursor() as cur:
            sql = 'select settings from users where username=%s'
            cur.execute(sql, (getusername(), ))
            data = cur.fetchall()
        if len(data) == 0:
            with tconn.cursor() as cur:
                sql = 'insert into users(username, settings) values (%s, %s)'
                cur.execute(sql, (getusername(), getdefaultsettings(True)))
                tconn.commit()
    return flask.redirect(flask.url_for('index'))
Пример #6
0
def oauth_callback():
    """OAuth handshake callback."""
    if 'request_token' not in session:
        flash(gettext('OAuth callback failed. Are cookies disabled?'))
        return redirect(url_for('main.home'))

    consumer_token = mwoauth.ConsumerToken(app.config['CONSUMER_KEY'],
                                           app.config['CONSUMER_SECRET'])

    try:
        access_token = mwoauth.complete(
            app.config['OAUTH_MWURI'], consumer_token,
            mwoauth.RequestToken(**session['request_token']),
            request.query_string)
        identity = mwoauth.identify(app.config['OAUTH_MWURI'], consumer_token,
                                    access_token)
    except Exception:
        app.logger.exception('OAuth authentication failed')
    else:
        session['access_token'] = dict(zip(access_token._fields, access_token))
        session['username'] = identity['username']
        flash(gettext('Welcome  %(username)s!', username=session['username']),
              'success')
        if session.get('next_url'):
            next_url = session.get('next_url')
            session.pop('next_url', None)
            return redirect(next_url)
        else:
            return redirect(url_for('main.home'))
Пример #7
0
def oauth_callback(req):
    """OAuth handshake callback."""
    serialized_token = req.session.get(REQUEST_TOKEN_KEY, None)
    if serialized_token is None:
        messages.error(req, _("Session invalid."))
        return shortcuts.redirect(
            urlresolvers.reverse('labsauth:oauth_initiate'))
    # Convert from unicode stored in session to bytes expected by mwoauth
    serialized_token = utils.tuple_to_bytes(serialized_token)

    consumer_token = mwoauth.ConsumerToken(settings.OAUTH_CONSUMER_KEY,
                                           settings.OAUTH_CONSUMER_SECRET)
    request_token = mwoauth.RequestToken(*serialized_token)
    access_token = mwoauth.complete(settings.OAUTH_MWURL, consumer_token,
                                    request_token, req.META['QUERY_STRING'])
    # Convert to unicode for session storage
    req.session[ACCESS_TOKEN_KEY] = utils.tuple_to_unicode(access_token)
    req.user.set_accesstoken(access_token)

    sul_user = mwoauth.identify(settings.OAUTH_MWURL, consumer_token,
                                access_token)
    req.user.sulname = sul_user['username']
    req.user.sulemail = sul_user['email']
    req.user.realname = sul_user['realname']
    req.user.save()

    messages.info(
        req,
        _("Authenticated as OAuth user {user}".format(
            user=sul_user['username'])))
    return shortcuts.redirect(req.session.get(NEXT_PAGE, '/'))
Пример #8
0
def login():
    """Initiate an OAuth login.

    Call the MediaWiki server to get request secrets and then redirect the
    user to the MediaWiki server to sign the request.
    """
    if current_user.is_authenticated:
        return redirect(url_for('main.home'))
    else:
        consumer_token = mwoauth.ConsumerToken(app.config['CONSUMER_KEY'],
                                               app.config['CONSUMER_SECRET'])
        try:
            redirect_string, request_token = mwoauth.initiate(
                app.config['OAUTH_MWURI'], consumer_token)
        except Exception:
            app.logger.exception('mwoauth.initiate failed')
            return redirect(url_for('main.home'))
        else:
            session['request_token'] = dict(
                zip(request_token._fields, request_token))
            user = User.query.filter_by(
                username=session.get('username', None)).first()
            if user and user.username is not None:
                login_user(user)
            return redirect(redirect_string)
Пример #9
0
def test_if_needs_oauth_redirect_not_logged_in(monkeypatch):
    monkeypatch.setitem(lexeme_forms.app.config, 'oauth', {})
    monkeypatch.setattr(lexeme_forms, 'consumer_token', mwoauth.ConsumerToken('test key', 'test secret'), raising=False)
    monkeypatch.setattr(mwoauth, 'initiate', lambda mw_uri, consumer_token, user_agent: ('test redirect', mwoauth.RequestToken('test key', 'test secret')))
    with lexeme_forms.app.test_request_context() as context:
        response = lexeme_forms.if_needs_oauth_redirect()
    assert response is not None
    assert str(response.status_code).startswith('3')
Пример #10
0
def login(return_url):
    if return_url:
        session['return_url'] = return_url
    consumer_token = mwoauth.ConsumerToken(config['OAUTH_TOKEN'],
                                           config['OAUTH_SECRET'])
    redirect_url, request_token = mwoauth.initiate(config['OAUTH_URI'],
                                                   consumer_token)
    session['request_token'] = dict(zip(request_token._fields, request_token))
    return redirect(redirect_url)
Пример #11
0
 def __init__(self, thank_batch_size=1, lang=None):
     self.thank_batch_size = os.getenv('CS_WIKIPEDIA_OAUTH_BATCH_SIZE',
                                       thank_batch_size)
     logging.info(f"Thanking batch size set to : {self.thank_batch_size}")
     self.db_session = init_session()
     self.lang = lang
     logging.info(f"Thanking language set to. {self.lang}")
     self.consumer_token = mwoauth.ConsumerToken(
         os.environ['CS_OAUTH_CONSUMER_KEY'],
         os.environ['CS_OAUTH_CONSUMER_SECRET'])
     self.max_send_errors = int(
         os.environ['CS_OAUTH_THANKS_MAX_SEND_ERRORS'])
Пример #12
0
def callback():
    logger = logging.getLogger('auth.callback')
    if 'access_token' in session or 'username' in session:
        logger.warn(
            f"User '{session['username']}' appears to be already logged in...")
    if 'request_token' not in session:
        logger.warn('OAuth callback failed. Are cookies disabled?')
        return get_auth_redirect_request()

    consumer_token = mwoauth.ConsumerToken(
        current_app.config['CONSUMER_KEY'],
        current_app.config['CONSUMER_SECRET'])

    try:
        access_token = mwoauth.complete(
            current_app.config['OAUTH_MWURI'], consumer_token,
            mwoauth.RequestToken(**session['request_token']),
            request.query_string)

        identity = mwoauth.identify(current_app.config['OAUTH_MWURI'],
                                    consumer_token, access_token)
    except Exception:
        logger.exception('OAuth authentication failed')
        # TODO should potentially do something more informative for the user here (even a 404 might be clearer?)
        return get_auth_redirect_request()
    else:
        session['access_token'] = dict(zip(access_token._fields, access_token))
        username = identity['username']
        session['username'] = username
        session.permanent = True  # ideally, this will keep the user logged-in
        logger.info(
            f"Session created for user '{username}'; (new session? = {session.new})"
        )

    response = get_auth_redirect_request()
    # note: could set an additional cookie here, using response.set_cookie?
    # otherwise: figure out what cookie mwoauth is setting and check for it on the front-end?
    # currently, planning to use the existence of the username cookie
    response.set_cookie(
        "username",
        username,
    )
    # I *believe* this is a manual form of what the Flask session implementation is doing
    #import jwt
    #response.set_cookie(
    #    'user_secret',
    #    jwt.encode({
    #        'access_token': dict(zip(access_token._fields, access_token)),
    #        'username': username,
    #    }, current_app.config['SECRET_KEY'], algorithm="HS256")
    #)
    return response
Пример #13
0
def login():
    consumer_token = mwoauth.ConsumerToken(app.config["CONSUMER_KEY"],
                                           app.config["CONSUMER_SECRET"])
    try:
        redirect, request_token = mwoauth.initiate(app.config["OAUTH_MWURI"],
                                                   consumer_token)
    except Exception:
        app.logger.exception("mwoauth.initiate failed")
        return flask.redirect(flask.url_for("index"))
    else:
        flask.session["request_token"] = dict(
            zip(request_token._fields, request_token))
        return flask.redirect(redirect)
Пример #14
0
def login():
    consumer_token = mwoauth.ConsumerToken(app.config['CONSUMER_KEY'],
                                           app.config['CONSUMER_SECRET'])
    try:
        redirect, request_token = mwoauth.initiate(app.config['OAUTH_MWURI'],
                                                   consumer_token)
    except Exception:
        app.logger.exception('mwoauth.initiate failed')
        return flask.redirect(flask.url_for('index'))
    else:
        flask.session['request_token'] = dict(
            zip(request_token._fields, request_token))
        return flask.redirect(redirect)
Пример #15
0
    def from_config(cls, config):

        oauth_config = yaml.load(
            open(
                os.path.join(config.snuggle['root_directory'],
                             config.snuggle['oauth_config'])))

        consumer_token = mwoauth.ConsumerToken(oauth_config['consumer_key'],
                                               oauth_config['consumer_secret'])

        return cls(
            "%s://%s%s%s" %
            (config.mediawiki['protocol'], config.mediawiki['domain'],
             config.mediawiki['path']['scripts'],
             config.mediawiki['file']['index']), consumer_token)
Пример #16
0
    def identity(self) -> Optional[dict]:
        """Get identifying information about a user via an authorized token."""
        if self.access_token is None:
            pywikibot.error('Access token not set')
            return None

        consumer_token = mwoauth.ConsumerToken(*self.consumer_token)
        access_token = mwoauth.AccessToken(*self.access_token)
        try:
            identity = mwoauth.identify(self.site.base_url(self.site.path()),
                                        consumer_token, access_token)
            return identity
        except Exception as e:
            pywikibot.error(e)
            return None
Пример #17
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
Пример #18
0
def login():
    logger = logging.getLogger('auth.login')

    consumer_token = mwoauth.ConsumerToken(
        current_app.config['CONSUMER_KEY'],
        current_app.config['CONSUMER_SECRET'])
    try:
        redirect_request, request_token = mwoauth.initiate(
            current_app.config['OAUTH_MWURI'], consumer_token)
    except Exception:
        logger.exception('mwoauth.initiate failed')
        return get_auth_redirect_request()
    else:
        session['request_token'] = dict(
            zip(request_token._fields, request_token))
        return redirect(redirect_request)
Пример #19
0
    def check_auth(self, user_id, login_type, login_dict):
        """Authenticate user with mediawiki

        This will receive OAuth comsumer and request tokens and identify
        the user. Initiating and handling the OAuth callback will be done
        in the clients"""

        logger.info("Request to auth user %s", user_id)
        consumer_token = mwoauth.ConsumerToken(self.config.consumer_key,
                                               self.config.consumer_secret)

        try:
            access_token = mwoauth.complete(
                self.config.oauth_mwuri, consumer_token,
                mwoauth.RequestToken(login_dict['request_key'],
                                     login_dict['request_secret']),
                login_dict['oauth_query'])

            identity = yield mwoauth.identify(self.config.oauth_mwuri,
                                              consumer_token, access_token)
        except Exception as e:
            logger.exception('OAuth authentication failed, %s', e)
            yield defer.returnValue(None)

        if user_id.startswith("@"):
            localpart = user_id.split(":", 1)[0][1:]
        else:
            localpart = user_id
            user_id = UserID(localpart,
                             self.account_handler.hs.hostname).to_string()
        if localpart.title() != identity["username"]:
            logger.error(("username from mediawiki differs from provided %s !="
                          " %s"), localpart, identity["username"])
            yield defer.returnValue(None)
        logger.info("User %s authenticated", user_id)
        if not (yield self.account_handler.check_user_exists(user_id)):
            logger.info("User %s does not exist yet, creating...", user_id)
            user_id, access_token = (yield self.account_handler.register(
                localpart=localpart))
            #  registration = True
            logger.info("Registration based on MW_OAuth was successful for %s",
                        user_id)
        else:
            logger.info("User %s already exists, registration skipped",
                        user_id)

        yield defer.returnValue((user_id, None))
Пример #20
0
def oauth_callback():
    """OAuth handshake callback."""
    if 'request_token' not in flask.session:
        flask.flash(u'OAuth callback failed. Are cookies disabled?')
        return flask.redirect(flask.url_for('index'))

    consumer_token = mwoauth.ConsumerToken(app.config['CONSUMER_KEY'],
                                           app.config['CONSUMER_SECRET'])

    try:
        access_token = mwoauth.complete(
            app.config['OAUTH_MWURI'], consumer_token,
            mwoauth.RequestToken(**flask.session['request_token']),
            flask.request.query_string)

        identity = mwoauth.identify(app.config['OAUTH_MWURI'], consumer_token,
                                    access_token)
    except Exception:
        app.logger.exception('OAuth authentication failed')
    else:
        flask.session['access_token'] = dict(
            zip(access_token._fields, access_token))
        flask.session['username'] = identity['username']

    regdate = registration_date(flask.session['username'])
    if regdate:
        delta = datetime.datetime.now() - regdate
        if delta.days >= 365:
            return flask.redirect(flask.url_for('index'))
        else:
            return flask.render_template(
                'error.html',
                error={
                    'msg':
                    'Ցավոք, Դուք չունեք բավարար վիքիստաժ։ Խնդրում եմ '
                    'կրկին փորձել ' + str(365 - delta.days) + ' օր '
                    'հետո։'
                })
    return flask.render_template(
        'error.html',
        error={
            'msg':
            'Չստացվեց գտնել Ձեր գրանցման ամսաթիվը։ Խնդրում եմ կրկին '
            'փորձել կամ դիմել ԱշոտՏՆՂ մասնակցին, եթե խնդիրը '
            'շարունակվում է։։'
        })
def login():
    """Initiate an OAuth login.
    Call the MediaWiki server to get request secrets and then redirect the
    user to the MediaWiki server to sign the request.
    """
    consumer_token = mwoauth.ConsumerToken(app.config['CONSUMER_KEY'],
                                           app.config['CONSUMER_SECRET'])
    try:
        redirect, request_token = mwoauth.initiate(app.config['OAUTH_MWURI'],
                                                   consumer_token)
    except Exception:
        app.logger.exception('mwoauth.initiate failed')
        return flask.redirect(flask.url_for('index'))
    else:
        flask.session['request_token'] = dict(
            zip(request_token._fields, request_token))
        return flask.redirect(redirect)
Пример #22
0
def oauth_callback():
    consumer_token = mwoauth.ConsumerToken(config['OAUTH_TOKEN'],
                                           config['OAUTH_SECRET'])
    access_token = mwoauth.complete(
        config['OAUTH_URI'], consumer_token,
        mwoauth.RequestToken(**session['request_token']), request.query_string)
    identity = mwoauth.identify(config['OAUTH_URI'], consumer_token,
                                access_token)

    user = db_insert_if_not_exist(User(sul_id=identity['sub'],
                                       username=identity['username']),
                                  sul_id=identity['sub'])

    session['user_id'] = user.id
    session['username'] = user.username
    session['access_token'] = dict(zip(access_token._fields, access_token))
    return redirect(session.pop('return_url', url_for('main.home')))
Пример #23
0
def login():
    """Initiate an OAuth login.
    Call the MediaWiki server to get request secrets and then redirect the
    user to the MediaWiki server to sign the request.
    """
    consumer_token = mwoauth.ConsumerToken(
        app.config['CONSUMER_KEY'], app.config['CONSUMER_SECRET'])
    try:
        redirect, request_token = mwoauth.initiate(
            app.config['OAUTH_MWURI'], consumer_token)
    except Exception:
        app.logger.exception('mwoauth.initiate failed')
        flash(_('login-fail-text', url="https://phabricator.wikimedia.org/maniphest/task/edit/form/1/?project=massmailer"), 'danger')
        return flask.redirect(flask.url_for('index'))
    else:
        flask.session['request_token'] = dict(zip(
            request_token._fields, request_token))
        flash(_('login-success-text'), 'success')
        return flask.redirect(redirect)
Пример #24
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
            })
Пример #25
0
def oauth_initiate(req):
    """Initiate an OAuth login."""
    next_page = req.GET.get('next', None)
    if next_page is not None:
        req.session[NEXT_PAGE] = next_page
    consumer_token = mwoauth.ConsumerToken(settings.OAUTH_CONSUMER_KEY,
                                           settings.OAUTH_CONSUMER_SECRET)
    try:
        redirect, request_token = mwoauth.initiate(
            settings.OAUTH_MWURL, consumer_token,
            req.build_absolute_uri(
                urlresolvers.reverse('labsauth:oauth_callback')))
    except Exception:
        # FIXME: get upstream to use a narrower exception class
        logger.exception('mwoauth.initiate failed')
        messages.error(req, _("OAuth handshake failed."))
        return shortcuts.redirect(next_page or '/')
    else:
        # Convert to unicode for session storage
        req.session[REQUEST_TOKEN_KEY] = utils.tuple_to_unicode(request_token)
        return shortcuts.redirect(redirect)
Пример #26
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
Пример #27
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
 def __init__(self,
              lang=None,
              enable_create_actions=True,
              enable_execute_actions=True):
     self.config = read_config_file(os.environ['CS_EXTRA_CONFIG_FILE'],
                                    __file__)
     # self.config = read_config_file(os.environ['CS_EXTRA_CONFIG_FILE'], __file__) #consider changing to os.path.abspath('')
     self.batch_size = int(os.getenv('CS_WIKIPEDIA_ACTION_BATCH_SIZE', 2))
     logging.info(f"Survey batch size set to : {self.batch_size}")
     self.db_session = init_session()
     self.lang = os.getenv('CS_WIKIPEDIA_LANG', lang)
     logging.info(f"Survey sending language set to. {self.lang}")
     self.consumer_token = mwoauth.ConsumerToken(
         os.environ['CS_OAUTH_CONSUMER_KEY'],
         os.environ['CS_OAUTH_CONSUMER_SECRET'])
     self.max_send_errors = int(
         os.getenv('CS_OAUTH_THANKS_MAX_SEND_ERRORS', 5))
     self.intervention_type = self.config['settings']['intervention_type']
     self.intervention_name = self.config['settings']['intervention_name']
     self.api_con = None  # a slot for a connection or session to keep open between different phases.
     self.dry_run = bool(int(os.getenv('CS_DRY_RUN', False)))
     self.enable_create_actions = enable_create_actions
     self.enable_execute_actions = enable_execute_actions
Пример #29
0
    cursor = db.connection.cursor()
    cursor.execute("""
        SELECT lang, code
        FROM languages
        """)
    results = cursor.fetchall()
    languages = {"Q" + str(k): v for k, v in results}
    cursor.close()

wdqurl = "https://query.wikidata.org/sparql?format=json&query="
wdapiurl = "https://www.wikidata.org/w/api.php"

# Load configuration from YAML file
__dir__ = os.path.dirname(__file__)
app.config.update(yaml.safe_load(open(os.path.join(__dir__, "config.yaml"))))
consumer_token = mwoauth.ConsumerToken(app.config["CONSUMER_KEY"],
                                       app.config["CONSUMER_SECRET"])


def runquery(query):
    url = wdqurl + urllib.parse.quote_plus(query)
    r = requests.get(url)
    if r.status_code == 200:
        return r.json()["results"]
    else:
        return None


def get_tokens(tokentype, auth):
    params = {
        "action": "query",
        "format": "json",
Пример #30
0
from translations import translations

app = OrderedFlask(__name__)
app.session_interface.serializer.register(TagOrderedMultiDict, index=0)
app.session_interface.serializer.register(TagImmutableOrderedMultiDict,
                                          index=0)

user_agent = toolforge.set_user_agent('lexeme-forms',
                                      email='*****@*****.**')

__dir__ = os.path.dirname(__file__)
try:
    with open(os.path.join(__dir__, 'config.yaml')) as config_file:
        app.config.update(yaml.safe_load(config_file))
        consumer_token = mwoauth.ConsumerToken(
            app.config['oauth']['consumer_key'],
            app.config['oauth']['consumer_secret'])
except FileNotFoundError:
    print('config.yaml file not found, assuming local development setup')
    app.secret_key = 'fake'


@app.before_request
def fixSessionToken():
    """Fix the session token after its path was changed.

    Old versions of this tool on Toolforge used '/' for the session
    cookie path, which was insecure, sending our session cookie to
    other tools as well. However, changing it to the tool name does
    not invalidate the old cookie, so the first time a client visits
    the tool again after this change was made, when we try to update