<filename>code/05_mqtt_to_giotcloud/get_jwt.py
#!/usr/bin/env python3

import datetime

import jwt

PROJECT_ID = 'iot-workshop-2020'
SSL_PRIVATE_KEY_FILEPATH = PROJECT_ID+"_ec_private.pem"
SSL_ALGORITHM = 'ES256'


def create_jwt(project_id, private_key_file, algorithm):
    """Creates a JWT (https://jwt.io) to establish an MQTT connection.
        Args:
         project_id: The cloud project ID this device belongs to
         private_key_file: A path to a file containing either an RSA256 or
                 ES256 private key.
         algorithm: The encryption algorithm to use. Either 'RS256' or 'ES256'
        Returns:
            An MQTT generated from the given project_id and private key, which
            expires in 60 minutes. After 60 minutes, your client will be
            disconnected, and a new JWT will have to be generated.
        Raises:
            ValueError: If the private_key_file does not contain a known key.
        """

    token = {
        # The time that the token was issued at
        'iat': datetime.datetime.utcnow(),
        # The time the token expires.
        'exp': datetime.datetime.utcnow() + datetime.timedelta(minutes=60),
        # The audience field should always be set to the GCP project id.
        'aud': project_id
    }

    # Read the private key file.
    with open(private_key_file, 'r') as f:
        private_key = f.read()

    #print('Creating JWT using {} from private key file {}'.format(algorithm, private_key_file))

    return str(jwt.encode(token, private_key, algorithm=algorithm), "utf-8")


#print('JWT token:')
print(create_jwt(PROJECT_ID, SSL_PRIVATE_KEY_FILEPATH, SSL_ALGORITHM))
