def checkMinData(_dict, _reqr): try: for item in _reqr: if not item in _dict: return _functions.setModuleError( payload=f'Missing field {item} on the request', error=f'{item} whas not found on the request') return True except Exception as e: return _functions.setModuleError(payload=e, error='Error checkig endpoint data')
def openToken(**args): try: oFile = 'access' if args.get('t_type' == 'refresh'): oFile = 'refresh' path=f'{_defaults.app_config}/auth/{oFile}.token.jwt' rInst = _functions.openFile(path, 'r') if _functions.resultError(rInst): return rInst return rInst.read() except Exception as e: _functions.setModuleError(payload=e, error='Error looking for the local token')
def unHashPassword(p_password, h_password): try: if not bcrypt.checkpw(p_password.encode(), h_password.encode()): return _functions.setModuleError(payload='Hases not equals', error='Bad password', status=401) return True except Exception as e: return _functions.setModuleError( payload=e, error='Error unhashing password, try it later...', status=500)
def storeTokens(**args): try: nFile = 'access' if args.get('t_type') == 'refresh': nFile == 'refresh' path=f'{_defaults.app_config}/auth/{nFile}.token.jwt' wInst = _functions.openFile(path, 'w+') if _functions.resultError(wInst): return wInst wInst.write(f'Bearer {args.get("token")}') except Exception as e: _functions.setModuleError(payload=e, error='Error storage tokens') exit(1)
def allowedRead(userId): try: userAllowed = _models.Chat.objects( alloweds__contains=_utilsDb.hexToObjectId(userId)) if userAllowed: return True return _functions.setModuleError( payload='userId is not in alloweds array', error='User not allowed to access the chat') except Exception as e: return _functions.setModuleError( payload=e, error='Error checking if user is allowed to access chat ...', status=500)
def post(self): try: args = request.args parser.add_argument('message', help='Chat message', required=True) reqData = parser.parse_args() userId = get_jwt_claims() userAllowed = _mSharedChat.allowedRead(userId['identity']) if _functions.resultError(userAllowed): return userAllowed.flaskResp() sChat = _mChat.findById(args['chatId']) if _functions.resultError(sChat): return sChat.flaskResp() new_message = { 'message': reqData['message'], 'from': userId['identity'], 'read': False, } uChat = _mSharedMessage.new(sChat.id, new_message) if _functions.resultError(uChat): return uChat.flaskResp() return _functions.setModuleSuccess(payload=uChat.messages, key='mongo', status=200).flaskResp() except Exception as e: return _functions.setModuleError(payload=e, error='Error posting new message', status=500).flaskResp()
def findById(userId): try: return _models.User.objects.get(_id=userId) except Exception as e: return _functions.setModuleError(payload=e, error='Error find user ...', status=500)
def list(): try: r = _sUtils.request('/chat', {}, _defaults.access_token).get() r.res.raise_for_status() return r except requests.exceptions.HTTPError as err: return _functions.setModuleError(payload=err, error=r.body['msg'])
def findById(chatId): try: return _models.Chat.objects.get(id=chatId) except Exception as e: return _functions.setModuleError(payload=e, error='Error find chat by id ...', status=500)
def alive(): try: return _functions.setModuleSuccess(payload='Hi, how are you', status=200) except Exception as e: return _functions.setModuleError(payload=e, error="Error checking alive", status=500)
def checkExists(field, value): try: return _models.User.objects.get(**{'{}'.format(field): value}) except _models.User.DoesNotExist: return False except Exception as e: return _functions.setModuleError(payload=e, error='Error check user exists ...', status=500)
def new(chatId, new_message): try: new_message['from'] = _utilsDb.hexToObjectId(new_message['from']) _models.Chat.objects(id=chatId).update_one(push__messages=new_message) return _models.Chat.objects.get(id=chatId) except Exception as e: return _functions.setModuleError(payload=e, error='Error list chat messages ...', status=500)
def signup(user): try: r = _sUtils.request('/signup', { 'username': user.username, 'password': user.password }).post() r.res.raise_for_status() return r except requests.exceptions.HTTPError as err: return _functions.setModuleError(payload=err, error=r.body['msg'])
def hashPassword(p_password): try: e_p_password = p_password.encode() sal = bcrypt.gensalt() return bcrypt.hashpw(e_p_password, sal) except Exception as e: return _functions.setModuleError( payload=e, error='Error hashing password, try it later...', status=500)
def encodeJwt(user): try: return _auth.Tokens( token=createAccessToken(user), rToken=create_refresh_token(identity=str(user._id))) except Exception as e: return _functions.setModuleError( payload=e, error='Error generating token, try it later...', status=500)
def delete(self): try: jti = get_raw_jwt()['jti'] _tmpDb.RevokeInstance.set(jti, 'true', ACCESS_EXPIRES * 1.2) return _functions.setModuleSuccess(payload='Access token revoked', status=200).flaskResp() except Exception as e: return _functions.setModuleError( payload=e, error='Error access token revoked ...', status=500).flaskResp()
def checkPassword(password): _min = 16 _max = 100 valid = validLength(_min=_min, _max=_max, _str=password) if valid is True: return valid return _functions.setModuleError( payload=f'Password wrong length: {len(password)}', error=f'Min password length {_min}, maximum {_max}', status=400)
def get(self): try: userId = get_jwt_identity() sUser = _mUser.findById(userId) if sUser is None: return _responses.userNotFound().flaskResp() if _functions.resultError(sUser): return sUser.flaskResp() return _functions.setModuleSuccess(payload=_mUser.selectInfo(['email', 'dni', 'name', 'surname', 'age'], sUser), key='master', status=200).flaskResp() except Exception as e: return _functions.setModuleError(payload=e, error='Error accessing user information ...').flaskResp()
def createAccessToken(user): try: return create_access_token({ 'identity': str(user._id), 'username': user['username'] }) except Exception as e: return _functions.setModuleError( payload=e, error='Error creating access token, try it later...', status=500)
def myChats(userId): try: userChats = list( _models.User.objects.aggregate(*[ { '$match': { '_id': _mDbUtils.hexObjId(userId) } }, { '$lookup': { 'from': _models.Chat._get_collection_name(), 'localField': 'chats', 'foreignField': '_id', 'as': 'chatObjects' } }, { '$unwind': { 'path': '$chatObjects', 'preserveNullAndEmptyArrays': True } }, { '$lookup': { 'from': _models.User._get_collection_name(), 'localField': 'chatObjects.creator', 'foreignField': '_id', 'as': 'chatObjects.creator' } }, { '$lookup': { 'from': _models.User._get_collection_name(), 'localField': 'chatObjects.alloweds', 'foreignField': '_id', 'as': 'chatObjects.alloweds' } }, { '$group': { '_id': "$_id", 'chats': { "$push": "$chatObjects" } } }, ]))[0]['chats'] return myChatsClear(userChats) except Exception as e: return _functions.setModuleError(payload=e, error='Error listing user chats ...', status=500)
def findOneAndUpdate(field, value, uField, uValue): try: condition = {'{}'.format(field): value} checkChat = checkExists(field, value) if _functions.resultError(checkChat): return checkChat if not checkChat: return _responses.userNotFound() return _models.Chat.objects(**condition).update_one(push__chats=uValue) except Exception as e: return _functions.setModuleError(payload=e, error='Error updating chat ...', status=500)
def findOne(field, value): try: condition = {'{}'.format(field): value} checkUser = checkExists(field, value) if _functions.resultError(checkUser): return checkUser if not checkUser: return _responses.userNotFound() return _models.User.objects.get(**condition) except Exception as e: return _functions.setModuleError(payload=e, error='Error find user ...', status=500)
def post(self): try: reqData = parser.parse_args() user = _moduleUser.findOne('username', reqData['username']) if user is None: return _functions.setModuleError( payload='User not found on DB', error='User not found, try it later...', status=404).flaskResp() unHashPassword = _auth.unHashPassword(reqData['password'], user['password']) if _functions.resultError(unHashPassword): return unHashPassword.flaskResp() tokens = _auth.encodeJwt(user) if _functions.resultError(tokens): return tokens.flaskResp() access_jti = get_jti(encoded_token=tokens.token) refresh_jti = get_jti(encoded_token=tokens.rToken) _tmpDb.RevokeInstance.set( access_jti, 'false', _tmpDb.TokensExpires.access_expires * 1.2) _tmpDb.RevokeInstance.set( refresh_jti, 'false', _tmpDb.TokensExpires.refresh_expires * 1.2) return _functions.setModuleSuccess(payload={ 'msg': 'Login success', 'access_token': tokens.token, 'refresh_token': tokens.rToken }, key='master', status=201).flaskResp() except Exception as e: return _functions.setModuleError( payload=e, error='Error login user, try it later...', status=500).flaskResp()
def post(self): try: current_user = get_jwt_identity() access_token = _utilAuth.createAccessToken(current_user) access_jti = get_jti(encoded_token=access_token) _tmpDb.RevokeInstance.set(access_jti, 'false', ACCESS_EXPIRES * 1.2) return _functions.setModuleSuccess(payload={ 'access_token': access_token }, key='master', status=201).flaskResp() except Exception as e: return _functions.setModuleError( payload=e, error='Error refreshing token ...').flaskResp()
def get(self): try: user = get_jwt_claims() sUser = _mUser.findOne('_id', user['identity']) if _functions.resultError(sUser): return sChat.flaskResp() userChats = _mUser.myChats(user['identity']) if _functions.resultError(sUser._id): return userChats.flaskResp() return _functions.setModuleSuccess(payload=list(userChats), key='mongo', status=200).flaskResp() except Exception as e: return _functions.setModuleError( payload=e, error='Error listing chats, try it later ...', status=500).flaskResp()
def get(self): try: args = request.args userId = get_jwt_claims() userAllowed = _mSharedChat.allowedRead(userId['identity']) if _functions.resultError(userAllowed): return userAllowed.flaskResp() sChat = _mChat.findById(args['chatId']) if _functions.resultError(sChat): return sChat.flaskResp() return _functions.setModuleSuccess(payload=sChat.messages, key='mongo', status=200).flaskResp() except Exception as e: return _functions.setModuleError(payload=e, error='Error posting new message', status=500).flaskResp()
def myChatsClear(aggregateObj): try: userUnwantedRes = _responses.unwantedRes('user') for count, chat in enumerate(aggregateObj): aggregateObj[count]['creator'] = aggregateObj[count]['creator'][0] [ aggregateObj[count]['creator'].pop(_pull) for _pull in userUnwantedRes ] for u_count, allowed in enumerate(aggregateObj[count]['alloweds']): [ aggregateObj[count]['alloweds'][u_count].pop(_pull) for _pull in userUnwantedRes ] return aggregateObj except Exception as e: return _functions.setModuleError( payload=e, error='Error cleaning user chats list ...', status=500)
def findOneAndUpdate(field, value, uField, uValue): try: condition = {'{}'.format(field): value} checkUser = checkExists(field, value) if _functions.resultError(checkUser): return checkUser if not checkUser: return _responses.userNotFound() if uField == 'chats': return _models.User.objects(**condition).update_one( push__chats=uValue) elif uField == 'sids': if isinstance(value, str): value = _uDb.hexToObjectId(value) return _models.User.objects(**condition).update_one( push__sids=uValue) except Exception as e: return _functions.setModuleError(payload=e, error='Error updating user ...', status=500)
def post(self): try: reqData = parser.parse_args() vPassword = _validators.checkPassword(reqData['password']) if _functions.resultError(vPassword): return vPassword.flaskResp() hashPassword = _auth.hashPassword(reqData['password']) if _functions.resultError(hashPassword): return hashPassword newRoundsMan = _models.User( username=reqData['username'], password=hashPassword, ) newRoundsMan.save() return _functions.setModuleSuccess( payload='User created successfully', status=200).flaskResp() except Exception as e: return _functions.setModuleError( payload=e, error='Error crating new user, try it later...', status=500).flaskResp()
def post(self): try: parser.add_argument('username', help='User with whom to start the chat', required=False) parser.add_argument('chat', help='Chat id', required=False) reqData = parser.parse_args() alloweds = [] sUser = _mUser.findOne('username', reqData['username']) if _functions.resultError(sUser): return sUser.flaskResp() alloweds.append(sUser._id) creator = get_jwt_claims() alloweds.append(creator['identity']) newChat = _models.Chat(creator=creator['identity'], alloweds=alloweds) newChat.save() uUser = _mUser.findOneAndUpdate('_id', creator['identity'], 'chats', newChat.id) if _functions.resultError(uUser): return uUser.flaskResp() uToUser = _mUser.findOneAndUpdate('_id', sUser._id, 'chats', newChat.id) if _functions.resultError(uToUser): return uUser.flaskResp() return _functions.setModuleSuccess( payload='Chat initialized correctly', status=200).flaskResp() except Exception as e: return _functions.setModuleError( payload=e, error='Error creating new chat, try it later ...', status=500).flaskResp()