def on_session_creation(login_manager): app = frappe.get_request_header('App-Version') if app: device = json.loads(frappe.get_request_header('User-Id')) device = { 'serial': device['serial'], 'platform': device['platform'], 'platform_version': device['version'], 'uuid': device['uuid'], 'last_active_on': now_datetime(), 'user': login_manager.user, 'doctype': 'Field App Device', 'last_active_user': login_manager.user, 'app_version': frappe.get_doc("Field App Version", app).name, 'device_meta': frappe.get_request_header('User-Id') } device_obj = None try: device_obj = frappe.get_doc("Field App Device", device['serial']) device_obj.update(device) except DoesNotExistError: device_obj = frappe.get_doc(device) device_obj.ignore_permissions = True device_obj.save()
def init_request(request): frappe.local.request = request frappe.local.is_ajax = frappe.get_request_header( "X-Requested-With") == "XMLHttpRequest" site = _site or request.headers.get('X-Frappe-Site-Name') or get_site_name( request.host) frappe.init(site=site, sites_path=_sites_path) request_id = frappe.get_request_header('X-Request-Id') if not request_id: request_id = str(uuid4()) frappe.flags.task_id = frappe.flags.request_id = request_id frappe.flags.runner_type = 'web' if not (frappe.local.conf and frappe.local.conf.db_name): # site does not exist raise NotFound if frappe.local.conf.get('maintenance_mode'): raise frappe.SessionStopped make_form_dict(request) frappe.local.http_request = frappe.auth.HTTPRequest()
def get_url(uri=None, full_address=False): """get app url from request""" host_name = frappe.local.conf.host_name if not host_name: if hasattr(frappe.local, "request" ) and frappe.local.request and frappe.local.request.host: protocol = 'https' == frappe.get_request_header( 'X-Forwarded-Proto', "") and 'https://' or 'http://' host_name = protocol + frappe.local.request.host elif frappe.local.site: host_name = "http://{}".format(frappe.local.site) else: host_name = frappe.db.get_value("Website Settings", "Website Settings", "subdomain") if host_name and "http" not in host_name: host_name = "http://" + host_name if not host_name: host_name = "http://localhost" if not uri and full_address: uri = frappe.get_request_header("REQUEST_URI", "") url = urllib.basejoin(host_name, uri) if uri else host_name return url
def get_url(uri=None, full_address=False): """get app url from request""" host_name = frappe.local.conf.host_name if not host_name: if hasattr(frappe.local, "request") and frappe.local.request and frappe.local.request.host: protocol = 'https' == frappe.get_request_header('X-Forwarded-Proto', "") and 'https://' or 'http://' host_name = protocol + frappe.local.request.host elif frappe.local.site: host_name = "http://{}".format(frappe.local.site) else: host_name = frappe.db.get_value("Website Settings", "Website Settings", "subdomain") if host_name and "http" not in host_name: host_name = "http://" + host_name if not host_name: host_name = "http://localhost" if not uri and full_address: uri = frappe.get_request_header("REQUEST_URI", "") url = urllib.basejoin(host_name, uri) if uri else host_name return url
def start(self): """start a new session""" # generate sid if self.user == 'Guest': sid = 'Guest' else: sid = frappe.generate_hash() self.data['user'] = self.user self.data['sid'] = sid self.data['data']['user'] = self.user self.data['data']['session_ip'] = frappe.get_request_header( 'REMOTE_ADDR') if self.user != "Guest": self.data['data']['last_updated'] = frappe.utils.now() self.data['data']['session_expiry'] = get_expiry_period() self.data['data']['session_country'] = get_geo_ip_country( frappe.get_request_header('REMOTE_ADDR')) # insert session if self.user != "Guest": frappe.db.begin() self.insert_session_record() # update user frappe.db.sql( """UPDATE tabUser SET last_login = %s, last_ip = %s where name=%s""", (frappe.utils.now(), frappe.get_request_header('REMOTE_ADDR'), self.data['user'])) frappe.db.commit()
def validate_auth(): if frappe.get_request_header("Authorization") is None: return VALID_AUTH_PREFIX_TYPES = ['basic', 'bearer', 'token'] VALID_AUTH_PREFIX_STRING = ", ".join(VALID_AUTH_PREFIX_TYPES).title() authorization_header = frappe.get_request_header("Authorization", str()).split(" ") authorization_type = authorization_header[0].lower() if len(authorization_header) == 1: frappe.throw( _('Invalid Authorization headers, add a token with a prefix from one of the following: {0}.' .format(VALID_AUTH_PREFIX_STRING)), frappe.InvalidAuthorizationHeader) if authorization_type == "bearer": validate_oauth(authorization_header) elif authorization_type in VALID_AUTH_PREFIX_TYPES: validate_auth_via_api_keys(authorization_header) else: frappe.throw( _('Invalid Authorization Type {0}, must be one of {1}.'.format( authorization_type, VALID_AUTH_PREFIX_STRING)), frappe.InvalidAuthorizationPrefix)
def valid_auth_code(): if frappe.session.user != "Guest": return auth_code = frappe.get_request_header("HDB-AuthorizationCode") user = None if auth_code: frappe.logger(__name__).debug( _("HDB-AuthorizationCode as {0}").format(auth_code)) user = IOTHDBSettings.get_on_behalf(auth_code) else: auth_code = frappe.get_request_header("AuthorizationCode") if auth_code: user = frappe.get_value("IOT User Api", {"authorization_code": auth_code}, "user") else: throw(_("Authorization Code/Login is required!")) if not user: throw(_("Authorization Code is incorrect!")) # form dict keeping form_dict = frappe.local.form_dict frappe.set_user(user) frappe.local.form_dict = form_dict
def start(self): """start a new session""" # generate sid if self.user == "Guest": sid = "Guest" else: sid = frappe.generate_hash() self.data["user"] = self.user self.data["sid"] = sid self.data["data"]["user"] = self.user self.data["data"]["session_ip"] = frappe.get_request_header("REMOTE_ADDR") if self.user != "Guest": self.data["data"]["last_updated"] = frappe.utils.now() self.data["data"]["session_expiry"] = get_expiry_period() self.data["data"]["session_country"] = get_geo_ip_country(frappe.get_request_header("REMOTE_ADDR")) # insert session if self.user != "Guest": frappe.db.begin() self.insert_session_record() # update user frappe.db.sql( """UPDATE tabUser SET last_login = %s, last_ip = %s where name=%s""", (frappe.utils.now(), frappe.get_request_header("REMOTE_ADDR"), self.data["user"]), ) frappe.db.commit()
def start(self): """start a new session""" # generate sid if self.user=='Guest': sid = 'Guest' else: sid = frappe.generate_hash() self.data['user'] = self.user self.data['sid'] = sid self.data['data']['user'] = self.user self.data['data']['session_ip'] = frappe.get_request_header('REMOTE_ADDR') if self.user != "Guest": self.data['data']['last_updated'] = frappe.utils.now() self.data['data']['session_expiry'] = get_expiry_period() self.data['data']['session_country'] = get_geo_ip_country(frappe.get_request_header('REMOTE_ADDR')) # insert session if self.user!="Guest": frappe.db.begin() self.insert_session_record() # update user frappe.db.sql("""UPDATE tabUser SET last_login = %s, last_ip = %s where name=%s""", (frappe.utils.now(), frappe.get_request_header('REMOTE_ADDR'), self.data['user'])) frappe.db.commit()
def validate_oauth(): from frappe.oauth import get_url_delimiter form_dict = frappe.local.form_dict authorization_header = frappe.get_request_header("Authorization").split( " ") if frappe.get_request_header("Authorization") else None if authorization_header and authorization_header[0].lower() == "bearer": from frappe.integrations.oauth2 import get_oauth_server token = authorization_header[1] r = frappe.request parsed_url = urlparse(r.url) access_token = {"access_token": token} uri = parsed_url.scheme + "://" + parsed_url.netloc + parsed_url.path + "?" + urlencode( access_token) http_method = r.method body = r.get_data() headers = r.headers required_scopes = frappe.db.get_value( "OAuth Bearer Token", token, "scopes").split(get_url_delimiter()) valid, oauthlib_request = get_oauth_server().verify_request( uri, http_method, body, headers, required_scopes) if valid: frappe.set_user( frappe.db.get_value("OAuth Bearer Token", token, "user")) frappe.local.form_dict = form_dict
def logout(**kwards): request = frappe.request secret_key = "HR System" if frappe.get_request_header("Authorization"): authorization_header = frappe.get_request_header( "Authorization").split(" ") if authorization_header[0] != "Bearer" and len( authorization_header) != 2: return { "status": { "message": "Invalid Token", "success": False, "code": 15 } } token = frappe.get_request_header("Authorization").replace( 'Bearer ', '') userDevices = frappe.get_all("User Device", ['name'], filters={ "access_token": token, "docstatus": ['<', 2] }) if not userDevices: frappe.local.response['http_status_code'] = 403 return { "status": { "message": "Not Permitted", "success": False, "code": 15 } } try: token = jwt.decode(token, secret_key) except Exception, e: frappe.local.response['http_status_code'] = 401 return { "status": { "message": "Expired Token", "success": False, "code": 15 } } user_device = frappe.get_doc("User Device", userDevices[0].name) frappe.db.sql( """update `tabUser Device` set docstatus=2 where name = '{0}' """. format(user_device.name)) frappe.db.commit() msg = "تم تسجيل الخروج بنجاح" return {"status": {"message": msg, "success": True, "code": 15}}
def set_request_ip(self): if frappe.get_request_header('X-Forwarded-For'): frappe.local.request_ip = (frappe.get_request_header( 'X-Forwarded-For').split(",")[0]).strip() elif frappe.get_request_header('REMOTE_ADDR'): frappe.local.request_ip = frappe.get_request_header('REMOTE_ADDR') else: frappe.local.request_ip = '127.0.0.1'
def set_request_ip(self): if frappe.get_request_header("X-Forwarded-For"): frappe.local.request_ip = (frappe.get_request_header( "X-Forwarded-For").split(",")[0]).strip() elif frappe.get_request_header("REMOTE_ADDR"): frappe.local.request_ip = frappe.get_request_header("REMOTE_ADDR") else: frappe.local.request_ip = "127.0.0.1"
def validate(self): self.ip = frappe.get_request_header('REMOTE_ADDR', None) or \ frappe.get_request_header('X-Forwarded-For') or '127.0.0.1' duplicate = frappe.db.get_value("Poll Vote", {"ip": self.ip, "poll": self.poll}) status = frappe.db.get_value("Poll", {"name": self.name}, "poll_status") if duplicate: raise DuplicateVoteError if status == "Inactive": raise InactivePollStatusError
def verify_request(): woocommerce_settings = frappe.get_doc("Woocommerce Settings") sig = base64.b64encode( hmac.new(woocommerce_settings.secret.encode('utf8'), frappe.request.data, hashlib.sha256).digest()) if frappe.request.data and \ frappe.get_request_header("X-Wc-Webhook-Signature") and \ not sig == bytes(frappe.get_request_header("X-Wc-Webhook-Signature").encode()): frappe.throw(_("Unverified Webhook Data")) frappe.set_user(woocommerce_settings.creation_user)
def get_url(uri=None, full_address=False): """get app url from request""" host_name = frappe.local.conf.host_name or frappe.local.conf.hostname if uri and (uri.startswith("http://") or uri.startswith("https://")): return uri if not host_name: if hasattr(frappe.local, "request" ) and frappe.local.request and frappe.local.request.host: protocol = 'https://' if 'https' == frappe.get_request_header( 'X-Forwarded-Proto', "") else 'http://' host_name = protocol + frappe.local.request.host elif frappe.local.site: protocol = 'http://' if frappe.local.conf.ssl_certificate: protocol = 'https://' elif frappe.local.conf.wildcard: domain = frappe.local.conf.wildcard.get('domain') if domain and frappe.local.site.endswith( domain) and frappe.local.conf.wildcard.get( 'ssl_certificate'): protocol = 'https://' host_name = protocol + frappe.local.site else: host_name = frappe.db.get_value("Website Settings", "Website Settings", "subdomain") if not host_name: host_name = "http://localhost" if host_name and not (host_name.startswith("http://") or host_name.startswith("https://")): host_name = "http://" + host_name if not uri and full_address: uri = frappe.get_request_header("REQUEST_URI", "") port = frappe.conf.http_port or frappe.conf.webserver_port if not (frappe.conf.restart_supervisor_on_update or frappe.conf.restart_systemd_on_update ) and host_name and not url_contains_port(host_name) and port: host_name = host_name + ':' + str(port) url = urljoin(host_name, uri) if uri else host_name return url
def validate_ip_address(self): """check if IP Address is valid""" ip_list = frappe.db.get_value('User', self.user, 'restrict_ip', ignore=True) if not ip_list: return ip_list = ip_list.replace(",", "\n").split('\n') ip_list = [i.strip() for i in ip_list] for ip in ip_list: if frappe.get_request_header('REMOTE_ADDR', '').startswith(ip) or frappe.get_request_header('X-Forwarded-For', '').startswith(ip): return frappe.throw(_("Not allowed from this IP Address"), frappe.AuthenticationError)
def verify_request(): woocommerce_settings = frappe.get_doc("Woocommerce Settings") sig = base64.b64encode( hmac.new( woocommerce_settings.secret.encode('utf8'), frappe.request.data, hashlib.sha256 ).digest() ) if frappe.request.data and \ frappe.get_request_header("X-Wc-Webhook-Signature") and \ not sig == bytes(frappe.get_request_header("X-Wc-Webhook-Signature").encode()): frappe.throw(_("Unverified Webhook Data")) frappe.set_user(woocommerce_settings.creation_user)
def valid_auth_code(app=None, auth_code=None): app = app or frappe.get_request_header("AppName") if not app: throw(_("AppName is required in HTTP Header!")) auth_code = auth_code or frappe.get_request_header("AuthorizationCode") if not auth_code: throw(_("AuthorizationCode is required in HTTP Header!")) frappe.logger(__name__).debug( _("App as {0} AuthorizationCode as {1}").format(app, auth_code)) if auth_code != frappe.get_value("Wechat App", app, "authorization_code"): throw(_("Authorization Code is incorrect!")) frappe.session.user = frappe.get_value("Wechat App", app, "on_behalf") return app
def __init__(self): # Get Environment variables self.domain = frappe.request.host if self.domain and self.domain.startswith('www.'): self.domain = self.domain[4:] # language self.set_lang(frappe.get_request_header('HTTP_ACCEPT_LANGUAGE')) # load cookies frappe.local.cookie_manager = CookieManager() # override request method. All request to be of type POST, but if _type == "POST" then commit if frappe.form_dict.get("_type"): frappe.local.request_method = frappe.form_dict.get("_type") del frappe.form_dict["_type"] # set db self.connect() # login frappe.local.login_manager = LoginManager() # write out latest cookies frappe.local.cookie_manager.init_cookies() # check status check_session_stopped() # load user self.setup_user() # run login triggers if frappe.form_dict.get('cmd') == 'login': frappe.local.login_manager.run_trigger('on_session_creation')
def get_doc(doctype, name): """ Builds the response to be sent back Fills in with doc data """ try: doc = frappe.get_doc(doctype, name) if not doc.has_permission("read"): raise frappe.PermissionError user_lang = frappe.get_request_header('Accept-Language') if user_lang: frappe.local.lang = user_lang.split('-')[0] update_http_response({ "data": update_transalte(doc.doctype, doc.as_dict()), "status": "success" }) except Exception as ex: update_http_response({ "data": "failed", "status": "failed", "exception": ex, "traceback": traceback.format_exc() })
def webhooks(): r = frappe.request payload = json.loads(r.get_data()) or [] if not payload: frappe.response.message = "Missing payload" frappe.response.http_status_code = 400 account, stripe_key = get_api_key(r) webhook_secret = frappe.get_request_header("HTTP_STRIPE_SIGNATURE") event = None try: event = stripe.Event.construct_from( payload, webhook_secret, stripe_key ) except Exception as e: frappe.response.message = "Webhook event construction failed" frappe.response.http_status_code = 400 # Handle the event doc = create_new_integration_log(event, account) frappe.enqueue(method='erpnext.erpnext_integrations.doctype.stripe_settings.stripe_settings.handle_webhooks',\ queue='long', timeout=600, is_async=True, **{"doctype": "Integration Request",\ "docname": doc.name}) frappe.response.message = "Webhook received and event type handled" frappe.response.http_status_code = 200
def application(request): frappe.local.request = request frappe.local.is_ajax = frappe.get_request_header( "X-Requested-With") == "XMLHttpRequest" response = None try: rollback = True init_site(request) if frappe.local.conf.get('maintenance_mode'): raise frappe.SessionStopped make_form_dict(request) frappe.local.http_request = frappe.auth.HTTPRequest() if frappe.local.form_dict.cmd: response = frappe.handler.handle() elif frappe.request.path.startswith("/api/"): response = frappe.api.handle() elif frappe.request.path.startswith('/backups'): response = frappe.utils.response.download_backup(request.path) elif frappe.local.request.method in ('GET', 'HEAD'): response = frappe.website.render.render(request.path) else: raise NotFound except HTTPException, e: return e
def handle_exception(e): response = None http_status_code = getattr(e, "http_status_code", 500) return_as_message = False if frappe.get_request_header('Accept') and (frappe.local.is_ajax or 'application/json' in frappe.get_request_header('Accept')): # handle ajax responses first # if the request is ajax, send back the trace or error message response = frappe.utils.response.report_error(http_status_code) elif (http_status_code==500 and (frappe.db and isinstance(e, frappe.db.InternalError)) and (frappe.db and (frappe.db.is_deadlocked(e) or frappe.db.is_timedout(e)))): http_status_code = 508 elif http_status_code==401: frappe.respond_as_web_page(_("Session Expired"), _("Your session has expired, please login again to continue."), http_status_code=http_status_code, indicator_color='red') return_as_message = True elif http_status_code==403: frappe.respond_as_web_page(_("Not Permitted"), _("You do not have enough permissions to complete the action"), http_status_code=http_status_code, indicator_color='red') return_as_message = True elif http_status_code==404: frappe.respond_as_web_page(_("Not Found"), _("The resource you are looking for is not available"), http_status_code=http_status_code, indicator_color='red') return_as_message = True else: traceback = "<pre>"+frappe.get_traceback()+"</pre>" if frappe.local.flags.disable_traceback: traceback = "" frappe.respond_as_web_page("Server Error", traceback, http_status_code=http_status_code, indicator_color='red', width=640) return_as_message = True if e.__class__ == frappe.AuthenticationError: if hasattr(frappe.local, "login_manager"): frappe.local.login_manager.clear_cookies() if http_status_code >= 500: if not frappe.conf.developer_mode: for fn in frappe.get_hooks("exception_handlers"): frappe.get_attr(fn)() frappe.logger().error('Request Error', exc_info=True) make_error_snapshot(e) if return_as_message: response = frappe.website.render.render("message", http_status_code=http_status_code) return response
def __init__(self): # Get Environment variables self.domain = frappe.request.host if self.domain and self.domain.startswith('www.'): self.domain = self.domain[4:] # language self.set_lang(frappe.get_request_header('HTTP_ACCEPT_LANGUAGE')) # load cookies frappe.local.cookie_manager = CookieManager() # override request method. All request to be of type POST, but if _type == "POST" then commit if frappe.form_dict.get("_type"): frappe.local.request_method = frappe.form_dict.get("_type") del frappe.form_dict["_type"] # set db self.connect() # login frappe.local.login_manager = LoginManager() # write out latest cookies frappe.local.cookie_manager.init_cookies() # check status check_session_stopped() # load user self.setup_user() # run login triggers if frappe.form_dict.get('cmd')=='login': frappe.local.login_manager.run_trigger('on_session_creation')
def get_context(context): # if frappe.form_dict.new: name = frappe.form_dict.user or frappe.form_dict.name if not name: frappe.local.flags.redirect_location = "/me" raise frappe.Redirect user_roles = frappe.get_roles(frappe.session.user) if 'IOT User' not in user_roles or frappe.session.user == 'Guest': raise frappe.PermissionError("Your account is not an IOT User!") context.no_cache = 1 context.show_sidebar = True # Get target user document object doc = frappe.get_doc('Cloud Employee', name) # Check for Company permission if not is_company_admin(frappe.session.user, doc.get("company")): raise frappe.PermissionError("Your account is not company admin!") doc.has_permission('read') context.parents = [{ "title": _("Back"), "route": frappe.get_request_header("referer") }] context.user_doc = frappe.get_doc("User", doc.user) context.doc = doc
def get_host_name_from_request(): if hasattr( frappe.local, "request") and frappe.local.request and frappe.local.request.host: protocol = 'https://' if 'https' == frappe.get_request_header( 'X-Forwarded-Proto', "") else 'http://' return protocol + frappe.local.request.host
def authenticate_client(self, request, *args, **kwargs): #Get ClientID in URL if request.client_id: oc = frappe.get_doc("OAuth Client", request.client_id) else: #Extract token, instantiate OAuth Bearer Token and use clientid from there. if "refresh_token" in frappe.form_dict: oc = frappe.get_doc( "OAuth Client", frappe.db.get_value( "OAuth Bearer Token", {"refresh_token": frappe.form_dict["refresh_token"]}, 'client')) elif "token" in frappe.form_dict: oc = frappe.get_doc( "OAuth Client", frappe.db.get_value("OAuth Bearer Token", frappe.form_dict["token"], 'client')) else: oc = frappe.get_doc( "OAuth Client", frappe.db.get_value( "OAuth Bearer Token", frappe.get_request_header("Authorization").split(" ") [1], 'client')) try: request.client = request.client or oc.as_dict() except Exception as e: print("Failed body authentication: Application %s does not exist". format(cid=request.client_id)) cookie_dict = get_cookie_dict_from_headers(request) user_id = unquote(cookie_dict.get( 'user_id').value) if 'user_id' in cookie_dict else "Guest" return frappe.session.user == user_id
def authenticate_credentials(): """ Process Authorization header in HTTP response according to basic HTTP authorization. Request is stored as Wekzeug local, frappe provides access to headers. """ received_credentials = frappe.get_request_header("Authorization") # seems like a dummy post request if not received_credentials: return False # invalid HTTP basic authorization header if not received_credentials.startswith("Basic"): return False splitted_credentials = received_credentials.split(" ", 1) if len(splitted_credentials) != 2: frappe.errprint("SendGrid webhook authentication failed with header: {}".format( received_credentials)) return False received_credentials = splitted_credentials[1] for credentials in get_webhook_credentials(): # matched => authenticated if received_credentials == base64.b64encode(credentials): return True # no match => failure return False
def validate_auth_via_api_keys(authorization_header): """ Authenticate request using API keys and set session user Args: authorization_header (list of str): The 'Authorization' header containing the prefix and token """ try: auth_type, auth_token = authorization_header authorization_source = frappe.get_request_header( "Frappe-Authorization-Source") if auth_type.lower() == "basic": api_key, api_secret = frappe.safe_decode( base64.b64decode(auth_token)).split(":") validate_api_key_secret(api_key, api_secret, authorization_source) elif auth_type.lower() == "token": api_key, api_secret = auth_token.split(":") validate_api_key_secret(api_key, api_secret, authorization_source) except binascii.Error: frappe.throw( _("Failed to decode token, please provide a valid base64-encoded token." ), frappe.InvalidAuthorizationToken, ) except (AttributeError, TypeError, ValueError): pass
def _order(*args, **kwargs): woocommerce_settings = frappe.get_doc("Woocommerce Settings") if frappe.flags.woocomm_test_order_data: order = frappe.flags.woocomm_test_order_data event = "created" elif frappe.request and frappe.request.data: verify_request() try: order = json.loads(frappe.request.data) except ValueError: #woocommerce returns 'webhook_id=value' for the first request which is not JSON order = frappe.request.data event = frappe.get_request_header("X-Wc-Webhook-Event") else: return "success" if event == "created": raw_billing_data = order.get("billing") customer_name = raw_billing_data.get( "first_name") + " " + raw_billing_data.get("last_name") link_customer_and_address(raw_billing_data, customer_name) link_items(order.get("line_items"), woocommerce_settings) create_sales_order(order, woocommerce_settings, customer_name)
def authenticate_client(self, request, *args, **kwargs): cookie_dict = get_cookie_dict_from_headers(request) #Get ClientID in URL if request.client_id: oc = frappe.get_doc("OAuth Client", request.client_id) else: #Extract token, instantiate OAuth Bearer Token and use clientid from there. if frappe.form_dict.has_key("refresh_token"): oc = frappe.get_doc( "OAuth Client", frappe.db.get_value( "OAuth Bearer Token", {"refresh_token": frappe.form_dict["refresh_token"]}, 'client')) elif frappe.form_dict.has_key("token"): oc = frappe.get_doc( "OAuth Client", frappe.db.get_value("OAuth Bearer Token", frappe.form_dict["token"], 'client')) else: oc = frappe.get_doc( "OAuth Client", frappe.db.get_value( "OAuth Bearer Token", frappe.get_request_header("Authorization").split(" ") [1], 'client')) try: request.client = request.client or oc.as_dict() except Exception, e: print "Failed body authentication: Application %s does not exist".format( cid=request.client_id)
def __init__(self): # Get Environment variables self.domain = frappe.request.host if self.domain and self.domain.startswith('www.'): self.domain = self.domain[4:] # language self.set_lang(frappe.get_request_header('HTTP_ACCEPT_LANGUAGE')) # load cookies frappe.local.cookie_manager = CookieManager() # override request method. All request to be of type POST, but if _type == "POST" then commit if frappe.form_dict.get("_type"): frappe.local.request_method = frappe.form_dict.get("_type") del frappe.form_dict["_type"] # set db self.connect() # login frappe.local.login_manager = LoginManager() # check status if frappe.db.get_global("__session_status") == 'stop': frappe.msgprint(frappe.db.get_global("__session_status_message")) raise frappe.SessionStopped('Session Stopped') # load profile self.setup_profile() # run login triggers if frappe.form_dict.get('cmd') == 'login': frappe.local.login_manager.run_trigger('on_session_creation')
def application(request): frappe.local.request = request frappe.local.is_ajax = frappe.get_request_header("X-Requested-With")=="XMLHttpRequest" response = None try: rollback = True init_site(request) if frappe.local.conf.get('maintenance_mode'): raise frappe.SessionStopped make_form_dict(request) frappe.local.http_request = frappe.auth.HTTPRequest() if frappe.local.form_dict.cmd: response = frappe.handler.handle() elif frappe.request.path.startswith("/api/"): response = frappe.api.handle() elif frappe.request.path.startswith('/backups'): response = frappe.utils.response.download_backup(request.path) elif frappe.local.request.method in ('GET', 'HEAD'): response = frappe.website.render.render(request.path) else: raise NotFound except HTTPException, e: return e
def handle_exception(e): response = None http_status_code = getattr(e, "http_status_code", 500) return_as_message = False if frappe.local.is_ajax or 'application/json' in frappe.get_request_header('Accept'): # handle ajax responses first # if the request is ajax, send back the trace or error message response = frappe.utils.response.report_error(http_status_code) elif (http_status_code==500 and isinstance(e, MySQLdb.OperationalError) and e.args[0] in (1205, 1213)): # 1205 = lock wait timeout # 1213 = deadlock # code 409 represents conflict http_status_code = 508 elif http_status_code==401: frappe.respond_as_web_page(_("Session Expired"), _("Your session has expired, please login again to continue."), http_status_code=http_status_code, indicator_color='red') return_as_message = True elif http_status_code==403: frappe.respond_as_web_page(_("Not Permitted"), _("You do not have enough permissions to complete the action"), http_status_code=http_status_code, indicator_color='red') return_as_message = True elif http_status_code==404: frappe.respond_as_web_page(_("Not Found"), _("The resource you are looking for is not available"), http_status_code=http_status_code, indicator_color='red') return_as_message = True else: traceback = "<pre>"+frappe.get_traceback()+"</pre>" if frappe.local.flags.disable_traceback: traceback = "" frappe.respond_as_web_page("Server Error", traceback, http_status_code=http_status_code, indicator_color='red', width=640) return_as_message = True if e.__class__ == frappe.AuthenticationError: if hasattr(frappe.local, "login_manager"): frappe.local.login_manager.clear_cookies() if http_status_code >= 500: frappe.logger().error('Request Error', exc_info=True) make_error_snapshot(e) if return_as_message: response = frappe.website.render.render("message", http_status_code=http_status_code) return response
def validate(): authorization_header = frappe.get_request_header("Authorization", str()).split(" ") if len(authorization_header) == 2: token = authorization_header[1] if frappe.get_conf().get("castlecraft_auth_introspect_bearer"): validate_bearer_with_introspection(token) elif frappe.get_conf().get("castlecraft_auth_jwt"): validate_jwt_with_jwks(token)
def get_url(uri=None, full_address=False): """get app url from request""" host_name = frappe.local.conf.host_name or frappe.local.conf.hostname if uri and (uri.startswith("http://") or uri.startswith("https://")): return uri if not host_name: if hasattr(frappe.local, "request") and frappe.local.request and frappe.local.request.host: protocol = 'https://' if 'https' == frappe.get_request_header('X-Forwarded-Proto', "") else 'http://' host_name = protocol + frappe.local.request.host elif frappe.local.site: protocol = 'http://' if frappe.local.conf.ssl_certificate: protocol = 'https://' elif frappe.local.conf.wildcard: domain = frappe.local.conf.wildcard.get('domain') if domain and frappe.local.site.endswith(domain) and frappe.local.conf.wildcard.get('ssl_certificate'): protocol = 'https://' host_name = protocol + frappe.local.site else: host_name = frappe.db.get_value("Website Settings", "Website Settings", "subdomain") if not host_name: host_name = "http://localhost" if host_name and not (host_name.startswith("http://") or host_name.startswith("https://")): host_name = "http://" + host_name if not uri and full_address: uri = frappe.get_request_header("REQUEST_URI", "") port = frappe.conf.http_port or frappe.conf.webserver_port if not (frappe.conf.restart_supervisor_on_update or frappe.conf.restart_systemd_on_update) and host_name and not url_contains_port(host_name) and port: host_name = host_name + ':' + str(port) url = urljoin(host_name, uri) if uri else host_name return url
def innerfn(fn): settings = frappe.get_doc(doctype) if frappe.request and settings and settings.get( secret_key) and not frappe.flags.in_test: sig = base64.b64encode( hmac.new( settings.get(secret_key).encode('utf8'), frappe.request.data, hashlib.sha256).digest()) if frappe.request.data and \ frappe.get_request_header(hmac_key) and \ not sig == bytes(frappe.get_request_header(hmac_key).encode()): frappe.throw(_("Unverified Webhook Data")) frappe.set_user(settings.modified_by) return fn
def get_post_json_data(): if frappe.request.method != "POST": throw(_("Request Method Must be POST!")) ctype = frappe.get_request_header("Content-Type") if "json" not in ctype.lower(): throw(_("Incorrect HTTP Content-Type found {0}").format(ctype)) if not frappe.form_dict.data: throw(_("JSON Data not found!")) return json.loads(frappe.form_dict.data)
def validate_request_header(): key_header = frappe.get_request_header("awfis-api-key") key_local = frappe.get_single("Awfis Settings").api_key_knowlarity if key_header == "": return -1 #"Key header is blank" elif key_header != key_local: return 0 #"{0} != {1} : Key header does not match local key".format(key_header, key_local) else: return 1 #""
def __init__(self): # Get Environment variables self.domain = frappe.request.host if self.domain and self.domain.startswith('www.'): self.domain = self.domain[4:] if frappe.get_request_header('X-Forwarded-For'): frappe.local.request_ip = (frappe.get_request_header('X-Forwarded-For').split(",")[0]).strip() elif frappe.get_request_header('REMOTE_ADDR'): frappe.local.request_ip = frappe.get_request_header('REMOTE_ADDR') else: frappe.local.request_ip = '127.0.0.1' # language self.set_lang() # load cookies frappe.local.cookie_manager = CookieManager() # set db self.connect() # login frappe.local.login_manager = LoginManager() if frappe.form_dict._lang: lang = get_lang_code(frappe.form_dict._lang) if lang: frappe.local.lang = lang self.validate_csrf_token() # write out latest cookies frappe.local.cookie_manager.init_cookies() # check status check_session_stopped() # run login triggers if frappe.form_dict.get('cmd')=='login': frappe.local.login_manager.run_trigger('on_session_creation')
def __init__(self): # Get Environment variables self.domain = frappe.request.host if self.domain and self.domain.startswith('www.'): self.domain = self.domain[4:] if frappe.get_request_header('X-Forwarded-For'): frappe.local.request_ip = frappe.get_request_header('X-Forwarded-For') elif frappe.get_request_header('REMOTE_ADDR'): frappe.local.request_ip = frappe.get_request_header('REMOTE_ADDR') else: frappe.local.request_ip = '127.0.0.1' # language self.set_lang(frappe.request.accept_languages.values()) # load cookies frappe.local.cookie_manager = CookieManager() # override request method. All request to be of type POST, but if _type == "POST" then commit if frappe.form_dict.get("_type"): frappe.local.request_method = frappe.form_dict.get("_type") del frappe.form_dict["_type"] # set db self.connect() # login frappe.local.login_manager = LoginManager() # write out latest cookies frappe.local.cookie_manager.init_cookies() # check status check_session_stopped() # run login triggers if frappe.form_dict.get('cmd')=='login': frappe.local.login_manager.run_trigger('on_session_creation') self.clear_active_sessions()
def validate_oauth(): form_dict = frappe.local.form_dict authorization_header = frappe.get_request_header("Authorization").split(" ") if frappe.get_request_header("Authorization") else None if authorization_header and authorization_header[0].lower() == "bearer": from frappe.integration_broker.oauth2 import get_oauth_server token = authorization_header[1] r = frappe.request parsed_url = urlparse(r.url) access_token = { "access_token": token} uri = parsed_url.scheme + "://" + parsed_url.netloc + parsed_url.path + "?" + urlencode(access_token) http_method = r.method body = r.get_data() headers = r.headers required_scopes = frappe.db.get_value("OAuth Bearer Token", token, "scopes").split(";") valid, oauthlib_request = get_oauth_server().verify_request(uri, http_method, body, headers, required_scopes) if valid: frappe.set_user(frappe.db.get_value("OAuth Bearer Token", token, "user")) frappe.local.form_dict = form_dict
def get_url(uri=None, full_address=False): """get app url from request""" host_name = frappe.local.conf.host_name or frappe.local.conf.hostname if uri and (uri.startswith("http://") or uri.startswith("https://")): return uri if not host_name: if hasattr(frappe.local, "request") and frappe.local.request and frappe.local.request.host: protocol = 'https' == frappe.get_request_header('X-Forwarded-Proto', "") and 'https://' or 'http://' host_name = protocol + frappe.local.request.host elif frappe.local.site: protocol = 'http://' if frappe.local.conf.ssl_certificate: protocol = 'https://' elif frappe.local.conf.wildcard: domain = frappe.local.conf.wildcard.get('domain') if domain and frappe.local.site.endswith(domain) and frappe.local.conf.wildcard.get('ssl_certificate'): protocol = 'https://' host_name = protocol + frappe.local.site else: host_name = frappe.db.get_value("Website Settings", "Website Settings", "subdomain") if host_name and "http" not in host_name: host_name = "http://" + host_name if not host_name: host_name = "http://localhost" if not uri and full_address: uri = frappe.get_request_header("REQUEST_URI", "") url = urllib.basejoin(host_name, uri) if uri else host_name return url
def authenticate_signature(r): """Returns True if the received signature matches the generated signature""" received_signature = frappe.get_request_header("Webhook-Signature") if not received_signature: return False for key in get_webhook_keys(): computed_signature = hmac.new(key.encode("utf-8"), r.get_data(), hashlib.sha256).hexdigest() if hmac.compare_digest(str(received_signature), computed_signature): return True return False
def validate_csrf_token(self): if frappe.local.request and frappe.local.request.method=="POST": if not frappe.local.session.data.csrf_token or frappe.local.session.data.device=="mobile": # not via boot return csrf_token = frappe.get_request_header("X-Frappe-CSRF-Token") if not csrf_token and "csrf_token" in frappe.local.form_dict: csrf_token = frappe.local.form_dict.csrf_token del frappe.local.form_dict["csrf_token"] if frappe.local.session.data.csrf_token != csrf_token: frappe.local.flags.disable_traceback = True frappe.throw(_("Invalid Request"), frappe.CSRFTokenError)
def application(request): frappe.local.request = request frappe.local.is_ajax = frappe.get_request_header("X-Requested-With")=="XMLHttpRequest" response = None try: rollback = True init_site(request) #wirte comment if "api_handler" in frappe.get_all_apps() and frappe.get_hooks("api_name", app_name="api_handler"): api_name = frappe.get_hooks("api_name", app_name="api_handler")[0] if frappe.local.conf.get('maintenance_mode'): raise frappe.SessionStopped make_form_dict(request) frappe.local.http_request = frappe.auth.HTTPRequest() if frappe.local.form_dict.cmd: response = frappe.handler.handle() elif frappe.request.path.startswith("/api/"): response = frappe.api.handle() elif frappe.request.path.startswith('/backups'): response = frappe.utils.response.download_backup(request.path) elif frappe.request.path.startswith('/private/files/'): response = frappe.utils.response.download_private_file(request.path) elif frappe.local.request.method in ('GET', 'HEAD'): response = frappe.website.render.render(request.path) #write comment elif api_name and frappe.request.path.startswith("/%s/"%api_name): response = api_handler.api.handle() else: raise NotFound except HTTPException, e: return e
def validate_auth_via_api_keys(): """ authentication using api key and api secret set user """ try: authorization_header = frappe.get_request_header("Authorization", None).split(" ") if frappe.get_request_header("Authorization") else None if authorization_header and authorization_header[0] == 'Basic': token = frappe.safe_decode(base64.b64decode(authorization_header[1])).split(":") validate_api_key_secret(token[0], token[1]) elif authorization_header and authorization_header[0] == 'token': token = authorization_header[1].split(":") validate_api_key_secret(token[0], token[1]) except Exception as e: raise e
def init_request(request): frappe.local.request = request frappe.local.is_ajax = frappe.get_request_header("X-Requested-With")=="XMLHttpRequest" site = _site or request.headers.get('X-Frappe-Site-Name') or get_site_name(request.host) frappe.init(site=site, sites_path=_sites_path) if not (frappe.local.conf and frappe.local.conf.db_name): # site does not exist raise NotFound if frappe.local.conf.get('maintenance_mode'): raise frappe.SessionStopped make_form_dict(request) frappe.local.http_request = frappe.auth.HTTPRequest()
def authenticate_client(self, request, *args, **kwargs): cookie_dict = get_cookie_dict_from_headers(request) #Get ClientID in URL if request.client_id: oc = frappe.get_doc("OAuth Client", request.client_id) else: #Extract token, instantiate OAuth Bearer Token and use clientid from there. if frappe.form_dict.has_key("refresh_token"): oc = frappe.get_doc("OAuth Client", frappe.db.get_value("OAuth Bearer Token", {"refresh_token": frappe.form_dict["refresh_token"]}, 'client')) elif frappe.form_dict.has_key("token"): oc = frappe.get_doc("OAuth Client", frappe.db.get_value("OAuth Bearer Token", frappe.form_dict["token"], 'client')) else: oc = frappe.get_doc("OAuth Client", frappe.db.get_value("OAuth Bearer Token", frappe.get_request_header("Authorization").split(" ")[1], 'client')) try: request.client = request.client or oc.as_dict() except Exception, e: print "Failed body authentication: Application %s does not exist".format(cid=request.client_id)
def authenticate_signature(post_url=None): """Returns True if the received signature matches the generated signature""" received_signature = frappe.get_request_header("X-Mandrill-Signature") # seems like a dummy post request if not received_signature: return False to_hash = get_post_url_for_hashing(post_url) for key in get_webhook_keys(): # generate signature using the webhook key hashed = hmac.new(key.encode("utf-8"), to_hash, hashlib.sha1) generated_signature = hashed.digest().encode("base64").rstrip('\n') # matched => authenticated if received_signature==generated_signature: return True # no match => failure return False
def accept_gzip(): if "gzip" in frappe.get_request_header("HTTP_ACCEPT_ENCODING", ""): return True
def handle(): """ Handler for `/api` methods ### Examples: `/api/method/{methodname}` will call a whitelisted method `/api/resource/{doctype}` will query a table examples: - `?fields=["name", "owner"]` - `?filters=[["Task", "name", "like", "%005"]]` - `?limit_start=0` - `?limit_page_length=20` `/api/resource/{doctype}/{name}` will point to a resource `GET` will return doclist `POST` will insert `PUT` will update `DELETE` will delete `/api/resource/{doctype}/{name}?run_method={method}` will run a whitelisted controller method """ form_dict = frappe.local.form_dict authorization_header = frappe.get_request_header("Authorization").split(" ") if frappe.get_request_header("Authorization") else None if authorization_header and authorization_header[0].lower() == "bearer": token = authorization_header[1] r = frappe.request parsed_url = urlparse(r.url) access_token = { "access_token": token} uri = parsed_url.scheme + "://" + parsed_url.netloc + parsed_url.path + "?" + urlencode(access_token) http_method = r.method body = r.get_data() headers = r.headers required_scopes = frappe.db.get_value("OAuth Bearer Token", token, "scopes").split(";") valid, oauthlib_request = oauth_server.verify_request(uri, http_method, body, headers, required_scopes) if valid: frappe.set_user(frappe.db.get_value("OAuth Bearer Token", token, "user")) frappe.local.form_dict = form_dict parts = frappe.request.path[1:].split("/",3) call = doctype = name = None if len(parts) > 1: call = parts[1] if len(parts) > 2: doctype = parts[2] if len(parts) > 3: name = parts[3] if call=="method": frappe.local.form_dict.cmd = doctype return frappe.handler.handle() elif call=="resource": if "run_method" in frappe.local.form_dict: method = frappe.local.form_dict.pop("run_method") doc = frappe.get_doc(doctype, name) doc.is_whitelisted(method) if frappe.local.request.method=="GET": if not doc.has_permission("read"): frappe.throw(_("Not permitted"), frappe.PermissionError) frappe.local.response.update({"data": doc.run_method(method, **frappe.local.form_dict)}) if frappe.local.request.method=="POST": if not doc.has_permission("write"): frappe.throw(_("Not permitted"), frappe.PermissionError) frappe.local.response.update({"data": doc.run_method(method, **frappe.local.form_dict)}) frappe.db.commit() else: if name: if frappe.local.request.method=="GET": doc = frappe.get_doc(doctype, name) if not doc.has_permission("read"): raise frappe.PermissionError frappe.local.response.update({"data": doc}) if frappe.local.request.method=="PUT": data = json.loads(frappe.local.form_dict.data) doc = frappe.get_doc(doctype, name) if "flags" in data: del data["flags"] # Not checking permissions here because it's checked in doc.save doc.update(data) frappe.local.response.update({ "data": doc.save().as_dict() }) frappe.db.commit() if frappe.local.request.method=="DELETE": # Not checking permissions here because it's checked in delete_doc frappe.delete_doc(doctype, name) frappe.local.response.http_status_code = 202 frappe.local.response.message = "ok" frappe.db.commit() elif doctype: if frappe.local.request.method=="GET": if frappe.local.form_dict.get('fields'): frappe.local.form_dict['fields'] = json.loads(frappe.local.form_dict['fields']) frappe.local.form_dict.setdefault('limit_page_length', 20) frappe.local.response.update({ "data": frappe.call(frappe.client.get_list, doctype, **frappe.local.form_dict)}) if frappe.local.request.method=="POST": data = json.loads(frappe.local.form_dict.data) data.update({ "doctype": doctype }) frappe.local.response.update({ "data": frappe.get_doc(data).insert().as_dict() }) frappe.db.commit() else: raise frappe.DoesNotExistError else: raise frappe.DoesNotExistError return build_response("json")
def order(): woocommerce_settings = frappe.get_doc("Woocommerce Settings") if frappe.flags.woocomm_test_order_data: fd = frappe.flags.woocomm_test_order_data event = "created" elif frappe.request and frappe.request.data: verify_request() fd = json.loads(frappe.request.data) event = frappe.get_request_header("X-Wc-Webhook-Event") else: return "success" if event == "created": raw_billing_data = fd.get("billing") customer_woo_com_email = raw_billing_data.get("email") if frappe.get_value("Customer",{"woocommerce_email": customer_woo_com_email}): # Edit link_customer_and_address(raw_billing_data,1) else: # Create link_customer_and_address(raw_billing_data,0) items_list = fd.get("line_items") for item in items_list: item_woo_com_id = item.get("product_id") if frappe.get_value("Item",{"woocommerce_id": item_woo_com_id}): #Edit link_item(item,1) else: link_item(item,0) customer_name = raw_billing_data.get("first_name") + " " + raw_billing_data.get("last_name") new_sales_order = frappe.new_doc("Sales Order") new_sales_order.customer = customer_name created_date = fd.get("date_created").split("T") new_sales_order.transaction_date = created_date[0] new_sales_order.po_no = fd.get("id") new_sales_order.woocommerce_id = fd.get("id") new_sales_order.naming_series = woocommerce_settings.sales_order_series or "SO-WOO-" placed_order_date = created_date[0] raw_date = datetime.datetime.strptime(placed_order_date, "%Y-%m-%d") raw_delivery_date = frappe.utils.add_to_date(raw_date,days = 7) order_delivery_date_str = raw_delivery_date.strftime('%Y-%m-%d') order_delivery_date = str(order_delivery_date_str) new_sales_order.delivery_date = order_delivery_date default_set_company = frappe.get_doc("Global Defaults") company = raw_billing_data.get("company") or default_set_company.default_company found_company = frappe.get_doc("Company",{"name":company}) company_abbr = found_company.abbr new_sales_order.company = company for item in items_list: woocomm_item_id = item.get("product_id") found_item = frappe.get_doc("Item",{"woocommerce_id": woocomm_item_id}) ordered_items_tax = item.get("total_tax") new_sales_order.append("items",{ "item_code": found_item.item_code, "item_name": found_item.item_name, "description": found_item.item_name, "delivery_date":order_delivery_date, "uom": woocommerce_settings.uom or _("Nos"), "qty": item.get("quantity"), "rate": item.get("price"), "warehouse": woocommerce_settings.warehouse or "Stores" + " - " + company_abbr }) add_tax_details(new_sales_order,ordered_items_tax,"Ordered Item tax",0) # shipping_details = fd.get("shipping_lines") # used for detailed order shipping_total = fd.get("shipping_total") shipping_tax = fd.get("shipping_tax") add_tax_details(new_sales_order,shipping_tax,"Shipping Tax",1) add_tax_details(new_sales_order,shipping_total,"Shipping Total",1) new_sales_order.submit() frappe.db.commit()