class Polly: def __init__(self): self.dbClass = Helper() def polly(self, Text, language, appToken): languages = { "English" : "Salli", "Korean" : "Seoyeon", "Japanese" : "Mizuki" } try: user = self.dbClass.getUser(appToken) #userId = self.utilClass.getStrUserId(user) except: Util.error_message("polly.py의 앱토큰 검증부분에서 에러가 발생하였습니다.") return HTTP_503_SERVICE_UNAVAILABLE, { "statusCode": 503, "error": "Bad Request", "message": "허용되지 않은 토큰 값입니다." } if language not in languages: Util.error_message("polly.py의 언어코드부분에서 에러가 발생하였습니다.") return HTTP_503_SERVICE_UNAVAILABLE, { "statusCode": 503, "error": "Bad Request", "message": "지원하지 않는 언어코드입니다." } Polly = client("polly", aws_access_key_id=shem_configs['aws_access_key_id'], aws_secret_access_key=shem_configs['aws_secret_access_key'], region_name="ap-northeast-2") try: response = Polly.synthesize_speech( Text=Text, OutputFormat="mp3", VoiceId=languages[language]) stream = response.get("AudioStream") with open('test1.mp3', 'wb') as f: data = stream.read() f.write(data) return HTTP_201_CREATED, { "statusCode": 201, "error": "Bad Request", "message": "변환이 완료되었습니다." } except: Util.error_message(tracback.format_exc()) print(traceback.format_exc()) return HTTP_500_INTERNAL_SERVER_ERROR, { "statusCode": 500, "error": "Bad Request", "message": "잘못된 접근입니다." } pass
def __init__(self): self.dbClass = Helper(init=True) self.utilClass = Util() self.paymentClass = ManagePayment() self.s3 = self.utilClass.getBotoClient('s3') self.invaildUserAuthResponse = { "statusCode": 500, "error": "Bad Request", "message": "잘못된 접근입니다." } self.failUserAuthResponse = { "statusCode": 500, "error": "Bad Request", "message": "유저 정보를 찾을 수 없습니다." } self.sendEmailAuthResponse = { "statusCode": 200, "message": "고객님의 메일로 링크를 보내드렸습니다. 메일발송까지 5-10분 정도 소요될 수 있습니다." }
class Hardware: def __init__(self): self.dbClass = Helper() def digital(self, hardware, status): return HTTP_200_OK, not status def analog(self, value): test = {"value": value} self.dbClass.analogTestInput(value) return HTTP_200_OK, {'result': value} def analogTest(self): data = {"value": 52.789} req = requests.post("http://52.78.65.114/analog/", data=json.dumps(data)) return req.status_code, req.text
class ManageUser: def __init__(self): self.dbClass = Helper(init=True) self.utilClass = Util() self.paymentClass = ManagePayment() self.s3 = self.utilClass.getBotoClient('s3') self.invaildUserAuthResponse = { "statusCode": 500, "error": "Bad Request", "message": "잘못된 접근입니다." } self.failUserAuthResponse = { "statusCode": 500, "error": "Bad Request", "message": "유저 정보를 찾을 수 없습니다." } self.sendEmailAuthResponse = { "statusCode": 200, "message": "고객님의 메일로 링크를 보내드렸습니다. 메일발송까지 5-10분 정도 소요될 수 있습니다." } def registerUser(self, userInfoRaw): userInfo = userInfoRaw.__dict__ salt = bcrypt.gensalt(10) if not re.match(r'[A-Za-z0-9!@#$%^&+=]{8,}', userInfo["password"]): return HTTP_500_INTERNAL_SERVER_ERROR, { "statusCode": 500, "error": "Bad Request", "message": "비밀번호가 양식에 맞지 않습니다. 다시 시도하여 주시길 바랍니다." } if len(re.findall("[a-z]", userInfo["password"])) == 0 or len(re.findall("[0-9]", userInfo["password"])) == 0 or len(re.findall("[!@#$%^&+=]",userInfo["password"])) == 0: return HTTP_500_INTERNAL_SERVER_ERROR, { "statusCode": 500, "error": "Bad Request", "message": "영어, 숫자, 특수기호가 최소 1개이상 포함되어야 합니다." } userInfo["password"] = bcrypt.hashpw(userInfo["password"].encode(), salt) try: userInfoRaw = self.dbClass.createUser(userInfo) userInfo = userInfoRaw.__dict__['__data__'] del userInfo["password"] except: print(traceback.format_exc()) return HTTP_400_BAD_REQUEST, { "statusCode": 400, "error": "Bad Request", "message": "이미 가입된 이메일입니다." } pass userInit = { "confirmed": True, "appTokenCode": uuid.uuid4().hex, "appTokenCodeUpdatedAt": datetime.datetime.utcnow(), 'isFirstplanDone': True, 'isDeleteRequested': 0, 'usageplan': businessPlan["id"], 'dynos': 1, } else: userInit = { "confirmed": False, "emailTokenCode": uuid.uuid4().hex, "appTokenCode": uuid.uuid4().hex, "appTokenCodeUpdatedAt": datetime.datetime.utcnow(), } userInfo = {**userInfo, **userInit} self.dbClass.updateUser(userInfo['id'], userInit) return HTTP_201_CREATED, userInfo def loginUser(self, userLoginInfo): userInfo = {} try: userInfo['user'] = self.dbClass.loginUser(userLoginInfo.identifier, userLoginInfo.password).__dict__['__data__'] except: pass if userInfo.get('user'): del userInfo['user']["password"] userInfo['jwt'] = userInfo['user']["token"] if not userInfo['user']["token"]: token = jwt.encode({'email': userInfo['user']["email"]}, 'aistorealwayswinning', algorithm='HS256') self.dbClass.updateUser(userInfo['user']["id"], { 'token': token }) userInfo['jwt'] = token if userInfo['user']['confirmed'] and not userInfo['user']['isDeleteRequested']: self.utilClass.sendSlackMessage(f"로그인하였습니다. {userInfo['user']['email']} (ID: {userInfo['user']['id']})", appLog=True) return HTTP_200_OK, userInfo else: self.utilClass.sendSlackMessage(f"이메일 확인되지 않은 로그인 시도입니다. " + json.dumps(userLoginInfo.get('identifier'), indent=4, ensure_ascii=False), appLog=True) return HTTP_400_BAD_REQUEST, { "status_code": 400, "message": "Email verification is not confirmed." } else: self.utilClass.sendSlackMessage(f"로그인 시도 실패입니다. " + json.dumps(userLoginInfo.__dict__.get('identifier'), indent=4, ensure_ascii=False), appLog=True) return HTTP_400_BAD_REQUEST, userInfo def verifyEmailConfirm(self, token, userid): isVerified = self.dbClass.verifyEmailConfirm(token, userid) if isVerified: return HTTP_200_OK, RedirectResponse(url=self.utilClass.frontendURL + "/signin?email_confirm=true") else: return HTTP_503_SERVICE_UNAVAILABLE, RedirectResponse( url=self.utilClass.frontendURL + "/signin?email_confirm=false") def forgotPassword(self, email): try: user = self.dbClass.getUserByEmail(email) except: return HTTP_200_OK, self.sendEmailAuthResponse pass if user['isDeleteRequested']: return HTTP_500_INTERNAL_SERVER_ERROR, self.failUserAuthResponse with open("./src/email/password_reset.html", "r") as r: token = jwt.encode({'email': email + str(datetime.datetime.utcnow())}, 'aistorealwayswinning', algorithm='HS256') print(token.decode()) content = r.read().replace("<%= TOKEN %>", token.decode()) result = self.utilClass.sendEmail(email, f'[Click AI] 비밀번호 리셋', content) self.dbClass.updateUser(user["id"], { "resetPasswordVerifyTokenID": token.decode(), "resetPasswordRequestDatetime": datetime.datetime.utcnow() }) def resetPassword(self, token, password, passwordConfirmation): if password != passwordConfirmation: return HTTP_500_INTERNAL_SERVER_ERROR, { "statusCode": 500, "error": "Bad Request", "message": "비밀번호가 일치하지 않습니다. 다시 시도하여 주시길 바랍니다." } if not re.match(r'[A-Za-z0-9@#$%^&+=]{8,}', password): return HTTP_500_INTERNAL_SERVER_ERROR, { "statusCode": 500, "error": "Bad Request", "message": "비밀번호가 양식에 맞지 않습니다. 다시 시도하여 주시길 바랍니다." } if len(re.findall("[a-z]", password)) == 0 or len(re.findall("[0-9]", password)) == 0 or len(re.findall("[!@#$%^&+=]", password)) == 0: return HTTP_500_INTERNAL_SERVER_ERROR, { "statusCode": 500, "error": "Bad Request", "message": "영어, 숫자, 특수기호가 최소 1개이상 포함되어야 합니다." } try: user = self.dbClass.getUserByForgetEmailToken(token) except: return HTTP_500_INTERNAL_SERVER_ERROR, self.failUserAuthResponse pass if user["resetPasswordRequestDatetime"] + datetime.timedelta(days=1) < datetime.datetime.utcnow(): return HTTP_500_INTERNAL_SERVER_ERROR, { "statusCode": 500, "error": "Bad Request", "message": "갱신기한이 지났습니다. 비밀번호 찾기 페이지부터 다시 진행해주시길 바랍니다." } salt = bcrypt.gensalt(10) password = bcrypt.hashpw(password.encode(), salt) self.dbClass.updateUser(user["id"],{ "password": password }) self.utilClass.sendSlackMessage(f"비밀번호 리셋 완료합니다. {user['email']} (ID: {user['id']})", appLog=True) return HTTP_200_OK, { "statusCode": 200, "message": "비밀번호가 변경되었습니다. 다시 로그인해주시길 바랍니다." }
def __init__(self): self.dbClass = Helper(init=True) self.utilClass = Util()
def __init__(self): self.dbClass = Helper()
from fastapi import FastAPI, File, Header, Form from src import manageUser from starlette.middleware.cors import CORSMiddleware from src.manageUser import ManageUser from src import util from models import dbconn from pydantic import BaseModel from starlette.responses import Response from starlette.status import HTTP_200_OK from starlette.status import HTTP_503_SERVICE_UNAVAILABLE from starlette.status import HTTP_422_UNPROCESSABLE_ENTITY from src.util import Util from models.helper import Helper # manageUserClass = ManageUser() dbClass = Helper(init=True) utilClass = Util() app = FastAPI(openapi_url="/api/v1/openapi.json", docs_url="/docs", redoc_url=None) # app.include_router(getObject.router) # app.include_router(labelRouter.router) # app.include_router(fileRouter.router) # app.include_router(predictRouter.router) app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"],
def execute_cli_wrapper(cls, device_ip, username, password, cli, uuid, sa, va, domain): logger.info("Value of username is " + username + " password " + password) config.ERROR, sw_ver_str, device_type_dict = Helper.check_dlc_required( device_ip, uuid, sa, va, domain, "x", username, password) dlc_required = TokensModel.select_dlc(uuid) logger.info("DLC_Required Flag set to:" + dlc_required) if not config.ERROR: if sw_ver_str and device_type_dict['device_type'] is not None: s = slr("", "", "") s.update_req_token(SLR_REQUEST_CODE_TABLE_NAME, uuid, device_ip, "") result = "" result_lic_count = "" try: if dlc_required == "True": dlc_process_status = SlrRequestCode.check_dlc_status_on_device( device_ip, username, password, dlc_proc_stat_cmd) if dlc_process_status != '' and dlc_process_status == 'Not Complete': dlc_conversion_data = SlrRequestCode.execute_dlc_cli( device_ip, username, password, dlc_conversion_command) if dlc_conversion_data != '': logger.info("DLC_conversion_data") logger.info(type(dlc_conversion_data)) logger.info(dlc_conversion_data) SlrRequestCode.generate_dlc_data_dict( device_ip, dlc_conversion_data, va) SlrRequestCode.insert_dlc_data_to_table( uuid, device_ip, dlc_conversion_data) lic_rows = s.find_by_uuid_ipaddr( uuid, SLR_REQUEST_CODE_TABLE_NAME, device_ip) device_license = s.get_license(lic_rows[0]) if device_license is None: output = SlrRequestCode.config_commands( device_ip, username, password, cli) logger.info("Value of the output is " + output) req_code = output.split('\n')[-2] if req_code.find("Request code:") != -1: data = req_code.split("code: ") req_code = data[1] s.update_req_token(SLR_REQUEST_CODE_TABLE_NAME, uuid, device_ip, req_code) output = SlrRequestCode.config_commands( device_ip, username, password, req_udi_command) logger.info(output) udi = (output.split('\n')) logger.info("Value of udi is " + str(udi)) first = 1 first_count = 1 for entitlement_tag in udi: logger.info(entitlement_tag) if "Entitlement tag" in entitlement_tag: if first: lic = entitlement_tag.split( ":")[-1].replace(" ", "") first = 0 else: lic = entitlement_tag.split(":")[-1] result = result + lic if "Count:" in entitlement_tag: if first_count: lic_count_string = entitlement_tag.split( ":")[-1].replace(" ", "") first_count = 0 else: lic_count_string = entitlement_tag.split( ":")[-1] result_lic_count = result_lic_count + lic_count_string logger.info("Value of entitlement tag is " + result) logger.info("Value of count of licenses is " + result_lic_count) # If we don't get lic ent tag and count from the device, indicate error if (result == "") or (result_lic_count == ""): result = "LIC_ENT_TAG_NOT_FOUND" result_lic_count = "LIC_COUNT_NOT_FOUND" s.update_entitlement_tag(SLR_REQUEST_CODE_TABLE_NAME, uuid, device_ip, result) s.update_license_count(SLR_REQUEST_CODE_TABLE_NAME, uuid, device_ip, result_lic_count) else: output = SlrRequestCode.config_commands( device_ip, username, password, cli) logger.info("Value of the output is " + output) req_code = output.split('\n')[-2] if req_code.find("Request code:") != -1: data = req_code.split("code: ") req_code = data[1] s.update_req_token(SLR_REQUEST_CODE_TABLE_NAME, uuid, device_ip, req_code) s.update_entitlement_tag(SLR_REQUEST_CODE_TABLE_NAME, uuid, device_ip, device_license) # If we don't get lic ent tag and count from the device, it is considered as failed if (result == "LIC_ENT_TAG_NOT_FOUND") or ( result_lic_count == "LIC_COUNT_NOT_FOUND"): s.update_status( SLR_REQUEST_CODE_TABLE_NAME, uuid, device_ip, "License details not found from the " "device", "step1") else: s.update_status(SLR_REQUEST_CODE_TABLE_NAME, uuid, device_ip, "Completed", "step1") except Exception as e: print(e) s.update_status(SLR_REQUEST_CODE_TABLE_NAME, uuid, device_ip, str(e).split(":")[0], "step1") # Added 04/16/19 - As export button and get auth key button is enabled eventhough # connection to device timed-out # Updating response status to Step 2 failed response_update = {'status': "S2f"} TokensModel.update(uuid, response_update, "upload_info_store") rows = s.find_by_step_status(SLR_REQUEST_CODE_TABLE_NAME, uuid, "Started", "step1") rows_completed = s.find_by_step_status( SLR_REQUEST_CODE_TABLE_NAME, uuid, "Completed", "step1") if (len(rows) == 0) and (len(rows_completed) != 0): # Updating the response status to Step 2 completed response_update = {'status': "S2c"} TokensModel.update(uuid, response_update, "upload_info_store") del s else: logger.info("==>> Unsupported Network Device type...") response = { 'ipaddr': device_ip, 'username': username, 'password': password, 'sa_name': sa, 'va_name': va, 'domain': domain, 'status': 'Unsupported Device PID!' } config.ERROR = True TokensModel.update(uuid, response, "device_status_store") else: logger.error("No connectivity to the device...") response_update = { 'ipaddr': device_ip, 'username': username, 'password': password, 'sa_name': sa, 'va_name': va, 'domain': domain, 'status': 'No Connectivity!' } config.ERROR = True TokensModel.update(uuid, response_update, "device_status_store")