Ejemplo n.º 1
0
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')
Ejemplo n.º 2
0
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')
Ejemplo n.º 3
0
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)
Ejemplo n.º 4
0
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)
Ejemplo n.º 5
0
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)
Ejemplo n.º 6
0
 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()
Ejemplo n.º 7
0
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)
Ejemplo n.º 8
0
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'])
Ejemplo n.º 9
0
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)
Ejemplo n.º 10
0
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)
Ejemplo n.º 11
0
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)
Ejemplo n.º 12
0
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)
Ejemplo n.º 13
0
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'])
Ejemplo n.º 14
0
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)
Ejemplo n.º 15
0
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)
Ejemplo n.º 16
0
 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()
Ejemplo n.º 17
0
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)
Ejemplo n.º 18
0
 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()
Ejemplo n.º 19
0
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)
Ejemplo n.º 20
0
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)
Ejemplo n.º 21
0
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)
Ejemplo n.º 22
0
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)
Ejemplo n.º 23
0
    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()
Ejemplo n.º 24
0
 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()
Ejemplo n.º 25
0
 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()
Ejemplo n.º 26
0
 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()
Ejemplo n.º 27
0
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)
Ejemplo n.º 28
0
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)
Ejemplo n.º 29
0
 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()
Ejemplo n.º 30
0
    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()