Пример #1
0
async def iam_login(request):
    client = request.app.iam_client

    # Check if is not redirect from provider
    if client.shared_key not in request.query:
        # Redirect client to provider
        return web.HTTPTemporaryRedirect(
            client.get_authorize_url(access_type='offline'))

    try:
        meta, userinfo = await auth.get_token_userinfo(request)
    except web.HTTPInternalServerError as e:
        raise e
    except Exception:
        return web.HTTPTemporaryRedirect(
            client.get_authorize_url(access_type='offline'))

    session = await aiohttp_session.get_session(request)
    session["userinfo"] = userinfo
    session["username"] = userinfo["name"]
    session["gravatar"] = utils.avatar(userinfo["email"], 26)
    session['organisation_name'] = userinfo['organisation_name']

    user_id = userinfo["sub"]

    redirect_response = web.HTTPFound("/")
    await aiohttp_security.remember(request, redirect_response, user_id)

    request.app.sla_loader = await sla.load_slas_as_task(request)

    return redirect_response
Пример #2
0
async def middleware(request, handler):
    path = request.url.path
    if len(path) > 100:
        return web.HTTPTemporaryRedirect('/nou')
    if request.url.path[-1] == '/' and request.url.path != '/':
        stripped_url = request.url.path.rstrip('/')
        return web.HTTPPermanentRedirect(stripped_url)
    r = await handler(request)
    if isinstance(r, str):
        r = web.Response(text=r, headers={'content-type': 'text/html'})
    content_types = {
        'css': 'text/css',
        'js': 'text/javascript',
        'html': 'text/html',
        'json': 'application/json',
        'xml': 'application/xml',
        'rss': 'application/rss+xml',
        'png': 'image/png'
    }
    # if r.content_type == 'application/octet-stream':
    parts = request.url.parts
    last_path = parts[-1]
    ext = last_path.rsplit('.', 1)[-1]
    if ext in content_types:
        r.content_type = content_types[ext]
    else:
        if r.content_type == 'application/octet-stream':
            r.content_type = 'text/plain'
    try:
        r = await custom_replace(r, request)
    except AttributeError:
        pass
    return r
    async def get(self, request: web.Request, camera_id: str,
                  event_id: str) -> web.Response:
        """ start a GET request. """

        authenticated = request.get(KEY_AUTHENTICATED, False)
        if not authenticated:
            token: str = request.query.get("token")
            if not token:
                raise web.HTTPUnauthorized()

            data: dict = self.hass.data.get(DOMAIN_DATA)
            data = data.get(MEDIA_SOURCE) if data else None
            tokens: List[str] = data.get(LONG_TOKENS) if data else None
            if not tokens or not token in tokens:
                raise web.HTTPUnauthorized()

        if not camera_id or not event_id:
            raise web.HTTPNotFound()

        data: Dict[str, dict] = self.hass.data[DOMAIN]
        base: ReolinkBase = (data[camera_id].get(BASE, None)
                             if camera_id in data else None)
        if not base:
            _LOGGER.debug("camera %s not found", camera_id)
            raise web.HTTPNotFound()

        file = unquote_plus(event_id)
        url = await base.api.get_vod_source(file)
        return web.HTTPTemporaryRedirect(url)
Пример #4
0
async def logout(request: web.Request) -> web.Response:
    session = await aiohttp_session.get_session(request)
    if "sp_user_id" in session:
        del session["sp_user_id"]
    return web.HTTPTemporaryRedirect(
        location=request.app.router["index"].url_for()
    )
