Esempio n. 1
0
def token_endpoint():
    if request.method == 'POST':
        code = request.form.get('code')
        me = request.form.get('me')
        redirect_uri = request.form.get('redirect_uri')
        client_id = request.form.get('client_id')

        auth = DB.indieauth.find_one({
            'code': code,
            'me': me,
            'redirect_uri': redirect_uri,
            'client_id': client_id
        })
        if not auth:
            abort(403)
        scope = ' '.join(auth['scope'])
        payload = dict(me=me,
                       client_id=client_id,
                       scope=scope,
                       ts=datetime.now().timestamp())
        token = JWT.dumps(payload).decode('utf-8')

        return build_auth_resp({
            'me': me,
            'scope': scope,
            'access_token': token
        })

    # Token verification
    token = request.headers.get('Authorization').replace('Bearer ', '')
    try:
        payload = JWT.loads(token)
    except BadSignature:
        abort(403)

    # TODO(tsileo): handle expiration

    return build_auth_resp({
        'me': payload['me'],
        'scope': payload['scope'],
        'client_id': payload['client_id'],
    })
Esempio n. 2
0
def _api_required():
    if session.get('logged_in'):
        #if request.method not in ['GET', 'HEAD']:
        #    # If a standard API request is made with a "login session", it must havw a CSRF token
        #    csrf.protect()
        return

    # Token verification
    token = request.headers.get('Authorization', '').replace('Bearer ', '')
    if not token:
        # IndieAuth token
        token = request.form.get('access_token', '')

    # Will raise a BadSignature on bad auth
    payload = JWT.loads(token)
    logger.info(f'api call by {payload}')
Esempio n. 3
0
def _api_required() -> None:
    if session.get("logged_in"):
        if request.method not in ["GET", "HEAD"]:
            # If a standard API request is made with a "login session", it must havw a CSRF token
            csrf.protect()
        return

    # Token verification
    token = request.headers.get("Authorization", "").replace("Bearer ", "")
    if not token:
        # IndieAuth token
        token = request.form.get("access_token", "")

    # Will raise a BadSignature on bad auth
    payload = JWT.loads(token)
    app.logger.info(f"api call by {payload}")
Esempio n. 4
0
def token_endpoint():
    # Generate a new token with the returned access code
    if request.method == "POST":
        code = request.form.get("code")
        me = request.form.get("me")
        redirect_uri = request.form.get("redirect_uri")
        client_id = request.form.get("client_id")

        now = datetime.now()
        ip, geoip = _get_ip()

        # This query ensure code, client_id, redirect_uri and me are matching with the code request
        auth = DB.indieauth.find_one_and_update(
            {
                "code": code,
                "me": me,
                "redirect_uri": redirect_uri,
                "client_id": client_id,
                "verified": False,
            },
            {
                "$set": {
                    "verified": True,
                    "verified_by": "code",
                    "verified_at": now.timestamp(),
                    "ip_address": ip,
                    "geoip": geoip,
                }
            },
        )

        if not auth:
            abort(403)

        scope = auth["scope"].split()

        # Ensure there's at least one scope
        if not len(scope):
            abort(400)

        # Ensure the code is recent
        if (now - datetime.fromtimestamp(auth["ts"])) > timedelta(minutes=5):
            abort(400)

        payload = dict(me=me, client_id=client_id, scope=scope, ts=now.timestamp())
        token = JWT.dumps(payload).decode("utf-8")
        DB.indieauth.update_one(
            {"_id": auth["_id"]},
            {
                "$set": {
                    "token": token,
                    "token_expires": (now + timedelta(minutes=30)).timestamp(),
                }
            },
        )

        return build_auth_resp(
            {"me": me, "scope": auth["scope"], "access_token": token}
        )

    # Token verification
    token = request.headers.get("Authorization").replace("Bearer ", "")
    try:
        payload = JWT.loads(token)
    except BadSignature:
        abort(403)

    # Check the token expritation (valid for 3 hours)
    if (datetime.now() - datetime.fromtimestamp(payload["ts"])) > timedelta(
        minutes=180
    ):
        abort(401)

    return build_auth_resp(
        {
            "me": payload["me"],
            "scope": " ".join(payload["scope"]),
            "client_id": payload["client_id"],
        }
    )