def wrapper(*args, **kwars):

        token = request.headers.get("Authorization")
        role = Utils.request_role()

        try:
            if not token or token.split(" ")[0] != "Bearer":
                raise InvalidTokenError(token, "Token must be a bearer token",
                                        "Invalid token")

            token_decode = Auth.token_decode(token.split(" ")[1])
            session_id = token_decode["token"]
            exists = Auth.session_exists(session_id, role)

            if not exists:
                raise InvalidTokenError(
                    token, "User does not have an active session",
                    "Invalid token")

        except InvalidTokenError as e:
            return Utils.response(status=e.status,
                                  message="Invalid token",
                                  data=e.errors)

        return f(*args, **kwars)
    def refresh(self, refresh_token: str) -> dict:

        session = Auth.get_session(refresh_token)
        admin = Admin.query.filter_by(id=session["id"]).first()
        data = AdminCreateSchema().dump(admin)
        tokens = Auth.update_session(refresh_token, **data)

        return tokens
    def test_decode_jwt_fail(self):

        with self.assertRaises(InvalidTokenError):
            Auth.token_decode(None)

        with self.assertRaises(InvalidTokenError):
            self.data["exp"] = datetime.now() - timedelta(seconds=30)
            token = jwt.encode(self.data,
                               key=self.secret_key,
                               algorithm=self.algorithms[0])
            Auth.token_decode(token)
    def test_delete_session(self):

        with patch("app.src.common.auth.Auth.token_decode",
                   return_value=self.jwt_decode):
            with patch("app.src.common.auth.config.redis",
                       new=self.mock_redis) as mock:
                Auth.delete_session("token_jwt")
                mock.hgetall.assert_called_with(SESSION_KEY +
                                                self.jwt_decode["token"])
                mock.delete.assert_any_call(SESSION_KEY +
                                            self.jwt_decode["token"])
                mock.delete.assert_any_call(self.session["refresh_id"])
    def test_save_session(self):

        with patch("app.src.common.auth.config.redis",
                   new=self.mock_redis) as mock:
            data = dict(name="test", id=1, ROLE="test")
            Auth.save_session(
                self.session_id.split(":")[1],
                self.refresh_id.split(":")[1], **data)
            data["refresh_id"] = self.refresh_id
            mock.hmset.assert_any_call(self.session_id, data)
            mock.hmset.assert_any_call(
                self.refresh_id,
                dict(ROLE=data["ROLE"], session=self.session_id))
    def test_refresh_token_not_exists(self):

        with patch("app.src.common.auth.config.redis",
                   new=self.mock_redis) as mock_redis:
            exists = Auth.refresh_token_exists("refresh_id", "not")

        self.assertFalse(exists)
Beispiel #7
0
	def login(self, credentials: dict) -> dict:

		schema = AdminLoginSchema()
		
		try:
			credentials = schema.load(credentials)
			storedAdmin = Admin.query.filter_by(username=credentials["username"]).first()
			
			if storedAdmin is None:
				return None

			isLogged = Utils.verify_password(
				storedAdmin.password[0], storedAdmin.password[1], credentials["password"]
				)

			if not isLogged:
				return None
				
			data = AdminCreateSchema().dump(storedAdmin)
			tokens = Auth.generate_session_token("ADMIN", **data)

		except ValidationError as e:
			raise InvalidParametersError(e.data, e.messages, "Error occurred when trying to loggin admin", e)
			
		return tokens
    def test_session_exists(self):

        with patch("app.src.common.auth.config.redis",
                   new=self.mock_redis) as mock_redis:
            exists = Auth.session_exists("session_id", self.role)

        self.assertTrue(exists)
Beispiel #9
0
	def login(self, credentials: dict) -> dict:

		schema = UserLoginSchema()

		try:
			credentials = schema.load(credentials)
			storedUser = User.query.filter_by(email=credentials["email"]).first()
			
			if storedUser is None:
				return None

			isLogged = Utils.verify_password(
				storedUser.password[0], storedUser.password[1], credentials["password"]
				)

			if not isLogged:
				return None

			data = UserCreateSchema().dump(storedUser)
			tokens = Auth.generate_session_token("USER", **data)
			
		except ValidationError as e:
			raise InvalidParametersError(e.data, e.messages, "Error occurred when trying to loggin user", e)	
			
		return tokens
    def test_decode_jwt(self):

        token = jwt.encode(self.data,
                           key=self.secret_key,
                           algorithm=self.algorithms[0])
        token_decode = Auth.token_decode(token)
        self.assertIsNotNone(token_decode)
        self.assertEqual(self.data, token_decode)
    def test_encode_jwt(self):

        token = Auth.token_encode(self.data)
        self.assertIsNotNone(token)
        token_decode = jwt.decode(token,
                                  self.secret_key,
                                  algorithms=self.algorithms)
        self.assertEqual(self.data, token_decode)
    def test_generate_session_token(self):

        with patch("app.src.common.auth.Auth.session_token",
                   return_value="session token"):
            with patch("app.src.common.auth.Auth.token_encode",
                       return_value="token jwt"):
                with patch("app.src.common.auth.Auth.refresh_token",
                           return_value="refresh token"):
                    with patch("app.src.common.auth.Auth.save_session",
                               return_value=None):
                        tokens = Auth.generate_session_token(
                            self.role, **self.data)

        self.assertIsNotNone(tokens)
        self.assertDictEqual(
            dict(token_id="token jwt", refresh_token="refresh token"), tokens)
    def test_update_session(self):

        with patch("app.src.common.auth.Auth.generate_session_token",
                   return_value=dict()):
            with patch("app.src.common.auth.config.redis",
                       new=self.mock_redis) as mock:
                data = dict(name="test", id=1)
                refresh = "refresh_token"
                new_session = Auth.update_session(refresh, **data)

                mock.hget.assert_any_call(REFRESH_TOKEN_KEY + refresh,
                                          "session")
                mock.hget.assert_any_call(self.role, "ROLE")
                mock.delete.assert_any_call(REFRESH_TOKEN_KEY + refresh)
                mock.delete.assert_any_call(self.role)

        self.assertDictEqual(new_session, dict())
        def wrapper(*args, **kwars):

            token = request.headers.get("REFRESH_TOKEN")

            try:
                if not token or token.split(" ")[0] != "Bearer":
                    raise InvalidTokenError(token,
                                            "Token must be a bearer token",
                                            "Invalid token")

                exists = Auth.refresh_token_exists(token.split(" ")[1], role)

                if not exists:
                    raise InvalidTokenError(token, "Invalid refresh token",
                                            "Invalid token")

            except InvalidTokenError as e:
                return Utils.response(status=e.status,
                                      message="Invalid token",
                                      data=e.errors)

            return f(*args, **kwars)
    def test_get_session(self):

        with patch("app.src.common.auth.config.redis", new=self.mock_redis):
            session = Auth.get_session("refresh_id")

        self.assertDictEqual(session, self.session)
Beispiel #16
0
	def get(self):

		token = request.headers.get("Authorization").split(" ")[-1]
		Auth.delete_session(token)

		return Utils.response(message="Request succesfull")
    def test_get_refresh_token(self):

        token = Auth.refresh_token()
        self.assertIsNotNone(token)
    def test_get_session_token(self):

        token = Auth.session_token()
        self.assertIsNotNone(token)