Пример #5
0
async def link_redirect(request: web.Request):
    dataset = request.match_info['dataset']
    distribution = request.match_info['distribution']
    etag_if_none_match = conditional.parse_if_header(
        request, conditional.HEADER_IF_NONE_MATCH)
    if etag_if_none_match == '*':
        raise web.HTTPBadRequest(
            body='Endpoint does not support * in the If-None-Match header.')

    try:
        doc, etag = await request.app.hooks.storage_retrieve(
            app=request.app, docid=dataset, etags=etag_if_none_match)
    except KeyError:
        raise web.HTTPNotFound()
    if doc is None:
        raise web.HTTPNotModified(headers={'ETag': etag})
    headers = {'ETag': etag}
    resource_url = None
    for dist in doc.get('dcat:distribution', []):
        if dist.get('dc:identifier', None) == distribution:
            resource_url = dist.get('dcat:accessURL', None)
            break
    if resource_url is None:
        raise web.HTTPNotFound(headers=headers)
    raise web.HTTPTemporaryRedirect(location=resource_url, headers=headers)
Пример #6
0
async def so_callback(req: web.Request) -> web.Response:
    """Handle OAuth2 callback from stack exchange API.

    Expects code in query and exchanges it for a token.
    """
    if req.query.get("error"):
        return web.Response(text="Error: " + req.query.get("error"))

    res_code = req.query.get("code")
    if not res_code:
        return web.Response(text="Error: Missing code")

    def token_error(msg: str) -> web.Response:
        return web.Response(text=f"OAuth2 Token retrieval error: {msg}",
                            status=500)

    async with sess.post(
            "https://stackoverflow.com/oauth/access_token/json",
            data={
                "client_id": CLIENT_ID,
                "client_secret": CLIENT_SECRET,
                "code": res_code,
                "redirect_uri": REDIRECT_URI,
            },
    ) as r:
        if r.status != 200:
            text = await r.text()
            return token_error(text)
        data = await r.json()
        if "error_message" in data:
            return token_error(data.get("error_message"))
        if "access_token" not in data:
            return token_error("Missing token in response: " + str(data))
        return web.HTTPTemporaryRedirect(
            "/so/success?" + urlencode({"token": data["access_token"]}))
Пример #7
0
    async def get_request(self, request):
        '''
        Handle the request from client if leader, otherwise 
        redirect to the leader.
        '''
        self._log.info("%d: on request", self._index)

        if not self._is_leader:
            if self._leader != None:
                raise web.HTTPTemporaryRedirect(
                    self.make_url(self._nodes[self._leader],
                                  MessageType.REQUEST))
            else:
                raise web.HTTPServiceUnavailable()
        else:

            # print(request.headers)
            # print(request.__dict__)

            json_data = await request.json()

            # print("\t\t--->node"+str(self._index)+": on request :")
            # print(json_data)

            await self.preprepare(json_data)
            return web.Response()
Пример #8
0
    async def get_obs_request(self, get_obs_request):
        """
        Node function. If not leader, re-directs to leader.
        Calls preprepare function.
        :return:
        """
        if self._index != self.leader:  # if self is not leader redirect to leader
            raise web.HTTPTemporaryRedirect(make_url(self.leader, 'get_obs_request'))
        else:
            j = await get_obs_request.json()
            if self.observations_recieved is None:
                self.observations_recieved = {}
                self.time_started = time.time()
            self.observations_recieved[j['id'][0]] = j['data']
            
            #if not self._sent: print(self.observations_recieved)
            if ("LF" not in self.method) and (self.value_to_send is None) and (len(self.observations_recieved.keys()) >= ((2 * self._f) + 1)):
                vals = (list(self.observations_recieved.values()))
                self.value_to_send = np.array([ast.literal_eval(val) for val in vals])[0]
            elif (self.value_to_send is None) and (len(self.observations_recieved.keys()) >= ((2 * self._f) + 1)):   #### CHANGED THIS TO >=
                vals = (list(self.observations_recieved.values()))  # list of strings
                self.value_to_send = np.array([ast.literal_eval(val) for val in vals])
                self.value_to_send = np.median(self.value_to_send, axis=0)

            if self.value_to_send is not None and not self._sent:
                self._sent = True
                self.log(f"VALUE TO SEND: {self.value_to_send}")
                request = {
                    'leader': self._index,
                    'data': json.dumps(self.value_to_send.tolist())}
                await self.preprepare(request)
                return web.Response()
