def profile_view(id_num):
    encoded = jwt.encode({'some': 'payload'}, 'secret', algorithm='HS256')
    current_id = session['id_num']
    profile = Myprofile.query.get(id_num)
    data = Mylist.query.filter_by(id_num=current_id).all()
    if request.method == 'GET':
        for each in data:
            if each.id_num == current_id:
                return render_template('profile_view.html', profile=profile, data=data)
        return render_template('profile_view.html', profile=profile)
    else:
        db.create_all()
        url = request.form['image']
        description = request.form['description']
        title = request.form['title']
        id_num = session['id_num']
        new_list = Mylist(id_num=id_num,
                               description=description, url=url, title=title)
        db.session.add(new_list)
        db.session.commit()
        payload = {'some': 'data'}
        jwt_token = jwt.encode({'some': 'payload'}, 'secret', algorithm='HS256')
        
        #send data to database here
        return redirect(url_for('profile_view', profile=profile, id_num=current_id, encoded=encoded))
Example #2
0
    def test_encode_decode_with_ecdsa_sha512(self):
        # PEM-formatted EC key
        with open('tests/testkey_ec', 'r') as ec_priv_file:
            priv_eckey = load_pem_private_key(ensure_bytes(ec_priv_file.read()),
                                              password=None, backend=default_backend())
            jwt_message = jwt.encode(self.payload, priv_eckey,
                                     algorithm='ES512')

        with open('tests/testkey_ec.pub', 'r') as ec_pub_file:
            pub_eckey = load_pem_public_key(ensure_bytes(ec_pub_file.read()), backend=default_backend())
            assert jwt.decode(jwt_message, pub_eckey)

            load_output = jwt.load(jwt_message)
            jwt.verify_signature(key=pub_eckey, *load_output)

        # string-formatted key
        with open('tests/testkey_ec', 'r') as ec_priv_file:
            priv_eckey = ec_priv_file.read()
            jwt_message = jwt.encode(self.payload, priv_eckey,
                                     algorithm='ES512')

        with open('tests/testkey_ec.pub', 'r') as ec_pub_file:
            pub_eckey = ec_pub_file.read()
            assert jwt.decode(jwt_message, pub_eckey)

            load_output = jwt.load(jwt_message)
            jwt.verify_signature(key=pub_eckey, *load_output)
Example #3
0
    def test_encode_decode_with_rsa_sha384(self):
        # PEM-formatted RSA key
        with open('tests/testkey_rsa', 'r') as rsa_priv_file:
            priv_rsakey = load_pem_private_key(ensure_bytes(rsa_priv_file.read()),
                                               password=None, backend=default_backend())
            jwt_message = jwt.encode(self.payload, priv_rsakey,
                                     algorithm='RS384')

        with open('tests/testkey_rsa.pub', 'r') as rsa_pub_file:
            pub_rsakey = load_ssh_public_key(ensure_bytes(rsa_pub_file.read()),
                                             backend=default_backend())
            assert jwt.decode(jwt_message, pub_rsakey)

        # string-formatted key
        with open('tests/testkey_rsa', 'r') as rsa_priv_file:
            priv_rsakey = rsa_priv_file.read()
            jwt_message = jwt.encode(self.payload, priv_rsakey,
                                     algorithm='RS384')

        with open('tests/testkey_rsa.pub', 'r') as rsa_pub_file:
            pub_rsakey = rsa_pub_file.read()
            assert jwt.decode(jwt_message, pub_rsakey)

            load_output = jwt.load(jwt_message)
            jwt.verify_signature(key=pub_rsakey, *load_output)
Example #4
0
def make_tokens(response, User, user_type):
	response.set_refreshtoken(jwt.encode(
		access_token(User.user_id, user_type, 30, 'r'), secret,
		algorithm = 'HS256'))
	response.set_accesstoken(jwt.encode(
		access_token(User.user_id, user_type, 1, 'a'), secret,
		algorithm = 'HS256'))
Example #5
0
    def test_encode_decode_with_ecdsa_sha512(self):
        try:
            import ecdsa

            # PEM-formatted EC key
            with open('tests/testkey_ec', 'r') as ec_priv_file:
                priv_eckey = ecdsa.SigningKey.from_pem(ec_priv_file.read())
                jwt_message = jwt.encode(self.payload, priv_eckey,
                                         algorithm='ES512')

            with open('tests/testkey_ec.pub', 'r') as ec_pub_file:
                pub_eckey = ecdsa.VerifyingKey.from_pem(ec_pub_file.read())
                assert jwt.decode(jwt_message, pub_eckey)

                load_output = jwt.load(jwt_message)
                jwt.verify_signature(key=pub_eckey, *load_output)

            # string-formatted key
            with open('tests/testkey_ec', 'r') as ec_priv_file:
                priv_eckey = ec_priv_file.read()
                jwt_message = jwt.encode(self.payload, priv_eckey,
                                         algorithm='ES512')

            with open('tests/testkey_ec.pub', 'r') as ec_pub_file:
                pub_eckey = ec_pub_file.read()
                assert jwt.decode(jwt_message, pub_eckey)

                load_output = jwt.load(jwt_message)
                jwt.verify_signature(key=pub_eckey, *load_output)
        except ImportError:
            pass
Example #6
0
    def test_shortURL(self):
        url = 'http://www.facebook.com'
        requestData = jwt.encode({'link': url}, 'hellominiaturespoon',
                                 algorithm='HS256')
        rv = self.app.post('/v1/link', data=requestData)
        data = json.loads(rv.data)
        self.assertEqual(rv._status_code, 201, "POST request is failed")

        rv2 = self.app.get('/v1/link?request_id=' + str(data['request_id']))
        data2 = json.loads(rv2.data)
        self.assertEqual(rv2._status_code, 200, "GET request is failed")
        self.assertEqual(data['short_url'], data2['short_url'],
                         "Get short url by request id is failed")

        rv3 = self.app.get(str(data['short_url']), follow_redirects=False)
        self.assertEqual(rv3._status_code, 302,
                         "Can not redirect to original link with short link")
        self.assertEqual(rv3.location, url,
                         "Can not redirect to original link with short link")

        requestData2 = jwt.encode({'request_id': data['request_id']},
                                  'hellominiaturespoon', algorithm='HS256')
        rv4 = self.app.delete('/v1/link', data=requestData2)
        self.assertEqual(rv4._status_code, 200,
                         "Failed to delete url from db")
  def get(self):
    """Handles get requests."""

    curr_time = int(time.time())
    exp_time = curr_time + 3600

    request_info = {'currencyCode': 'USD',
                    'sellerData': 'Custom Data'}
    jwt_info = {'iss': SELLER_ID,
                'aud': 'Google',
                'typ': 'google/payments/inapp/item/v1',
                'iat': curr_time,
                'exp': exp_time,
                'request': request_info}

    # create JWT for first item
    request_info.update({'name': 'Drive In Aniversary Poster', 'price': '20.00'})
    token_1 = jwt.encode(jwt_info, SELLER_SECRET)

    # create JWT for second item
    request_info.update({'name': 'Golden Gate Bridge Poster', 'price': '25.00'})
    token_2 = jwt.encode(jwt_info, SELLER_SECRET)

    # update store web page
    template_vals = {'jwt_1': token_1,
                     'jwt_2': token_2}

    path = os.path.join(os.path.dirname(__file__), 'templates', 'index.html')
    self.response.out.write(template.render(path, template_vals))
