Ejemplo n.º 1
0
    async def authorized(request: Request) -> RedirectResponse:

        # see https://github.com/Azure-Samples/ms-identity-python-webapp/blob/e342e93a2a7e0cc4d4955c20660e6a81fd2536c5/app.py#L35-L45
        # for try except pattern. Kind of annoying, means you may have to click sign in twice
        try:
            cache = msal.SerializableTokenCache()

            flow = request.session.get("flow", {})
            result = build_msal_app(
                cache=cache).acquire_token_by_auth_code_flow(
                    flow,
                    dict(request.query_params),
                    scopes=get_auth_settings().scopes,
                )

            # Remove flow cookie
            request.session.pop("flow", None)

            # Just store the oid (https://docs.microsoft.com/en-us/azure/active-directory/develop/id-tokens) in a signed cookie
            oid = result.get("id_token_claims").get("oid")
            await f_save_cache(oid, cache)
            request.session["user"] = oid
        except ValueError as error:
            logging.debug("%s", error)

        return RedirectResponse(url=request.url_for("home"), status_code=302)
async def get_detect_image(
    request: Request,
    taskId: str,
    # token: str = Query(...),
) -> Any:
    job = run_yolo.AsyncResult(taskId)
    if job.state == "PENDING":
        return dict(status=job.state, progress=0)
    elif job.state == "PROGRESS":
        return dict(status=job.state, progress=job.result['progress'])
    elif job.state == "SUCCESS":
        detections_thumb = request.url_for(
            "images", path=f"{taskId}/thumbs/detections.jpg")
        detected_objs = []
        # for file in (Path(IMAGE_DIRECTORY) / taskId / "objects" / "thumbs").iterdir():
        for file in os.listdir(
                str(Path(IMAGE_DIRECTORY) / taskId / "objects" / "thumbs")):
            url = request.url_for("images",
                                  path=f"{taskId}/objects/thumbs/{file}")
            obj = dict(src=url, file=file)
            detected_objs.append(obj)
        return dict(
            status=job.state,
            progress=1,
            image=detections_thumb,
            objs=detected_objs,
            taskId=taskId,
            detectPlateUrl=request.url_for("detect-plate"),
            detectColoursUrl=request.url_for("detect-colours"),
        )
    else:
        return dict(status="FAILURE", progress=1)
Ejemplo n.º 3
0
async def login(request: Request, provider: OAuthProvider):
    if provider is OAuthProvider.GOOGLE:
        redirect_uri = request.url_for('authorize_google')
        return await oauth.google.authorize_redirect(request, redirect_uri)
    elif provider is OAuthProvider.GITHUB:
        redirect_uri = request.url_for('authorize_github')
        return await oauth.github.authorize_redirect(request, redirect_uri)
Ejemplo n.º 4
0
async def login_redirect(
        request: Request,
        code: str = Query(  # noqa: B008
            ...,
            title="Secret code for getting Spotify Web API token"),
        state: str = Query(...,
                           title="State for this login attempt"),  # noqa: B008
) -> Union[RedirectResponse, JSONResponse]:
    _check_initialized()
    session_state = request.session.pop("state", None)
    next_url = request.session.pop("next_url", "/")
    if session_state != state:
        return envelope(
            description="State in session and request don't match!",
            status=status.HTTP_409_CONFLICT,
        )

    try:
        token: TekoreToken = await _credentials.request_user_token(code)
    except (ClientError, ServerError):
        _logger.exception("Error during request for user token:")
        return envelope(
            description="Cannot obtain token with provided code!",
            status=status.HTTP_401_UNAUTHORIZED,
        )

    with _api.token_as(token) as api:
        # TODO: REFACTOR. Wrap this in try-catch block (request can fail)
        user: PrivateUser = await api.current_user()

    # TODO: REFACTOR. Wrap this in try-catch block (INSERT can fail)
    await Token.upsert(user.id, token)
    request.session["scope"] = str(token.scope)
    request.session["user"] = user.id
    return RedirectResponse(next_url)