Пример #9
0
async def handle_logout(request):
    session = await get_session(request)
    sid = session.get('id')
    if sid is not None:
        db_sessions.delete_one({'_id': ObjectId(sid)})
    session.invalidate()
    return web.HTTPTemporaryRedirect(location="/")
Пример #10
0
 def get(self):
     item = self.ctx.get('submittedhomework', self.request.match_info['id'])
     for homework in item.course.children['homework']:
         if f'SubmittedHomework-{self.id}' in homework.meta['children']:
             raise web.HTTPTemporaryRedirect(
                 f'/homework/{homework.meta["id"]}/submissions/{self.id}')
     raise web.HTTPServerError
Пример #11
0
def icon_redirect(request):
    filename = request.match_info['filename']
    try:
        icon = ICON_MAPPING[filename]
    except KeyError:
        raise web.HTTPNotFound
    raise web.HTTPTemporaryRedirect(
        f'https://fonts.gstatic.com/s/i/materialicons/{icon}/v6/24px.svg')
Пример #12
0
 async def wrapped(request: web.Request) -> web.Response:
     session = await aiohttp_session.get_session(request)
     auth = session.get("spotify_auth")
     if auth is None:
         raise web.HTTPTemporaryRedirect(
             location=request.app["spotify_app"].router["auth"].url_for(
             ).with_query(redirect=request.url.path))
     return await handler(request, SpotifyAuth(*auth))
Пример #13
0
async def confirm_18plus(request):
    target = request.query.get('next')
    if target is None:
        return web.HTTPTemporaryRedirect('/')
    if not is_safe_url(request, target):
        return web.HTTPBadRequest()
    if '18+' in request.cookies:
        return web.HTTPTemporaryRedirect(target)
    is_18plus = request.query.get('confirm')
    if is_18plus is None:
        return await render_template('confirm-18+.html', target=target)
    elif is_18plus == 'false':
        response = web.HTTPTemporaryRedirect('/')
        return response
    response = web.HTTPTemporaryRedirect(target)
    response.set_cookie('18+', '', max_age=ONE_YEAR)
    return response
Пример #14
0
 async def playlists_handler(self, request):
     try:
         display_list = await self.spotify_controller.get_user_playlists()
         return web.json_response(display_list)
     except requests.exceptions.HTTPError:
         self.goback = request.raw_path
         raise web.HTTPTemporaryRedirect('/auth')
     except:
         logger.info('error getting user playlists', exc_info=True)
         return web.json_response([])
Пример #15
0
    async def move(request: web.Request):
        raw_state = request.match_info['state']
        post_data = await request.post()
        move1 = Pot(int(post_data['pot']))

        state = State([int(x) for x in raw_state.split(',')])
        if move1 not in state.possible_moves(Player.ONE):
            raise web.HTTPTemporaryRedirect(f"/game/{state.to_web}")

        state = state.move(Player.ONE, move1)
        if not state.possible_moves(Player.ONE) or not state.possible_moves(Player.TWO):
            raise web.HTTPTemporaryRedirect(f"/end/{state.to_web}")

        move2 = state.suggest(Player.TWO)
        state = state.move(Player.TWO, move2)
        if not state.possible_moves(Player.ONE) or not state.possible_moves(Player.TWO):
            raise web.HTTPTemporaryRedirect(f"/end/{state.to_web}")

        raise web.HTTPTemporaryRedirect(f"/game/{state.to_web}")
Пример #16
0
async def on_github_login(request: web.Request, github_token):
    session = await get_session(request)

    async with request.app["session"].get(
        "https://api.github.com/user",
        headers={"Authorization": f"Bearer {github_token['access_token']}"},
    ) as r:
        session["user"] = await r.json()

    return web.HTTPTemporaryRedirect(location="/")