Example #8
0
    def test_encode_decode_with_rsa_sha512(self):
        try:
            from Crypto.PublicKey import RSA

            # PEM-formatted RSA key
            with open('tests/testkey_rsa', 'r') as rsa_priv_file:
                priv_rsakey = RSA.importKey(rsa_priv_file.read())
                jwt_message = jwt.encode(self.payload, priv_rsakey,
                                         algorithm='RS512')

            with open('tests/testkey_rsa.pub', 'r') as rsa_pub_file:
                pub_rsakey = RSA.importKey(rsa_pub_file.read())
                assert jwt.decode(jwt_message, pub_rsakey)

                load_output = jwt.load(jwt_message)
                jwt.verify_signature(key=pub_rsakey, *load_output)

            # string-formatted key
            with open('tests/testkey_rsa', 'r') as rsa_priv_file:
                priv_rsakey = rsa_priv_file.read()
                jwt_message = jwt.encode(self.payload, priv_rsakey,
                                         algorithm='RS512')

            with open('tests/testkey_rsa.pub', 'r') as rsa_pub_file:
                pub_rsakey = rsa_pub_file.read()
                assert jwt.decode(jwt_message, pub_rsakey)

                load_output = jwt.load(jwt_message)
                jwt.verify_signature(key=pub_rsakey, *load_output)
        except ImportError:
            pass
Example #9
0
  def get(self):
    """Handles get requests."""

    curr_time = int(time.time())
    exp_time = curr_time + 3600

    request_info = {'currencyCode': 'GBP',
                    'sellerData': 'Custom Data'}
    jwt_info = {'iss': SELLER_ID,
                'aud': 'Google',
                'typ': 'google/payments/inapp/item/v1',
                'iat': curr_time,
                'exp': exp_time,
                'request': request_info}

    # create JWT for first item
    request_info.update({'name': 'Euro Millions single draw entry', 'price': '2.11'})
    token_1 = jwt.encode(jwt_info, SELLER_SECRET)

    # create JWT for second item
    request_info.update({'name': 'Euro Millions bank 10 pounds', 'price': '10.53'})
    token_2 = jwt.encode(jwt_info, SELLER_SECRET)

    # create JWT for third item
    request_info.update({'name': 'Euro Millions bank 20 pounds', 'price': '21.05'})
    token_3 = jwt.encode(jwt_info, SELLER_SECRET)

    # update store web page
    template_vals = {'jwt_1': token_1,
                     'jwt_2': token_2,
                     'jwt_3': token_3}

    template_path = 'index.html'
    template = jinja_environment.get_template(template_path)
    self.response.out.write(template.render(template_vals))
Example #10
0
    def test_encode_bad_type(self):

        types = ["string", tuple(), list(), 42, set()]

        for t in types:
            with self.assertRaises(TypeError):
                jwt.encode(t, "secret")
Example #11
0
    def get(self):
        try:
            redirect_uri = urlunparse(
                (self.get_scheme(), self.request.host,
                 conf.login_path, '', '', '')
            )
            #remember the user for a longer period of time
            remember = self.get_argument('remember',
                                         False)
            state = jwt.encode({'remember': remember},
                               secrets['simple'])
            flow = oa2_client.OAuth2WebServerFlow(
                google_secrets['web']['client_id'],
                google_secrets['web']['client_secret'],
                scope = 'openid profile',
                redirect_uri = redirect_uri,
                state = state)
            
            auth_code = self.get_argument('code', False)
            
            if not auth_code:
                auth_uri = flow.step1_get_authorize_url()
                self.redirect(auth_uri)

            else:
                with ThreadPoolExecutor(1) as thread:
                    credentials = yield thread.submit(
                        flow.step2_exchange, auth_code)
                #Intercambiar el codigo antes que nada para
                #evitar ataques
                
                yield self.request_disc_doc()
                
                userinfo_endpoint = \
                    self.disc_doc['userinfo_endpoint']
                    
                http_auth = credentials.authorize(
                    httplib2.Http())
                    
                with ThreadPoolExecutor(1) as thread:
                    userinfo = yield thread.submit(
                        http_auth.request,
                        userinfo_endpoint)
                userinfo = self.decode_httplib2_json(
                    userinfo)
                #https://developers.google.com/+/api/
                #openidconnect/getOpenIdConnect
                
                user = yield db.User.from_google_userinfo(
                    userinfo)
                token = jwt.encode({'id': user.id,
                                    'exp': self.get_exp()},
                                   user.secret)
                messages.code_debug(self.path+'.get',
                    'Rendering login.html ...')
                self.render('login.html', token=token)
        
        except oa2_client.FlowExchangeError:
            self.render('boxes.html',
                        critical='Error de autenticación!')
Example #12
0
    def test_rsa_encode(self):
        root = os.path.dirname(__file__)
        pubkey = jwt.rsa_load_pub(os.path.join(root, "rsapubkey.pem"))

        jwt.decode(
            b"eyJhbGciOiJSUzI1NiJ9.eyJpc3MiOiJqb2UiLA0KICJleHAiOjEzMDA4MTkzODAsDQogImh0dHA6Ly9leGFtcGxlLmNvbS9pc19yb290Ijp0cnVlfQ.cC4hiUPoj9Eetdgtv3hF80EGrhuB__dzERat0XF9g2VtQgr9PJbu3XOiZj5RZmh7AAuHIm4Bh-0Qc_lF5YKt_O8W2Fp5jujGbds9uJdbF9CUAr7t1dnZcAcQjbKBYNX4BAynRFdiuB--f_nZLgrnbyTyWzO75vRK5h6xBArLIARNPvkSjtQBMHlb1L07Qe7K0GarZRmB_eSN9383LcOLn6_dO--xi12jzDwusC-eOkHWEsqtFZESc6BfI7noOPqvhJ1phCnvWh6IeYI2w9QOYEUipUTI8np6LbgGY9Fs98rqVt5AXLIhWkWywlVmtVrBp0igcN_IoypGlUPQGe77Rw",
            pubkey,
        )

        key = jwt.rsa_load(os.path.join(root, "rsakey.pem"))
        # Example from the JWS spec
        assert jwt.check(
            b"eyJhbGciOiJSUzI1NiJ9.eyJpc3MiOiJqb2UiLA0KICJleHAiOjEzMDA4MTkzODAsDQogImh0dHA6Ly9leGFtcGxlLmNvbS9pc19yb290Ijp0cnVlfQ.cC4hiUPoj9Eetdgtv3hF80EGrhuB__dzERat0XF9g2VtQgr9PJbu3XOiZj5RZmh7AAuHIm4Bh-0Qc_lF5YKt_O8W2Fp5jujGbds9uJdbF9CUAr7t1dnZcAcQjbKBYNX4BAynRFdiuB--f_nZLgrnbyTyWzO75vRK5h6xBArLIARNPvkSjtQBMHlb1L07Qe7K0GarZRmB_eSN9383LcOLn6_dO--xi12jzDwusC-eOkHWEsqtFZESc6BfI7noOPqvhJ1phCnvWh6IeYI2w9QOYEUipUTI8np6LbgGY9Fs98rqVt5AXLIhWkWywlVmtVrBp0igcN_IoypGlUPQGe77Rw",
            key,
        )
        assert not jwt.check(
            b"eyJhbGciOiJSUzI1NiJ9.AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA.cC4hiUPoj9Eetdgtv3hF80EGrhuB__dzERat0XF9g2VtQgr9PJbu3XOiZj5RZmh7AAuHIm4Bh-0Qc_lF5YKt_O8W2Fp5jujGbds9uJdbF9CUAr7t1dnZcAcQjbKBYNX4BAynRFdiuB--f_nZLgrnbyTyWzO75vRK5h6xBArLIARNPvkSjtQBMHlb1L07Qe7K0GarZRmB_eSN9383LcOLn6_dO--xi12jzDwusC-eOkHWEsqtFZESc6BfI7noOPqvhJ1phCnvWh6IeYI2w9QOYEUipUTI8np6LbgGY9Fs98rqVt5AXLIhWkWywlVmtVrBp0igcN_IoypGlUPQGe77Rw",
            key,
        )

        # XXX Should test the Signer classes directly. The check(encode()) dance
        # doesn't really verify that the correct algorithm was used, or that the
        # algorithm was implemented properly.
        assert jwt.check(jwt.encode(u"test", key, u"RS256"), key)
        assert jwt.check(jwt.encode(u"test", key, u"RS384"), key)
        assert jwt.check(jwt.encode(u"test", key, u"RS512"), key)