Ejemplo n.º 5
0
async def forredirect(request: Request, db: Session = Depends(get_db)):
    if request.query_params["state"] != request.session["state"]:
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST)

    code = request.query_params["code"]
    params = {
        "code": code,
        "client_id": osenv.GOOGLE_CLIENT_ID,
        "client_secret": osenv.GOOGLE_CLIENT_SECRET,
        'redirect_uri': f'{request.base_url}forredirect',
        "grant_type": "authorization_code",
    }
    res = requests.post(urls.GOOGLE_GET_TOKEN_URL, data=params)
    response_json = res.json()
    id_token = response_json.get('id_token')
    res_info = jwt.decode(id_token, options={"verify_signature": False})
    user_email = res_info.get('email')
    user_name = res_info.get('given_name')
    request.session['user_email'] = user_email
    request.session['user_name'] = user_name
    request.session['user_token'] = response_json['access_token']
    email = schemas.UserCreate(email=user_email)
    db_user = crud.get_user_by_email(db=db, email=user_email)
    if db_user:
        if not crud.get_user_hiragana_score(db=db, user_id=db_user.id):
            crud.create_user_scoreboard(db=db, user_id=db_user.id)
    else:
        current_db_user = crud.create_user(db=db, user=email)
        crud.create_user_scoreboard(db=db, user_id=current_db_user.id)
    return RedirectResponse('/')
Ejemplo n.º 6
0
async def login(request: Request, code: str = None, state: str = None, error: str = None):
    if not code:
        state = token_urlsafe()
        auth_url = make_discord_session().get_authorize_url(scope='identify guilds', redirect_uri=urljoin(LOG_URL, request.url.path), state=state)
        request.session['oauth2_state'] = state
        return RedirectResponse(auth_url)

    if error:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail=f'There was an error authenticating with discord: {error}'
        )

    #Verify state
    if request.session.get('oauth2_state') != state:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=f'State mismatch'
        )

    # Fetch token
    discord = make_discord_session()

    try:
        await discord.get_access_token(code, redirect_uri=urljoin(LOG_URL, request.url.path))

    except Exception as e:
        traceback.print_exc()
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail=f'There was an error authenticating with discord: {e}'
        )

    user = DiscordUser.parse_obj(await discord.request('GET', 'users/@me'))
    guilds = [Guild.parse_obj(obj) for obj in await discord.request('GET', 'users/@me/guilds') if int(obj.get('permissions')) & 32]

    log_guilds = list(map(int, await logs.distinct('guild_id')))

    if not any(x.id in log_guilds for x in guilds):
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail=f'You do not have access to modlogs in any guilds'
        )

    doc = await users.find_one_and_update(
        {'id': user.id},
        {"$set": {
            **user.dict(),
            **{"guilds": [guild.id for guild in guilds]}
        }},
        upsert=True,
        return_document=ReturnDocument.AFTER
    )

    request.session["user"] = SERIALIZER.dumps(str(doc.get('_id')))

    target = SERIALIZER.loads(request.session.get('goto')) or app.url_path_for('root')
    return RedirectResponse(target)
Ejemplo n.º 7
0
async def main(request: Request,
               xmlFile: List[bytes] = File(...),
               typesystemFile: List[bytes] = File(...)):
    print(request.body())
    print(request.form())

    # file_like = open(video_path, mode="rb")
    # return StreamingResponse(file_like, media_type="video/mp4")
    return {"filenames": [f.filename for f in file]}
Ejemplo n.º 8
0
def read_department(request:Request, department_id):
	department = db.query(models.Department).get(department_id)
	if not department:
		raise HTTPException(status_code=404, detail=f"Could not find Department with ID {department_id}")
	_links = {}
	_links.update({"self" : request.url_for("read_department", department_id=department.id)})
	_links.update({"collection" : request.url_for("read_departments")})
	_links.update({"users" : request.url_for("read_department_users", department_id=department_id)})
	department.__setattr__("_links", _links)
	return {'data':department}
Ejemplo n.º 9
0
def read_departments(request:Request, offset=0, limit=100):
	total = db.query(models.Department).count()
	departments = db.query(models.Department).offset(offset).limit(limit).all()	
	for department in departments:
		_links = {}
		_links.update({"self" : request.url_for("read_department", department_id=department.id)})
		_links.update({"collection" : request.url_for("read_departments")})
		_links.update({"users" : request.url_for("read_department_users", department_id=department.id)})
		department.__setattr__("_links", _links)
	return {'data':departments, 'total':total, 'offset':offset, 'limit':limit}
