Exemple #1
0
class AccessToken:
    """ Access Token Util Class"""
    def __init__(self):

        self.__instance = JWT()
        self.__algorithm = "RS256"
        with open(get_root() + 'auth' + os.sep + 'jwtRS256_private.pem',
                  'rb') as fh:
            self.__signing_key = jwk_from_pem(fh.read())
        with open(get_root() + 'auth' + os.sep + 'jwtRS256_public.pem',
                  'rb') as fh:
            self.__verifying_key = jwk_from_pem(fh.read())

    def create_access_token(self,
                            *,
                            data: dict,
                            expires_delta: timedelta = None) -> str:
        """Create Access Token Using JWT with RSA256 Encryption"""
        to_encode = data.copy()
        if expires_delta:
            expire = datetime.utcnow() + expires_delta
        else:
            expire = datetime.utcnow() + timedelta(minutes=15)
        to_encode.update({"ist": get_int_from_datetime(datetime.utcnow())})
        to_encode.update({"exp": get_int_from_datetime(expire)})
        encoded_jwt = self.__instance.encode(to_encode, self.__signing_key,
                                             self.__algorithm)
        return encoded_jwt

    def decode_access_token(self, *, token: str) -> Dict:
        """ Decode Access Token """
        return self.__instance.decode(token,
                                      self.__verifying_key,
                                      do_time_check=False)

    def generate_password_reset_token(self, email: str) -> str:
        """ Generate Access Token for password Reset email"""
        delta = timedelta(hours=EmailSettings.EMAIL_RESET_TOKEN_EXPIRE_HOURS)
        now = datetime.utcnow()
        expires = now + delta
        encoded_jwt = self.__instance.encode(
            {
                "exp": get_int_from_datetime(expires),
                "ist": get_int_from_datetime(now),
                "sub": email
            },
            self.__signing_key,
            alg=self.__algorithm,
        )
        return encoded_jwt

    def verify_password_reset_token(self, token: str) -> Dict:
        """ Decode Access Token """
        return self.__instance.decode(token,
                                      self.__verifying_key,
                                      do_time_check=False)
Exemple #2
0
def sign_in():
    if request.method == "GET":
        if get_jwt():
            return redirect(url_for("videos"))
        else:
            return template("sign_in.html")
    if request.method == "POST":
        # Maybe use an actual db here? idk lol
        conn = sqlite3.connect(":memory:")
        c = conn.cursor()
        c.execute("CREATE TABLE users (username char, password char, privilege int)")
        c.execute("INSERT INTO users (username, password, privilege) VALUES ('Harry', 'P@ssw0rd123!s%dgyASD', 1);")
        c.execute("INSERT INTO users (username, password, privilege) VALUES ('John', 'cr1k3yth4ts4l0ngp4ss', 1);")
        c.execute("INSERT INTO users (username, password, privilege) VALUES ('Dave', 'p3rf3ct1nfr4structre', 1);")
        c.execute(f"SELECT * FROM users WHERE username = '******'user']}' AND password = '******'pass']}';")
        res = c.fetchall()
        if len(res) == 0:
            return template("sign_in.html", error="Invalid username / password.")
        if len(res) > 1:
            return template("sign_in.html", error="Attempting to login as more than one user!??")

        key = jwk.OctetJWK(bytes(JWT_SECRET, "utf-8"))

        jwt = JWT()
        jwt = jwt.encode({"user": res[0][0], "privilege": res[0][2]}, key, 'HS256')

        resp = make_response(redirect(url_for("videos")))
        resp.set_cookie("auth", jwt)
        return resp
Exemple #3
0
def genToken(appid):
    import json
    import datetime
    import time
    import calendar
    import requests
    from jwt import (
        JWT,
        jwk_from_pem,
    )
    exp = datetime.datetime.utcnow() + datetime.timedelta(minutes=10)
    exp = calendar.timegm(exp.timetuple())
    message = {
        'iat': int(time.time()),
        'exp': exp,
        'iss': 39888,
    }
    with open('now-deploy.pem', 'rb') as fh:
        signing_key = jwk_from_pem(fh.read())
    jwt = JWT()
    compact_jws = jwt.encode(message, signing_key, 'RS256')
    data = {
        'Authorization': f'Bearer {compact_jws}',
        'Accept': 'application/vnd.github.machine-man-preview+json'
    }
    r = requests.post(
        url=f"https://api.github.com/app/installations/{appid}/access_tokens",
        headers=data)
    data = r.json()
    token = data["token"]
    return token
