Example #1
0
def logincallback():
    """Finialize OAuth login."""
    request_token = RequestToken(session['request_token_key'],
                                 session['request_token_secret'])
    access_token = handshaker.complete(request_token, request.query_string)

    session.pop('access_token_key', None)
    session.pop('access_token_secret', None)
    session.pop('username', None)

    identify = handshaker.identify(access_token)
    if not (identify['editcount'] >= 50
            and 'autoconfirmed' in identify['rights']):
        return render_template(
            'error.min.html',
            message='Due to ongoing abuse, you must be autoconfirmed '
            'with at least 50 edits on Commons to use this tool.',
            loggedin=True)

    session['access_token_key'], session['access_token_secret'] = \
        access_token.key, access_token.secret

    session['username'] = identify['username']

    return redirect(url_for('main'))
Example #2
0
    def get(self, request, *args, **kwargs):
        if 'oauth_request_token' not in request.session:
            messages.warning(request,
                             _("Something went wrong. Please try again."))
            return redirect(REDIRECT_TO)
        d = request.GET
        t = request.session['oauth_request_token']
        request_token = RequestToken(t[0].encode(), t[1].encode())
        s = f"oauth_verifier={d.get('oauth_verifier', '')}&oauth_token={d.get('oauth_token', '')}"
        try:
            access_token = complete(WIKIDATA_URL, CONSUMER_TOKEN,
                                    request_token, s)
        except OAuthException as e:
            logger.exception("OAuth error")
            messages.error(request,
                           _("Something went wrong. Please try again."))
            return redirect(REDIRECT_TO)

        request.user.wikidata_access_token = {
            'key': access_token.key.decode(),
            'secret': access_token.secret.decode(),
        }
        request.user.wikidata_access_token_created_at = timezone.now()
        request.user.save()

        messages.success(request, _("Authenticated successfully."))

        return redirect(REDIRECT_TO)
Example #3
0
def complete_login(request, consumer_token, cookie, rdb_session, root_path, api_log):
    # TODO: Remove or standardize the DEBUG option
    if DEBUG:
        identity = {'sub': 6024474,
                    'username': '******'}
    else:
        handshaker = Handshaker(WIKI_OAUTH_URL, consumer_token)

        with api_log.debug('load_login_cookie') as act:
            try:
                rt_key = cookie['request_token_key']
                rt_secret = cookie['request_token_secret']
            except KeyError:
                # in some rare cases, stale cookies are left behind
                # and users have to click login again
                act.failure('clearing stale cookie, redirecting to {}', root_path)
                cookie.set_expires()
                return redirect(root_path)

        req_token = RequestToken(rt_key, rt_secret)

        access_token = handshaker.complete(req_token,
                                           request.query_string)
        identity = handshaker.identify(access_token)

    userid = identity['sub']
    username = identity['username']
    user = rdb_session.query(User).filter(User.id == userid).first()
    now = datetime.datetime.utcnow()
    if user is None:
        user = User(id=userid, username=username, last_active_date=now)
        rdb_session.add(user)
    else:
        user.last_active_date = now

    # These would be useful when we have oauth beyond simple ID, but
    # they should be stored in the database along with expiration times.
    # ID tokens only last 100 seconds or so
    # cookie['access_token_key'] = access_token.key
    # cookie['access_token_secret'] = access_token.secret

    # identity['confirmed_email'] = True/False might be interesting
    # for contactability through the username. Might want to assert
    # that it is True.

    cookie['userid'] = identity['sub']
    cookie['username'] = identity['username']

    return_to_url = cookie.get('return_to_url')
    # TODO: Clean up
    if not DEBUG:
        del cookie['request_token_key']
        del cookie['request_token_secret']
        del cookie['return_to_url']
    else:
        return_to_url = '/'
    return redirect(return_to_url)
Example #4
0
def logincallback():
    """Finialize OAuth login."""
    request_token = RequestToken(session['request_token_key'],
                                 session['request_token_secret'])
    access_token = handshaker.complete(request_token, request.query_string)
    session['access_token_key'], session['access_token_secret'] = \
        access_token.key, access_token.secret

    return redirect(url_for('main'))
Example #5
0
def auth_meta_mw():
    """
    Callback for meta.wikimedia.org to send us authentication results.
    This is responsible for fetching existing users or creating new ones.
    If a new user is created, they get the default role of GUEST and
    an email or username to match their details from the OAuth provider.
    """
    try:
        handshaker = make_handshaker_mw()
        raw_req_token = session['request_token']
        request_token = RequestToken(key=raw_req_token[0],
                                     secret=raw_req_token[1])
        access_token = handshaker.complete(request_token, request.query_string)
        session['access_token'] = access_token

        identity = handshaker.identify(access_token)
        username = identity['username']
        userid = identity['sub']

        db_session = db.get_session()
        user = None
        try:
            user = db_session.query(UserStore).filter_by(
                meta_mw_id=userid).one()

        except NoResultFound:
            try:
                user = UserStore(
                    username=username,
                    meta_mw_id=userid,
                    role=UserRole.GUEST,
                )
                db_session.add(user)
                db_session.commit()
            except:
                db_session.rollback()
                raise

        except MultipleResultsFound:
            flash('Multiple users found with your id!!! Contact Administrator',
                  'error')
            return redirect(url_for('login'))

        user.login(db_session)
        if login_user(user):
            user.detach_from(db_session)
            del session['request_token']

    except Exception:
        flash('You need to grant the app permissions in order to login.',
              'error')
        app.logger.exception(traceback.format_exc())
        return redirect(url_for('login'))

    redirect_to = session.get('next') or url_for('home_index')
    return redirect(urllib2.unquote(redirect_to))
Example #6
0
def complete_login(request, consumer_token, cookie):
    handshaker = Handshaker(WIKI_OAUTH_URL, consumer_token)

    req_token = RequestToken(cookie['request_token_key'],
                             cookie['request_token_secret'])

    access_token = handshaker.complete(req_token, request.query_string)

    identity = handshaker.identify(access_token)

    userid = identity['sub']
    username = identity['username']

    cookie['userid'] = userid
    cookie['username'] = username
    # Is this OK to put in a cookie?
    cookie['oauth_access_key'] = access_token.key
    cookie['oauth_access_secret'] = access_token.secret

    return_to_url = cookie.get('return_to_url', '/')

    return redirect(return_to_url)
Example #7
0
def complete_login(request, consumer_token, cookie, rdb_session):
    handshaker = Handshaker(WIKI_OAUTH_URL, consumer_token)

    req_token = RequestToken(cookie['request_token_key'],
                             cookie['request_token_secret'])

    access_token = handshaker.complete(req_token, request.query_string)
    identity = handshaker.identify(access_token)

    userid = identity['sub']
    username = identity['username']
    user = rdb_session.query(User).filter(User.id == userid).first()
    now = datetime.datetime.utcnow()
    if user is None:
        user = User(id=userid, username=username, last_login_date=now)
        rdb_session.add(user)
    else:
        user.last_login_date = now

    # These would be useful when we have oauth beyond simple ID, but
    # they should be stored in the database along with expiration times.
    # ID tokens only last 100 seconds or so
    # cookie['access_token_key'] = access_token.key
    # cookie['access_token_secret'] = access_token.secret

    # identity['confirmed_email'] = True/False might be interesting
    # for contactability through the username. Might want to assert
    # that it is True.

    cookie['userid'] = identity['sub']
    cookie['username'] = identity['username']

    return_to_url = cookie.get('return_to_url')
    del cookie['request_token_key']
    del cookie['request_token_secret']
    del cookie['return_to_url']
    return redirect(return_to_url)