Example #13
0
def refresh_token(token):
	if token['token_type'] != 'r':
		# token 不为 RefreshToken
		raise Exception('10006')
	ReToken = access_token(token['user_id'], token['aud'], 30, 'r')
	AcToken = access_token(token['user_id'], token['aud'], 1, 'a')
	ReToken = jwt.encode(ReToken, secret, algorithm = 'HS256')
	AcToken = jwt.encode(AcToken, secret, algorithm = 'HS256')
	return ReToken, AcToken
Example #14
0
	def test_validate_sig(self):
		token = jwt.encode({'iss': 'realm', 'exp': 
                calendar.timegm(datetime.utcnow().utctimetuple()) + 3600},
				'key')
		self.assertTrue(validate_sig(token, 'key'))
		token = jwt.encode({'iss': 'realm', 'exp':
                calendar.timegm(datetime.utcnow().utctimetuple()) - 3600},
				'key')
		self.assertEqual(validate_sig(token, 'key'), False) 
		token = jwt.encode({'iss': 'realm', 'exp': 
                calendar.timegm(datetime.utcnow().utctimetuple()) + 3600},
				'key')
		self.assertEqual(validate_sig(token, 'wrong_key'), False) 
Example #15
0
def login(ctx, request):
    payload = request.json()
    if payload.get('username') == 'comyn' and payload.get('password') == 'pass':
        exp = datetime.datetime.utcnow() + datetime.timedelta(hours=8)
        token = jwt.encode({'user': '******', 'exp': exp}, __KEY, 'HS512').decode()
        return jsonfy(code=200, token=token)
    return jsonfy(code=401, message='username or password not match')
Example #16
0
 def test_provider_request_payment_token(self):
     request = MagicMock()
     request.POST = {'jwt': jwt.encode(JWT_DATA, SELLER_SECRET)}
     provider = GoogleWalletProvider(payment=None, seller_id=SELLER_ID,
                                     seller_secret=SELLER_SECRET)
     token = provider.get_token_from_request(request)
     self.assertEqual(token, PAYMENT_TOKEN)
Example #17
0
 def getAccessToken(self):
     poyntTokenUrl = self.apiHost + "/token"
     currentDatetime = datetime.utcnow()
     expiryDatetime = datetime.utcnow() + timedelta(seconds=300)
     payload = {
         'exp': expiryDatetime,
         'iat': currentDatetime,
         'iss': self.applicationId,
         'sub': self.applicationId,
         'aud': 'https://services.poynt.net',
         'jti': str(uuid.uuid4())
     }
     encodedJWT = jwt.encode(payload, self.rsaPrivateKey, algorithm='RS256')
     #print encodedJWT
     payload = {'grantType':'urn:ietf:params:oauth:grant-type:jwt-bearer', 'assertion':encodedJWT}
     print "Obtaining AccessToken using self-signed JWT:"
     code, jsonObj = self._sendFormPostRequest(poyntTokenUrl, payload, {})
     #r = requests.post(poyntTokenUrl, data=payload, headers=headers)
     #prettyPrint(r.json())
     if code == requests.codes.ok:
         self.accessToken = jsonObj['accessToken']
         self.tokenType = jsonObj['tokenType']
         self.refreshToken = jsonObj['refreshToken']
         return True
     else:
         print "*** FAILED TO OBTAIN ACCESS TOKEN ***"
         return False
Example #18
0
def jwt_token(base_url, jwt_issuer, jwt_secret):
    payload = {
        "iss": jwt_issuer,
        "iat": datetime.datetime.utcnow(),
        "exp": datetime.datetime.utcnow() + datetime.timedelta(seconds=30),
    }
    return jwt.encode(payload, jwt_secret, algorithm="HS256")
Example #19
0
def generate_identity_token(user_id, nonce):
    """Creates Layer Identity Token
    :Parameter user_id:   Your (the Provider) ID that represents the user.
    :Type user_id: string
    :Parameter nonce:     The nonce returned by the Layer SDK.
    :Type nonce: string
    """
    jwt_token = jwt.encode(
        payload={
            # String - The Provider ID found in the Layer Dashboard
            "iss": PROVIDER_ID,
            # String - Provider's internal ID for the authenticating user
            "prn": user_id,
            # Integer - Time of Token Issuance in RFC 3339 seconds
            "iat": datetime.now(),
            # Integer - Token Expiration in RFC 3339 seconds; set to 2 minutes
            "exp": datetime.utcnow() + timedelta(seconds=120),
            "nce": nonce    # The nonce obtained via the Layer client SDK.
        },
        key=_read_rsa_private_key(),
        headers={
            "typ": "JWT",   # String - Expresses a MIME Type of application/JWT
            # String - Expresses the type of algorithm used to sign the token;
            # must be RS256
            "alg": 'RS256',
            # String - Express a Content Type of Layer External Identity Token,
            # version 1
            "cty": "layer-eit;v=1",
            # String - Private Key associated with "layer.pem", found in the
            # Layer Dashboard
            "kid": KEY_ID
        },
        algorithm='RS256'
    )
    return jwt_token.decode("utf8")
Example #20
0
 def test_some_jwt(self):
     with self.settings(REQUIRE_JWT=True,
                        CLIENT_JWT_KEYS={'f': 'b'}):
         enc = jwt.encode({'jwt-encode-key': 'f', 'name': 'x'}, 'b')
         res = self.client.post(self.url, data=enc,
                                content_type='application/jwt')
         eq_(res.status_code, 201, res.status_code)