Exemple #4
0
def jwt_for_user(user):
    init = time.time()
    exp = datetime.now() + timedelta(hours=3)
    exp = time.mktime(exp.timetuple())
    message = {'iss': 'dc_games', 'sub': user.id, 'iat': init, 'exp': exp}
    jwt = JWT()
    return jwt.encode(message, jwt_key_priv, 'RS256'), exp
Exemple #5
0
def genToken(appid):
    exp = datetime.datetime.utcnow() + datetime.timedelta(minutes=10)
    exp = calendar.timegm(exp.timetuple())
    message = {
        'iat': int(time.time()),
        'exp': exp,
        'iss': 41287,
    }

    signing_key = get_key()

    jwt = JWT()

    compact_jws = jwt.encode(message, signing_key, 'RS256')

    data = {
        'Authorization': f'Bearer {compact_jws}',
        'Accept': 'application/vnd.github.machine-man-preview+json'
    }

    r = requests.post(
        url=f"https://api.github.com/app/installations/{appid}/access_tokens",
        headers=data)

    data = r.json()

    token = data["token"]
    return token
Exemple #6
0
    def gen_jwt_token(self, user):
        token_dict = {
            'username': user.username,
            'phone': user.telephone,
            'exp': time.time() + 24 * 3600,
            'iat': time.time()
        }

        obj = JWT()
        token = obj.encode(token_dict, key=self.verifying_key)
        return token
Exemple #7
0
def get_jwt(pem):
    # Encodes and returns JWT
    from jwt import JWT, jwk_from_pem

    payload = {
        "iat": int(time.time()),
        "exp": int(time.time()) + (10 * 60),
        "iss": os.environ.get("APP_ID"),
    }

    jwt = JWT()

    return jwt.encode(payload, jwk_from_pem(pem), "RS256")
Exemple #8
0
def get_jwt(subject, name, issuer) -> str:
    ident = {
        'sub': subject,
        'name': name,
        'iss': issuer,
        'iat': get_int_from_datetime(datetime.now(timezone.utc)),
    }

    signing_key = get_signing_key()

    instance = JWT()

    return instance.encode(ident, signing_key, alg='RS256')
Exemple #9
0
    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        if serializer.is_valid(raise_exception=True):
            print(request.data)
            account = Account.objects.filter(request.data)
            if account:
                account = JWT.encode(account, key='jhl')
                res = Response(serializer.data, status=status.HTTP_200_OK)
                res.set_cookie('account', account)
                return res
            return Response('No this account',
                            status=status.HTTP_404_NOT_FOUND)

        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Exemple #10
0
def get_auth_header(installation_id, priv_key):
    payload = {"iss": 6166,
               "iat": int(time.time()),
               "exp": int(time.time()) + 300}
    jwt = JWT()
    token = jwt.encode(payload, priv_key, 'RS256')
    # url = "https://api.github.com/app"
    url = "https://api.github.com/installations/%s/access_tokens" % installation_id
    headers = {'Accept': 'application/vnd.github.machine-man-preview+json',
               'Authorization': 'Bearer ' + token}
    r = requests.post(url, headers=headers)
    ret_headers = {"Authorization": "token " + r.json()["token"],
                   "Accept": "application/vnd.github.machine-man-preview+json"}
    return ret_headers
Exemple #11
0
    def generate_token(self):
        jwt = JWT()
        # Generate the JWT
        payload = {
            # issued at time
            'iat': int(time.time()),
            # JWT expiration time (10 minute maximum)
            'exp': int(time.time()) + self.expiration,
            # GitHub App's identifier
            'iss': self.iss
        }

        token = jwt.encode(payload, self.key, 'RS256')

        return token
 def _get_jwt(self):
     """ This creates a JWT that can be used to retrieve an authentication
     token for the Github app."""
     jwt = JWT()
     now = int(time.time())
     payload = {
         "iat": now,
         "exp": now + (60),
         "iss": self.noisepage_repo_client.app_id
     }
     private_key = jwk_from_pem(str.encode(self.private_key))
     return {
         "jwt": jwt.encode(payload, private_key, alg='RS256'),
         "exp": payload.get('exp')
     }
