async def index(session: Session = Depends(db.session), ): """ ELB 상태 체크용 API :return: """ user = Users(status='active', name="HelloWorld") session.add(user) session.commit() Users.create(session, auto_commit=True, name="코알라") current_time = datetime.utcnow() return Response( f"Notification API (UTC: {current_time.strftime('%Y.%m.%d %H:%M:%S')})" )
async def login(sns_type: SnsType, user_info: UserRegister): if sns_type == SnsType.email: is_exist = await is_email_exist(user_info.email) if not user_info.email or not user_info.pw: return JSONResponse( status_code=400, content=dict(msg="Email and PW must be provided'")) if not is_exist: return JSONResponse(status_code=400, content=dict(msg="NO_MATCH_USER")) # 유저 정보 가져옴 user = Users.get(email=user_info.email) # 유저 패스워드 확인 is_verified = bcrypt.checkpw(user_info.pw.encode("utf-8"), user.pw.encode("utf-8")) if not is_verified: return JSONResponse(status_code=400, content=dict(msg="NO_MATCH_USER")) # 토큰 발급 token = dict( Authorization= f"Bearer {create_access_token(data=UserToken.from_orm(user).dict(exclude={'pw', 'marketing_agree'}),)}" ) return token return JSONResponse(status_code=400, content=dict(msg="NOT_SUPPORTED"))
async def register(sns_type: SnsType, reg_info: UserRegister, session: Session = Depends(db.session)): """ `회원가입 API`\n :param sns_type: :param reg_info: :param session: :return: """ if sns_type == SnsType.email: is_exist = await is_email_exist(reg_info.email) if not reg_info.email or not reg_info.pw: return JSONResponse( status_code=400, content=dict(msg="Email and PW must be provided'")) if is_exist: return JSONResponse(status_code=400, content=dict(msg="EMAIL_EXISTS")) hash_pw = bcrypt.hashpw(reg_info.pw.encode("utf-8"), bcrypt.gensalt()) new_user = Users.create(session, auto_commit=True, pw=hash_pw, email=reg_info.email) token = dict( Authorization= f"Bearer {create_access_token(data=UserToken.from_orm(new_user).dict(exclude={'pw', 'marketing_agree'}),)}" ) return token return JSONResponse(status_code=400, content=dict(msg="NOT_SUPPORTED"))
def login(session): """ 테스트전 사용자 미리 등록 :param session: :return: """ db_user = Users.create(session=session, email="*****@*****.**", pw="123") session.commit() access_token = create_access_token(data=UserToken.from_orm(db_user).dict( exclude={'pw', 'marketing_agree'}), ) return dict(Authorization=f"Bearer {access_token}")
def test_registration_exist_email(client, session): """ 레버 로그인 :param client: :param session: :return: """ user = dict(email="*****@*****.**", pw="123", name="라이언", phone="01099999999") db_user = Users.create(session=session, **user) session.commit() res = client.post("api/auth/register/email", json=user) res_body = res.json() assert res.status_code == 400 assert 'EMAIL_EXISTS' == res_body["msg"]
async def access_control(request: Request, call_next): request.state.req_time = D.datetime() request.state.start = time.time() request.state.inspect = None request.state.user = None request.state.service = None ip = request.headers[ "x-forwarded-for"] if "x-forwarded-for" in request.headers.keys( ) else request.client.host request.state.ip = ip.split(",")[0] if "," in ip else ip headers = request.headers cookies = request.cookies url = request.url.path if await url_pattern_check(url, EXCEPT_PATH_REGEX) or url in EXCEPT_PATH_LIST: response = await call_next(request) if url != "/": await api_logger(request=request, response=response) return response try: if url.startswith("/api"): # api 인경우 헤더로 토큰 검사 if url.startswith("/api/services"): qs = str(request.query_params) qs_list = qs.split("&") session = next(db.session()) if not config.conf().DEBUG: try: qs_dict = { qs_split.split("=")[0]: qs_split.split("=")[1] for qs_split in qs_list } except Exception: raise ex.APIQueryStringEx() qs_keys = qs_dict.keys() if "key" not in qs_keys or "timestamp" not in qs_keys: raise ex.APIQueryStringEx() if "secret" not in headers.keys(): raise ex.APIHeaderInvalidEx() api_key = ApiKeys.get(session=session, access_key=qs_dict["key"]) if not api_key: raise ex.NotFoundAccessKeyEx(api_key=qs_dict["key"]) mac = hmac.new(bytes(api_key.secret_key, encoding='utf8'), bytes(qs, encoding='utf-8'), digestmod='sha256') d = mac.digest() validating_secret = str( base64.b64encode(d).decode('utf-8')) if headers["secret"] != validating_secret: raise ex.APIHeaderInvalidEx() now_timestamp = int(D.datetime(diff=9).timestamp()) if now_timestamp - 10 > int( qs_dict["timestamp"]) or now_timestamp < int( qs_dict["timestamp"]): raise ex.APITimestampEx() user_info = to_dict(api_key.users) request.state.user = UserToken(**user_info) else: # Request User 가 필요함 if "authorization" in headers.keys(): key = headers.get("Authorization") api_key_obj = ApiKeys.get(session=session, access_key=key) user_info = to_dict( Users.get(session=session, id=api_key_obj.user_id)) request.state.user = UserToken(**user_info) # 토큰 없음 else: if "Authorization" not in headers.keys(): raise ex.NotAuthorized() session.close() response = await call_next(request) return response else: if "authorization" in headers.keys(): token_info = await token_decode( access_token=headers.get("Authorization")) request.state.user = UserToken(**token_info) # 토큰 없음 else: if "Authorization" not in headers.keys(): raise ex.NotAuthorized() else: # 템플릿 렌더링인 경우 쿠키에서 토큰 검사 cookies[ "Authorization"] = "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6MTQsImVtYWlsIjoia29hbGFAZGluZ3JyLmNvbSIsIm5hbWUiOm51bGwsInBob25lX251bWJlciI6bnVsbCwicHJvZmlsZV9pbWciOm51bGwsInNuc190eXBlIjpudWxsfQ.4vgrFvxgH8odoXMvV70BBqyqXOFa2NDQtzYkGywhV48" if "Authorization" not in cookies.keys(): raise ex.NotAuthorized() token_info = await token_decode( access_token=cookies.get("Authorization")) request.state.user = UserToken(**token_info) response = await call_next(request) await api_logger(request=request, response=response) except Exception as e: error = await exception_handler(e) error_dict = dict(status=error.status_code, msg=error.msg, detail=error.detail, code=error.code) response = JSONResponse(status_code=error.status_code, content=error_dict) await api_logger(request=request, error=error) return response
async def is_email_exist(email: str): get_email = Users.get(email=email) if get_email: return True return False
async def get_me(request: Request): user = request.state.user user_info = Users.get(id=user.id) return user_info