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 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 displayLogin(): username = input('Username: '******'Password: '******'msg']) _uAuth.storeTokens(t_type='access', token=r.body['access_token']) return _pageLogged.menu()
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 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 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 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 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 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 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()
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 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 displayInnit(): username = input('Type the user with whom to start the chat: ') r = _serviceChat.innit(username) if _functions.resultError(r): return r _functions.setModuleSuccess(payload=r.body['msg'])
def displayList(): r = _serviceChat.list() if _functions.resultError(r): return r _functions.setModuleSuccess(payload=r.body) return _pageLogged.menu()
# Routes imports from routes.public import status as _status, signup as _signup, login as _login from routes.private import user as _privUser, auth as _privAuth, chat as _privChat, message as _privMessage # Models from models import rest as _rest, redis as _redis, auth as _modelAuth # Modules from modules.db import db as _db, tmp_db as _tmpDb from modules.user import user as _moduleUser _db.instance() app = Flask(__name__) # Create http server CORS(app) _Config = _functions.Config if _functions.resultError(_Config): exit(1) app.secret_key = _Config['app']['secret'] api = Api(app) socketio = SocketIO(app) ACCESS_EXPIRES = _tmpDb.TokensExpires.access_expires REFRESH_EXPIRES = _tmpDb.TokensExpires.refresh_expires app.config['JWT_ACCESS_TOKEN_EXPIRES'] = ACCESS_EXPIRES app.config['JWT_REFRESH_TOKEN_EXPIRES'] = REFRESH_EXPIRES app.config['JWT_BLACKLIST_ENABLED'] = True app.config['JWT_BLACKLIST_TOKEN_CHECKS'] = ['access', 'refresh'] app.config['JWT_SECRET_KEY'] = _Config['jwt']['secret']