Example #21
0
def get_id_token(user):
    """
    Return a JWT for `user`, suitable for use with the course discovery service.

    Arguments:
        user (User): User for whom to generate the JWT.

    Returns:
        str: The JWT.
    """
    try:
        # Service users may not have user profiles.
        full_name = UserProfile.objects.get(user=user).name
    except UserProfile.DoesNotExist:
        full_name = None

    now = datetime.datetime.utcnow()
    expires_in = getattr(settings, 'OAUTH_ID_TOKEN_EXPIRATION', 30)

    payload = {
        'preferred_username': user.username,
        'name': full_name,
        'email': user.email,
        'administrator': user.is_staff,
        'iss': configuration_helpers.get_value('OAUTH_OIDC_ISSUER', settings.OAUTH_OIDC_ISSUER),
        'exp': now + datetime.timedelta(seconds=expires_in),
        'iat': now,
        'aud': configuration_helpers.get_value('JWT_AUTH', settings.JWT_AUTH)['JWT_AUDIENCE'],
        'sub': anonymous_id_for_user(user, None),
    }
    secret_key = configuration_helpers.get_value('JWT_AUTH', settings.JWT_AUTH)['JWT_SECRET_KEY']

    return jwt.encode(payload, secret_key).decode('utf-8')
Example #22
0
def subscribe(request):
    f = UserForm(request.POST)
    try:
        f.clean_phone_number()
    except ValidationError as e:
        return render(request, 'home.html', {'error': e.message})
    u = f.save()
    u.save()

    dogeToken = jwt.encode(
    {
      "iss" : settings.SELLER_ID,
      "aud" : "Google",
      "typ" : "google/payments/inapp/item/v1",
      "exp" : int(time.time() + 3600),
      "iat" : int(time.time()),
      "request" :{
        "name" : "Doge Fact",
        "description" : "A 30-day subscription to Doge Fact for {0}".format(u.phone_number),
        "price" : "1.00",
        "currencyCode" : "USD",
        "sellerData" : "user_id:{0}".format(u.id)
      }
    },
    settings.SELLER_SECRET)
    return render(request, 'subscribe.html', {'user': u, 'token': dogeToken})
Example #23
0
def socket_auth_token():
    secret = cfg['flask']['secret-key']
    token = jwt.encode({
        'exp': datetime.datetime.utcnow() + datetime.timedelta(minutes=15),
        'username': get_username()
        }, secret)
    return success({'token': token})
Example #24
0
def get_token(request):
    now = datetime.datetime.utcnow()
    token_payload = {
                     'iss' : 'auth_server',
                     'sub' : 'test',
                     'aud' : 'test-registry',
                     'exp' : now + datetime.timedelta(seconds = settings.TOKEN_VALID_FOR_SECONDS),
                     'nbf' : now,
                     'iat' : now,
                     'jti' : uuid.uuid4().get_hex(),
                     'access' : [
                                {
                                 'type' : scope.type,
                                 'name' : scope.name,
                                 'actions' : scope.actions
                                 }
                                for scope in (Scope.parse(s) for s
                                              in request.GET.getlist('scope'))
                                 ]
                     }
    logger.debug(('token', token_payload))
    response_payload = {
                        'token' : jwt.encode(token_payload,
                                             get_private_key(),
                                             headers = {
                                                        'x5c' : [ get_certificate() ]
                                                        },
                                             algorithm = settings.JWT_SIGNATURE_ALGO),
                        'expires_in' : 3600,
                        'issued_at' : datetime.datetime.utcnow().isoformat() + 'Z'
                        }
    logger.debug(('response', json.dumps(response_payload)))
    return HttpResponse(json.dumps(response_payload),
                        content_type = 'application/json')
    def test_id_site_callback_handler(self):
        _, acc = self.create_account(self.app.accounts)
        now = datetime.datetime.utcnow()

        try:
            irt = uuid4().get_hex()
        except AttributeError:
            irt = uuid4().hex

        fake_jwt_data = {
                'exp': now + datetime.timedelta(seconds=3600),
                'aud': self.app._client.auth.id,
                'irt': irt,
                'iss': 'Stormpath',
                'sub': acc.href,
                'isNewSub': False,
                'state': None,
        }

        fake_jwt = to_unicode(jwt.encode(
            fake_jwt_data,
            self.app._client.auth.secret,
            'HS256'), 'UTF-8')
        fake_jwt_response = 'http://localhost/?jwtResponse=%s' % fake_jwt
        ret = self.app.handle_id_site_callback(fake_jwt_response)
        self.assertIsNotNone(ret)
        self.assertEqual(ret.account.href, acc.href)
        self.assertIsNone(ret.state)
Example #26
0
def create_receipt(installed_pk):
    installed = Installed.objects.get(pk=installed_pk)
    addon_pk = installed.addon.pk
    verify = '%s%s' % (settings.WEBAPPS_RECEIPT_URL, addon_pk)
    detail = reverse('account.purchases.receipt', args=[addon_pk])
    reissue = installed.addon.get_purchase_url('reissue')
    time_ = calendar.timegm(time.gmtime())
    receipt = dict(typ='purchase-receipt',
                   product={'url': installed.addon.origin,
                            'storedata': urlencode({'id': int(addon_pk)})},
                   user={'type': 'directed-identifier',
                         'value': installed.uuid},
                   iss=settings.SITE_URL,
                   nbf=time_,
                   iat=time_,
                   exp=(time_ + settings.WEBAPPS_RECEIPT_EXPIRY_SECONDS),
                   detail=absolutify(detail),
                   verify=absolutify(verify),
                   reissue=absolutify(reissue))
    if settings.SIGNING_SERVER_ACTIVE:
        # The shiny new code.
        return sign(receipt)
    else:
        # Our old bad code.
        return jwt.encode(receipt, get_key(), u'RS512')
Example #27
0
    def test_tracking_context(self):
        """
        Ensure the tracking context is set up in the api client correctly and
        automatically.
        """
        # fake an ecommerce api request.
        httpretty.register_uri(
            httpretty.POST,
            '{}/baskets/1/'.format(TEST_API_URL),
            status=200, body='{}',
            adding_headers={'Content-Type': 'application/json'}
        )
        mock_tracker = mock.Mock()
        mock_tracker.resolve_context = mock.Mock(return_value={'client_id': self.TEST_CLIENT_ID})
        with mock.patch('commerce.tracker.get_tracker', return_value=mock_tracker):
            ecommerce_api_client(self.user).baskets(1).post()

        # make sure the request's JWT token payload included correct tracking context values.
        actual_header = httpretty.last_request().headers['Authorization']
        expected_payload = {
            'username': self.user.username,
            'full_name': self.user.profile.name,
            'email': self.user.email,
            'tracking_context': {
                'lms_user_id': self.user.id,  # pylint: disable=no-member
                'lms_client_id': self.TEST_CLIENT_ID,
            },
        }
        expected_header = 'JWT {}'.format(jwt.encode(expected_payload, TEST_API_SIGNING_KEY))
        self.assertEqual(actual_header, expected_header)
Example #28
0
def _gen_auth_jwt_header(claim, key):
	if 'exp' not in claim:
		claim = copy.copy(claim)
		claim['exp'] = calendar.timegm(datetime.utcnow().utctimetuple()) + 3600
	else:
		claim = claim
	return 'Bearer ' + jwt.encode(claim, key).decode('utf-8')
