from eve import Eve from machine import more_than # def before_insert(resource_name, documents): # if resource_name == 'request': # for document in documents: # print(document) # document['more_than_one_hour'] = more_than(1) # document['more_than_two_hours'] = more_than(2) def before_get(resource_name, response): print(response) if resource_name == 'request': response['_items'] = [{ 'more_than_one_hour': more_than(1), 'more_than_two_hours': more_than(2) }] app = Eve(settings='settings.py') # app.on_insert += before_insert app.on_fetched_resource += before_get app.run(debug=True)
# -*- coding: utf-8 -*- import platform import psutil import shutil import json from eve import Eve from flask import Response as RS settings = {'MONGO_HOST': 'localhost', 'MONGO_PORT': 27017, 'DOMAIN': {}} app = Eve(settings=settings) #rs = RS() # always have problem in this deployment, put into each function @app.route('/processor') def processor(): rs = RS() rs.headers["status"] = 200 rs.headers["Content-Type"] = "application/json; charset=utf-8" info = {'processor': platform.processor()} rs.data = json.dumps(info) return rs @app.route('/system') def os():
methods to public access -see docs). Since we are using werkzeug we don't need any extra import (werkzeug being one of Flask/Eve prerequisites). Checkout Eve at https://github.com/nicolaiarocci/eve This snippet by Nicola Iarocci can be used freely for anything you like. Consider it public domain. """ from eve import Eve from eve.auth import BasicAuth from werkzeug.security import check_password_hash from settings_security import SETTINGS class Sha1Auth(BasicAuth): def check_auth(self, username, password, allowed_roles, resource, method): # use Eve's own db driver; no additional connections/resources are used accounts = app.data.driver.db['accounts'] account = accounts.find_one({'username': username}) return account and \ check_password_hash(account['password'], password) if __name__ == '__main__': app = Eve(auth=Sha1Auth, settings=SETTINGS) app.run()
from eve import Eve from eve.auth import BasicAuth class Authenticate(BasicAuth): def check_auth(self, username, password, allowed_roles, resource, method): print resource print method if resource == 'user' and method == 'GET': user = app.data.driver.db['user'] user = user.find_one({'username': username, 'password': password}) if user: return True else: return False elif resource == 'user' and method == 'POST': print username print password return username == 'admin' and password == 'password' else: return True if __name__ == '__main__': app = Eve(auth=Authenticate) app.run()
from eve import Eve from flask import jsonify, request, abort from auth import LibraryAuth from auth import create_token, get_user_by_token, get_user_by_login_data, update_user_token from auth import on_insert_users from datetime import timedelta from utils import get_request_param app = Eve(auth=LibraryAuth) app.on_insert_users += on_insert_users @app.route('/login', methods=['POST']) def login(): email = get_request_param(request, 'email') if not email: abort(400, description="Missing email parameter") password = get_request_param(request, 'password') if not password: abort(400, description="Missing password parameter") user = get_user_by_login_data(email, password) if not user: abort(404, description="No such user") user_id = str(user['_id']) expiration = timedelta(days=1) token = create_token(user_id, expiration) update_user_token(user, token)
from http import HTTPStatus from eve import Eve from flask import request, jsonify, current_app from authentication import route_auth from event_hooks import (open_waitress_session_actions, change_waitress_session_actions, new_order_actions, close_order_actions, orders_dynamic_filter) from infrastructure import get_action_log_data, ClientManager application = Eve() # region Custom endpoint @application.route('/visitors/') def get_visitor_data(): client = ClientManager(request, is_waitress=False) return client.get_client_data_response() @application.route('/action_log/') def get_action_log_data(): return jsonify( get_action_log_data({'waitress_status': 'S'}) or {'waitress_status': 'C'}) @application.route('/food_category/enable/<int:code>', methods=['PATCH']) @route_auth def enable_food_by_code(code):
def test_bad_auth_class(self): self.app = Eve(settings=self.settings_file, auth=BadHMACAuth) self.test_client = self.app.test_client() r = self.test_client.get("/", headers=self.valid_auth) # will fail because check_auth() is not implemented in the custom class self.assert500(r.status_code)
from io import BytesIO from math import radians, cos, sin, asin, sqrt import herepy import ast port = 5000 host = '10.42.0.1' #host = "127.0.0.1" class MyBasicAuth(BasicAuth): def check_auth(self, username, password, allowed_roles, resource, method): return username == 'root' and password == '66224466' app = Eve(__name__, auth=MyBasicAuth) app.config['SESSION_TYPE'] = 'memcached' app.config['SECRET_KEY'] = '5234124584324' headers = { 'Authorization': 'Basic cm9vdDo2NjIyNDQ2Ng==', 'Content-Type': 'application/json' } app.config['MONGO_HOST'] = '0.0.0.0' app.config['MONGO_PORT'] = '27017' app.config['MONGO_DBNAME'] = 'sahayak' app.config['MONGO_USERNAME'] = '******' app.config['MONGO_PASSWORD'] = '******' UPLOAD_FOLDER = "../static/uploads/"
from eve import Eve from eve.auth import BasicAuth, requires_auth from flask import Response, abort, g, current_app, request from eve_sqlalchemy import SQL from eve_sqlalchemy.validation import ValidatorSQL from mmdps.dms.tables import Base, MRIScan from mmdps.remote_service import mridata import users class SimpleAuth(BasicAuth): def check_auth(self, username, password, allowed_roles, resource, method): return users.check_user(username, password) app = Eve(validator=ValidatorSQL, data=SQL, auth=SimpleAuth) # bind sqlalchemy db = app.data.driver Base.metadata.bind = db.engine db.Model = Base # mridata server accessor_urlbase = app.config['MY_STORAGE_URLBASE'] accessor_auth = app.config['MY_STORAGE_AUTH'] mridataaccessor = mridata.MRIDataAccessor(accessor_urlbase, accessor_auth) # feature server accessor_feature_urlbase = app.config['MY_FEATURE_STORAGE_URLBASE'] accessor_feature_auth = app.config['MY_FEATURE_STORAGE_AUTH'] accessor_feature_root = app.config['MY_FEATURE_ROOT']
# if not companies_cache.get(value): # companies_cache.rebuild() # if not companies_cache.get(value): # self._error(field, "companyId field does not exist: %s" % value) def _validate_type_hour(self, field, value): try: strptime(value, "%H:%M:%S") except ValueError: self._error( field, "Field %s is not valid: %s. Expected format: hh:mm:ss" % (field, value)) def _validate_type_month(self, field, value): try: strptime(value, "%m-%d") except ValueError: self._error( field, "Field %s is not valid: %s. Expected format: MM-DD" % (field, value)) app = Eve(validator=EmpoweringValidator, auth=EVETokenAuth) set_hooks(app) set_methods(app) set_docs(app) prefix = api_prefix(api_version=app.config['API_VERSION']) if __name__ == '__main__': app.run()
def __init__(self, mongoclient=MongoClient(host='localhost', port=27017), name='arduinolog'): self.al = query.ArduinoLog(db=mongoclient, name=name) self.app = Eve(settings='../settings.py') self.tz = gettz(TZst) def route(self, rule, **options): def decorator(f): endpoint = options.pop('endpoint', None) self.app.add_url_rule(rule, endpoint, f, **options) return f return decorator @route(self, '/sensors') def sensor_list(): return '\n'.join(self.al.all_sensors) @route(self, '/sensorcount') def sensor_count(): return str(len([x for x in self.al.all_sensors])) @route(self, '/timeseriesdata/lastreading/<sensor>') def lastreading(sensor): if sensor in self.al.ts_sensors: return str(self.al.last_value(sensor)) else: sl = ',\n'.join(self.al.ts_sensors) msg = ('Unacceptible sensors. Please try:\n' + sl) return msg @route(self, '/eventdata/table/') def table_events(): return pre_wrap(self.al._print_events()) @route(self, '/eventdata/table/<dt>') def events_date(dt): d = datetime.utcnow() mesg = '' try: d = parse(dt.split('(')[1].split(')')[0]) except ValueError as ve: mesg = ('ERR: Invalid date ({}), ' 'showing table for {}').format(ve, d) + linesep output = (mesg + self.al._print_events(parsedt(d, TZst))) return pre_wrap(output) @route(self, '/timeseriesdata/table/hourstats') def table_hourstats(): return pre_wrap(self.al._print_hour_table()) @route(self, '/timeseriesdata/table/hourstats/<dt>') def hour_stats_date(dt): d = datetime.utcnow() mesg = '' try: d = parse(dt.split('(')[1].split(')')[0]) except ValueError as ve: mesg = ('ERR: Invalid date ({}), ' 'showing table for {}').format(ve, d) + linesep output = (mesg + self.al._print_hour_table(parsedt(d, TZst))) return pre_wrap(output) @route(self, '/timeseriesdata/table/<sensor>') def table(sensor): if sensor in self.al.ts_sensors: return pre_wrap(self.al._print_values(sensor)) else: sl = ',\n'.join(self.al.ts_sensors) msg = pre_wrap('Unacceptible sensors. Please try:\n' + sl) return msg @route(self, '/timeseriesdata/table/<sensor>/<dt>') def table_date(sensor, dt): d = datetime.utcnow() mesg = '' try: d = parse(dt.split('(')[1].split(')')[0]) except ValueError as ve: mesg = ('ERR: Invalid date ({}), ' 'showing table for {}').format(ve, d) + linesep if sensor in self.al.ts_sensors: return pre_wrap(self.al._print_values(sensor, parsedt(d, TZst))) else: sl = ',\n'.join(self.al.ts_sensors) msg = pre_wrap('Unacceptible sensors. Please try:\n' + sl) return msg
def start_eve(): global app global db_conn global rebot_instance app = Eve(data=SQL, validator=ValidatorSQL, auth=BCryptAuth) @app.route('/api/login/') @requires_auth('login') def login_check(): return jsonify({'success': True}) @app.route('/api/order/<prod_id>/<anz>/<comment>') @requires_auth('order') def order(prod_id, anz, comment): auth_val = app.auth.get_request_auth_value().split('#') customer_id = int(auth_val[0]) customer = db_conn.get_poster(customer_id, None) try: ordered = order_product(rebot_instance, prod_id, anz, comment, customer) return jsonify({'success': True, 'order_id': ordered.order_id}) except ValueError as e: return jsonify({'success': False, 'reason': str(e)}) @app.route('/api/order/cancel/<order_id>/<reason>') @requires_auth('order_cancel') def order_cancel(order_id, reason): auth_val = app.auth.get_request_auth_value().split('#') customer_id = int(auth_val[0]) customer = db_conn.get_poster(customer_id, None) if cancel_order(rebot_instance, order_id, reason, customer.poster_id): return jsonify({'success': True}) else: return jsonify({'success': False, 'reason': 'NOT AUTHORIZED'}) @app.route('/api/user/register', methods=['POST']) def user_reg(): body = request.get_json(force=True) try: username = body.get('username') if username is None: raise AttributeError('BODY HAS NO ATTRIBUTE: username') password = body.get('password') if password is None: raise AttributeError('BODY HAS NO ATTRIBUTE: password') ret = register_user( rebot_instance, username, password, body.get('telegram_id') if 'telegram_id' in body else None) if ret is not True: return jsonify({'success': False, 'reason': ret}) else: return jsonify({'success': True}) except AttributeError as e: return jsonify({'success': False, 'reason': str(e)}) @app.route('/api/user/register-telegram/<tele_id>') @requires_auth('telegram_register') def user_reg_tele(tele_id): auth_val = app.auth.get_request_auth_value().split('#') ret = register_telegram(rebot_instance, auth_val[1], tele_id) if ret is not True: return jsonify({'success': False, 'reason': ret}) else: return jsonify({'success': True}) @app.route('/api/user/update/password/', methods=['POST']) @requires_auth('user_pass_update') def user_update_pass(): auth_val = app.auth.get_request_auth_value().split('#') body = request.get_json(force=True) try: password = body.get('password') if password is None: raise AttributeError('BODY HAS NO ATTRIBUTE: password') ret = change_password(db_conn, auth_val[1], password) if ret is not True: return jsonify({'success': False, 'reason': ret}) else: return jsonify({'success': True}) except AttributeError as e: return jsonify({'success': False, 'reason': str(e)}) @app.route('/api/order/approve/<order_id>') @requires_auth('order_approve') def order_approve(order_id): auth_val = app.auth.get_request_auth_value().split('#') customer_id = int(auth_val[0]) customer = db_conn.get_poster(customer_id, None) if approve_order(rebot_instance, order_id, customer.poster_id): return jsonify({'success': True}) else: return jsonify({'success': False, 'reason': 'NOT AUTHORIZED'}) @app.route('/api/order/finish/<order_id>') @requires_auth('order_finish') def order_finish(order_id): auth_val = app.auth.get_request_auth_value().split('#') customer_id = int(auth_val[0]) customer = db_conn.get_poster(customer_id, None) if finish_order(rebot_instance, order_id, customer.poster_id): return jsonify({'success': True}) else: return jsonify({'success': False, 'reason': 'NOT AUTHORIZED'}) @app.route('/api/order/deny/<order_id>/<reason>') @requires_auth('order_deny') def order_deny(order_id, reason): auth_val = app.auth.get_request_auth_value().split('#') customer_id = int(auth_val[0]) customer = db_conn.get_poster(customer_id, None) if deny_order(rebot_instance, order_id, reason, customer.poster_id): return jsonify({'success': True}) else: return jsonify({'success': False, 'reason': 'NOT AUTHORIZED'}) @app.route('/api/edit/shop/<shop_id>', methods=['POST']) @requires_auth('shop_edit') def edit_shop(shop_id): auth_val = app.auth.get_request_auth_value().split('#') owner = int(auth_val[0]) shop = db_conn.get_shop(shop_id) if shop.owner != owner: return jsonify({'success': False, 'reason': 'NOT OWNER'}) body = request.get_json(force=True) shop.name = body.get('name') if body.get( 'name') is not None else shop.name shop.description = body.get('description') if body.get( 'description') is not None else shop.name db_conn.save(shop) return jsonify({ 'success': True, 'shop': { 'name': shop.name, 'description': shop.description, 'shop_id': shop.shop_id, 'owner': shop.owner } }) @app.route('/api/edit/product/<product_id>', methods=['POST']) @requires_auth('product_edit') def edit_product(product_id): auth_val = app.auth.get_request_auth_value().split('#') issuer = int(auth_val[0]) shop_owner, product, shop = db_conn.get_owner(product_id) if shop_owner != issuer: return jsonify({'success': False, 'reason': 'NOT OWNER'}) body = request.get_json(force=True) product.name = body.get('name') if body.get( 'name') is not None else product.name product.comment = body.get('comment') if body.get( 'comment') is not None else product.comment try: product.price = float(body.get('price')) if body.get( 'price') is not None else product.price except ValueError: return jsonify({'success': False, 'reason': 'NOT A NUMBER'}) db_conn.save(product) return jsonify({ 'success': True, 'product': { 'product_id': product.product_id, 'name': product.name, 'shop': product.shop_id, 'comment': product.comment, 'price': product.price } }) @app.route('/api/add/product/<shop_id>') @requires_auth('product_add') def add_product(shop_id): auth_val = app.auth.get_request_auth_value().split('#') issuer = int(auth_val[0]) shop = db_conn.get_shop(shop_id) if shop.owner != issuer: return jsonify({'success': False, 'reason': 'NOT OWNER'}) product = db.Product(name='NEW PRODUCT', price=0, comment='[ ]') body = request.get_json(force=True) product.name = body.get('name') if body.get( 'name') is not None else product.name product.comment = body.get('comment') if body.get( 'comment') is not None else product.comment try: product.price = float(body.get('price')) if body.get( 'price') is not None else product.price except ValueError: return jsonify({'success': False, 'reason': 'NOT A NUMBER'}) db_conn.save(product) return jsonify({ 'success': True, 'product': { 'product_id': product.product_id, 'name': product.name, 'shop': product.shop_id, 'comment': product.comment, 'price': product.price } }) @app.route('/api/delete/product/<product_id>') @requires_auth('product_delete') def delete_product(product_id): auth_val = app.auth.get_request_auth_value().split('#') issuer = int(auth_val[0]) shop_owner, product, shop = db_conn.get_owner(product_id) if shop_owner != issuer: return jsonify({'success': False, 'reason': 'NOT OWNER'}) db_conn.delete(product) return jsonify({'success': True, 'product_id': product_id}) @app.route('/api/orders/unapproved/') @requires_auth('orders') def user_unapproved_orders(): auth_val = app.auth.get_request_auth_value().split('#') owner = int(auth_val[0]) if not owner: return jsonify([]) unap = db_conn.get_unapproved_orders(owner) ret_list = [] # rebot.bot.send_message(update.message.chat.id, str(order['order_id']) + '#O\nFROM ' + customer.name + ':\n' + # str(order['amount']) + 'x' + order['name'] + '\n' + order['comment']) for order in unap: product = db_conn.get_product(order.product_id) # customer = db_conn.get_poster(row['customer'], None) obj = { 'order_id': order['order_id'], 'amount': order['amount'], 'comment': order['comment'], 'product_id': order['product_id'], 'customer': order['customer'], 'timestamp_ordered': db.dump_datetime(order['timestamp_ordered']), 'timestamp_done': db.dump_datetime(order['timestamp_done']), 'timestamp_approved': db.dump_datetime(order['timestamp_approved']), 'product': { 'product_id': product.product_id, 'name': product.name, 'shop': product.shop_id, 'comment': product.comment, 'price': product.price } } ret_list.append(obj) return jsonify(json_list=ret_list) @app.route('/api/orders/open/') @requires_auth('orders') def user_open_orders(): auth_val = app.auth.get_request_auth_value().split('#') owner = int(auth_val[0]) if not owner: return jsonify([]) unap = db_conn.get_open_orders(owner) ret_list = [] # rebot.bot.send_message(update.message.chat.id, str(order['order_id']) + '#O\nFROM ' + customer.name + ':\n' + # str(order['amount']) + 'x' + order['name'] + '\n' + order['comment']) for order in unap: product = db_conn.get_product(order.product_id) # customer = db_conn.get_poster(row['customer'], None) obj = { 'order_id': order['order_id'], 'amount': order['amount'], 'comment': order['comment'], 'product_id': order['product_id'], 'customer': order['customer'], 'timestamp_ordered': db.dump_datetime(order['timestamp_ordered']), 'timestamp_done': db.dump_datetime(order['timestamp_done']), 'timestamp_approved': db.dump_datetime(order['timestamp_approved']), 'product': { 'product_id': product.product_id, 'name': product.name, 'shop': product.shop_id, 'comment': product.comment, 'price': product.price } } ret_list.append(obj) return jsonify(json_list=ret_list) @app.route('/api/orders/my/') @requires_auth('orders') def user_my_orders(): auth_val = app.auth.get_request_auth_value().split('#') issuer = int(auth_val[0]) if not issuer: return jsonify([]) my = db_conn.get_orders(issuer) ret_list = [] # rebot.bot.send_message(update.message.chat.id, str(order['order_id']) + '#O\nFROM ' + customer.name + ':\n' + # str(order['amount']) + 'x' + order['name'] + '\n' + order['comment']) for order in my: product = db_conn.get_product(order.product_id) # customer = db_conn.get_poster(row['customer'], None) obj = { 'order_id': order.order_id, 'amount': order.amount, 'comment': order.comment, 'product_id': order.product_id, 'customer': order.customer, 'timestamp_ordered': db.dump_datetime(order.timestamp_ordered), 'timestamp_done': db.dump_datetime(order.timestamp_done), 'timestamp_approved': db.dump_datetime(order.timestamp_approved), 'product': { 'product_id': product.product_id, 'name': product.name, 'shop': product.shop_id, 'comment': product.comment, 'price': product.price } } ret_list.append(obj) return jsonify(json_list=ret_list) db_eve = app.data.driver db.Base.metadata.bind = db_eve.engine db_eve.Model = db.Base app.run(port=mod_conf.rest_port, host=mod_conf.rest_host, use_reloader=False)
"""Walnut Launch Script.""" # pylint: disable=no-member from eve import Eve from auth import add_token, hash_password WALNUT = Eve() WALNUT.on_insert_accounts += add_token WALNUT.on_insert_accounts += hash_password if __name__ == "__main__": WALNUT.run()
import settings from eve import Eve from components import initialize, users, categories, likes, offers, products import os PWD = os.environ.get('PWD') STATIC_FOLDER = os.path.join(PWD, 'public') app = Eve(settings=settings.EVE_SETTINGS, static_folder=STATIC_FOLDER) initialize.initialize_components(app, [users, categories, likes, offers, products]) import login import melinder.common import melinder.buyer import melinder.seller
from eve import Eve eve_rest = Eve(settings='settings.py') if __name__ == '__main__': eve_rest.run(host='0.0.0.0')
Since we are using werkzeug we don't need any extra import (werkzeug being one of Flask/Eve prerequisites). Checkout Eve at https://github.com/nicolaiarocci/eve This snippet by Nicola Iarocci can be used freely for anything you like. Consider it public domain. """ from eve import Eve from eve.auth import BasicAuth from werkzeug.security import check_password_hash class RolesAuth(BasicAuth): def check_auth(self, username, password, allowed_roles): # use Eve's own db driver; no additional connections/resources are used accounts = app.data.driver.db['accounts'] lookup = {'username': username} if allowed_roles: # only retrieve a user if his roles match ``allowed_roles`` lookup['roles'] = {'$in': allowed_roles} account = accounts.find_one(lookup) return account and check_password_hash(account['password'], password) if __name__ == '__main__': app = Eve(auth=RolesAuth) app.run()
#from flask import Flask #app = Flask(__name__) from eve import Eve app = Eve(__name__) def log_every_get(resource, request, payload): #def pre_get_callback(resource, request, lookup): print('A GET request on the "{}" endpoint has just been received!\n{}'.format(resource, request)) app.on_post_GET += log_every_get print("my dears!") @app.route("/") def hello(): return "Hello Eva!" if __name__ == "__main__": app.run(host='0.0.0.0')
This snippet by Nicola Iarocci can be used freely for anything you like. Consider it public domain. """ import hmac from eve import Eve from eve.auth import HMACAuth from hashlib import sha1 from settings_security import SETTINGS class HMACAuth(HMACAuth): def check_auth(self, userid, hmac_hash, headers, data, allowed_roles, resource, method): # use Eve's own db driver; no additional connections/resources are used accounts = app.data.driver.db['accounts'] user = accounts.find_one({'userid': userid}) if user: secret_key = user['secret_key'] # in this implementation we only hash request data, ignoring the # headers. return user and \ hmac.new(str(secret_key), str(data), sha1).hexdigest() == hmac_hash if __name__ == '__main__': app = Eve(auth=HMACAuth, settings=SETTINGS) app.run()
from eve import Eve from oauth2 import BearerAuth from flask.ext.sentinel import ResourceOwnerPasswordCredentials, oauth from flask import request import json from pymongo import MongoClient from proj.tasks import add import cPickle from flask import request, Response # users = cPickle.load(open('./users.pd','r')) users = [] client = MongoClient() collect = client['eve']['orders'] app = Eve(auth=BearerAuth) ResourceOwnerPasswordCredentials(app) # app.debug = True app.config['CORS_HEADERS'] = 'Content-Type' cors = CORS(app) @app.route('/query_order') @oauth.require_oauth() def query_order(): a = Response("") a.headers['Access-Control-Allow-Origin'] = '*' if request.method == 'POST': data = request.form else:
def pre_GET(resource, request, lookup): isCampaign = request.args.get('isCampaign') if resource == 'posts' or resource == 'meta': if isCampaign: if isCampaign == 'true': lookup.update({"isCampaign": True}) elif isCampaign == 'false': lookup.update({"isCampaign": False}) elif isCampaign is None: lookup.update({"isCampaign": False}) #app = Eve(auth=RolesAuth) if ENV == 'prod': app = Eve(auth=TokenAuth) else: app = Eve() app.on_replace_article += lambda item, original: remove_extra_fields(item) app.on_insert_article += lambda items: remove_extra_fields(items[0]) app.on_insert_accounts += add_token app.on_fetched_resource_posts += before_returning_posts app.on_fetched_resource_albums += before_returning_albums app.on_fetched_resource_meta += before_returning_meta app.on_fetched_resource_listing += before_returning_listing app.on_fetched_resource_choices += before_returning_choices app.on_fetched_resource_sections += before_returning_sections app.on_pre_GET += pre_GET @app.route("/sections-featured", methods=['GET', 'POST'])
def test_put_resource_auth(self): # no global auth. self.app = Eve(settings=self.settings_file) # set auth at resource level instead. resource_def = self.app.config["DOMAIN"][self.url] resource_def["authentication"] = ValidBasicAuth resource_def["auth_field"] = "username" # post r = self.app.test_client().post( self.url, data=self.data, headers=self.valid_auth, content_type="application/json", ) data, status = self.parse_response(r) # retrieve document metadata url = "%s/%s" % (self.url, data["_id"]) response = self.app.test_client().get(url, headers=self.valid_auth) etag = response.headers["ETag"] new_ref = "9999999999999999999999999" changes = json.dumps({"ref": new_ref}) # put headers = [("If-Match", etag), self.valid_auth[0]] response, status = self.parse_response(self.app.test_client().put( url, data=json.dumps(changes), headers=headers, content_type="application/json", )) self.assert200(status) etag = '"%s"' % response["_etag"] # document still accessible with same auth data, status = self.parse_response(self.app.test_client().get( url, headers=self.valid_auth)) self.assert200(status) self.assertEqual(data["ref"], new_ref) # put on same item with different auth fails original_auth_val = resource_def["authentication"].request_auth_value resource_def["authentication"].request_auth_value = "alt" alt_auth = ("Authorization", "Basic YWx0OnNlY3JldA==") alt_changes = {"ref": "1111111111111111111111111"} headers = [("If-Match", etag), alt_auth] response, status = self.parse_response(self.app.test_client().put( url, data=json.dumps(alt_changes), headers=headers, content_type="application/json", )) self.assert403(status) # document still accessible with original auth resource_def["authentication"].request_auth_value = original_auth_val data, status = self.parse_response(self.app.test_client().get( url, headers=self.valid_auth)) self.assert200(status) self.assertEqual(data["ref"], new_ref)
def setUp(self): super(TestTokenAuth, self).setUp() self.app = Eve(settings=self.settings_file, auth=ValidTokenAuth) self.test_client = self.app.test_client() self.valid_auth = [('Authorization', 'Basic dGVzdF90b2tlbjo=')]
i['metadata'] = json.loads(i['metadata']) def on_insert_projects(items): for i in items: # Convert encode string as json if isinstance(i['scan_parameters'], str): i['scan_parameters'] = json.loads(i['scan_parameters']) class TokenAuth(TokenAuth): def check_auth(self, token, allowed_roles, resource, method): return token == API_TOKEN app = Eve(settings=settings, auth=TokenAuth) app.register_blueprint(swagger, url_prefix='/docs/api') app.add_url_rule('/docs/api', 'eve_swagger.index') app.config.from_envvar('MINDR_CFG_PATH') app.config['TOKEN_RE'] = re.compile('access_token=([a-zA-Z0-9]+)') CORS(app) @app.route('/api/socket_auth_token/<token>') def socket_authenticate(token): if token != API_TOKEN: raise RuntimeError("DOES NOT MATCH") secret = app.config["SECRET_KEY"] # self.cfg['app:secret-key'] wstoken = jwt.encode( {
def setUp(self): super(TestHMACAuth, self).setUp() self.app = Eve(settings=self.settings_file, auth=ValidHMACAuth) self.test_client = self.app.test_client() self.valid_auth = [('Authorization', 'admin:secret')]
if 'transform' in schema: dynamic_schema = schema['transform'](dynamic_schema) self._validate_schema(dynamic_schema, field, dct) else: self._error( field, "Could not find any %s for query %s" % (schema['resource'], query)) def _validate_keyschema(self, schema, field, dct): "Validate all keys of dictionary `dct` against schema `schema`." for key, value in dct.items(): self._validate_schema(schema, key, value) settingsfile = path.join(path.abspath(path.dirname(__file__)), 'settings.py') api = Eve(API_NAME, validator=KeySchemaValidator, settings=settingsfile) Bootstrap(api) api.register_blueprint(eve_docs, url_prefix='/docs') resource_url = lambda resource: '/' + api.config['URL_PREFIX'] + '/' + resource def get_schema(resource): "Get the schema for a given resource." return api.config['DOMAIN'][resource]['schema'] def add_document(resource, document): "Add a new document to the given resource." with api.test_request_context(resource_url(resource)):
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright © 2017 Ryan Kanno <*****@*****.**> # # Distributed under terms of the MIT license. from eve import Eve import os from uuid_encoder import UUIDEncoder from uuid_validator import UUIDValidator host = '0.0.0.0' port = int(os.environ.get('PORT')) if 'PORT' in os.environ else 50050 app = Eve(json_encoder=UUIDEncoder, validator=UUIDValidator) @app.route('/aloha') def code_for_hawaii(): return 'Aloha from Code for Hawaii!' if __name__ == '__main__': app.run(host=host, port=port) # vim: fenc=utf-8 # vim: filetype=python
from weberdb import WeberDB from flask.ext.socketio import SocketIO, emit, join_room, leave_room from flask import Flask from flask_mail import Mail, Message from bson import json_util import string import random class TokenAuth(TokenAuth): def check_auth(self, token, allowed_roles, resource, method): accounts = app.data.driver.db['people'] return accounts.find_one({'token': token}) app = Eve(__name__, static_url_path='/static') app.debug = True, app.config.update( DEBUG=True, #EMAIL SETTINGS MAIL_SERVER='smtp.gmail.com', MAIL_PORT=465, MAIL_USE_SSL=True, MAIL_USERNAME='******', MAIL_PASSWORD='******') mail = Mail(app) socketio = SocketIO(app) def create_token(user): payload = {
from eve import Eve from eve_sqlalchemy import SQL from eve_sqlalchemy.examples.one_to_many.domain import Base, Child, Parent from eve_sqlalchemy.validation import ValidatorSQL app = Eve(validator=ValidatorSQL, data=SQL) db = app.data.driver Base.metadata.bind = db.engine db.Model = Base # create database schema on startup and populate some example data db.create_all() db.session.add_all( [Parent(children=[Child() for k in range(n)]) for n in range(10)]) db.session.commit() # using reloader will destroy the in-memory sqlite db app.run(debug=True, use_reloader=False)
from eve import Eve from eve.auth import BasicAuth class MyAuthenticate(BasicAuth): def check_auth(self, email_address, password, allowed_roles, resource, method): if method == 'GET': users = app.data.driver.db['users'] user = users.find_one({'email_address':email_address,'password':password}) if user: return True else: return False elif method == 'POST': return email_address == '*****@*****.**' and password == 'abc123' else: return True # app = Eve(auth=MyAuthenticate) app = Eve() if __name__ == '__main__': app.run(port=8080)
my_settings = { 'MONGO_HOST': 'localhost', 'MONGO_PORT': 27017, 'MONGO_DBNAME': 'as_ftp', 'RESOURCE_METHODS' : ['GET', 'POST'], 'ITEM_METHODS' : ['GET', 'PATCH', 'PUT', 'DELETE'], 'DOMAIN': { 'ftp_server_info': { 'schema' : schema_info }, 'ftp_data': { 'authentication': MyBasicAuth, 'schema' : schema_data }, 'ftp_action': { 'authentication': MyBasicAuth }, 'ASftp_data': { 'authentication': MyBasicAuth } } } app = Eve(settings=my_settings) if __name__ == '__main__': app.run('',5000)