Exemplo n.º 1
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)
Exemplo n.º 2
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, '/'))
Exemplo n.º 3
0
def oauth_callback(req):
    """OAuth handshake callback."""
    serialized_token = req.session.get(constants.REQUEST_TOKEN_KEY, None)
    if serialized_token is None:
        messages.error(req, _("Session invalid."))
        return shortcuts.redirect(
            urls.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[constants.ACCESS_TOKEN_KEY] = utils.tuple_to_unicode(
        access_token)
    sul_user = mwoauth.identify(
        settings.OAUTH_MWURL, consumer_token, access_token)
    req.session[constants.OAUTH_USERNAME_KEY] = sul_user['username']
    req.session[constants.OAUTH_EMAIL_KEY] = sul_user['email']
    req.session[constants.OAUTH_REALNAME_KEY] = sul_user['realname']

    if req.user.is_authenticated:
        req.user.set_accesstoken(access_token)
        req.user.sulname = sul_user['username']
        req.user.sulemail = sul_user['email']
        req.user.realname = sul_user['realname']
        try:
            req.user.save()
            messages.info(
                req, _("Updated OAuth credentials for {user}".format(
                    user=sul_user['username'])))
        except IntegrityError:
            logger.exception('user.save failed')
            messages.error(
                req,
                _(
                    'Wikimedia account "{sul}" is already attached '
                    'to another LDAP account.'
                ).format(sul=sul_user['username']))
        except DatabaseError:
            logger.exception('user.save failed')
            messages.error(
                req,
                _("Error saving OAuth credentials. [req id: {id}]").format(
                    id=req.id))
    else:
        messages.info(
            req, _("Authenticated as OAuth user {user}".format(
                user=sul_user['username'])))

    return shortcuts.redirect(req.session.get(constants.NEXT_PAGE, '/'))
Exemplo n.º 4
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
Exemplo n.º 5
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))
Exemplo n.º 6
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')))
Exemplo n.º 7
0
def authentication_area():
    if 'oauth' not in app.config:
        return flask.Markup()

    if 'oauth_access_token' not in flask.session:
        return (flask.Markup(r'<a id="login" class="navbar-text" href="') +
                flask.Markup.escape(flask.url_for('login')) +
                flask.Markup(r'">Log in</a>'))

    access_token = mwoauth.AccessToken(**flask.session['oauth_access_token'])
    identity = mwoauth.identify(index_php,
                                consumer_token,
                                access_token)

    return (flask.Markup(r'<span class="navbar-text">Logged in as ') +
            user_link(identity['username']) +
            flask.Markup(r'</span>'))
Exemplo n.º 8
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':
            'Չստացվեց գտնել Ձեր գրանցման ամսաթիվը։ Խնդրում եմ կրկին '
            'փորձել կամ դիմել ԱշոտՏՆՂ մասնակցին, եթե խնդիրը '
            'շարունակվում է։։'
        })
Exemplo n.º 9
0
    def identity(self):
        """
        Get identifying information about a user via an authorized token.

        @rtype: None or dict
        """
        if self.access_token is None:
            pywikibot.error('Access token not set')
            return None
        consumer_token = mwoauth.ConsumerToken(self.consumer_token[0],
                                               self.consumer_token[1])
        access_token = mwoauth.AccessToken(self.access_token[0],
                                           self.access_token[1])
        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
Exemplo n.º 10
0
def oauth_callback():
    """OAuth handshake callback."""
    if 'request_token' not in flask.session:
        flask.flash(_('oauth-callback-failed-text'))
        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'))
Exemplo n.º 11
0
def oauth_callback():
    if 'request_token' not in session:
        flash('OAuth callback failed, do you have your cookies disabled?')
        return redirect('/')

    consumer_token = create_consumer_token()
    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:
        flash('OAuth callback caused an exception, aborting')
        app.logger.exception('OAuth callback failed')
    else:
        session['access_token'] = dict(zip(access_token._fields, access_token))
        session['username'] = identity['username']

    return redirect('/')
Exemplo n.º 12
0
def oauth_callback():
    """OAuth handshake callback."""
    if "request_token" not in flask.session:
        flask.flash("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"]

        user_payload = {
            flask.session["username"],
            flask.session["access_token"]["key"],
            flask.session["access_token"]["secret"],
        }

        bot_action("add", user_payload)

    return flask.redirect(flask.url_for("index"))
Exemplo n.º 13
0
sys.path.insert(0, ".")

try:
    creds_doc = json.load(open("credentials.do_not_commit.json"))
    consumer_key = creds_doc['consumer_key']
    consumer_secret = creds_doc['consumer_secret']
except FileNotFoundError:
    print('Couldn\'t find "credentials.do_not_commit.json". ' +
          'Please manually input credentials.')
    consumer_key = input('Consumer key: ')
    consumer_secret = input('Consumer secret: ')

consumer_token = ConsumerToken(consumer_key, consumer_secret)

mw_uri = "https://en.wikipedia.org/w/index.php"

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

# 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 = complete(mw_uri, consumer_token, request_token, response_qs)
print(str(access_token))

# Step 4: Identify -- (optional) get identifying information about the user
identity = identify(mw_uri, consumer_token, access_token)
print("Identified as {username} (id={sub}).".format(**identity))
Exemplo n.º 14
0
            flask.Markup(r'</a>'))


@app.template_global()
def authentication_area(){% if cookiecutter.set_up_mypy == "True" %} -> flask.Markup{% endif %}:
    if 'oauth' not in app.config:
        return flask.Markup()

    if 'oauth_access_token' not in flask.session:
        return (flask.Markup(r'<a id="login" class="navbar-text" href="') +
                flask.Markup.escape(flask.url_for('login')) +
                flask.Markup(r'">Log in</a>'))

    access_token = mwoauth.AccessToken(**flask.session['oauth_access_token'])
    identity = mwoauth.identify(index_php,
                                consumer_token,
                                access_token)

    return (flask.Markup(r'<span class="navbar-text">Logged in as ') +
            user_link(identity['username']) +
            flask.Markup(r'</span>'))


def authenticated_session(){% if cookiecutter.set_up_mypy == "True" %} -> Optional[mwapi.Session]{% endif %}:
    if 'oauth_access_token' not in flask.session:
        return None

    access_token = mwoauth.AccessToken(
        **flask.session['oauth_access_token'])
    auth = requests_oauthlib.OAuth1(client_key=consumer_token.key,
                                    client_secret=consumer_token.secret,