Ejemplo n.º 10
0
def read_users(request:Request, offset=0, limit=100):
	total = db.query(models.User).count()
	users = db.query(models.User).offset(offset).limit(limit).all()	
	for user in users:
		_links = {}
		_links.update({"self" : request.url_for("read_user", user_id=user.id)})
		_links.update({"collection" : request.url_for("read_users")})
		_links.update({"department" : request.url_for("read_department", department_id=user.department_id)})
		user.__setattr__("_links", _links)
	return {'data':users, 'total':total, 'offset':offset, 'limit':limit}
Ejemplo n.º 11
0
def read_user(request:Request, user_id):
	user = db.query(models.User).get(user_id)
	if not user:
		raise HTTPException(status_code=404, detail=f"Could not find User with ID {user_id}")			
	_links = {}
	_links.update({"self" : request.url_for("read_user", user_id=user.id)})
	_links.update({"collection" : request.url_for("read_users")})
	_links.update({"department" : request.url_for("read_department", department_id=user.department_id)})
	user.__setattr__("_links", _links)
	return {'data':user}
Ejemplo n.º 12
0
def create_department(request:Request, response: Response, department_data: schemas.DepartmentIn):
	department = models.Department(name=department_data.name)
	db.add(department)
	db.commit()
	_links = {}
	_links.update({"self" : request.url_for("read_department", department_id=department.id)})
	_links.update({"collection" : request.url_for("read_departments")})
	_links.update({"users" : request.url_for("read_department_users", department_id=department.id)})
	department.__setattr__("_links", _links)
	response.status_code = status.HTTP_201_CREATED
	return {'data':department}
Ejemplo n.º 13
0
async def login(
    request: Request,
    redirect: str = "/",
):
    logger.info("endpoint: login")

    if relative_url_regex.fullmatch(redirect) is None:
        redirect = "/"
    request.session["redirect"] = redirect
    redirect_uri = request.url_for("authorize")
    return await oauth.discord.authorize_redirect(request, redirect_uri)
Ejemplo n.º 14
0
async def oauth_in_post(request: Request, post_id=None):
    if post_id is None:
        url = '/'
    else:
        url = request.url_for('post', ident=post_id)
    if 'github_user' in request.session:
        return RedirectResponse(url)
    else:
        client = GithubClient()
        request.session['post_url'] = str(request.url)
        return RedirectResponse(client.auth_url)
def test_check_auth_error_auth_error():
    """Test: check_auth(request: Request) -> None
    Error: Auth error."""

    scope = {'type': 'http'}
    request = Request(scope)
    request._headers = Headers(headers={'X-Key': 'fake-key'})
    with pytest.raises(HTTPException) as ex:
        check_auth(request)
    assert ex.value.status_code == 400
    assert ex.value.detail == 'Auth error'
Ejemplo n.º 16
0
def create_user(request:Request, response: Response, user_data: schemas.UserIn):
	user = models.User(username=user_data.username, email=user_data.email)
	db.add(user)
	db.commit()
	_links = {}
	_links.update({"self" : request.url_for("read_user", user_id=user.id)})
	_links.update({"collection" : request.url_for("read_users")})
	_links.update({"department" : request.url_for("read_department", department_id=user.department_id)})
	user.__setattr__("_links", _links)
	response.status_code = status.HTTP_201_CREATED
	return {'data':user}
def test_check_auth_error_key_is_not_set():
    """Test: check_auth(request: Request) -> None
    Error: Key is not set."""

    scope = {'type': 'http'}
    request = Request(scope)
    request._headers = []
    with pytest.raises(HTTPException) as ex:
        check_auth(request)
    assert ex.value.status_code == 400
    assert ex.value.detail == 'Key is not set'
Ejemplo n.º 18
0
def temp_login_with_password(user: UserLogin, request: Request):
    if user.username == "user" and user.password == "pass":
        request.session['user'] = {'id': 1234, 'privilege': 1, 'username': user.username}
        return {'result': 'successful', 'privilege': 1}
    elif user.username == 'admin' and user.password == 'pass':
        request.session['user'] = {'id': 1235, 'privilege': 2, 'username': user.username}
        return {'result': 'successful', 'privilege': 2}
    elif user.username == 'op' and user.password == 'pass':
        request.session['user'] = {'id': 1236, 'privilege': 3, 'username': user.username}
        return {'result': 'successful', 'privilege': 3}
    else:
        return {'result': 'failed'}