Пример #17
0
    async def get(self) -> web.Response:
        params = {
            'client_id': self.request.app['CLIENT_ID'],
            'redirect_uri': redirect_uri(self.request),
            'response_type': 'code',
            **self.request.app['AUTH_EXTRAS'],
        }

        if self.request.app['SCOPES']:
            params['scope'] = " ".join(self.request.app['SCOPES'])
        location = str(URL(self.request.app['AUTHORIZE_URL']).with_query(params))
        return web.HTTPTemporaryRedirect(location=location)
Пример #18
0
async def readFileHandler(request):
    filename = request.match_info['filename']
    response = await readFile(filename)
    if response:
        if isinstance(response, str):
            # print('http://{}/file/{}'.format(response,filename))
            raise web.HTTPTemporaryRedirect('http://{}/file/{}'.format(
                response, filename))
        else:
            return web.Response(body=response)
    else:
        raise web.HTTPNotFound
Пример #19
0
 async def redirect_handler(self, request):
     # this is part of the actual spotify service authentication callback after manual authentication
     try:
         vals = self.get_query_string_variables(request.query_string)
         if 'code' in vals:
             code = vals['code']
             result = await self.spotify_controller.set_token(code)
     except:
         logger.error(
             '.. Error handling Spotify redirect callback after manual authentication',
             exc_info=True)
     raise web.HTTPTemporaryRedirect('/')
Пример #20
0
async def auth(request: web.Request) -> web.Response:
    session = await get_session(request)
    session["spotify_target_url"] = request.query.get("redirect")

    # Generate a state token
    state = secrets.token_urlsafe()
    session["spotify_state"] = state

    # Construct the redirect URL
    location = request.app["spotify_client"].get_oauth_url(state=state)

    return web.HTTPTemporaryRedirect(location=str(location))
Пример #21
0
    async def setpreview_handler(self, request):

        try:
            playlist = await self.spotify_controller.get_playlist(
                request.match_info['playlist'])
            return web.json_response(playlist)
        except requests.exceptions.HTTPError:
            self.goback = request.raw_path
            raise web.HTTPTemporaryRedirect('/auth')
        except:
            logger.info('error getting playlist', exc_info=True)
            return web.json_response([])
Пример #22
0
async def get_shortener(request: web.Request):
    id = request.match_info['id']
    if id is None:
        return web.HTTPBadRequest()
    doc = await request.app['db'].url_shortener.urls.find_one_and_update(
        {'id': id}, {'$inc': {
            'count': 1
        }})
    if doc is None:
        return web.HTTPNotFound()
    url = doc['url']
    return web.HTTPTemporaryRedirect(url)
Пример #23
0
async def blog_post_new(request):
    form = await request.post()
    username = await get_username(request)
    if username is None:
        return web.HTTPTemporaryRedirect('/blog/login')
    body = form['body']
    title = form['title']
    print(form)
    unlisted = form.get('unlisted', 'off') == 'on'
    r = await db.new_blog_post(title, body, username, unlisted=unlisted)
    print(r)
    return web.HTTPFound(f'/blog/post/{r}')
Пример #24
0
async def blog_post_preview(request):
    form = await request.post()
    username = await get_username(request)
    if username is None:
        return web.HTTPTemporaryRedirect('/blog/login')
    body = form['body']
    title = form['title']
    post = db.get_blog_post_dict(title, body, username)
    post = await db.convert_post(post, get_html=True)
    return await load_template('blogpost.html',
                               p=post,
                               is_admin=False,
                               is_preview=True)
Пример #25
0
async def on_google_login(request: web.Request, login_data: Dict[str, Any]):
    session = await get_session(request)
    id_token = login_data.get('id_token')
    access_token = login_data.get('access_token')
    logger.debug('token: ' + str(id_token))
    logger.debug('session: ' + str(session))
    logger.debug('access_token: ' + str(access_token))
    async with request.app['session'].get(
            'https://oauth2.googleapis.com/tokeninfo?id_token=' + id_token,
            headers={'Authorization': f'Bearer {access_token}'},
    ) as r:
        user_info = await r.json()
        session['user'] = user_info.get('name')
    return web.HTTPTemporaryRedirect(location="/")