Example #29
0
def create_test_receipt(root, status):
    time_ = calendar.timegm(time.gmtime())
    detail = absolutify(reverse('receipt.test.details'))
    receipt = {
        'detail': absolutify(detail),
        'exp': time_ + (60 * 60 * 24),
        'iat': time_,
        'iss': settings.SITE_URL,
        'nbf': time_,
        'product': {
            'storedata': urlencode({'id': 0}),
            'url': root,
        },
        'reissue': detail,
        'typ': 'test-receipt',
        'user': {
            'type': 'directed-identifier',
            'value': 'none'
        },
        'verify': absolutify(reverse('receipt.test.verify',
                                     kwargs={'status': status}))

    }
    if settings.SIGNING_SERVER_ACTIVE:
        return sign(receipt)
    else:
        return jwt.encode(receipt, get_key(), u'RS512')
Example #30
0
 def request(self, app_secret=None, payload=None, **payload_kw):
     if not app_secret:
         app_secret = self.app_secret
     if not payload:
         payload = json.dumps(self.payload(**payload_kw))
     encoded = jwt.encode(payload, app_secret, algorithm='HS256')
     return unicode(encoded)  # django always passes unicode
Example #31
0
def identity():
    url = "https://amer-api-partner67-test.apigee.net/identity/v1/token?grant_type=client_credentials"

    payload = {}
    headers = {
        'Authorization':
        'Basic emNXVTBvQ3RjVHJjVFlIajdmUHg5bHZBR0Jzb1N2aE06dGhaeXk5b09DaU5YaEdJVA=='
    }

    response = requests.request("POST", url, headers=headers, data=payload)
    Msj = response.text
    if response.status_code == 200:
        respuesta = response.json()
        access_token = respuesta['access_token']

        url = "https://amer-api-partner67-test.apigee.net/account-access-consent/v3.1"

        payload = "{\n    \"Data\": {\n        \"TransactionToDateTime\": \"2020-10-19T11:25:41-05:00\",\n        \"ExpirationDateTime\": \"2020-11-03T11:25:41-06:00\",\n        \"Permissions\": [\n            \"ReadAccountsBasic\",\n            \"ReadAccountsDetail\",\n            \"ReadBalances\",\n            \"ReadTransactionsBasic\",\n            \"ReadTransactionsDebits\",\n            \"ReadTransactionsDetail\"\n        ],\n        \"TransactionFromDateTime\": \"2020-10-19T11:25:41-05:00\"\n    }\n}"
        headers = {
            'Authorization': 'Bearer ' + access_token,
            'Content-Type': 'application/json'
        }

        response = requests.request("POST", url, headers=headers, data=payload)
        if response.status_code == 200:
            respuesta = response.json()
            Data = respuesta['Data']
            consent_id = Data['ConsentId']
            Ruta = 'https://amer-api-partner67-test.apigee.net/identity/v1/authorize?response_type=code id_token'
            parametro = Parametros.objects.get(parametro_id='CLIENT_ID',
                                               parametro_proxi='banorte')
            client_id = parametro.parametro_valor
            parametro2 = Parametros.objects.get(parametro_id='RUTA_RED',
                                                parametro_proxi='banorte')
            redirect_uri = parametro2.parametro_valor
            parametro3 = Parametros.objects.get(parametro_id='PRIVATEKEY',
                                                parametro_proxi='banorte')
            #secret = parametro3.parametro_valor
            scope = 'openid email profile'
            noncec = uuid.uuid4()
            nonce = str(noncec)
            verifier_bytes = os.urandom(32)
            code_verifier = base64.urlsafe_b64encode(verifier_bytes).rstrip(
                b'=')
            challenge_bytes = hashlib.sha256(code_verifier).digest()
            code_challenge = base64.urlsafe_b64encode(challenge_bytes).rstrip(
                b'=')
            code_challenge_method = 'S256'
            statex = uuid.uuid4()
            state = str(statex)
            id_application = "e452e391-5afb-476d-9343-70b394e3c051"
            audience = "https://amer-api-partner67-test.apigee.net/identity/v1/token"
            jwt_idx = uuid.uuid4()
            jwt_id = str(jwt_idx)
            now = datetime.datetime.now()
            payload = {
                "max_age": "3600",
                "iss": client_id,
                "sub": client_id,
                "iat": now,
                "jti": jwt_id,
                "id": id_application,
                "client_id": client_id,
                "redirect_uri": redirect_uri,
                "aud": audience,
                "scope": scope,
                "response_type": "code id_token",
                "state": state,
                "nonce": nonce,
                "claims": {
                    "id_token": {
                        "openbanking_intent_id": {
                            "value": consent_id,
                            "essential": "true"
                        }
                    }
                }
            }
            priv_key = b'-----BEGIN RSA PRIVATE KEY-----\n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\n-----END RSA PRIVATE KEY-----\n'
            client_assertion = jwt.encode(payload, priv_key, algorithm='RS256')
            X = str(client_assertion)
            Y = X[2:len(X) - 1]
            URLGenerada = Ruta + "&client_id=" + client_id + "&scope=" + scope + "&nonce=" + nonce + "&code_challenge=" + str(
                code_challenge
            ) + "&code_challenge_method=" + code_challenge_method + "&state=" + state + "&client_assertion=" + Y
            return (URLGenerada)
        elif response.status_code == 400 or response.status_code == 401:
            codigo = response.status_code
            Mensaje = 'Error:' + str(codigo)
        else:
            codigo = response.status_code
            Descrip = response.error_description
            Mensaje = 'Error:' + str(codigo) + ' Que indica:' + Descrip
    elif response.status_code == 400 or response.status_code == 401:
        codigo = response.status_code
        Mensaje = 'Error:' + str(codigo)
    else:
        codigo = response.status_code
        Descrip = response.error_description
        Mensaje = 'Error:' + str(codigo) + ' Que indica:' + Descrip
Example #32
0
def jwsSignatureToString(jwsAlgorithm, jwkRsaPrivateKey, jwtPayloadObject):
    return jwt.encode(jwtPayloadObject,
                      jwkRsaPrivateKey,
                      algorithm=jwsAlgorithm)
Example #33
0
 def generate_token(self):
     data = {'recipient': self.user.id}
     activation_token = jwt.encode(data, settings.SECRET_KEY)
     return activation_token.decode('utf-8')
Example #34
0
def get_auth(auth, **kwargs):
    cas_resp = None
    if not auth.user:
        # Central Authentication Server OAuth Bearer Token
        authorization = request.headers.get('Authorization')
        if authorization and authorization.startswith('Bearer '):
            client = cas.get_client()
            try:
                access_token = cas.parse_auth_header(authorization)
                cas_resp = client.profile(access_token)
            except cas.CasError as err:
                sentry.log_exception()
                # NOTE: We assume that the request is an AJAX request
                return json_renderer(err)
            if cas_resp.authenticated:
                auth.user = OSFUser.load(cas_resp.user)

    try:
        data = jwt.decode(jwe.decrypt(
            request.args.get('payload', '').encode('utf-8'),
            WATERBUTLER_JWE_KEY),
                          settings.WATERBUTLER_JWT_SECRET,
                          options={'require_exp': True},
                          algorithm=settings.WATERBUTLER_JWT_ALGORITHM)['data']
    except (jwt.InvalidTokenError, KeyError) as err:
        sentry.log_message(str(err))
        raise HTTPError(httplib.FORBIDDEN)

    if not auth.user:
        auth.user = OSFUser.from_cookie(data.get('cookie', ''))

    try:
        action = data['action']
        node_id = data['nid']
        provider_name = data['provider']
    except KeyError:
        raise HTTPError(httplib.BAD_REQUEST)

    node = AbstractNode.load(node_id)
    if not node:
        raise HTTPError(httplib.NOT_FOUND)

    check_access(node, auth, action, cas_resp)

    provider_settings = node.get_addon(provider_name)
    if not provider_settings:
        raise HTTPError(httplib.BAD_REQUEST)

    try:
        credentials = provider_settings.serialize_waterbutler_credentials()
        waterbutler_settings = provider_settings.serialize_waterbutler_settings(
        )
    except exceptions.AddonError:
        log_exception()
        raise HTTPError(httplib.BAD_REQUEST)

    return {
        'payload':
        jwe.encrypt(
            jwt.encode(
                {
                    'exp':
                    timezone.now() + datetime.timedelta(
                        seconds=settings.WATERBUTLER_JWT_EXPIRATION),
                    'data': {
                        'auth':
                        make_auth(
                            auth.user
                        ),  # A waterbutler auth dict not an Auth object
                        'credentials':
                        credentials,
                        'settings':
                        waterbutler_settings,
                        'callback_url':
                        node.api_url_for(('create_waterbutler_log'
                                          if not node.is_registration else
                                          'registration_callbacks'),
                                         _absolute=True,
                                         _internal=True),
                    }
                },
                settings.WATERBUTLER_JWT_SECRET,
                algorithm=settings.WATERBUTLER_JWT_ALGORITHM),
            WATERBUTLER_JWE_KEY)
    }
