class MongoMixin(object): # serviceDb = None ''' try: #USER_DBPOOL = txmongo.MongoConnection( # CONFIG['database'][0]['host'], # CONFIG['database'][0]['port'], # ) #USER_DATABASE = getattr(USER_DBPOOL, CONFIG['database'][0]['key']) Log.i('MONGO', 'User Database Service has been Initialized!') except: Log.i('MONGO', 'User Database Service has been Initialization Failed!') ''' # def initUserDb(): try: client = motor.motor_asyncio.AsyncIOMotorClient( CONFIG['database'][0]['host'], CONFIG['database'][0]['port'], ) # options = {'async': True} # await client.fsync(**options) # MongoMixin.userDb = client[CONFIG['database'][0]['key']] userDb = client[CONFIG['database'][0]['key']] client = None # Log.i(userDb) Log.i('MONGO', '{} has been Initialized!'.format(CONFIG['database'][0]['key'])) except: userDb = None Log.i('MONGO', 'Ether Database has been Initialization Failed!')
def JWT_DECODE(token=str): try: if len(SECRETS): for s in SECRETS: try: # Log.i('key', s) tokenObj = jwt.decode(token, s, algorithms=["HS256"]) # Log.i('token_key', tokenObj['key']) kyDe = FN_DECRYPT(tokenObj['key']) # Log.i('session_key', kyDe) if kyDe: if type(kyDe) is bytes: return kyDe.decode() else: return kyDe except Exception as e: # exc_type, exc_obj, exc_tb = sys.exc_info() # fname = exc_tb.tb_frame.f_code.co_filename # Log.d('EX2', # 'FILE: ' + str(fname) + ' LINE: ' + str(exc_tb.tb_lineno) + ' TYPE: ' + str(exc_type)) continue except Exception as e: exc_type, exc_obj, exc_tb = sys.exc_info() fname = exc_tb.tb_frame.f_code.co_filename Log.d( 'EX2', 'FILE: ' + str(fname) + ' LINE: ' + str(exc_tb.tb_lineno) + ' TYPE: ' + str(exc_type)) return False
async def get(self): status = False code = 4000 result = [] message = '' try: rs = await self.signedSession.delete_many({ '_id': self.sessionId, }) if rs.deleted_count > 0: message = 'Sign out is successful.' status = True code = 2000 else: message = 'Session not found.' except Exception as e: status = False # self.set_status(400) if not len(message): template = 'Exception: {0}. Argument: {1!r}' code = 5010 iMessage = template.format(type(e).__name__, e.args) message = 'Internal Error, Please Contact the Support Team.' exc_type, exc_obj, exc_tb = sys.exc_info() fname = exc_tb.tb_frame.f_code.co_filename Log.w('EXC', iMessage) Log.d( 'EX2', 'FILE: ' + str(fname) + ' LINE: ' + str(exc_tb.tb_lineno) + ' TYPE: ' + str(exc_type)) response = {'code': code, 'status': status, 'message': message} Log.d('RSP', response) try: response['result'] = result self.write(response) await self.finish() return except Exception as e: status = False template = 'Exception: {0}. Argument: {1!r}' code = 5011 iMessage = template.format(type(e).__name__, e.args) message = 'Internal Error, Please Contact the Support Team.' exc_type, exc_obj, exc_tb = sys.exc_info() fname = exc_tb.tb_frame.f_code.co_filename Log.w('EXC', iMessage) Log.d( 'EX2', 'FILE: ' + str(fname) + ' LINE: ' + str(exc_tb.tb_lineno) + ' TYPE: ' + str(exc_type)) response = {'code': code, 'status': status, 'message': message} self.write(response) await self.finish() return
def FN_DECRYPT(token=str): try: if len(FERNETS): for f in FERNETS: try: if type(token) != bytes: d_token = f.decrypt(token.encode()) else: d_token = f.decrypt(token) return d_token except Exception as e: # Log.i(e) continue except Exception as e: Log.i(e) return False return False
def __init__(self): settings = { 'debug': False } super(App, self).__init__( handlers=[ # (r'/', IndexHandler), (r'/api/get_origin_key', AsyncHttpHandler), (r'/api/country', CountryHandler), (r'/api/resource/profile', ProfileHandler), (r'/api/auth/sign_in', SignInHandler), (r'/api/auth/sign_up', SignUpHandler), (r'/api/auth/sign_out', SignOutHandler), (r'/api/forms', FormsHandler), (r'/api/forms_data', FormsDataHandler), (r'/api/organization', OrganizationHandler), (r'/api/organization_structure', OrganizationStructureHandler), (r'/api/organization_pos_structure', OrganizationPositionHandler), ], **settings, default_handler_class=IndexHandler ) Log.i('APP', 'Running Tornado Application Port - [ {} ]'.format(WEB_SERVER_PORT))
def JWT_ENCODE(payload=str): try: kyE = FN_ENCRYPT(payload, True) if kyE: if type(kyE) is bytes: kyE = kyE.decode() index = random.randint(0, len(SECRETS) - 1) kyEn = jwt.encode({'key': kyE}, SECRETS[index], algorithm='HS256') # Log.i('type', type(kyEn)) # Log.i('token', kyEn) if type(kyEn) is bytes: return kyEn.decode() else: return kyEn else: return False except Exception as e: exc_type, exc_obj, exc_tb = sys.exc_info() fname = exc_tb.tb_frame.f_code.co_filename Log.d( 'EX2', 'FILE: ' + str(fname) + ' LINE: ' + str(exc_tb.tb_lineno) + ' TYPE: ' + str(exc_type)) return False
async def get(self): status = False code = 4000 result = [] message = '' try: fq = self.orgPos.find({ 'profileId': self.profileId, # 'formId': ObjectId(self.get_arguments('id')[0]) }) async for r in fq: result.append(r) if len(result): status = True message = '' code = 2000 else: message = 'No data found.' code = 3100 Log.i('Hello') except Exception as e: status = False if not len(message): template = 'Exception: {0}. Argument: {1!r}' code = 5010 iMessage = template.format(type(e).__name__, e.args) message = 'Internal Error, Please Contact the Support Team.' exc_type, exc_obj, exc_tb = sys.exc_info() fname = exc_tb.tb_frame.f_code.co_filename Log.w('EXC', iMessage) Log.d( 'EX2', 'FILE: ' + str(fname) + ' LINE: ' + str(exc_tb.tb_lineno) + ' TYPE: ' + str(exc_type)) response = {'code': code, 'status': status, 'message': message} Log.d('RSP', response) try: response['result'] = result response = json.loads(bdumps(response)) self.write(response) await self.finish() return except Exception as e: status = False template = 'Exception: {0}. Argument: {1!r}' code = 5011 iMessage = template.format(type(e).__name__, e.args) message = 'Internal Error, Please Contact the Support Team.' exc_type, exc_obj, exc_tb = sys.exc_info() fname = exc_tb.tb_frame.f_code.co_filename Log.w('EXC', iMessage) Log.d( 'EX2', 'FILE: ' + str(fname) + ' LINE: ' + str(exc_tb.tb_lineno) + ' TYPE: ' + str(exc_type)) response = {'code': code, 'status': status, 'message': message} self.write(response) await self.finish() return
async def post(self): status = False code = 4000 result = [] message = '' try: try: # CONVERTS BODY INTO JSON self.request.arguments = bloads(self.request.body.decode()) except Exception as e: code = 4100 message = 'Expected Request Type JSON.' raise Exception self.request.arguments['profileId'] = self.profileId rs = await self.orgPos.insert_one(self.request.arguments) status = True code = 2000 message = 'Organization position structure has been created.' result = [rs.inserted_id] except Exception as e: status = False # self.set_status(400) if not len(message): template = 'Exception: {0}. Argument: {1!r}' code = 5010 iMessage = template.format(type(e).__name__, e.args) message = 'Internal Error, Please Contact the Support Team.' exc_type, exc_obj, exc_tb = sys.exc_info() fname = exc_tb.tb_frame.f_code.co_filename Log.w('EXC', iMessage) Log.d( 'EX2', 'FILE: ' + str(fname) + ' LINE: ' + str(exc_tb.tb_lineno) + ' TYPE: ' + str(exc_type)) response = {'code': code, 'status': status, 'message': message} Log.d('RSP', response) try: response['result'] = result response = json.loads(bdumps(response)) self.write(response) await self.finish() return except Exception as e: status = False template = 'Exception: {0}. Argument: {1!r}' code = 5011 iMessage = template.format(type(e).__name__, e.args) message = 'Internal Error, Please Contact the Support Team.' exc_type, exc_obj, exc_tb = sys.exc_info() fname = exc_tb.tb_frame.f_code.co_filename Log.w('EXC', iMessage) Log.d( 'EX2', 'FILE: ' + str(fname) + ' LINE: ' + str(exc_tb.tb_lineno) + ' TYPE: ' + str(exc_type)) response = {'code': code, 'status': status, 'message': message} self.write(response) await self.finish() return
async def post(self): status = False code = 4000 result = [] message = '' try: try: # CONVERTS BODY INTO JSON self.request.arguments = json.loads(self.request.body.decode()) except Exception as e: code = 4002 message = 'Expected Request Type JSON.' raise Exception applicationId = self.request.arguments.get('applicationId') if applicationId is None: code = 4100 message = 'Missing Argument - [ applicationId ].' raise Exception else: try: applicationId = ObjectId(applicationId) except: code = 4102 message = 'Invalid Argument - [ applicationId ].' raise Exception appQ = self.applications.find({'_id': applicationId}, limit=1) app = [] async for i in appQ: app.append(i) if len(app) and app[0]['selfRegister']: entityQ = self.entity.find({'_id': self.entityId}, limit=1) entity = [] async for i in entityQ: entity.append(i) if not len(entity): entityQ = self.entity.find({'origin': []}, limit=1) entity = [] async for i in entityQ: entity.append(i) if not len(entity): code = 5050 message = 'Internal Error Please Contact the Support Team.' raise Exception method = self.request.arguments.get('method') if method == None: code = 4130 message = 'Missing Argument - [ method ].' raise Exception elif type(method) != int: code = 4131 message = 'Invalid Argument - [ method ].' raise Exception if method == 0: try: userId = str(self.request.arguments['userId']) password = str(self.request.arguments['password']) status = True except Exception as e: status = False code = 4110 template = "Exception: {0}. Argument: {1!r}" message = template.format(type(e).__name__, e.args) elif method == 2: try: regexSp = re.compile('[@_`+!#$%^&*()<>?/\-|}{~:,.]') regexEm = re.compile('[@`+!#$%^&*()<>?/\|}{~:],') regexNp = re.compile('[1234567890]') firstName = self.request.arguments.get('firstName') if firstName is None: code = 4510 message = 'Missing Argument - [ firstName ].' raise Exception elif type(firstName) != str: code = 4511 message = 'Invalid Argument - [ firstName ].' raise Exception elif not len(str(firstName)): code = 4512 message = 'Please enter the First Name.' raise Exception elif regexSp.search(firstName) is not None: code = 4513 message = 'First name should not contain any special character.' raise Exception elif regexNp.search(firstName) is not None: code = 4514 message = 'First name should not contain any number.' raise Exception elif len(firstName) > 50: code = 4515 message = 'First name should be less than 50 characters.' raise Exception firstName = firstName.strip() firstName = firstName.title() lastName = self.request.arguments.get('lastName') if lastName is None: code = 4520 message = 'Missing Argument - [ lastName ].' raise Exception elif type(lastName) != str: code = 4521 message = 'Invalid Argument - [ lastName ].' raise Exception elif not len(str(lastName)): code = 4522 message = 'Please enter the Last Name.' raise Exception elif regexSp.search(lastName) is not None: code = 4523 message = 'Last name should not contain any special character.' raise Exception elif regexNp.search(lastName) is not None: code = 4524 message = 'Last name should not contain any number.' raise Exception elif len(lastName) > 50: code = 4525 message = 'Last name should be less than 50 characters.' raise Exception lastName = lastName.strip() lastName = lastName.title() enUsername = self.request.arguments.get('username') code, message = Validate.i(enUsername, 'Username', dataType=str, notEmpty=True, noSpecial=True, minLength=6, maxLength=15) if code != 4100: raise Exception else: enUsername = enUsername.replace(" ", "") enUsername = enUsername.lower() phoneNumber = self.request.arguments.get('phoneNumber') if phoneNumber is None: code = 4241 message = 'Missing Argument - [ phoneNumber ].' raise Exception countryCode = self.request.arguments.get('dialCode') if countryCode is None: code = 4251 message = 'Missing Argument - [ dialCode ].' raise Exception elif type(countryCode) != int: code = 4552 message = 'Invalid Argument - [ dialCode ].' raise Exception else: countryCode = int(countryCode) countryQ = self.phoneCountry.find( {'code': countryCode}, limit=1) country = [] async for i in countryQ: country.append(i) if not len(country): code = 4242 message = 'Dial code does not exist.' raise Exception if len(str(phoneNumber)) != country[0]['telMaxLength']: code = 4252 message = 'Please enter a valid Phone Number.' raise Exception('phoneNumber') else: orgPhoneNumber = int(phoneNumber) phoneNumber = int( str(countryCode) + str(phoneNumber)) email = self.request.arguments.get('email') Log.i(len(email)) if email is None or type(email) != str or not len( email): code = 4510 message = 'Please enter your email.' raise Exception elif (len(email.split('@')) != 2 or '.' not in email or len(email) < 5): code = 4532 message = 'Please enter a valid email.' raise Exception elif regexEm.search(lastName) is not None: code = 4533 message = 'Email name should not contain any special characters.' raise Exception elif email is not None and len(email) > 60: code = 4525 message = 'Email name should be less than 60 characters.' raise Exception email = email.replace(" ", "") email = email.lower() enPassword = self.request.arguments.get('password') if enPassword is None: code = 4610 message = 'Please enter your password.' raise Exception enPassword = enPassword.strip() except Exception as e: exc_type, exc_obj, exc_tb = sys.exc_info() fname = os.path.split( exc_tb.tb_frame.f_code.co_filename)[1] Log.d( 'FILE: ' + str(fname), 'LINE: ' + str(exc_tb.tb_lineno) + ' TYPE: ' + str(exc_type)) if not len(message): code = 4210 template = "Exception: {0}. Argument: {1!r}" message = template.format(type(e).__name__, e.args) raise Exception accountData = { 'firstName': firstName, 'lastName': lastName, 'createdAt': timeNow(), 'createdBy': None, 'country': [{ 'code': country[0]['isoAlpha3Code'], 'name': country[0]['name'], '_id': country[0]['cId'], }], 'privacy': [{ 'value': enPassword }], 'contact': [{ 'type': 0, 'value': enUsername, }, { 'type': 1, 'verified': False, 'value': phoneNumber, 'dialCode': countryCode, 'sDialCode': country[0]['sCode'], 'phoneNumber': orgPhoneNumber, 'countryCode': country[0]['isoAlpha3Code'] }, { 'verified': False, 'value': email, 'type': 2 }] } try: accountId = await self.account.insert_one(accountData) except Exception as e: exe = str(e).split(':') if len(exe) < 2: status = False code = 4280 message = 'Internal Error Please Contact the Support Team.' elif 'contact.0.value_1' in exe[2]: status = False code = 4281 message = 'This Username is already registered.' elif 'contact.1.value_1' in exe[2]: status = False code = 4281 message = 'This Phone Number is already registered.' elif 'contact.2.value_1' in exe[2]: status = False code = 4282 message = 'This email is already registered.' else: status = False code = 4283 message = 'Internal Error Please Contact the Support Team.' raise Exception try: accountId = accountId.inserted_id profileId = await self.profile.insert_one({ 'active': False, 'locked': False, 'closed': False, 'time': timeNow(), 'insertTime': self.time, 'accountId': accountId, 'signedFullName': firstName + ' ' + lastName, 'applicationId': app[0]['_id'], 'entityId': entity[0]['_id'], 'data': [], }) profileId = profileId.inserted_id except: code = 5830 message = 'Internal Error Please Contact the Support Team.' raise Exception createSession = await self.signedSession.insert_one( { 'signedAt': datetime.utcnow(), 'accountId': accountId, 'profileId': profileId, 'entityId': entity[0]['_id'], 'createdAt': timeNow(), 'createdBy': profileId }, ) if createSession.inserted_id is not None: xToken = JWT_ENCODE(str(createSession.inserted_id)) result.append(xToken) status = True code = 2000 message = 'Sign Up Successful, Welcome to Ether World.' else: code = 4110 message = 'Sign In method not supported.' raise Exception else: message = 'Application ID not found.' code = 4200 raise Exception except Exception as e: status = False # self.set_status(400) if not len(message): template = 'Exception: {0}. Argument: {1!r}' code = 5010 iMessage = template.format(type(e).__name__, e.args) message = 'Internal Error Please Contact the Support Team.' exc_type, exc_obj, exc_tb = sys.exc_info() fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1] Log.w('EXC', iMessage) Log.d( 'FILE: ' + str(fname), 'LINE: ' + str(exc_tb.tb_lineno) + ' TYPE: ' + str(exc_type)) response = {'code': code, 'status': status, 'message': message} Log.d('RSP', response) try: response['result'] = result self.write(response) await self.finish() return except Exception as e: status = False template = 'Exception: {0}. Argument: {1!r}' code = 5011 iMessage = template.format(type(e).__name__, e.args) message = 'Internal Error Please Contact the Support Team.' exc_type, exc_obj, exc_tb = sys.exc_info() fname = exc_tb.tb_frame.f_code.co_filename Log.w('EXC', iMessage) Log.d( 'EX2', 'FILE: ' + str(fname) + ' LINE: ' + str(exc_tb.tb_lineno) + ' TYPE: ' + str(exc_type)) response = {'code': code, 'status': status, 'message': message} self.write(response) await self.finish() return
from util.log_util import Log try: # SERVER CONFIGURATION FILE CONFIG_FILE_PATH = './configuration.json' CONFIG_FILE = open(CONFIG_FILE_PATH) CONFIG = json.loads(CONFIG_FILE.read()) CONFIG_FILE.close() # Project Code PROJECT_NAME = CONFIG['name'] timeOffsetIST = CONFIG['timeOffsetIST'] # Project Code PROJECT_CODE = CONFIG['projectCode'] # WEB SERVER CONFIGURATION WEB_SERVER_PORT = CONFIG["instance"][0]['port'] except Exception as e: status = False template = 'Exception: {0}. Argument: {1!r}' code = 5011 iMessage = template.format(type(e).__name__, e.args) message = 'Internal Error Please Contact the Support Team.' exc_type, exc_obj, exc_tb = sys.exc_info() fname = exc_tb.tb_frame.f_code.co_filename Log.c('BUILD-EXC', iMessage) Log.c( 'BUILD-EX2', 'FILE: ' + str(fname) + ' LINE: ' + str(exc_tb.tb_lineno) + ' TYPE: ' + str(exc_type))
async def post(self): status = False code = 4000 result = [] message = '' try: try: # CONVERTS BODY INTO JSON self.request.arguments = json.loads(self.request.body.decode()) except Exception as e: Log.i(e) code = 4100 message = 'Expected Request Type JSON.' raise Exception entityQ = self.entity.find({'_id': self.entityId}, limit=1) entity = [] async for r in entityQ: entity.append(r) if not len(entity): code = 4003 message = 'You are not Authorized.' self.set_status(401) raise Exception applicationId = self.request.arguments.get('applicationId') app = [] if applicationId is not None: try: applicationId = ObjectId(applicationId) appQ = self.applications.find_one({'_id': applicationId}, limit=1) app.append(appQ) except: code = 4006 message = 'Invalid application Id.' self.set_status(401) raise Exception if applicationId is None or len(app): method = self.request.arguments.get('method') if method == None: code = 4130 message = 'Missing Argument - [ method ].' raise Exception # if method == 0: # try: # # TODO: need to give validation # username = str(self.request.arguments['username']) # password = str(self.request.arguments['password']) # except Exception as e: # code = 4110 # template = "Exception: {0}. Argument: {1!r}" # message = template.format(type(e).__name__, e.args) # raise Exception # try: # accountQ = self.account.find( # { # 'contact.0.value': int(username), # 'privacy.0.value': password # }, # { # '_id': 1 # }, # limit=1 # ) # # account = [] # async for r in accountQ: # account.append(r) # if len(account): # ''' # Searching for profile # Blocked for 20 sec ( in microseconds ) # ''' # profileQ = self.profile.find( # { # 'accountId': account[0]['_id'], # 'applicationId': app[0]['_id'], # # '$or': [ # # { # # 'lastSignInRequest': None # # }, # # { # # 'lastSignInRequest': # # { # # '$lt': self.time - 20000000 # # } # # } # # ] # }, # { # '_id': 1, # 'entityId': 1, # 'role': 1 # }, # limit=1 # ) # profile = [] # async for r in profileQ: # profile.append(r) # if not len(profile): # subAdminAppQ = self.applications.find( # { # 'apiId': 402023 # } # ) # subAdminApp = [] # async for i in subAdminAppQ: # subAdminApp.append(i) # profileQ = self.profile.find( # { # 'accountId': account[0]['_id'], # 'applicationId': subAdminApp[0]['_id'] # }, # { # '_id': 1, # 'entityId': 1, # 'role': 1 # }, # limit=1 # ) # profile = [] # async for i in profileQ: # profile.append(i) # if len(profile): # role = profile[0]['role'] # ''' # # Sign in blocked for 20min based on phone number # Log.i('last_sign_in_time', profile[0].get('lastSignInRequest')) # if profile[0].get('lastSignInRequest') != None and profile[0].get('lastSignInRequest') > self.time - 20000000: # # # TODO: for counter logic # self.write( # { # 'status': False, # 'message': 'Please try again after later.', # 'code': 4040, # 'result': [] # } # ) # self.finish() # return # ''' # # entities = [] # for p in profile: # entQ = self.entity.find( # { # '_id': p['entityId'] # }, # { # '_id': 1, # 'name': 1 # }, # limit=1 # ) # ent = [] # async for r in entQ: # ent.append(r) # # if len(ent): # k = FN_ENCRYPT(str(ent[0]['_id']), True) # v = { # 'key': k.decode(), # 'name': ent[0]['name'] # } # entities.append(v) # if not len(entities): # Log.d('ENT', 'No Entity Found.') # message = 'No Entity Found.' # raise Exception # else: # ''' # Saving the Last Sign In Reqested Time # ''' # updateResult = await self.profile.update_one( # { # '_id': profile[0]['_id'] # }, # { # '$set': # { # 'lastSignInRequest': self.time # } # } # ) # if updateResult.modified_count: # bToken = JWT_ENCODE(str(account[0]['_id'])) # xApiKey = FN_ENCRYPT(str(app[0]['_id']), True) # if role == 1 or role == 2: # xApiKey = FN_ENCRYPT(str(subAdminApp[0]['_id']), True) # secureCache = { # 'bearerToken': bToken.decode(), # 'apiKey': xApiKey.decode() # } # secureCache['accessOrigin'] = entities # result.append(secureCache) # status = True # code = 2000 # message = 'Sign In Successful, Welcome Back.' # else: # code = 5310 # message = 'Internal Error, Please Contact the Support Team.' # else: # code = 4310 # message = 'Wrong Username or Password.' # else: # code = 4311 # message = 'Wrong Username or Password.' # except Exception as e: # exc_type, exc_obj, exc_tb = sys.exc_info() # fname = exc_tb.tb_frame.f_code.co_filename # Log.d('EX2', # 'FILE: ' + str(fname) + ' LINE: ' + str(exc_tb.tb_lineno) + ' TYPE: ' + str(exc_type)) # code = 5210 # message = 'Internal Error, Please Contact the Support Team.' # # TODO: for sign in with email # raise Exception # account = self.account.find( # { # 'contact.1.value': userName, # 'privacy.0.value': password # }, # limit=1 # ) # if len(account): # profile = self.profile.find( # { # 'accountId': account[0]['_id'], # 'applicationId': app[0]['_id'] # } # ) # if len(profile): # entities = [] # for p in profile: # ent = self.entity.find( # { # '_id': p['entityId'] # }, # limit=1 # ) # if len(ent): # v = { # 'id': str(ent[0]['id']), # 'name': ent[0]['name'] # } # entities.append(v) # if not len(entities): # Log.d('ENT', 'No Entity Found.') # message = 'No Entity Found.' # raise Exception # else: # result.append( # str(JWT_ENCODE( # str(account[0]['_id']) # ) # ) # ) # result.append(entities) # status = True # code = 2000 # message = 'Sign In Successful, Welcome Back.' # else: # code = 4320 # message = 'Wrong Username or Password.' # else: # code = 4321 # message = 'Wrong Username or Password.' # elif method == 1: # try: # phoneNumber = self.request.arguments.get('phoneNumber') # if phoneNumber == None: # code = 4241 # message = 'Missing Argument - [ phoneNumber ].' # raise Exception # else: # phoneNumber = int(phoneNumber) # countryCode = self.request.arguments.get('countryCode') # if countryCode == None: # code = 4251 # message = 'Missing Argument - [ countryCode ].' # raise Exception # else: # countryCode = int(countryCode) # countryQ = self.phoneCountry.find( # { # 'code': countryCode # }, # limit=1 # ) # country = [] # async for r in countryQ: # country.append(r) # # if not len(country): # code = 4242 # message = 'Invalid Country Code.' # raise Exception # if len(str(phoneNumber)) != country[0]['telMaxLength']: # code = 4252 # message = 'Invalid Phone Number.' # raise Exception('phoneNumber') # else: # phoneNumber = int(str(countryCode) + str(phoneNumber)) # except Exception as e: # if not len(message): # code = 4210 # template = "Exception: {0}. Argument: {1!r}" # message = template.format(type(e).__name__, e.args) # raise Exception # accountQ = self.account.find( # { # 'contact.0.value': phoneNumber # }, # { # '_id': 1 # }, # limit=1 # ) # account = [] # async for r in accountQ: # account.append(r) # # if len(account): # ''' # Searching for profile # Blocked for 20 sec ( in microseconds ) # ''' # profileQ = self.profile.find( # { # 'accountId': account[0]['_id'], # 'applicationId': app[0]['_id'], # # '$or': [ # # { # # 'lastSignInRequest': None # # }, # # { # # 'lastSignInRequest': # # { # # '$lt': self.time - 20000000 # # } # # } # # ] # }, # { # '_id': 1, # 'lastSignInRequest': 1, # 'retrySignInRequest': 1, # }, # limit=1 # ) # profile = [] # async for r in profileQ: # profile.append(r) # # if not len(profile): # if not app[0]['selfRegister']: # code = 4210 # message = 'Phone Number is not registered.' # raise Exception # try: # profileId = await self.profile.insert_one( # { # 'active': False, # 'locked': False, # 'closed': False, # 'time': timeNow(), # 'accountId': account[0]['_id'], # 'applicationId': app[0]['_id'], # 'entityId': entity[0]['_id'], # 'retrySignInRequest': 0, # 'data': [] # } # ) # except: # code = 5810 # message = 'Internal Error, Please Contact the Support Team.' # raise Exception # else: # profileId = profile[0]['_id'] # # # Sign in blocked for 20min based on phone number # # Log.i('last_sign_in_time', profile[0].get('lastSignInRequest')) # Log.i('retry_sign_in_request', profile[0].get('retrySignInRequest')) # # remote_ip = self.request.client_ip # # Log.i('ip', self.request.client_ip) # # Log.i('headers', self.request.headers) # # return # # if profile[0].get('retrySignInRequest') != None: # retrySignInRequest = profile[0].get('retrySignInRequest') # else: # retrySignInRequest = 1 # # if profile[0].get('lastSignInRequest') != None and profile[0].get( # 'lastSignInRequest') > self.time - 1200000000: # # try: # checkrequest = profile[0].get('retrySignInRequest') # if checkrequest == None: # checkrequest = 0 # except: # checkrequest = 0 # # if checkrequest > 2: # # self.write( # { # 'status': False, # 'message': 'Too many attemps, please try again later.', # 'code': 4040, # 'result': [] # } # ) # self.finish() # return # else: # retrySignInRequest = retrySignInRequest + 1 # else: # retrySignInRequest = 1 # # oOtpQ = self.oneTimePassword.find( # { # 'profileId': profileId, # }, # { # '_id': 1 # }, # limit=1 # ) # oOtp = [] # async for r in oOtpQ: # oOtp.append(r) # # nOtp = random.randint(100000, 999999) # if phoneNumber in [911234567890, 917005612276, 919738378908, 919612342112, 917005464481, # 917005612277, 917005612278]: # nOtp = 123456 # # rOtpQ = await self.oneTimePassword.delete_one({'profileId': profileId}) # if (rOtpQ.deleted_count >= 0): # a = await self.oneTimePassword.insert_one( # { # 'createdAt': dtime.now(), # 'profileId': profileId, # 'value': nOtp, # 'phoneNumber': phoneNumber, # } # ) # # ''' # Saving the Last Sign In Reqested Time # ''' # # updateResult = await self.profile.update_one( # { # '_id': profileId # }, # { # '$set': # { # 'lastSignInRequest': self.time, # 'retrySignInRequest': retrySignInRequest # } # } # ) # if updateResult.modified_count: # Log.i('Phone Number: ', str(phoneNumber) + ' OTP: ' + str(nOtp)) # # TODO: this need to be chaged to http client # gwResp = MSG91_GW.send(str(phoneNumber), str(entity[0]['smsGwId']), nOtp) # if gwResp: # # if True: # # Log.i('MSG91 Gateway Response', gwResp) # status = True # code = 2000 # message = 'A 6-digit One Time Password has been sent to your Phone Number.' # else: # code = 5030 # message = 'Internal Error, Please Contact the Support Team.' # raise Exception # else: # code = 5020 # message = 'Internal Error, Please Contact the Support Team.' # raise Exception # else: # code = 50101 # message = 'Internal Error, Please Contact the Support Team.' # else: # code = 4210 # message = 'Phone Number is not registered.' # el if method == 2: username = self.request.arguments.get('username') code, message = Validate.i(username, 'Username', dataType=str, maxLength=15, minLength=6) if code != 4100: raise Exception else: username = str(username).replace(' ', '') password = self.request.arguments.get('password') code, message = Validate.i(password, 'Password', dataType=str, maxLength=40) if code != 4100: raise Exception try: usernamePhone = int(username) except: usernamePhone = None try: account = await self.account.find_one( { '$or': [ { 'contact.0.value': username, 'privacy.0.value': password, }, # { # 'contact.1.value': usernamePhone, # 'privacy.0.value': password, # }, { 'contact.2.value': username, 'privacy.0.value': password, } ] }, { '_id': 1, 'firstName': 1, 'lastName': 1, }) if account is not None: ''' Saving the Last Sign In Requested Time ''' profile = [] if applicationId is None: profileQ = self.profile.find( { 'accountId': account['_id'], 'entityId': self.entityId }, { '_id': 1, 'entityId': 1, 'lastSignInRequest': 1 }) else: profileQ = self.profile.find( { 'accountId': account['_id'], 'entityId': self.entityId, 'applicationId': applicationId }, { '_id': 1, 'entityId': 1, 'lastSignInRequest': 1 }) async for p in profileQ: profile.append(p) Log.i("profiles", len(profile)) if not len(profile): message = 'No profiles found.' else: self.profileId = profile[0]['_id'] profileU = await self.profile.update_one( {'_id': self.profileId}, {'$set': { 'lastSignInRequest': self.time }}) # if (usernamePhone) == 911123123123: # nOtp = 111111 # else: # nOtp = random.randint(100000, 999999) createSession = await self.signedSession.insert_one( { 'signedAt': datetime.utcnow(), 'accountId': account['_id'], 'profileId': profile[0]['_id'], 'signedFullName': account['firstName'] + ' ' + account['lastName'], 'entityId': entity[0]['_id'], 'createdAt': timeNow(), 'createdBy': profile[0]['_id'] }, ) if createSession.inserted_id is not None: xToken = JWT_ENCODE( str(createSession.inserted_id)) result.append(xToken) status = True code = 2000 message = 'Sign In Successful, Welcome Back.' else: code = 5020 message = 'Internal Error, Please Contact the Support Team.' raise Exception else: code = 4311 message = 'Wrong Username or Password.' except Exception as e: exc_type, exc_obj, exc_tb = sys.exc_info() fname = exc_tb.tb_frame.f_code.co_filename Log.d( 'EX2', 'FILE: ' + str(fname) + ' LINE: ' + str(exc_tb.tb_lineno) + ' TYPE: ' + str(exc_type)) code = 5210 message = 'Internal Error, Please Contact the Support Team.' # TODO: for sign in with email raise Exception else: code = 4110 message = 'Sign In method not supported.' else: message = 'Application ID not found.' code = 4200 except Exception as e: status = False # self.set_status(400) if not len(message): template = 'Exception: {0}. Argument: {1!r}' code = 5010 iMessage = template.format(type(e).__name__, e.args) message = 'Internal Error, Please Contact the Support Team.' exc_type, exc_obj, exc_tb = sys.exc_info() fname = exc_tb.tb_frame.f_code.co_filename Log.w('EXC', iMessage) Log.d( 'EX2', 'FILE: ' + str(fname) + ' LINE: ' + str(exc_tb.tb_lineno) + ' TYPE: ' + str(exc_type)) response = {'code': code, 'status': status, 'message': message} Log.d('RSP', response) try: response['result'] = result self.write(response) await self.finish() return except Exception as e: status = False template = 'Exception: {0}. Argument: {1!r}' code = 5011 iMessage = template.format(type(e).__name__, e.args) message = 'Internal Error, Please Contact the Support Team.' exc_type, exc_obj, exc_tb = sys.exc_info() fname = exc_tb.tb_frame.f_code.co_filename Log.w('EXC', iMessage) Log.d( 'EX2', 'FILE: ' + str(fname) + ' LINE: ' + str(exc_tb.tb_lineno) + ' TYPE: ' + str(exc_type)) response = {'code': code, 'status': status, 'message': message} self.write(response) await self.finish() return
def require_auth(handler, kwargs): code = 4000 status = False message = '' result = [] try: handler.sessionId = None try: handler.request.client_ip = handler.request.headers.get("X-Real-IP") or \ handler.request.headers.get("X-Forwarded-For") or \ handler.request.remote_ip except: handler.request.client_ip = handler.request.remote_ip Log.i('client_ip', handler.request.client_ip) handler.time = timeNow() handler.set_header('Xen-Protocol-Version', '1.2') requestCros = handler.request.headers.get('Origin') handler.set_header('Access-Control-Allow-Origin', '*') handler.set_header('Access-Control-Allow-Headers', '*') handler.set_header('Access-Control-Allow-Methods', 'DELETE,OPTIONS,GET,HEAD,PATCH,POST,PUT') Log.i('Method', handler.request.method) if requestCros is not None or handler.request.method == 'OPTIONS': handler.set_header('Access-Control-Allow-Origin', '*') requestHeader = handler.request.headers.get( 'Access-Control-Request-Headers') # Log.i('Headers', requestHeader) if requestHeader is not None or handler.request.method == 'OPTIONS': handler.set_header('Access-Control-Allow-Headers', requestHeader) handler.set_header( 'Access-Control-Allow-Methods', 'DELETE,OPTIONS,GET,HEAD,PATCH,POST,PUT') handler._transforms = [] handler.set_status(204) handler.write() handler.finish() return True bearerToken = handler.request.headers.get('Authorization') if bearerToken: bearerToken = str(bearerToken).split('Bearer ') if len(bearerToken): bearerToken = bearerToken[1] sessionId = JWT_DECODE(bearerToken) if type(sessionId) is bytes: sessionId = sessionId.decode() handler.sessionId = sessionId Log.i('Authorization', sessionId) else: raise Exception('Bearer Token') else: handler._transforms = [] handler.set_status(501) code = 4010 message = 'Missing - [ Authorization ]' raise Exception try: # Saving query params in get_arguments handler.request.get_arguments = handler.request.arguments except: handler.request.get_arguments = None return True except Exception as e: if code == 4000: exc_type, exc_obj, exc_tb = sys.exc_info() fname = exc_tb.tb_frame.f_code.co_filename Log.d( 'Xen', 'FILE: ' + str(fname) + ' LINE: ' + str(exc_tb.tb_lineno) + ' TYPE: ' + str(exc_type)) handler._transforms = [] handler.set_status(401) code = 4001 if not len(message): message = 'Invalid headers.' response = { 'code': code, 'status': status, 'result': [], 'message': message } Log.d('Xen', response) handler.write(response) handler.finish()
def require_auth(handler, kwargs): code = 4000 status = False result = [] message = '' try: try: handler.request.client_ip = handler.request.headers.get("X-Real-IP") or \ handler.request.headers.get("X-Forwarded-For") or \ handler.request.remote_ip except: handler.request.client_ip = handler.request.remote_ip Log.i('client_ip', handler.request.client_ip) handler.time = timeNow() handler.set_header('No-Xen-Protocol-Version', '1.0') requestCros = handler.request.headers.get('Origin') if requestCros != None: handler.set_header('Access-Control-Allow-Origin', requestCros) requestHeader = handler.request.headers.get( 'Access-Control-Request-Headers') if requestHeader is not None: handler.set_header('Access-Control-Allow-Headers', requestHeader) handler.set_header('Access-Control-Allow-Methods', 'DELETE,GET,HEAD,PATCH,POST,PUT') handler._transforms = [] handler.set_status(204) handler.write({}) handler.finish() xOriginKey = handler.request.headers.get('x-Origin-Key') if xOriginKey: entityId = FN_DECRYPT(xOriginKey) if not entityId: raise Exception('x-Origin-Key') else: handler.entityId = ObjectId(entityId.decode('utf-8')) Log.i('x-Origin-Key', handler.entityId) else: handler._transforms = [] handler.set_status(501) code = 4020 message = 'Missing - [ x-Origin-Key ].' raise Exception return True except Exception as e: if code == 4000: exc_type, exc_obj, exc_tb = sys.exc_info() fname = exc_tb.tb_frame.f_code.co_filename Log.d( 'No-Xen', 'FILE: ' + str(fname) + ' LINE: ' + str(exc_tb.tb_lineno) + ' TYPE: ' + str(exc_type)) handler._transforms = [] handler.set_status(401) code = 4001 message = 'Invalid headers.' response = { 'code': code, 'status': status, 'result': [], 'message': message } Log.d('No-Xen', response) handler.write(response) handler.finish() return False
async def get(self): status = False code = 4000 result = [] message = '' try: profile = await self.profile.find_one({'_id': self.profileId}) if profile is None: message = 'Profile not found.' code = 4212 raise Exception pAccountQ = self.account.find({'_id': self.accountId}, limit=1) pAccount = [] async for i in pAccountQ: pAccount.append(i) if len(pAccount): v = {} v['closed'] = profile['closed'] v['locked'] = profile['locked'] v['active'] = profile['active'] v['id'] = str(profile.get('_id')) v['firstName'] = pAccount[0].get('firstName') v['lastName'] = pAccount[0].get('lastName') v['contact'] = pAccount[0].get('contact') result.append(v) status = True code = 2000 else: code = 3002 message = 'No Account Found.' except Exception as e: status = False # self.set_status(400) if not len(message): template = 'Exception: {0}. Argument: {1!r}' code = 5010 iMessage = template.format(type(e).__name__, e.args) message = 'Internal Error, Please Contact the Support Team.' exc_type, exc_obj, exc_tb = sys.exc_info() fname = exc_tb.tb_frame.f_code.co_filename Log.w('EXC', iMessage) Log.d( 'EX2', 'FILE: ' + str(fname) + ' LINE: ' + str(exc_tb.tb_lineno) + ' TYPE: ' + str(exc_type)) response = {'code': code, 'status': status, 'message': message} Log.d('RSP', response) try: response['result'] = result self.write(response) await self.finish() return except Exception as e: status = False template = 'Exception: {0}. Argument: {1!r}' code = 5011 iMessage = template.format(type(e).__name__, e.args) message = 'Internal Error, Please Contact the Support Team.' exc_type, exc_obj, exc_tb = sys.exc_info() fname = exc_tb.tb_frame.f_code.co_filename Log.w('EXC', iMessage) Log.d( 'EX2', 'FILE: ' + str(fname) + ' LINE: ' + str(exc_tb.tb_lineno) + ' TYPE: ' + str(exc_type)) response = {'code': code, 'status': status, 'message': message} self.write(response) await self.finish() return
async def get(self): status = False code = 4000 result = [] message = '' try: # TODO: this need to be moved in a global class profileQ = self.profile.find( { 'accountId': self.accountId, 'applicationId': self.applicationId, 'entityId': self.entityId }, limit=1 ) profile = [] async for i in profileQ: profile.append(i) if len(profile): appQ = self.applications.find( { '_id': self.applicationId }, limit=1 ) app = [] async for i in appQ: app.append(i) if len(app): if True: # TODO: till here self.apiId = app[0]['apiId'] Log.i(self.apiId) try: withExtra = bool(self.get_arguments('withExtra')[0]) except: withExtra = False try: limit = int(self.get_arguments('limit')[0]) except: limit = 0 try: skip = int(self.get_arguments('skip')[0]) except: skip = 0 countryQ = self.country.find( { 'disabled': False, }, limit=limit, skip=skip ) async for i in countryQ: i['_id'] = str(i['_id']) if not withExtra: x = {} x['code'] = i['code'] x['name'] = i['name'] x['flag'] = i['flag'] x['flagSymbol'] = i['flagSymbol'] x['dialCode'] = i['dialCode'] x['sDialCode'] = i['sDialCode'] result.append( x ) else: result.append( i ) if len(result): message = '' code = 2000 status = True else: code = 3030 message = 'No data Found.' else: code = 4003 self.set_status(401) message = 'You are not authorized.' else: code = 4003 self.set_status(401) message = 'You are not authorized.' else: code = 4003 self.set_status(401) message = 'You are not authorized.' except Exception as e: status = False # self.set_status(400) if not len(message): template = 'Exception: {0}. Argument: {1!r}' code = 5010 iMessage = template.format(type(e).__name__, e.args) message = 'Internal Error, Please Contact the Support Team.' exc_type, exc_obj, exc_tb = sys.exc_info() fname = exc_tb.tb_frame.f_code.co_filename Log.w('EXC', iMessage) Log.d('EX2', 'FILE: ' + str(fname) + ' LINE: ' + str(exc_tb.tb_lineno) + ' TYPE: ' + str(exc_type)) response = { 'code': code, 'status': status, 'message': message } Log.d('RSP', response) try: response['result'] = result self.write(response) self.finish() return except Exception as e: status = False template = 'Exception: {0}. Argument: {1!r}' code = 5011 iMessage = template.format(type(e).__name__, e.args) message = 'Internal Error, Please Contact the Support Team.' exc_type, exc_obj, exc_tb = sys.exc_info() fname = exc_tb.tb_frame.f_code.co_filename Log.w('EXC', iMessage) Log.d('EX2', 'FILE: ' + str(fname) + ' LINE: ' + str(exc_tb.tb_lineno) + ' TYPE: ' + str(exc_type)) response = { 'code': code, 'status': status, 'message': message } self.write(response) self.finish() return