Пример #26
0
    async def test_donate(self, data: web.Request):
        # update_config()
        print(f"New test donation amount: {data.query['size']}",
              file=sys.stderr)

        donation = Donation({
            "additional_data": "{}",
            "amount_main": int(data.query["size"]),
            "username": "******"
        })

        await self.callback(donation)
        # asyncio.get_running_loop().create_task(self.callback(donation))
        # asyncio.get_running_loop().create_task()
        return web.HTTPTemporaryRedirect("/")
Пример #27
0
    async def playlist_handler(self, request):
        try:
            display_list = []
            name = request.match_info['playlist']
            playlist = self.spotify_controller.get_user_playlist(
                request.match_info['playlist'])
            display_list = self.spotify_controller.get_playlist_tracks(
                playlist['id'])
            return web.json_response(display_list)
        except requests.exceptions.HTTPError:
            self.goback = request.raw_path
            raise web.HTTPTemporaryRedirect('/auth')

        except:
            logger.info('error getting playlist', exc_info=True)
            return web.json_response([])
Пример #28
0
    async def get(self) -> web.Response:
        params = {
            "client_id": self.request.app["CLIENT_ID"],
            "redirect_uri": redirect_uri(self.request),
            "response_type": "code",
            # "state": TODO
            **self.request.app["AUTH_EXTRAS"],
        }

        if self.request.app["SCOPES"]:
            params["scope"] = " ".join(self.request.app["SCOPES"])

        location = str(
            URL(self.request.app["AUTHORIZE_URL"]).with_query(params))

        return web.HTTPTemporaryRedirect(location=location)
Пример #29
0
async def facebook_login(request):
    session = await get_session(request)
    config = request.app['config']
    params = request.url.query
    if 'error_reason' in params:
        return web.HTTPForbidden(text=("You denied us because: "
                                       "{error_description}").format(**params))
    token_request_params = {
        "client_id": config['facebook']['app_id'],
        "redirect_uri": config['facebook']['redirect_uri'],
        "client_secret": config['facebook']['app_secret'],
        "code": params['code'],
    }

    access_token_url = "https://graph.facebook.com/v2.8/oauth/access_token"
    url = requests.build_url(access_token_url, token_request_params)
    access_token = await requests.get_json(url)

    fb_url = ("https://graph.facebook.com/v2.8/me?fields=email,name,"
              "verified,albums.order(reverse_chronological).limit(1)"
              "&access_token={access_token}").format(**access_token)
    user_data = await requests.get_json(fb_url)

    if not user_data['verified']:
        raise web.HTTPForbidden(text="facebook_not_verified")
    first_album_date = user_data['albums']['data'][0]["created_time"]
    min_account_age = timedelta(days=365.25 *
                                int(config['facebook']['min_account_years']))
    now = datetime.now(timezone.utc)
    if abs(date_parser(first_album_date) - now) < min_account_age:
        raise web.HTTPForbidden(text="facebook_account_not_old_enough")

    user_data['id'] = obscure_id(int(user_data['id']),
                                 config['server']['fernet_secret'], 'facebook')

    try:
        userid = request.app['db'].new_user(user_data['name'],
                                            user_data['email'],
                                            user_data['id'],
                                            access_token['access_token'])
    except db.UserAlreadyExists:
        userid = user_data['id']
    finally:
        session['userid'] = userid
        session['name'] = user_data['name']

    return web.HTTPTemporaryRedirect('/login', body=b'Redirecting...')
Пример #30
0
async def handle_success(request: web.Request,
                         auth: api.SpotifyAuth) -> web.Response:
    handler = request.app.get("spotify_handle_auth")
    if handler is not None:
        await handler(request, auth)

    handler = request.app.get("spotify_on_success")
    if handler is not None:
        return await handler(request, auth)

    session = await get_session(request)
    target_url = session.get("spotify_target_url")
    if target_url is None:
        target_url = request.app["spotify_default_redirect"]
        if target_url is None:
            return web.Response(body="authorized")

    return web.HTTPTemporaryRedirect(location=target_url)