I'm using pyramid_sacrud and get the error "403 Forbidden Access was denied to this resource. Unauthorized: sa_home failed permission check" - pyramid

I follow the official docs, and set it step by step.
Using browser point to http://localhost:6543/sacrud/, here raise 403 Forbidden error. I'm trying to delete sa_home function's parameter permission in pyramid_sacrud/views/init.py to solve it, though It could be access but it hasn't login page in there.
Here is my app's ini file:
from pyramid.config import Configurator
from sqlalchemy import engine_from_config
from pyramid.authentication import AuthTktAuthenticationPolicy
from pyramid.authorization import ACLAuthorizationPolicy
from pyramid.session import SignedCookieSessionFactory
from pyraid_blogr.models.models import BlogRecord, User
from .models.meta import (
DBSession,
Base,
)
def main(global_config, **settings):
""" This function returns a Pyramid WSGI application.
"""
engine = engine_from_config(settings, 'sqlalchemy.')
DBSession.configure(bind=engine)
Base.metadata.bind = engine
authentication_policy = AuthTktAuthenticationPolicy('your_secret', hashalg='sha512')
authorization_policy = ACLAuthorizationPolicy()
config = Configurator(settings=settings,
authentication_policy=authentication_policy,
authorization_policy=authorization_policy
)
config.set_session_factory(SignedCookieSessionFactory('replace_your_secret'))
config.include('pyramid_mako',)
config.include('pyramid_sacrud',)
settings = config.registry.settings
settings['pyramid_sacrud.models'] = (('Group1', [BlogRecord]), ('Group2', [User]))
config.add_static_view('static', 'static', cache_max_age=3600)
config.add_route('home', '/')
config.add_route('blog', '/blog/{id:\d+}/{slug}', request_method='GET')
config.add_route('blog_action', '/blog/{action}', factory='pyraid_blogr.security.BlogRecordFactory')
config.add_route('auth', 'sign/{action}')
config.scan()
return config.make_wsgi_app()
Here is the debug info
permission pyramid_sacrud_home value 'pyramid_sacrud_home' Source
Line 45 of file
/Users/liu-minglei/Web-Dev/my_pyramid/pyraid_blogr/admin/views/init.py:
permission=PYRAMID_SACRUD_HOME References view function
admin.views.sa_home