Ejemplo n.º 19
0
def package_url(request: Request, package: Package, name: str = None) -> str:
    res: str = ""
    if name is None:
        res = request.url_for("package", package_name=name or package.name)
        res += "?repo=" + package.repo
        if package.repo_variant:
            res += "&variant=" + package.repo_variant
    else:
        res = request.url_for("package", package_name=re.split("[<>=]+", name)[0])
        if package.repo_variant:
            res += "?repo=" + package.repo
            res += "&variant=" + package.repo_variant
    return res
Ejemplo n.º 20
0
async def logout(request: Request):
    token = request.session.get('user_token')
    request.session['user_email'] = None
    request.session['user_name'] = None
    request.session['user_token'] = None
    token_revoke = f"https://oauth2.googleapis.com/revoke?token={token}"
    header = {"Content-type": "application/x-www-form-urlencoded"}
    requests.post(token_revoke, headers=header)
    request.get('https://mail.google.com/mail/u/0/?logout&hl=en')
    return templates.TemplateResponse("error.html", {
        "request": request,
        "message": "로그아웃이 완료되었습니다."
    })
Ejemplo n.º 21
0
def read_department_users(request:Request, department_id:int, offset=0, limit=100):
	department = db.query(models.Department).get(department_id)
	if not department:
		raise HTTPException(status_code=404, detail=f"Could not find Department with ID {department_id}")	
	total = department.users.count()
	users = department.users.offset(offset).limit(limit).all()
	for user in users:
		_links = {}
		_links.update({"self" : request.url_for("read_user", user_id=user.id)})
		_links.update({"collection" : request.url_for("read_users")})
		_links.update({"department" : request.url_for("read_department_users", department_id=user.department_id)})
		user.__setattr__("_links", _links)
	return {'data':users, 'total':total, 'offset':offset, 'limit':limit}
Ejemplo n.º 22
0
async def process_auth(req: Request, call_next):
    """ modfiy the request body of authentication """
    req.scope["root_path"] = config.HOST_PATH
    h_copy = req.headers.mutablecopy()
    h_copy["host"] = ''
    req.scope["headers"] = h_copy.raw
    if req.scope['path'] == '/' or 'page' in req.scope['path']:
        req.state.partials = config.partials
        response = await call_next(req)
    else:

        response = await call_next(req)
    return response
Ejemplo n.º 23
0
def root(request: Request) -> Links:
    """
    Provides the root of our project.
    """

    return Links(
        documentation=DocumentationURL(
            swagger_ui=request.url_for("custom_doc"),
            redoc=request.url_for("custom_redoc"),
        ),
        projects=ProjectsURL(),
        support=SupportURL(),
    )
Ejemplo n.º 24
0
    async def authorize(
        self,
        request: Request,
        dao: Dao = Depends(get_dao),
        config: Config = Depends(get_config),
    ):
        """{prefix}/authorize endpoint
        Entry point for user submitted data or callback for oauth applications.

        To configure HTTP method that this endpoint will handle, set authorize_methods.
        """

        user_dict = await self._authenticate(request, dao, config)

        if user_dict is None:
            return Response("login failed")

        if isinstance(user_dict, str):
            # wrap string in a dictionary
            user_data: UserDict = {"username": user_dict}
        else:
            user_data = user_dict

        default_profile: UserProfile = {
            "login": user_data["username"],
            "id": user_data["username"],
            "name": user_data["username"],
            "avatar_url": "",
            "emails": [],
        }

        profile: UserProfile = user_data.get("profile", default_profile)

        role = await self.authenticator.user_role(request, profile)
        default_channel = await self.authenticator.user_channels(request, profile)

        user = auth_dao.get_user_by_identity(
            dao, self.authenticator.provider, profile, config, role, default_channel
        )

        user_id = str(uuid.UUID(bytes=user.id))

        request.session['user_id'] = user_id
        request.session['identity_provider'] = self.authenticator.provider
        request.session.update(user_data.get("auth_state", {}))

        # use 303 code so that the method is always changed to GET
        resp = RedirectResponse('/', status_code=303)

        return resp