def create_token(payload, key):
    token = jwt.encode({'user_id': payload}, key)
    return token
def make_token(username,expire=3600*24):# default expire time: 1 day

    now = time.time()
    key = settings.SHOP_TOKEN_KEY
    payload = {'username':username,'exp':int(now+expire)}
    return jwt.encode(payload,key,algorithm='HS256')
Example #37
0
 def generate_token(self, payload, secret=None):
     """Generate a JWT token with the provided payload."""
     secret = secret or self.JWT_SECRET_KEY
     token = jwt.encode(payload, secret)
     return token
Example #38
0
        # the inode serves as fileid, the mtime can be used for version information
        statx = xrdcl.statx(filename, ruid, rgid)
        inode = statx[2]
        mtime = statx[12]
    except IOError, e:
        Wopi.log.info(
            'msg="Requested file not found" filename="%s" error="%s"' %
            (filename, e))
        raise
    exptime = int(time.time()) + Wopi.tokenvalidity
    acctok = jwt.encode(
        {
            'ruid': ruid,
            'rgid': rgid,
            'filename': filename,
            'username': username,
            'canedit': canedit,
            'folderurl': folderurl,
            'exp': exptime
        },
        Wopi.wopisecret,
        algorithm='HS256')
    Wopi.log.info('msg="Access token generated" ruid="%s" rgid="%s" canedit="%r" filename="%s" inode="%s" ' \
                  'mtime="%s" folderurl="%s" expiration="%d" acctok="%s"' % \
                  (ruid, rgid, canedit, filename, inode, mtime, folderurl, exptime, acctok[-20:]))
    # return the inode == fileid and the access token
    return inode, acctok


#
# Utilities for the POST-related file actions
#
Example #39
0
	def get_reset_password_token(self, expires_in=600):
		return jwt.encode(
			{'reset_password': self.id, 'exp': time() + expires_in},
			current_app.config['SECRET_KEY'],
			algorithm='HS256')
def generate_jwt_token(key):
    """
    Function that returns a jwt token based on a key
    :return: Returns JWT Token
    """
    return jwt.encode({"some": "payload"}, key, algorithm="HS256")
Example #41
0
    def test_encode_decode(self):
        secret = 'secret'
        jwt_message = jwt.encode(self.payload, secret)
        decoded_payload = jwt.decode(jwt_message, secret)

        self.assertEqual(decoded_payload, self.payload)
def encode_jwt(payload, audience):
    return jwt.encode({**payload, "aud": audience}, current_app.secret_key)
Example #43
0
def set_policy(cmd,
               client,
               attestation_type,
               new_attestation_policy=None,
               new_attestation_policy_file=None,
               policy_format='Text',
               resource_group_name=None,
               provider_name=None):

    if new_attestation_policy_file and new_attestation_policy:
        raise CLIError(
            'Please specify just one of --new-attestation-policy and --new-attestation-policy-file/-f'
        )

    if not new_attestation_policy_file and not new_attestation_policy:
        raise CLIError(
            'Please specify --new-attestation-policy or --new-attestation-policy-file/-f'
        )

    if new_attestation_policy_file:
        file_path = os.path.expanduser(new_attestation_policy_file)
        if not os.path.exists(file_path):
            raise CLIError(
                'Policy file "{}" does not exist.'.format(file_path))

        if not os.path.isfile(file_path):
            raise CLIError('"{}" is not a valid file name.'.format(file_path))

        with open(file_path) as f:
            new_attestation_policy = f.read()

    provider_client = cf_attestation_provider(cmd.cli_ctx)
    provider = provider_client.get(resource_group_name=resource_group_name,
                                   provider_name=provider_name)

    if policy_format == 'Text':
        if provider.trust_model != 'AAD':
            raise CLIError(
                'Only supports Text policy under AAD model. Current model: {}. '
                'If you are using signed JWT policy, please specify --policy-format JWT'
                .format(provider.trust_model))

        import jwt
        try:
            new_attestation_policy = \
                base64.urlsafe_b64encode(new_attestation_policy.encode('ascii')).decode('ascii').strip('=')
            new_attestation_policy = {
                'AttestationPolicy': new_attestation_policy
            }
            new_attestation_policy = jwt.encode(
                new_attestation_policy, key='',
                algorithm='none').decode('ascii')

        except TypeError as e:
            print(e)
            raise CLIError(
                'Failed to encode text content, are you using JWT? If yes, please use --policy-format JWT'
            )

    client.set(tenant_base_url=provider.attest_uri,
               tee=tee_mapping[attestation_type],
               new_attestation_policy=new_attestation_policy)
    return get_policy(cmd,
                      client,
                      attestation_type,
                      resource_group_name=resource_group_name,
                      provider_name=provider_name)
def create_token(data, secret):
    token = jwt.encode(data, secret, algorithm= 'HS256') # irei criar o token nessa linha.
    return token
