async def register_post( request: Request, user: RegisterForm = Depends(RegisterForm.as_form) ): database = request.app.state.db user_exist = await get_user_by_login(database, user.login) if user_exist: return templates.TemplateResponse( 'user_exists.html', { 'request': request, 'user': user_exist, } ) user_id = await create_user(database, user) current_user = UserReturnSchema(id=user_id, **user.dict()) token = jwt.encode( {'current_user': current_user.dict()}, settings.SECRET_KEY ) url_home = request.app.url_path_for('home') rr = RedirectResponse(url=url_home, status_code=status.HTTP_303_SEE_OTHER) rr.set_cookie( "session", token, expires=60 * settings.ACCESS_TOKEN_EXPIRE_MINUTES ) return rr
async def check_session(request: Request, call_next): session = request.cookies.get("session") print("REQUEST URL:") print(request.url) print("REQUEST PATH") print(request.url.path) if ( session is None and request.url.path not in not_logged_in_paths and not request.url.path.startswith("/favicon.ico") and not request.url.path.startswith("/static") ): response = RedirectResponse(url="/login") return response elif session is not None and request.url.path in not_logged_in_paths: response = RedirectResponse(url="/") return response response = await call_next(request) if request.url.path != "/user/logout" and session is not None: response.set_cookie( key="session", value=session, max_age=600, ) return response
async def language(request: Request, set_lang: str = Form(...), next: str = Form(...), q: str = Form(default=None)): """ A POST route used to set a session's language. Return a 303 See Other redirect to {next}?next={next}. If we are setting the language on any page, we want to preserve query parameters across the redirect. """ if next[0] != '/': return HTMLResponse(b"Invalid 'next' parameter.", status_code=400) query_string = "?" + q if q else str() # If the user is authenticated, update the user's LangPreference. if request.user.is_authenticated(): with db.begin(): request.user.LangPreference = set_lang # In any case, set the response's AURLANG cookie that never expires. response = RedirectResponse(url=f"{next}{query_string}", status_code=HTTPStatus.SEE_OTHER) secure = aurweb.config.getboolean("options", "disable_http_login") response.set_cookie("AURLANG", set_lang, secure=secure, httponly=secure, samesite=cookies.samesite()) return response
async def login(credentials: HTTPBasicCredentials = Depends(app.security)): if not credentials: raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Incorrect login or password", headers={"WWW-Authenticate": "Basic"}, ) correct_username = secrets.compare_digest(credentials.username, app.user['login']) correct_password = secrets.compare_digest(credentials.password, app.user['password']) if not (correct_username and correct_password): raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Incorrect login or password", headers={"WWW-Authenticate": "Basic"}, ) # session_token = sha256(str.encode(f"{credentials.username}:{app.secret_key}")).hexdigest() session_token = jwt.encode({ app.API_KEY: True }, app.secret_key).decode("utf-8") response = RedirectResponse(url='/welcome', status_code=status.HTTP_302_FOUND) response.set_cookie(app.API_KEY, session_token) # session = {'user': credentials.username, 'token': session_token} # tokens.append(session) return response
async def callback(*, provider: str, request: Request): check_provider(provider) state_query = request.query_params.get("state") state_session = request.session.get("state") if not check_state(state_query, state_session): raise HTTPException(403) code = request.query_params.get("code") service = SocialService() method = getattr(service, f"callback_{provider}") sid, email = await method(code) try: tokens = await service.resolve_user(provider, sid, email) response = RedirectResponse("/") response.set_cookie( key=access_cookie_name, value=tokens.get("access"), secure=not debug, httponly=True, max_age=access_expiration, ) response.set_cookie( key=refresh_cookie_name, value=tokens.get("refresh"), secure=not debug, httponly=True, max_age=refresh_expiration, ) return response except SocialException as e: return HTMLResponse(e.content, status_code=e.status_code)
def logout(): response = RedirectResponse(url="/app") response.set_cookie("session", value="", samesite="lax", httponly=True, expires=0) return response
async def set_service_cluster( request: Request, service_cluster: str = Query( '__any__', title='The clients envoy version to emulate in this XDS request'), ): url = request.headers.get('Referer', '/ui') response = RedirectResponse(url=url) response.set_cookie(key='service_cluster', value=service_cluster) return response
async def set_envoy_version( request: Request, version: str = Query( '__any__', title='The clients envoy version to emulate in this XDS request'), ): url = request.headers.get('Referer', '/ui') response = RedirectResponse(url=url) response.set_cookie(key='envoy_version', value=version) return response
async def login(username: t.Optional[str] = Form(None), password: t.Optional[str] = Form(None)): if not (all((username, password)) and auth.is_user(username, password)): raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Incorrect username or password", ) resp = RedirectResponse("/", status_code=303) resp.set_cookie(key="session_token", value=auth.create_session(username)) return resp
async def set_service_cluster( request: Request, service_cluster: str = Query( "__any__", title="The clients envoy version to emulate in this XDS request"), ) -> Response: url = request.headers.get("Referer", "/ui") response = RedirectResponse(url=url) response.set_cookie(key="service_cluster", value=service_cluster) return response
async def toggle_dark_mode(request: Request): response = RedirectResponse(url='/') if "darkmode" in request.cookies: darkmode = str(1 - int(request.cookies.get("darkmode"))) else: darkmode = "1" response.set_cookie("darkmode", darkmode, max_age=315360000, expires=315360000) return response
def login(credentials: HTTPBasicCredentials = Depends(security)): if credentials.username == "trudnY" and credentials.password == "PaC13Nt": app.user = credentials.username session_token = sha256( bytes( f"{credentials.username}{credentials.password}{app.secret_key}", encoding='utf8')).hexdigest() response = RedirectResponse(url='/welcome', status_code=301) response.set_cookie(key="session_token", value=session_token) app.tokens.append(session_token) return response raise HTTPException(status_code=401, detail="Unathorised")
async def login( form_data: OAuth2PasswordRequestForm = Depends(), db: Session = Depends(get_db) ): user_authenticated = authenticate_user(form_data.username, form_data.password, db) if not user_authenticated: raise HTTPException(status_code=401, detail="Invalid credentials") token = create_jwt_token(user_authenticated.username) response = RedirectResponse(url="/chat", status_code=HTTP_303_SEE_OTHER) response.set_cookie(key="Authorization", value=token) return response
def kakaopay(): url = "https://kapi.kakao.com/v1/payment/ready" APP_ADMIN_KEY = "" headers = { "Authorization": f"KakaoAK {APP_ADMIN_KEY}", "content-type": "application/x-www-form-urlencoded;charset=utf-8" } query = f"?cid=TC0ONETIME&partner_order_id=partner_order_id&partner_user_id=partner_user_id&item_name=초코파이&quantity=1&total_amount=2200&vat_amount=200&tax_free_amount=0&approval_url=http://localhost:8000/kakaopay/success&fail_url=http://localhost:8000/kakaopay/fail&cancel_url=http://localhost:8000/kakaopay/cancel" _res = requests.post(url=url + query, headers=headers) _result = _res.json() _next_redirect_pc_url = _result["next_redirect_pc_url"] _redirectUrl = RedirectResponse(_next_redirect_pc_url, ) _redirectUrl.set_cookie(key="ttid", value=str(_result["tid"])) return _redirectUrl
def login(user_data: (str, str) = Depends(check_creds)): passes = user_data[0] session_token = user_data[1] response = RedirectResponse(url="/welcome", status_code=status.HTTP_302_FOUND) response.headers["Location"] = "/welcome" response.set_cookie(key="session_token", value=session_token) # response.set_cookie(key="username", value=username) response.headers['Authorization'] = f"Basic {passes}" return response
async def login(credentials: HTTPBasicCredentials = Depends(security)): correct_username = secrets.compare_digest(credentials.username, user['login']) correct_password = secrets.compare_digest(credentials.password, user['password']) if not (correct_username and correct_password): raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Incorrect email or password", headers={"WWW-Authenticate": "Basic"}, ) session_token = sha256(str.encode(f"{credentials.username}{credentials.password}{SECRET_ACCESS_KEY}")).hexdigest() response = RedirectResponse(url="/welcome", status_code=status.HTTP_302_FOUND) response.set_cookie(key=SESSION_TOKEN, value=session_token) return response
async def auth_callback(request: Request) -> RedirectResponse: """Authenticate the user with Discord OAuth.""" user = await get_user_details(request.state.session, request.query_params["code"]) userid = int(user["id"]) username = user["username"] + "#" + user["discriminator"] avatar = user.get("avatar", None) session = await request.state.db.user_login(userid, username, avatar) response = RedirectResponse("/") response.set_cookie("moot_session_token", session.token) return response
async def edit(status: str = Form(...), nick: str = Form(...), userID: Optional[str] = Cookie(None)): name = userID.split(",") if name[0] != nick: if not database.search(nick): response = RedirectResponse(f"/user/{nick}") response.set_cookie(key="userID", value=f"{nick},{name[1]}") database.update(name[0], nick, status) return response else: database.update(name[0], nick, status) return RedirectResponse(f"/user/{name[0]}")
def create_cookie(credentials: HTTPBasicCredentials = Depends(security)): username_pass = secrets.compare_digest(credentials.username, 'trudnY') password_pass = secrets.compare_digest(credentials.password, 'PaC13Nt') if not (username_pass and password_pass): raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Incorrect pass", ) session_token = sha256( str.encode( f"{credentials.username}{credentials.password}{router.secret_key}") ).hexdigest() response = RedirectResponse(url='/welcome', status_code=status.HTTP_302_FOUND) response.set_cookie(key="session_token", value=session_token) return response
async def set(request: Request, stem: Optional[int] = Query(DEFAULTS['stem'], ge=0, le=1), darkmode: Optional[int] = Query(DEFAULTS['darkmode'], ge=0, le=1), maxresults: Optional[int] = Query(DEFAULTS['maxresults'], ge=0), perpage: Optional[int] = Query(DEFAULTS['perpage'], ge=10, le=50), context: Optional[int] = Query(DEFAULTS['context'], ge=0), maxchars: Optional[int] = Query(DEFAULTS['maxchars'], ge=0), csvfields: Optional[str] = DEFAULTS['csvfields']): response = RedirectResponse(url='/') for setting in available_settings: response.set_cookie(setting, request.query_params[setting], max_age=315360000, expires=315360000) return response
async def post_consent(request: Request, idp: str = Form(default=None), webid: str = Form(default=None)): nonce = secrets.token_hex(10) if idp is not None: idp_config = consent.get_idp_config(idp) elif webid is not None: idp = consent.get_webid_idp(webid) print(idp) idp_config = consent.get_idp_config(idp) else: raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail="Please provide a Webid or Identity Provider.", ) code_request = consent.prepare_code_request(nonce) code_params = urllib.parse.urlencode(code_request) auth_url = idp_config['authorization_endpoint'] + '?' + code_params response = RedirectResponse(auth_url, status_code=303) response.set_cookie(key="challenge_secret", value=nonce, httponly=True) response.set_cookie(key="token_endpoint", value=idp_config['token_endpoint'], httponly=True) return response
async def auth( code: Optional[str] = None, error: Optional[str] = None, config: OIDCConfig = Depends(_openid_config), db: database.SessionLocal = Depends(depends.get_db), ) -> RedirectResponse: if error is not None: return _make_redirect(config, None) if code is None: raise HTTPException(400, "No error, code missing.") # https://auth0.com/docs/api/authentication#get-token resp = requests.post( config.well_known.token_endpoint, data={ "grant_type": "authorization_code", "code": code, "redirect_uri": build_url(settings.public_name, "/auth"), "client_id": settings.oidc_client_id, "client_secret": settings.oidc_client_secret, }, ) resp.raise_for_status() token = OIDCJWTokenResponse(**resp.json()) verified = _verify_jwt(token.id_token, config) user: schemas.UserDB = (db.query( models.User).filter(models.User.sub == verified.sub).first()) if user is None: user = models.User( username=verified.nickname or verified.email, email=verified.email, sub=verified.sub, ) db.add(user) db.commit() response = RedirectResponse(url="/app") response.set_cookie("session", value=token.id_token, samesite="lax", httponly=True) return response
def auth_session(request: Request): token = oauth.fetch_token( 'https://accounts.google.com/o/oauth2/token', authorization_response=str(request.url), # Google specific extra parameter used for client # authentication client_secret=client_secret) header = jwt.get_unverified_header(token['id_token']) cert_str = requests.get('https://www.googleapis.com/oauth2/v1/certs').json( )[header['kid']].encode() cert_obj = load_pem_x509_certificate(cert_str) pub_key = cert_obj.public_key() payload = jwt.decode(token['id_token'], pub_key, algorithms=['RS256'], audience=client_id) if payload['iat'] - 60 < time.time() < payload['exp']: if payload['email_verified']: response = RedirectResponse('/shop/goods/#') id_ = payload['sub'] user = session.query(Member).filter(Member.id == id_).first() if not user: session.add(Member(id=id_, email=payload['email'])) session.commit() response.set_cookie('kw_id', id_, max_age=token['expires_in']) return response else: raise jwt.PyJWTError('email_verified must be true') else: raise jwt.PyJWTError( f'this token is invalid at present {payload["iat"]} < {time.time()} < {payload["exp"]}' )
def login(token: Optional[str] = Depends(login_for_access_token)): """Redirects back to index, if invalid username or password""" if not token: response = RedirectResponse("../") response.set_cookie(key="info_type", value="danger") response.set_cookie( key="user_info", value=f"Wrong username or password.", ) else: response = RedirectResponse("../batches") response.set_cookie(key="token", value=token) return response