def fn():
     passport = AuthUtils().get_authorized_passport(
         from_where='Request',
         verify_blacklist=False,
         token_key='refresh_token')
     print(passport)
     data = request.get_json()
     if passport['user'].refresh_token == data['refresh_token']:
         try:
             token = create_access_token(
                 identity=passport['access']['identity'])
             refresh_token = create_refresh_token(
                 identity=passport['access']['identity'])
             passport['user'].refresh_token = refresh_token
             self.session.commit()
             return {
                 'access_token': token,
                 'refresh_token': refresh_token
             }, 200
         except Exception as e:
             print(e)
             return ErrorHandler().get_error(
                 500, 'Error to process the token refreshing.')
     else:
         return ErrorHandler().get_error(
             401, 'The given Refresh Token is not available.')
    def run_if_not_raise(self, fn):
        """Catch exception if it occurs, if not, execute the given function."""

        try:
            return fn()
        except NotAuthorizedError as e:
            return ErrorHandler().get_error(401, str(e))
        except BadRequestError as e:
            return ErrorHandler().get_error(400, str(e))
        except NotFoundError as e:
            return ErrorHandler().get_error(404, str(e))
        except Exception as e:
            return ErrorHandler().get_error(500, str(e))
 def fn():
     passport = AuthUtils().get_authorized_passport(
         from_where='Request', verify_blacklist=True)
     if not passport['user'].refresh_token or passport[
             'user'].refresh_token == '':
         return ErrorHandler().get_error(401, 'Token already revoked.')
     try:
         data = request.get_json()
         passport['user'].refresh_token = None
         blacklist = Blacklist(type='token',
                               value=data['token'],
                               target='auth')
         self.session.add(blacklist)
         self.session.commit()
         return {'message': 'Token revoked successfully.'}, 200
     except Exception as e:
         self.session.rollback()
         return ErrorHandler().get_error(
             500, 'Error to process the token revoking.')
    def post(self):
        """Sets the available endpoints to deal with Tokens."""

        if str(request.url_rule) == '/api/get-token':
            return self._get_token()
        elif str(request.url_rule) == '/api/refresh-token':
            return self._refresh_token()
        elif str(request.url_rule) == '/api/revoke-token':
            return self._revoke_token()
        elif str(request.url_rule) == '/api/test-token':
            return self._test_token()
        return ErrorHandler().get_error(405, 'Method not allowed.')
    def _get_token(self):
        """Gets the Token and Refresh Token to valid user."""

        data = request.get_json()
        if 'login' in data and 'password' in data and data[
                'login'] != '' and data['password'] != '':
            user = self.session.query(User).filter_by(
                login=data['login']).first()
            if user:
                if bcrypt.check_password_hash(user.password, data['password']):
                    user_identity = {
                        'id': user.id,
                        'login': user.login,
                        'role': user.role.name
                    }
                    try:
                        token = create_access_token(identity=user_identity)
                        refresh_token = create_refresh_token(
                            identity=user_identity)
                        user.refresh_token = refresh_token
                        self.session.commit()
                        return {
                            'access_token': token,
                            'refresh_token': refresh_token
                        }, 200
                    except Exception as e:
                        return ErrorHandler().get_error(
                            500, 'Error to process your login.')
                else:
                    return ErrorHandler().get_error(401,
                                                    'Invalid credencials.')
            else:
                return ErrorHandler().get_error(401, 'Invalid credencials.')
        else:
            return ErrorHandler().get_error(
                400, 'Insufficient data to authenticate.')
    def test_ErrorHandler_get_error__string(self):
        payload_1 = 200
        payload_2 = 'Lorem ipsum dolor.'
        payload_3 = 200

        error = ErrorHandler().get_error(200, 'Lorem ipsum dolor.')

        response_1 = int(error[0]['error'])
        response_2 = error[0]['message']
        response_3 = int(error[1])

        self.assertEqual(payload_1, response_1,
                         'ErrorHandler().get_error does not return 200.')
        self.assertEqual(
            payload_2, response_2,
            'ErrorHandler().get_error does not return \'Lorem ipsum dolor.\'.')
        self.assertEqual(payload_3, response_3,
                         'ErrorHandler().get_error does not return 200.')
    def run_if_not_raise(fn, session=None):
        """Catch exception if it occurs, if not, execute the given function."""

        try:
            return fn()
        except NotAuthorizedError as e:
            return ErrorHandler().get_error(401, e.message)
        except BadRequestError as e:
            return ErrorHandler().get_error(400, e.message)
        except NotFoundError as e:
            return ErrorHandler().get_error(404, e.message)
        except Exception as e:
            return ErrorHandler().get_error(500, str(e))
        except SQLAlchemyError as e:
            return ErrorHandler().get_error(500, str(e))
        except HTTPException as e:
            return ErrorHandler().get_error(500, str(e))
        except AttributeError as e:
            return ErrorHandler().get_error(500, str(e))
        except Exception as e:
            return ErrorHandler().get_error(500, str(e))
        finally:
            if session:
                session.rollback()