Example #45
0
def register(show_spinner=False) -> str:
    params = Params()
    params.put("SubscriberInfo", HARDWARE.get_subscriber_info())

    IMEI = params.get("IMEI", encoding='utf8')
    HardwareSerial = params.get("HardwareSerial", encoding='utf8')
    dongle_id = params.get("DongleId", encoding='utf8')
    needs_registration = None in (IMEI, HardwareSerial, dongle_id)

    # create a key for auth
    # your private key is kept on your device persist partition and never sent to our servers
    # do not erase your persist partition
    if not os.path.isfile(PERSIST + "/comma/id_rsa.pub"):
        needs_registration = True
        cloudlog.warning("generating your personal RSA key")
        mkdirs_exists_ok(PERSIST + "/comma")
        assert os.system("openssl genrsa -out " + PERSIST +
                         "/comma/id_rsa.tmp 2048") == 0
        assert os.system("openssl rsa -in " + PERSIST +
                         "/comma/id_rsa.tmp -pubout -out " + PERSIST +
                         "/comma/id_rsa.tmp.pub") == 0
        os.rename(PERSIST + "/comma/id_rsa.tmp", PERSIST + "/comma/id_rsa")
        os.rename(PERSIST + "/comma/id_rsa.tmp.pub",
                  PERSIST + "/comma/id_rsa.pub")

    if needs_registration:
        if show_spinner:
            spinner = Spinner()
            spinner.update("registering device")

        # Create registration token, in the future, this key will make JWTs directly
        with open(PERSIST +
                  "/comma/id_rsa.pub") as f1, open(PERSIST +
                                                   "/comma/id_rsa") as f2:
            public_key = f1.read()
            private_key = f2.read()

        # Block until we get the imei
        serial = HARDWARE.get_serial()
        start_time = time.monotonic()
        imei1, imei2 = None, None
        while imei1 is None and imei2 is None:
            try:
                imei1, imei2 = HARDWARE.get_imei(0), HARDWARE.get_imei(1)
            except Exception:
                cloudlog.exception("Error getting imei, trying again...")
                time.sleep(1)

            if time.monotonic() - start_time > 60 and show_spinner:
                spinner.update(
                    f"registering device - serial: {serial}, IMEI: ({imei1}, {imei2})"
                )

        params.put("IMEI", imei1)
        params.put("HardwareSerial", serial)

        backoff = 0
        start_time = time.monotonic()
        try_count = 0
        while True:
            try:
                register_token = jwt.encode(
                    {
                        'register': True,
                        'exp': datetime.utcnow() + timedelta(hours=1)
                    },
                    private_key,
                    algorithm='RS256')
                cloudlog.info("getting pilotauth")
                resp = api_get("v2/pilotauth/",
                               method='POST',
                               timeout=10,
                               imei=imei1,
                               imei2=imei2,
                               serial=serial,
                               public_key=public_key,
                               register_token=register_token)

                if resp.status_code in (402, 403, 404):
                    cloudlog.info(
                        f"Unable to register device, got {resp.status_code}")
                    dongle_id = UNREGISTERED_DONGLE_ID
                else:
                    dongleauth = json.loads(resp.text)
                    dongle_id = dongleauth["dongle_id"]
                break
            except Exception:
                try_count += 1
                if try_count >= 2:
                    dongle_id = UNREGISTERED_DONGLE_ID
                    break
                cloudlog.exception("failed to authenticate")
                backoff = min(backoff + 1, 15)
                time.sleep(backoff)

            if time.monotonic() - start_time > 60 and show_spinner:
                spinner.update(
                    f"registering device - serial: {serial}, IMEI: ({imei1}, {imei2})"
                )

        if show_spinner:
            spinner.close()

    if dongle_id:
        params.put("DongleId", dongle_id)
        set_offroad_alert("Offroad_UnofficialHardware",
                          dongle_id == UNREGISTERED_DONGLE_ID)
    return dongle_id
Example #46
0
 def jwt(self, req=None, **kw):
     if not req:
         req = self.jwt_dict(**kw)
     return jwt.encode(req, self.webpay_dev_secret)
Example #47
0
def sign(payload, headers=None):
    if headers is None:
        headers = {"jku": "https://api.cf.test.com", "kid": "key-id-0"}
    payload = {k: payload[k] for k in payload if payload[k] is not None}
    return jwt.encode(payload, PRIVATE_KEY, algorithm="RS256",
                      headers=headers).decode("utf-8")
Example #48
0
 def generate_token(self, expiration: datetime.timedelta=TWO_WEEKS):
     user_dict = UserType.from_orm(self).dict()
     user_dict["exp"] = datetime.datetime.utcnow() + TWO_WEEKS
     return jwt.encode(user_dict, SECRET_KEY, algorithm='HS256')
Example #49
0
 def jwt_token(self):
     integration = self.integration
     return jwt.encode({"id": integration.external_id},
                       integration.metadata["webhook_secret"])
            event.body,
            event.tags
        ))


def handle_incoming_error(error_msg):
    print("received error:%s'" % (
        error_msg
    ))


if __name__ == "__main__":
    print("Subscribing to event on channel example")
    cancel_token = ListenerCancellationToken()

    # Subscribe to events without store
    subscriber = Subscriber("localhost:50000", encryptionHeader=jwt.encode({}, algorithm="HS256", key="some-key"))
    subscribe_request = SubscribeRequest(
        channel="testing_event_channel",
        client_id="hello-world-subscriber",
        events_store_type=EventsStoreType.Undefined,
        events_store_type_value=0,
        group="",
        subscribe_type=SubscribeType.Events
    )
    subscriber.subscribe_to_events(subscribe_request, handle_incoming_events, handle_incoming_error, cancel_token)

    input("Press 'Enter' to stop Listen...\n")
    cancel_token.cancel()
    input("Press 'Enter' to stop the application...\n")
Example #51
0
def create_user(user_id, password):
	encoded_token = jwt.encode({str(user_id) : str(password)}, SECRET, ALGORITHM)
Example #52
0
def auth_register(email, password, name_first, name_last, url):
    '''
    Function registers users
    '''
    #Code below checks if any users in the users dictionary and checks if input email already exists
    if not check(email):
        raise InputError('Invalid Email')

    if len(users) != 0:
        for user in users:
            if user['email'] == email:
                print("error")
                raise InputError('Email already registered')

    #Code below checks the length of the input names against restrictions
    if len(name_first) > NAME_MAXLEN or len(name_first) < NAME_MINLEN:
        raise InputError('Invalid First Name')

    if len(name_last) > NAME_MAXLEN or len(name_last) < NAME_MINLEN:
        raise InputError('Invalid Last Name')

    #Code below checks if input email is a valid email using regex

    #Code below checks the length of the password
    if len(password) < 6:
        raise InputError('Invalid password')
    #Code below is for when all conditions are met

    encoded_token = jwt.encode({'u_id': len(users) +1}, SECRET, algorithm='HS256')
    if check(email) and len(password) >= 6:
        #Create a new dictionary with data about the user
        new_user = {
            'u_id': len(users)+1,
            'name_first': name_first,
            'name_last': name_last,
            'handle_str': name_first.lower() + name_last[0],
            'email': email,
            'password': hashlib.sha256(password.encode()).hexdigest(),
            'token': encoded_token.decode('utf-8'),
            'reset_code': 0,
            'profile_img_url': str(url) + "static/defult.jpg"
        }

        print(new_user['profile_img_url'])

        if len(users) == 0:
            new_user['permission_id'] = 1
        else:
            new_user['permission_id'] = 2

        #A copy of the dictionary is needed otherwise it messes with the references
        new_user_copy = new_user.copy()

        #Append the copied dictionary onto our list of users
        users.append(new_user_copy)

        saveUserData(users)
        #Return the correct output
        return {
            'u_id': new_user_copy['u_id'],
            'token': new_user_copy['token'],
        }
    return None