Ejemplo n.º 25
0
async def login(
    request: Request,
    state: str = Query(...,
                       title="State for this login attempt"),  # noqa: B008
    next_url: str = Query(
        "/", title="Where to redirect after success"),  # noqa: B008
    scope: Optional[List[str]] = Query(  # noqa: B008
        None, title="Scopes to request from Spotify"),
) -> RedirectResponse:
    _check_initialized()
    request.session["state"] = state
    request.session["next_url"] = next_url
    oauth_url = _credentials.user_authorisation_url(scope, state)
    return RedirectResponse(oauth_url)
Ejemplo n.º 26
0
async def api_oauth_callback(req: Request, resp: Response, code: str,
                             state: str):
    async with aiohttp.ClientSession() as session:
        oauth_token = await (await session.post(
            settings.OAUTH_TOKEN_ENDPOINT,
            params={
                "grant_type": "authorization_code",
                "code": code,
                "redirect_uri": req.url_for("api_oauth_callback"),
                "client_id": settings.OAUTH_CLIENT_ID,
                "client_secret": settings.OAUTH_CLIENT_SECRET,
            },
        )).json()
        logger.debug(f"oauth token data: {oauth_token}")
        if "access_token" not in oauth_token:
            raise HTTPException(
                status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
                detail="CTFTime error",
            )

        user_data = await (await session.get(
            settings.OAUTH_API_ENDPOINT,
            headers={"Authorization":
                     f"Bearer {oauth_token['access_token']}"})).json()
        logger.debug(f"User api token data: {user_data}")
        if "team" not in user_data or "id" not in user_data[
                "team"] or "name" not in user_data["team"]:
            raise HTTPException(
                status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
                detail="CTFTime error",
            )

        user = await db.get_user_oauth_id(user_data["team"]["id"])
        if user is None:
            user = await db.insert_oauth_user(
                user_data["team"]["id"], user_data["team"]["name"],
                user_data["team"].get("country", ""))
            metrics.users.inc()

        metrics.logons_per_user.labels(user_id=user.user_id,
                                       username=user.username).inc()

        access_token = auth.create_user_token(user)
        resp.set_cookie(key="access_token",
                        value=f"Bearer {access_token}",
                        httponly=True)

        resp.status_code = status.HTTP_307_TEMPORARY_REDIRECT
        resp.headers["Location"] = req.url_for("index")
    return "ok"
Ejemplo n.º 27
0
async def display_index(request: Request):
    """Return JSON with available table metadata. """
    return [
        TableMetadata(**table,
                      link=request.url_for("tilejson", table=table["id"]))
        for table in request.app.state.Catalog
    ]
Ejemplo n.º 28
0
async def send_message(request: Request, background: BackgroundTasks, name):
    if not name:
        raise HTTPException(status_code=400,
                            detail='You need to provide bot name')
    else:
        request_body = b''
        async for chunk in request.stream():
            request_body += chunk
        try:
            message = json.loads(request_body)
        except JSONDecodeError as e:
            LOGGER.log(
                logging.ERROR,
                msg="Got wrong JSON request from client, refusing processing")
            raise HTTPException(status_code=400, detail=dict(e.args))
        if message['access_token'] == running_bots[name].bot.access_token:
            if message['chat_id']:
                if 'asap' in message:
                    background.add_task(running_bots[name].send_to, message)
                    return 'ok'
                else:
                    try:
                        result = await running_bots[name].send_to(message)
                        return jsonable_encoder(result)
                    except Exception as e:
                        LOGGER.log(
                            logging.INFO,
                            msg='Failed to process send request because %s' %
                            e)
                        raise HTTPException(status_code=500,
                                            detail=jsonable_encoder(e))
        else:
            raise HTTPException(status_code=403, detail="Access denied.")
 def create_client(request: Request, item: Item = None):
     request.body = {}
     if item:
         request.body = {
             "client_name": item.client_name,
             "client_uri": item.client_uri,
             "redirect_uri": item.redirect_uri,
             "scope": item.scope,
             "software_statement": item.software_statement,
             "token_endpoint_auth_method":
             item.token_endpoint_auth_method,
             "grant_types": item.grant_types,
             "response_types": item.response_types,
         }
     return server.create_endpoint_response("client_registration",
                                            request=request)
Ejemplo n.º 30
0
    async def set_body(self, request: Request):
        _msg = await request._receive()

        async def new_receive():
            return _msg

        request._receive = new_receive