def compute_jwt_token(log,
                      private_file,
                      jwt_token_template=JWT_TEMPLATE,
                      max_timeout_hours=DEFAULT_EXPIRE_TIME):
    jwt_token_template["exp"] = expires_timestamp(max_timeout_hours)
    fp_private_file = os.path.realpath(private_file)
    log.info("Opening private file: " + fp_private_file)
    log.debug("JWT: " + json.dumps(jwt_token_template))
    jwt_token = "not-calculated"
    jwt_obj = JWT()

    with open(fp_private_file, "r", encoding="UTF-8") as priv_file_pointer:
        priv_key = jwk_from_pem(priv_file_pointer.read().encode())
        jwt_token = jwt_obj.encode(jwt_token_template, priv_key, 'RS256')
        log.debug("Calculated JWT token: " + str(jwt_token))
        return jwt_token
    return jwt_token
Exemple #14
0
def make_sign_api_signature_upload_request(auth_method, access_token, digest,
                                           algorithm):
    jwt_client = JWT()
    signing_base_url = get_signing_base_path(auth_method)

    # patch for RSS support whilst requirements for local signing and RSS are different
    # todo: remove this logic once they are aligned
    if auth_method == "cis2":
        pem = DEMO_APP_LOCAL_SIGNING_PRIVATE_KEY.encode("utf-8")
        sub = DEMO_APP_CLIENT_ID
        iss = DEMO_APP_CLIENT_ID
        kid = DEMO_APP_KEY_ID
    else:  # always 'simulated' (this will only support RSS Windows/IOS, smartcard simulated auth will fail as JWTs are different)
        pem = DEMO_APP_REMOTE_SIGNING_PRIVATE_KEY.encode("utf-8")
        sub = DEMO_APP_REMOTE_SIGNING_SUBJECT
        iss = DEMO_APP_REMOTE_SIGNING_ISSUER
        kid = DEMO_APP_REMOTE_SIGNING_KID

    signing_key = jwk_from_pem(pem)
    jwt_request = jwt_client.encode(
        {
            "sub": sub,
            "iss": iss,
            "aud": signing_base_url,
            "iat": time.time(),
            "exp": time.time() + 600,
            "payload": digest,
            "algorithm": algorithm,
        },
        signing_key,
        alg="RS512",
        optional_headers={"kid": kid},
    )

    print("Sending Signing Service signature upload request...")
    print(jwt_request)

    return httpx.post(
        f"{signing_base_url}/signaturerequest",
        headers={
            "Content-Type": "text/plain",
            "Authorization": f"Bearer {access_token}"
        },
        data=jwt_request,
        verify=False,
    ).json()
Exemple #15
0
class TokenHandler:
    def __init__(self):
        self.jwt = JWT()
        self.key = get_key()

    def generate_token(self, user):
        payload = {
            'id': user.id,
            'username': user.username,
            'admin': user.is_staff
        }
        return {'token': self.jwt.encode(payload, self.key, 'RS256')}
    
    def decode_token(self, token):
        return self.jwt.decode(token, self.key, 'RS256')

    def get_user_id_token(self, token):
        payload = self.decode_token(token)
        return payload["id"]
Exemple #16
0
def assertion_token(client_id, tenant_id, issuer, jwk):
    x5t = jwk['x5t']
    signing_key = jwk_from_dict(jwk)
    now = time.mktime(datetime.now().timetuple())

    headers = {
        'x5t': x5t
    }

    json_data = {
        'aud': issuer,
        'exp': now + 60,
        'iss': client_id,
        'jti': str(uuid.uuid4()),
        'nbf': now,
        'sub': client_id
    }

    instance = JWT()
    return instance.encode(json_data, signing_key, alg='RS256', optional_headers=headers)