Example #53
0
def oauth_login(userDetails):
    """
    function to oauth_login the user
    """
    try:
        firstname = userDetails["firstname"]
        lastname = userDetails["lastname"]
        email = userDetails["email"]
        provider = userDetails["provider"]
        providerId = userDetails["provider_id"]
        createdAt = time.strftime('%Y-%m-%d %H:%M:%S')
    except KeyError as err:
        return json.dumps({'error': True, 'error_found': format(err)})
    except TypeError as err:
        return json.dumps({'error': True, 'error_found': format(err)})
    except Exception as err:
        return json.dumps({'error': True, 'error_found': format(err)})

    results = UserModel.query.filter(UserModel.email == email).first()

    if results is not None:
        if results.email == email:
            """
            checking if user already exists or not
            """
            if results.phone is not None:
                data = [{
                    "firstname": results.firstname,
                    "lastname": results.lastname,
                    "dob": str(results.dob),
                    "email": results.email,
                    "phone": results.phone,
                    "userType": results.userType,
                    "created_at": str(results.createdAt),
                    "user_id": results.id
                }]
            else:
                data = [{
                    "firstname": results.firstname,
                    "lastname": results.lastname,
                    "email": results.email,
                    "userType": results.userType,
                    "created_at": str(results.createdAt),
                    "user_id": results.id,
                    "phone": '',
                    "dob": '',
                }]
            d = {"data": data, "session_expiry": time.time() + 86400}
            encodeJwt = jwt.encode(d, SECRET_KEY)
            return json.dumps({
                "error": False,
                "token": encodeJwt.decode(),
                "message": "Logged in successfully!"
            })
    else:
        try:
            """
            registering as new user
            """
            userType = "user"
            user = UserModel(firstname=firstname,
                             lastname=lastname,
                             email=email,
                             userType=userType,
                             createdAt=createdAt)
            db.session.add(user)
            db.session.commit()

            res = UserModel.query.filter(UserModel.email == email).first()
            relation = UserOAuthModel.query.filter(
                UserOAuthModel.userId == res.id).first()
            if relation is None:
                """
                saving data of OAuth
                """
                u = UserOAuthModel(
                    userId=res.id,
                    provider=provider,
                    providerId=providerId,
                )
                db.session.add(u)
                db.session.commit()

            data_ = [{
                "firstname": res.firstname,
                "lastname": res.lastname,
                "email": res.email,
                "userType": res.userType,
                "created_at": str(res.createdAt),
                "user_id": res.id
            }]
            obj = {"data": data_, "session_expiry": time.time() + 86400}
            encodeJwt = jwt.encode(obj, SECRET_KEY)
            return json.dumps({
                "error": False,
                "token": encodeJwt.decode(),
                "message": "Logged in successfully!"
            })
        except Exception as err:
            return {'error': True, 'error_found': format(err)}
    return json.dumps({"error": True, "message": "Unknown error!"})
Example #54
0
 def encode_jwt(self, message):
     return jwt.encode(message,
                       self._registration.get_tool_private_key(),
                       algorithm='RS256')
Example #55
0
def jwt_encode_handler(payload):
    return jwt.encode(
        payload,
        settings.JWT_SECRET_KEY,
        settings.JWT_ALGORITHM,
    ).decode('utf-8')
Example #56
0
def encode_token(data):
    return jwt.encode(data, app.config["SECRET_KEY"],
                      algorithm='HS256').decode()
Example #57
0
def get_token(json_obj):
    token = jwt.encode(json_obj, SECRET_KEY)
    return token
Example #58
0
def _get_jwt(user_data):
    exp_time = datetime.datetime.utcnow() + datetime.timedelta(weeks=2)
    payload = {'exp': exp_time,
               'nbf': datetime.datetime.utcnow(),
               'email': user_data['email']}
    return jwt.encode(payload, JWT_SECRET, algorithm='HS256')
    def test_bad_tokens(self):
        # Test expired access token
        response = self.client.post('/auth/login')
        data = json.loads(response.get_data(as_text=True))
        access_token = data['access_token']
        status_code, data = self._jwt_get('/protected', access_token)
        self.assertEqual(status_code, 200)
        self.assertIn('msg', data)
        time.sleep(2)
        status_code, data = self._jwt_get('/protected', access_token)
        self.assertEqual(status_code, 401)
        self.assertIn('msg', data)

        # Test expired refresh token
        response = self.client.post('/auth/login')
        data = json.loads(response.get_data(as_text=True))
        refresh_token = data['refresh_token']
        status_code, data = self._jwt_post('/auth/refresh', refresh_token)
        self.assertEqual(status_code, 200)
        self.assertIn('access_token', data)
        self.assertNotIn('msg', data)
        time.sleep(2)
        status_code, data = self._jwt_post('/auth/refresh', refresh_token)
        self.assertEqual(status_code, 401)
        self.assertNotIn('access_token', data)
        self.assertIn('msg', data)

        # Test Bogus token
        auth_header = "Bearer {}".format('this_is_totally_an_access_token')
        response = self.client.get('/protected',
                                   headers={'Authorization': auth_header})
        data = json.loads(response.get_data(as_text=True))
        status_code = response.status_code
        self.assertEqual(status_code, 422)
        self.assertIn('msg', data)

        # Test token that was signed with a different key
        with self.app.test_request_context():
            token = encode_access_token('foo',
                                        'newsecret',
                                        'HS256',
                                        timedelta(minutes=5),
                                        True, {},
                                        csrf=False,
                                        identity_claim='identity')
        auth_header = "Bearer {}".format(token)
        response = self.client.get('/protected',
                                   headers={'Authorization': auth_header})
        data = json.loads(response.get_data(as_text=True))
        status_code = response.status_code
        self.assertEqual(status_code, 422)
        self.assertIn('msg', data)

        # Test with valid token that is missing required claims
        now = datetime.utcnow()
        token_data = {'exp': now + timedelta(minutes=5)}
        encoded_token = jwt.encode(
            token_data, self.app.config['SECRET_KEY'],
            self.app.config['JWT_ALGORITHM']).decode('utf-8')
        auth_header = "Bearer {}".format(encoded_token)
        response = self.client.get('/protected',
                                   headers={'Authorization': auth_header})
        data = json.loads(response.get_data(as_text=True))
        status_code = response.status_code
        self.assertEqual(status_code, 422)
        self.assertIn('msg', data)
Example #60
0
def login(details):
    # destructuring data
    try:
        email = details["email"]
        password = details["password"]
        regType = details["regType"]
    except KeyError:
        return json.dumps({
            "error": True,
            "message": "One or more fields are missing!"
        })

    if email == "" or password == "":
        return json.dumps({"error": True, "message": "Empty Fields"})

    if type(email) is not str or type(password) is not str:
        return json.dumps({"error": True, "message": "Wrong data format!"})

    if regType == "user":
        data = UserModel.query.filter(UserModel.email == email).first()
    else:
        data = AdminModel.query.filter(AdminModel.email == email).first()

    if data is not None:
        if data.password == password:
            obj = {
                "email":
                data.email,
                "created_at":
                str(datetime.datetime.utcnow()),
                "expire_at":
                str(datetime.datetime.utcnow() + datetime.timedelta(days=1))
            }

            if regType == "user":
                # destructuring extra data for user
                try:
                    obj["accountType"] = data.accountType,
                except KeyError:
                    return json.dumps({
                        "error":
                        True,
                        "message":
                        "One or more fields are missing!"
                    })

            encode_jwt = jwt.encode(obj, SECRET_KEY)

            return json.dumps({
                "error": False,
                "token": encode_jwt.decode(),
                "message": "Logged in successfully!"
            })

        else:
            return json.dumps({
                "error": True,
                "message": "You have entered the wrong password!"
            })

    return json.dumps({"error": True, "message": "Unknown error!"})