def test_decode_jwt_with_key_override(app): jwt_manager = JWTManager(app) @jwt_manager.encode_key_loader @jwt_manager.decode_key_loader def custom(claims): return 'custom_encode_key' with app.test_request_context(): token = jwt_manager._create_jwt('foo') decode_jwt(token)
def test_decode_jwt_with_key_override_mismatch(app): jwt_manager = JWTManager(app) @jwt_manager.encode_key_loader def encode_key(claims): return 'custom_encode_key' @jwt_manager.decode_key_loader def decode_key(claims): return 'wrong_decode_key' with app.test_request_context(): token = jwt_manager._create_jwt('foo') with pytest.raises(pyjwt.InvalidSignatureError): decode_jwt(token)
def html_reset_password(token): jwt_data = decode_jwt(token) if jwt_data['role'] != 'password': raise APIException('Access denied', 401) if request.method == 'GET': return render_template('reset_password.html', data={ 'host': os.environ.get('API_HOST'), 'token': token }) # request.method == 'PUT' body = request.get_json() check_params(body, 'email', 'password') user = Users.query.filter_by(id=jwt_data['sub'], email=body['email']).first() if not user: raise APIException('User not found', 404) user.password = sha256(body['password']) db.session.commit() return jsonify({'message': 'Your password has been updated'}), 200
def test_correct_signup(client): resp = client.post('/create/token') assert resp.status_code == 200, "I should be able to create a token" decoded_data = decode_jwt(resp.data.decode().strip('"')) assert 'exp' in decoded_data, "The decoded data must have expiration"
def html_reset_password(token): jwt_data = decode_jwt(token) if request.method == 'GET': user = Users.query.filter_by(id=jwt_data['sub'], email=jwt_data['role']).first() if user is None: raise APIException('User not found', 404) return render_template('reset_password.html', host=os.environ.get('API_HOST'), token=token, email=jwt_data['role']) # request.method == 'PUT' req = request.get_json() utils.check_params(req, 'email', 'password') if len(req['password']) < 6: raise APIException('Password must be at least 6 characters long') user = Users.query.filter_by(id=jwt_data['sub'], email=req['email']) if user is None: raise APIException('User not found', 404) user.password = utils.sha256(req['password']) db.session.commit() return jsonify({'message': 'Your password has been updated'}), 200
def validate(token): jwt_data = decode_jwt(token) accepted_roles = ['first_time_validation', 'email_change'] if jwt_data['role'] not in accepted_roles: raise APIException('Incorrect token', 400) user = Users.query.get(jwt_data['sub']) if user is None: raise APIException('Invalid key payload', 400) if user.status._value_ == 'invalid': user.status = 'valid' db.session.commit() resp = requests.post( f"{os.environ['POKERSOCIETY_HOST']}/swapprofit/email/user/{user.pokersociety_id}", json={ 'api_token': utils.sha256(os.environ['POKERSOCIETY_API_TOKEN']), 'email': user.email }) if jwt_data['role'] == 'first_time_validation': send_email(template='welcome', emails=user.email) return render_template('email_validated_success.html')
def get_quickbooks_credentials(): token = request.args.get("token") decoded_payload = decode_jwt(token) url = auth_client.get_authorization_url( [Scopes.ACCOUNTING], state_token=decoded_payload["sub"]) return redirect(url), 200
def test_auth_with_valid_details(self): username = '******' password = '******' # act resp = self.client.post('/auth', json={ "uid": username, "password": password }) # assert self.assertEqual(resp.status_code, 200, resp.data) self.assertIn('access_token', resp.json) # checking if the access token is correct with self.app.app_context(): from flask_jwt_simple import decode_jwt user = decode_jwt(resp.json['access_token']) self.assertEqual(user['sub'], username)
def login(provider_name): response = make_response() adapt = WerkzeugAdapter(request, response) log.info(repr(request)) log.info(repr(adapt)) log.info(repr(response)) result = authomatic.login(adapt, provider_name, short_name=1) if result: if result.user: result.user.update() authres = json.loads(result.to_json()) identity = "{ \"userid\":\"" + str( authres['provider']['user']) + "\", \"siteid\":\"" + str( authres['provider']['id']) + "\"}" log.info("Created Identity: " + identity) ret = create_jwt(identity=identity) # log.debug(ret + "\n") log.debug(decode_jwt(ret)) user = result.user.name jsonstring = "{ \"jwt\" : \"" + ret + "\", \"user\" : \"" + user + "\", \"provider\" : \"" + provider_name + "\"}" log.info(jsonstring) ppp_js = """(function(){ closer = function() { window.close(); }; var result = JSON.parse('""" + jsonstring + """'); try { window.opener.authomatic.loginComplete(result, closer); } catch(e) {} })();""" return render_template( 'index.html', result={ "jwt": ret, "user": str(result.user.name), "provider": str(provider_name) }, popup_js=ppp_js, title='Authomatic Example', base_url='http://authomatic-example.appspot.com', oauth1='', oauth2='') return response
def validate(token): jwt_data = decode_jwt(token) if jwt_data['role'] != 'validating': raise APIException('Incorrect token', 400) user = Users.query.filter_by(id=jwt_data['sub']).first() if user is None: raise APIException('Invalid key payload', 400) if user.valid == False: user.valid = True db.session.commit() send_email(type='account_created', to=user.email) return render_template('email_validated_success.html')
def validate(token): jwt_data = decode_jwt(token) accepted_roles = ['first_time_validation', 'email_change'] if jwt_data['role'] not in accepted_roles: raise APIException('Incorrect token', 400) user = Users.query.get(jwt_data['sub']) if user is None: raise APIException('Invalid key payload', 400) if user.status._value_ == 'invalid': user.status = 'valid' db.session.commit() if jwt_data['role'] == 'first_time_validation': send_email(template='welcome', emails=user.email) return render_template('email_validated_success.html')
def validate(token): jwt_data = decode_jwt(token) if jwt_data['role'] != 'validating': raise APIException('Incorrect token', 400) user = Users.query.get(jwt_data['sub']) if not user.valid: user.valid = True db.session.commit() return jsonify({ 'message': 'Your email has been validated', 'jwt': create_jwt({ 'id': jwt_data['sub'], 'role': 'user', 'exp': 600000 }) }), 200
def test_views_auth_jwt_login(self, init_db_data): """Test JWT login api endpoint""" # retrieve database informations login_id, clear_pwd = init_db_data['occupant_users'][0] # try to sign in response = self._auth_jwt_login(login_id=login_id, password=clear_pwd) assert response.status_code == 200 assert 'access_token' in response.json # verify token content with self.app.app_context(): claim = self.app.config['JWT_IDENTITY_CLAIM'] token = decode_jwt(response.json['access_token']) assert 'exp' in token assert 'iat' in token assert 'nbf' in token assert claim in token assert token[claim]['uid'] == login_id assert token[claim]['roles'] == ['anonymous_occupant'] assert token[claim]['type'] == 'user' # verify authentication cookie assert 'set-cookie' in response.headers set_cookie = response.headers['set-cookie'] assert set_cookie is not None assert 'session=' in set_cookie # Errors # no login_id and/or password response = self._auth_jwt_login() assert response.status_code == 422 # unknown login_id value response = self._auth_jwt_login(login_id='bad_id', password=clear_pwd) assert response.status_code == 401 # bad password response = self._auth_jwt_login(login_id=login_id, password='******') assert response.status_code == 401
def post(self): """ Expire token endpoint Args: access_token (str) : access token from header Returns: str: success or error message """ # get access token from header header_name = current_app.config['JWT_HEADER_NAME'] jwt_header = request.headers.get(header_name, None) if len(jwt_header.split()) == 1: access_token = jwt_header elif len(jwt_header.split()) == 2: access_token = jwt_header.split()[1] user_id = decode_jwt(access_token) if user_id is not None: EXPIRED.append(access_token) current_app.logger.info("Expire token for user " + user_id['sub']) return mk_response("The token has been manually expired.", 200) else: return mk_response("The token could not expire.", 400)
def remove_expired(): for tk in EXPIRED: now = (datetime.now() - datetime(1970, 1, 1)).total_seconds() if now < decode_jwt(tk)['exp']: del tk
def file_upload(): # If user not logged in, send him to login page try: jwt = request.cookies.get('pokersociety-jwt') decode_jwt(jwt) except: return redirect('/users/login') # GET if request.method == 'GET': return render_template('file_upload.html', host=os.environ.get('API_HOST')) # POST if 'excel' not in request.files: raise APIException('"excel" property missing in the files array', 404) f = request.files['excel'] df = pd.read_excel(f, keep_default_na=False) headers = list(df) # TOURNAMENTS if utils.are_headers_for('tournaments', headers): returned_data = actions.process_tournament_excel(df) updated_df, error_list, trmnt_added = returned_data # updated_df = df # DELETE, ONLY FOR TESTING # error_list = [] # DELETE, ONLY FOR TESTING # Save file with added Tournament IDs, which will be downloaded in the frontend if trmnt_added: writer = pd.ExcelWriter( f"{os.environ['APP_PATH']}/src/excel_downloads/{f.filename}") df.to_excel(writer, index=False) writer.save() # Display any errors that happened while processing the file if len(error_list) > 0: return jsonify({'download': trmnt_added, 'error': error_list}) msg = 'Tournament excel processed successfully' return jsonify({ 'message': msg + '. File downloaded' if trmnt_added else msg, 'download': trmnt_added }), 200 # CASINOS if utils.are_headers_for('casinos', headers): actions.process_casinos_excel(df) return jsonify({'message': 'Casino excel proccessed successfully'}), 200 # RESULTS if utils.are_headers_for('results', headers): subscriber, subscriber_json, log = actions.process_results_excel(df) # swapprofit = Subscribers.query.filter_by(company_name='Swap Profit').first() if subscriber is None: return jsonify({'error': 'Swap Profit not a subscriber'}) aSub = subscriber.company_name.replace(" ", "") api_token = aSub.upper() + '_API_TOKEN' if subscriber_json is not None: # SWAPPROFUT ENDS HERE swapprofit.api_host resp = requests.post(subscriber.api_host + '/results/update', json={ 'api_token': os.environ[api_token], **subscriber_json }) if not resp.ok: log = {'error': 'There was a problem with the subscriber'} else: log = resp.json() print('resp', resp, log) # print('resp', resp.json()) return jsonify({'message': "Successfully Uploaded Results"}), 200 return jsonify({'error': 'Unrecognized file'}), 200
def forgot_password(token): jwt_data = decode_jwt(token) return 'ok'