Exemple #17
0
def create_jwt(app_id, private_key: bytes, expiration=60):
    """
    Creates a signed JWT, valid for 60 seconds by default.
    The expiration can be extended beyond this, to a maximum of 600 seconds.
    :param app_id: Github App ID
    :param private_key: Github App Private Key in PEM format
    :param expiration: int
    :return: an encoded JWT
    """
    now = int(time.time())
    payload = {
        "iat": now,
        "exp": now + expiration,
        "iss": int(app_id)
    }
    jwt = JWT()
    return jwt.encode(
        payload,
        jwk_from_pem(private_key),
        "RS256"
    )
Exemple #18
0
 def post():
     data = rest.request.get_json(silent=True)
     if data is None:
         response = jsonify({'data': {'success': False, 'code': 403, 'message': 'bad module name'}})
         response.status_code = 403
         return response
     username = data['username']
     password = data['password']
     if username != '!admin!' and password != '!admin!':
         user = PostGre().check_user(username, password)
     else:
         user = ['1']
     if len(user) == 0:
         response = jsonify({'data': {'success': False, 'code': 401, 'message': 'Kullanıcı Adı veya Şifre Hatalı'}})
         response.status_code = 401
         return response
     else:
         instance = JWT()
         user_id = user[0][0]
         JWT_ALGORITHM = 'RS512'
         with open('/opt/ante-jamnet/helper/certs/rsa_private_key.pem', 'rb') as fh:
             signing_key = jwk_from_pem(fh.read())
         payload = {
             'iss': 'Ante-Jamnet',
             'user_name': username,
             'iat': get_int_from_datetime(datetime.now(timezone.utc)),
             'user_id': user_id,
             'exp': get_int_from_datetime(
                 datetime.now(timezone.utc) + timedelta(hours=240)),
         }
         jwt_token = instance.encode(payload, signing_key, JWT_ALGORITHM)
         try:
             PostGre().set_user_token(user_id, username, jwt_token)
         except Exception as e:
             print(e)
         return {'data': {'success': True, 'token': jwt_token}}
Exemple #19
0
import time
import ssmenv
import os

from jwt import (
    JWT,
    jwk_from_dict,
    jwk_from_pem,
)

private_key = jwk_from_pem(os.environ['GITHUB_APP_PRIVATE_PEM'].encode())

timestamp = int(time.time())
payload = {
    'iss': os.environ['GITHUB_APP_ID'],
    'iat': timestamp,
    'exp': timestamp + 60,
}
jwt = JWT()
compact_jws = jwt.encode(payload, private_key, 'RS256')
print(compact_jws)
Exemple #20
0
def get_access_token():
    try:
        debug_print('Starting app authentication against GitHub', func_name='get_access_token')
        pem_file_path = str(current_app.config.get('GITHUB_APP_PEM_PATH'))

        # This is the flow to request data about the app
        # https://developer.github.com/apps/building-github-apps/authenticating-with-github-apps/#authenticating-as-a-github-app

        time_now = int(time.time())

        payload = {
            'iss': current_app.config.get('GITHUB_APP_ID'),
            'iat': time_now,
            'exp': time_now + (5 * 60)
        }

        debug_print('Opening PEM file for reading. PEM file path: {0}'.format(pem_file_path), func_name='get_access_token')

        with open(pem_file_path, 'rb') as f:
            private_key = jwk_from_pem(f.read())
            f.close()
        
        debug_print('PEM file successfully read', func_name='get_access_token') 

        jwtoken = JWT()
        jwsignature = jwtoken.encode(payload, private_key, 'RS256')

        api_app_url = 'https://api.github.com/app/installations'

        headers = {
            'Authorization': 'Bearer {0}'.format(str(jwsignature)),
            'Accept': 'application/vnd.github.machine-man-preview+json'
        }

        debug_print('Sending GET request to {0}'.format(api_app_url), func_name='get_access_token')
        response = requests.get(api_app_url, headers=headers)

        # Here starts the flow to acquire the access token
        # https://developer.github.com/apps/building-github-apps/authenticating-with-github-apps/#authenticating-as-an-installation

        if response.status_code == 200: #OK
            debug_print('GET request to {0} returned 200 OK'.format(api_app_url), func_name='get_access_token')

            json_content = json.loads(response.content.decode('utf8'))
            debug_print('Response content: {0}'.format(json_content), func_name='get_access_token')

            if type(json_content) is list: 

                debug_print('Content is list...', func_name='get_access_token')

                # the github account may have more than one application installed
                for l in json_content:
                    debug_print('json within content list: {0}'.format(l), func_name='get_access_token')
                    if l.get('app_id') == int(current_app.config.get('GITHUB_APP_ID')):
                        debug_print('found the right json: {0}'.format(l), func_name='get_access_token')
                        json_content = l
                        break

            debug_print('json_content before posting to the access tokens url: {0}'.format(json_content), func_name='get_access_token')
            access_tokens_url = json_content.get('access_tokens_url')

            debug_print('Sending POST request to {0}'.format(access_tokens_url), func_name='get_access_token')
            response = requests.post(access_tokens_url, headers=headers)

            if response.status_code == 201: #OK Created
                debug_print('POST request to {0} returned 201 OK Created'.format(access_tokens_url), func_name='get_access_token')
                json_content = json.loads(response.content.decode('utf8'))
                return json_content.get('token')
                
        else:
            debug_print('Unexpected response from github api with code: {0}'.format(response.status_code), func_name='get_access_token')    

    except JSONDecodeError:
        debug_print('ERROR reading json returned by github... (JSONDecodeError)', func_name='get_access_token')  

    except OSError:
        debug_print('ERROR reading PEM file...', func_name='get_access_token')      
        
    except:
        # debug_print('ERROR authorizing app...', func_name='get_access_token')
        return False
    else:
        debug_print('GitHub app authentication successful!', func_name='get_access_token')
        return True
