示例#1
0
    def authenticate(self, request: Union[Request, FlaskRequest]) -> Any:
        """Method that will extract the JWT authorization header from the request,
        and will then call the `deserialize_user` method with the decoded content of the token.
        The `validate_credentials` method should be implemented by the user. This method is called
        by Customs internally and is not intended for external use.

        Args:
            request (Union[Request, FlaskRequest]): The incoming request (usually a Flask request)

        Raises:
            UnauthorizedException: Raised when the user is not authorized (invalid or missing credentials)

        Returns:
            Dict: The user information
        """

        # Get the token
        credentials = self.extract_credentials(request)
        token = credentials.get("token")
        if token is None:
            raise UnauthorizedException("No token found")

        # Decode and validate the token
        try:
            decoded = jwt.decode(token, self.key)
            return self.deserialize_user(decoded)

        except Exception:
            raise UnauthorizedException()
示例#2
0
    def authenticate(self, request: Union[Request, FlaskRequest]) -> Any:
        """Method that will extract the basic authorization header from the request,
        and will then call the `validate_credentials` method with a username and password.
        The `validate_credentials` method should be implemented by the user. This method is called
        by Customs internally and is not intended for external use.

        Args:
            request (Union[Request, FlaskRequest]): The incoming request (usually a Flask request)

        Raises:
            UnauthorizedException: Raised when the user is not authorized (invalid or missing credentials)

        Returns:
            Dict: The user information
        """

        # Extract the credentials
        credentials = self.extract_credentials(request)
        username = credentials.get("username")
        password = credentials.get("password")

        # Test authentication
        if username is None or password is None:
            raise UnauthorizedException()  # pragma: no cover
        return self.validate_credentials(username, password)
示例#3
0
    def authenticate(self, request: Union[Request, FlaskRequest]) -> Any:
        credentials = self.extract_credentials(request)
        username = credentials.get("username")
        password = credentials.get("password")

        if username is None or password is None:
            raise UnauthorizedException()
        return self.validate_credentials(username, password)
示例#4
0
    def extract_credentials(
            self, request: Union[Request, FlaskRequest]) -> Dict[str, str]:

        # Parse the headers of the request
        headers = parse_headers(request)
        authorization_header = headers.get("authorization", "")

        if authorization_header.lower().startswith("basic "):
            try:
                decoded = base64.b64decode(
                    authorization_header[len("basic "):])
                username, password = decoded.decode("utf-8").split(":")
                return {"username": username, "password": password}
            except Exception as e:
                print(e)
                raise UnauthorizedException()

        else:
            raise UnauthorizedException()
示例#5
0
    def deserialize_user(self, data: Dict) -> Any:

        # Get the user ID from the session
        user_id = str(data.get("id"))

        # Conver the ID back to the user data from the database
        if user_id is not None and user_id in DATABASE:
            return {"id": str(data.get("id")), **DATABASE[str(data.get("id"))]}
        else:
            raise UnauthorizedException()
示例#6
0
def test_UnauthorizedException():

    # Create a instances of the exception to test
    exceptions = [UnauthorizedException(), UnauthorizedException("Test", 404)]

    # Test all instances
    for exception in exceptions:

        # Make sure it has the right subclass
        assert isinstance(
            exception,
            HTTPException), "All exceptions should subclass the HTTPException"

        # Make sure it has a message and status code
        assert (hasattr(exception, "message")
                and isinstance(exception.message, str)
                and exception.message != ""
                ), "UnauthorizedException has no valid 'message' attribute"

        assert (hasattr(exception, "status_code")
                and isinstance(exception.status_code, int)
                and exception.status_code >= 100 and exception.status_code <=
                900), "UnauthorizedException doesn't have a valid status code"
示例#7
0
    def authenticate(self, request: Union[Request, FlaskRequest]) -> Any:
        """Method to authenticate a user.

        Args:
            request (Union[Request, FlaskRequest]): [description]

        Raises:
            UnauthorizedException: [description]

        Returns:
            Any: [description]
        """

        # Deserialize the user from the session
        try:
            self.validate_token()
            return self.deserialize_user(session["user"])
        except Exception:
            raise UnauthorizedException()
示例#8
0
    def validate_token(self) -> Dict:
        """Method to validate a Google token with Google.

        Raises:
            UnauthorizedException: When the user isn't authenticated or token is not valid

        Returns:
            Dict: The data from the token
        """

        try:
            # Get the token
            access_token = self.token["access_token"]
            validate_url = f"https://www.googleapis.com/oauth2/v1/tokeninfo?access_token={access_token}"

            # No OAuth2Session is needed, just a plain GET request
            data = requests.get(validate_url).json()
            return data

        except Exception:
            raise UnauthorizedException()
示例#9
0
    def get_user_info(self) -> Dict:
        """Method to get user info for the logged in user.

        Raises:
            UnauthorizedException: When the user is not authenticated

        Returns:
            Dict: The user profile
        """

        try:

            # Get the token
            token = self.token

            # Helper method to update the token in the session
            def token_updater(token):
                self.token = token

            # Get a session with auto-refresh of the token
            client = OAuth2Session(
                self.client_id,
                token=token,
                auto_refresh_kwargs={
                    "client_id": self.client_id,
                    "client_secret": self.client_secret,
                },
                auto_refresh_url=self.refresh_url,
                token_updater=token_updater,
            )

            if self.name == "facebook":
                facebook_compliance_fix(client)

            # Return the user info
            return client.get(self.user_profile_endpoint + "fields=" +
                              ",".join(self.fields)).json()

        except Exception:
            raise UnauthorizedException()
示例#10
0
    def validate_token(self) -> Dict:
        """Method to validate a Github token with Github.

        Raises:
            UnauthorizedException: When the user isn't authenticated or token is not valid

        Returns:
            Dict: The data from the token
        """

        try:
            # Get the token
            access_token = self.token["access_token"]
            validate_url = f"https://api.github.com/applications/{self.client_id}/tokens/{access_token}"

            # No OAuth2Session is needed, just a plain GET request
            data = requests.get(validate_url).json()
            return data

        except Exception as e:
            print(e)
            raise UnauthorizedException()
示例#11
0
 def validate_credentials(self, username: str, password: str) -> Dict:
     if username in DATABASE and DATABASE[username].get(
             "password") == password:
         return DATABASE[username]
     else:
         raise UnauthorizedException()
示例#12
0
 def get_or_create_user(self, user: Dict) -> Dict:
     if user.get("username") in DATABASE:
         return DATABASE[user["username"]]
     else:
         raise UnauthorizedException()