I have created an example with authorization (https://github.com/ITCase/pyramid_sacrud/tree/master/example), in your case, you seem to have edit pyramid_sacrud/views/init.py file that is not location in your python env or not reload server. For your app you must add sacrud permission (http://pyramid-sacrud.readthedocs.org/en/latest/pages/permissions.html) to root_factory.

Related

How do I solve page not found error in flask rest api

I have developed a flask application that returns some text from OPEN-AI by giving some inputs.
But unfortunately the rest API in my application returns 404 error.
Here is the code:
from crypt import methods
from warnings import catch_warnings
from flask import Flask,request
from flask_cors import CORS
import flask
import openai
from flask_restful import Api,Resource
import base64
import json
#Init
app = Flask(__name__)
CORS(app)
api = Api(app)
app.run(host='0.0.0.0',port=8080)
#OPENAI CREDENTIALS
openai.api_key = ""
#Functions
class advert(Resource):
def post(self):
try:
request_body=request.json
A=request_body["data"]
adprompt = "Write an advertisement for " + A
response = openai.Completion.create(
engine="text-davinci-002",
prompt=adprompt,
temperature=0.7,
max_tokens=70,
top_p=1.0,
n=1
)
json_advert = json.loads(str(response))
advert_output = json_advert['choices'][0]['text']
to_return= json_advert = json.loads(str(advert_output))
return to_return,200
except:
return ({"ERROR":"Error Occured"}),500
#Mapping
api.add_resource(advert,'/data',methods=['POST'])
if __name__=='__main__':
app.run(debug=True)
This is the response i get:
192.168.1.21 - - [24/Nov/2022 11:52:59] "POST /data HTTP/1.1" 404 -
I've tried changing the port and endpoints, nothing helped .
How to solve this.
Your problem is at this line,
app.run(host='0.0.0.0',port=8080)
take it out, then add the parameters into the last line,
if __name__=='__main__':
app.run(debug=True, host='0.0.0.0',port=8080)
A bit more explanation, when the code hits app.run, it actually starts the server and not running the line api.add_resource. Hence, no path was configured.

superset keycloak configuration

I am trying to use keycloak with apache superset. I have spent hours on the links below but unable to replace the current login.
Using OpenID/Keycloak with Superset
2.Using KeyCloak(OpenID Connect) with Apache SuperSet
Using OpenID/Keycloak with Superset
I am using apache superset 0.34.5. While above links use 0.28 and below.
i am confused at inital step. let me explain the steps and see what i am missing.
I install superset using pip.
The structure i have is, i have config.py and security.py at the same level (i dont have security folder)
I renamed the security to oid_security.
I created a security.py with the following content.
from flask_appbuilder.security.manager import AUTH_OID
from superset.security import SupersetSecurityManager
from flask_oidc import OpenIDConnect
from flask_appbuilder.security.views import AuthOIDView
from flask_login import login_user
from urllib.parse import quote
from flask_appbuilder.views import ModelView, SimpleFormView, expose
import logging
class AuthOIDCView(AuthOIDView):
#expose('/login/', methods=['GET', 'POST'])
def login(self, flag=True):
sm = self.appbuilder.sm
oidc = sm.oid
#self.appbuilder.sm.oid.require_login
def handle_login():
user = sm.auth_user_oid(oidc.user_getfield('email'))
if user is None:
info = oidc.user_getinfo(['preferred_username', 'given_name', 'family_name', 'email'])
user = sm.add_user(info.get('preferred_username'), info.get('given_name'), info.get('family_name'), info.get('email'), sm.find_role('Gamma'))
login_user(user, remember=False)
return redirect(self.appbuilder.get_url_for_index)
return handle_login()
#expose('/logout/', methods=['GET', 'POST'])
def logout(self):
oidc = self.appbuilder.sm.oid
oidc.logout()
super(AuthOIDCView, self).logout()
redirect_url = request.url_root.strip('/') + self.appbuilder.get_url_for_login
return redirect(oidc.client_secrets.get('issuer') + '/protocol/openid-connect/logout?redirect_uri=' + quote(redirect_url))
class OIDCSecurityManager(SupersetSecurityManager):
authoidview = AuthOIDCView
def __init__(self,appbuilder):
super(OIDCSecurityManager, self).__init__(appbuilder)
if self.auth_type == AUTH_OID:
self.oid = OpenIDConnect(self.appbuilder.get_app)
I then created custom manager with the following
from flask_appbuilder.security.manager import AUTH_OID
from flask_appbuilder.security.sqla.manager import SecurityManager
from flask_oidc import OpenIDConnect
class OIDCSecurityManager(SecurityManager):
def __init__(self, appbuilder):
super(OIDCSecurityManager, self).__init__(appbuilder)
if self.auth_type == AUTH_OID:
self.oid = OpenIDConnect(self.appbuilder.get_app)
self.authoidview = AuthOIDCView
I created client secret.json with my credentials.
I edited config file as below.
from superset.security import OIDCSecurityManager
AUTH_TYPE = AUTH_OID
OIDC_CLIENT_SECRETS = 'client_secret.json'
OIDC_ID_TOKEN_COOKIE_SECURE = False
OIDC_REQUIRE_VERIFIED_EMAIL = False
AUTH_USER_REGISTRATION = True
AUTH_USER_REGISTRATION_ROLE = 'Gamma'
CUSTOM_SECURITY_MANAGER = OIDCSecurityManager
One thing to mention here is have manager py in security folder in flask appbuilder which has Abstract Security Manager cls. I am getting an error security py
It says cannot import name SupersetSecurityManager from superset - security
anyone please?
I suggest you start afresh and follow the steps that worked for me:
Create a virtual environment within your superset directory and activate it.
Install the flask-oidc and superset plugins within your virtual environment. pip install flask-oidc
Have a oidc_security.py file with the script you pasted above i.e. security.py in your setup.
Have a client_secret.json file with your keycloak config.
Have a superset_config.py with the script you pasted above.
Add all three of these files to your pythonpath.
Run superset db upgrade & superset init commands.
Finally, execute superset run. After the initialization completes, navigate to http://localhost:8088 on your browser. Expected behaviour: you'll be redirected to keycloak to login/register. After successful sign in, you'll be redirected to superset app.
I hope this helps. Do post back incase you succeed or face an error.
I then created custom manager with the following
where to update this??
from flask_appbuilder.security.manager import AUTH_OID
from flask_appbuilder.security.sqla.manager import SecurityManager
from flask_oidc import OpenIDConnect
class OIDCSecurityManager(SecurityManager):
def __init__(self, appbuilder):
super(OIDCSecurityManager, self).__init__(appbuilder)
if self.auth_type == AUTH_OID:
self.oid = OpenIDConnect(self.appbuilder.get_app)
self.authoidview = AuthOIDCView

Invalid credentials when trying to connect to vTiger

I'm trying to log in via webservice within vtiger CRM5 with python
When putting my key and user name in params, I just get an INVALID_AUTH_TOKEN, but when putting it into body, I get INVALID_USER_CREDENTIALS. Which seems better but not quite working !
{'success': False, 'error': {'code': 'INVALID_USER_CREDENTIALS', 'message': 'Invalid username or password'}}
# -*- coding: utf-8 -*-
import json
import requests
from hashlib import md5
from requests.auth import HTTPBasicAuth
api_url_base = 'http://crmaddress/webservice.php'
username = 'myusername'
accessKey = 'fghdhgfhfdhgfd'
headers = {"ContentType":"application/x-www-form-urlencoded"}
response = requests.get(api_url_base,params={"operation":"getChallenge","username":username})
token = json.loads(response.content.decode('utf-8'))['result']['token']
key = md5(accessKey.encode('utf-8')+token.encode('utf-8')).hexdigest()
print(key)
response = requests.post(api_url_base,data={"operation":"login","accessKey":key,"username":username,},auth=HTTPBasicAuth('myusername','mypassword'),headers=headers)
print(json.loads(response.content.decode('utf-8')))
I cannot verify without running the code, but the problem seems to be somewhere along
key = md5(accessKey.encode('utf-8')+token.encode('utf-8')).hexdigest()
Also, instead of directly using the webservice, I would recommend creating a wrapper class. Please check out a python3 wrapper I wrote at github. Let me know if this helps.

Azure :Working with GraphRbacManagementClient and ServicePrincipalCredentials results with Insufficient privileges error

I'm trying to run the code below and it ends up with the error :
azure.graphrbac.models.graph_error.GraphErrorException: Insufficient
privileges to complete the operation.
prerequisite:
create an azure app with Microsoft Graph permissions
The code (python):
from azure.graphrbac import graph_rbac_management_client
from msrestazure.azure_active_directory import ServicePrincipalCredentials
class TestAzureStuff(object):
def __init__(self):
self.tenant = "**YOUR*tenant******"
self.client = "*****YOUR*client*****"
self.secret = "******YOUR*secret****"
self.subscription = "*****YOUR*subscription****"
self.credentials = ServicePrincipalCredentials(client_id=self.client,
secret=self.secret,
tenant=self.tenant,
resource="https://graph.windows.net")
def remove_app(self):
client = graph_rbac_management_client.GraphRbacManagementClient(self.credentials,
self.tenant)
client.users.list().next()
stuff = TestAzureStuff()
stuff.remove_app()
the only way it does work is when instead of the ServicePrincipalCredentials I use UserPassCredentials with my own credentials.
I also Checked maybe there are some permissions differences between the app and my own user and looks like they have same permissions.
Do you have any clue what permission is missing?
or maybe I'm missing something else here?

Python - HttpError when using google drive API

I am using python 3.4 to leverage the Google API to access and read files from a users google drive. If a user has already used the app before they should have a credentials file so I was hoping to be able to test if the credentials are still valid by attempting to list the files on the users drive. The idea being if this errors then the app knows it needs to ask for access again.
After a lot of searching I've tried to piece together code from the following Examples:
Google API commands
Google Example
I currently have the following pieces of code:
import httplib2
from apiclient.discovery import build
from oauth2client.file import Storage
from oauth2client.client import AccessTokenRefreshError
from oauth2client.client import OAuth2WebServerFlow
def getAccess():
flow = OAuth2WebServerFlow(client_id, client_secret, scope, redirect_uri="urn:ietf:wg:oauth:2.0:oob")
auth_uri = flow.step1_get_authorize_url()
print("Please go to the following webpage and copy and paste the access key onto the command line:\n" + auth_uri + "\n")
code = input("Please enter your access code:\n")
credentials = flow.step2_exchange(code)
storage.put(credentials)
client_id = MYCLIENT_ID
client_secret = MYCLIENT_SECRET
scope = "https://www.googleapis.com/auth/drive"
storage = Storage('~/credentials.dat')
credentials = storage.get()
if credentials is None or credentials.invalid:
getAccess()
else:
try:
http = httplib2.Http()
http = credentials.authorize(http)
service = build('drive', 'v2', http=http)
param = {}
service.files().list(**param).execute()
except:
getAccess()
However the service.files().list(**param).execute() line produces the following error message:
Traceback (most recent call last):
File "GoogleAuth.py", line 64, in <module>
service.files().list(**param).execute()
File "C:\Anaconda3\lib\site-packages\oauth2client\util.py", line 137, in positional_wrapper
return wrapped(*args, **kwargs)
File "C:\Anaconda3\lib\site-packages\googleapiclient\http.py", line 729, in execute
raise HttpError(resp, content, uri=self.uri)
googleapiclient.errors.HttpError
I've tried playing around with a few different combinations such as:
service.files().list().execute()
service.apps().list().execute()
However I still get the same error message. Any idea what's going on ?
Issue was that
service = build('drive', 'v2')
Should have been
service = build('drive', 'v2', http=http)

Resources