def generate_credential(**payload):
    jwt = JWT()
    with open('private.pem', 'rb') as fh:
        private_key = jwk_from_pem(fh.read())
    token = jwt.encode(payload, private_key, 'RS256')
    return token
Exemple #22
0
def oauth_callback(provider):
    oauth = OAuthSignIn.get_provider(provider)
    social_id, username, email = oauth.callback()
    logging.info(social_id)
    logging.info(username)
    logging.info(email)

    #Login failed
    if social_id is None:
        return jsonify({'status': 'ng', 'data': {}}), 401

    #Login success
    user = User.query.filter_by(email=email).first()
    user = user_schema.dump(user).data
    logging.info(user)
    logging.info(user == {})
    logging.info(user != {})

    if user == {}:
        #User not existed
        logging.info('User not existed')
        user = User(username, provider, email, None, None, None)
        logging.info(user)
        db.session.add(user)
        db.session.commit()
        user = {
            "id": user.id,
            "username": user.username,
            "email": user.email,
            "social_id": user.social_id,
            "fullname": user.full_name,
            "phone_number": user.phone_number
        }
    else:
        #User existed
        logging.info('User existed')
        logging.info(user)
        if user['social_id'] == 'facebook' and provider == 'google':
            logging.info('User facebook sign in via google')
        else:
            logging.info('User facebook or google')

    #Data token
    data_encode = {
        'iss': 'http://localhost:5000',
        'sub': 'sudo',
        'data': {
            'user_id': user['id']
        }
    }
    #Get private key
    with open('rsa_private_key.pem', 'rb') as fh:
        signing_key = jwk_from_pem(fh.read())

    #Generate token
    jwt = JWT()
    token = jwt.encode(data_encode, signing_key, 'RS256')
    logging.info(token)

    #Return response
    response = make_response(jsonify({'status': 'ok', 'data': user}), 200)
    response.headers['token'] = token
    return response
Exemple #23
0
import json
import arrow
import sys

from jwt import (
    JWT,
    jwk_from_dict,
    jwk_from_pem,
)

utc = arrow.utcnow()
message = {
    'iss': 'Wise2c Technology Co.,Ltd',
    'sub': 'License',
    'aud': sys.argv[2],
    'iat': utc.timestamp,
    'exp': utc.shift(days=int(sys.argv[1])).timestamp,
}

with open('private.pem', 'rb') as fh:
    signing_key = jwk_from_pem(fh.read())

jwt = JWT()
compact_jws = jwt.encode(message, signing_key, 'RS256')
print(compact_jws)