I want to create user through apache superset API if user already exist it should show message.
import requests
payload = { 'username': 'My user name',
'password': 'my Password',
'provider': 'db'
}
base_url="http://0.0.0.0:8088"
login_url =f"{base_url}/api/v1/security/login"
login_response =requests.post(login_url,json=payload)
access_token = login_response.json()
print(access_token)
# header
header = {"Authorization":f"Bearer {access_token.get('access_token')}"}
base_url="http://0.0.0.0:8088" # apache superset is running in my local system on port 8088
user_payload={
'first_name': "Cp",
'last_name': "user",
'username':"A",
'email': "user.#gmail.com",
'active': True,
'conf_password': "user#1",
'password': "user#1",
"roles":["Dashboard View"]
}
users_url = f"{base_url}/users/add"
user_response= requests.get(users_url, headers=header)
print(user_response)
print(user_response.text)
user_response = user_response.json()
print(user_response)
I tried to create user through mentioned API, some time it gives 200 success message, but after checking in apache superset website i can not see created user details.
If i am using the wrong API endpoint or wrong methods to create user please suggest me.
Related
I'm trying to integrate AD authentication into my application, but my company requires connections over TLS to AD to trust company CA signed certificates to complete the SSL/TLS handshake. How would I go about adding certificate validation to these settings?
# LDAP Connection Settings
LDAP_AUTH_URL = ['ldap://xxx.xxx.xxx.xx:636', 'ldap://xxx.xxx.xxx.xx:636']
# Initiate TLS on Connection
LDAP_AUTH_USE_TLS = True
LDAP_AUTH_TLS_VERSION = ssl.PROTOCOL_TLSv1_2
# LDAP Search BASE for Looking up Users
LDAP_AUTH_SEARCH_BASE = 'ou=users,ou=authentication,ou=security,dc=corp,dc=companycom,dc=com'
# The LDAP class that represents a user.
LDAP_AUTH_OBJECT_CLASS = 'user'
# User model fields mapped to the LDAP
# attributes that represent them.
LDAP_AUTH_USER_FIELDS = {
'username': 'SamAccountName',
'first_name': 'givenName',
'last_name': 'sn',
'email': 'EmailAddress',
'manager': 'manager',
'enabled': 'Enabled'
}
# A tuple of fields used to uniquely identify a user.
LDAP_AUTH_USER_LOOKUP_FIELDS = ('username')
# Path to a callable that takes a dict of {model_field_name: value},
# returning a dict of clean model data.
# Use this to customize how data loaded from LDAP is saved to the User model.
LDAP_AUTH_CLEAN_USER_DATA = "django_python3_ldap.utils.clean_user_data"
# Path to a callable that takes a user model, a dict of {ldap_field_name: [value]}
# a LDAP connection object (to allow further lookups), and saves any additional
# user relationships based on the LDAP data.
# Use this to customize how data loaded from LDAP is saved to User model relations.
# For customizing non-related User model fields, use LDAP_AUTH_CLEAN_USER_DATA.
LDAP_AUTH_SYNC_USER_RELATIONS = "django_python3_ldap.utils.sync_user_relations"
# Path to a callable that takes a dict of {ldap_field_name: value},
# returning a list of [ldap_search_filter]. The search filters will then be AND'd
# together when creating the final search filter.
LDAP_AUTH_FORMAT_SEARCH_FILTERS = "django_python3_ldap.utils.format_search_filters"
# Path to a callable that takes a dict of {model_field_name: value}, and returns
# a string of the username to bind to the LDAP server.
# Use this to support different types of LDAP server.
LDAP_AUTH_FORMAT_USERNAME = "django_python3_ldap.utils.format_username_openldap"
# Sets the login domain for Active Directory users.
LDAP_AUTH_ACTIVE_DIRECTORY_DOMAIN = 'corp'
# The LDAP username and password of a user for querying the LDAP database for user
# details. If None, then the authenticated user will be used for querying, and
# the `ldap_sync_users`, `ldap_clean_users` commands will perform an anonymous query.
LDAP_AUTH_CONNECTION_USERNAME = 'placeholder'
LDAP_AUTH_CONNECTION_PASSWORD = 'placeholder'
# Set connection/receive timeouts (in seconds) on the underlying `ldap3` library.
LDAP_AUTH_CONNECT_TIMEOUT = None
LDAP_AUTH_RECEIVE_TIMEOUT = None
LOGGING = {
"version": 1,
"disable_existing_loggers": False,
"handlers": {
"console": {
"class": "logging.StreamHandler",
},
},
"loggers": {
"django_python3_ldap": {
"handlers": ["console"],
"level": "INFO",
},
},
}
Again, I already have the CA bundle. I just need to trust it to be able to communicate with the AD server. Thanks for any ideas in advance!
Hey guys I'm creating a multi-tenant app using DJANGO TENANTS and DRF
I'm trying to create a login api using the following function
login api-view
#api_view(['POST'])
#permission_classes([permissions.AllowAny])
def login(request):
restaurant_name = request.POST.get('restaurant_name')
email = request.POST.get('email')
password = request.POST.get('password')
restaurant_schema = restaurant_name
if not restaurant_name:
restaurant_schema = 'public'
domain_name = 'http://localhost:8000/o/token/'
else:
domain_name = 'http://' + restaurant_name + '.localhost:8000/o/token/'
with schema_context(restaurant_schema):
# c = Client.objects.get(name='BFC')
# return Response(c.reverse(request,'test'))
app = Application.objects.first()
r = requests.post(domain_name,
data={
'grant_type': 'password',
'username': email,
'password': password,
'client_id': app.client_id,
# 'scope': 'read',
'client_secret': app.client_secret,
},)
return Response(r.json())
But I'm getting this error:
HTTPConnectionPool(host='bfc.localhost', port=8000): Max retries exceeded with url: /o/token/ (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x000001E24200D600>: Failed to establish a new connection: [Errno 11001] getaddrinfo failed'))
I have tried to check the connection using:
socket.create_connection(('localhost',8000),timeout=2)
and
socket.create_connection(('bfc.localhost',8000),timeout=2)
bfc.localhost cant create a connection yet localhost and also I can access the domain from my browser
Additional info:
In Postman OAuth 2 section I can get a response with the same fields
I want to implement the same scenario for use in Android Kotlin which is given in this url.
For Web Application
I have created login with google for web application by follow this link. Here is my Google Login View in views.py for access token (as one user have explained here )
class GoogleLogin(SocialLoginView):
adapter_class = GoogleOAuth2Adapter
And It's working for me as I expected.
For Android Application
Now, Somehow I have managed a code for this google scenario.
Here is my Google Client login View.view.py code
class GoogleClientView(APIView):
def post(self, request):
token = {'id_token': request.data.get('id_token')}
print(token)
try:
# Specify the CLIENT_ID of the app that accesses the backend:
idinfo = id_token.verify_oauth2_token(token['id_token'], requests.Request(), CLIENT_ID)
print(idinfo)
if idinfo['iss'] not in ['accounts.google.com', 'https://accounts.google.com']:
raise ValueError('Wrong issuer.')
return Response(idinfo)
except ValueError as err:
# Invalid token
print(err)
content = {'message': 'Invalid token'}
return Response(content)
When I am requesting POST method with IdToken then this is providing below information and ofcourse we need this.
{
// These six fields are included in all Google ID Tokens.
"iss": "https://accounts.google.com",
"sub": "110169484474386276334",
"azp": "1008719970978-hb24n2dstb40o45d4feuo2ukqmcc6381.apps.googleusercontent.com",
"aud": "1008719970978-hb24n2dstb40o45d4feuo2ukqmcc6381.apps.googleusercontent.com",
"iat": "1433978353",
"exp": "1433981953",
// These seven fields are only included when the user has granted the "profile" and
// "email" OAuth scopes to the application.
"email": "testuser#gmail.com",
"email_verified": "true",
"name" : "Test User",
"picture": "https://lh4.googleusercontent.com/-kYgzyAWpZzJ/ABCDEFGHI/AAAJKLMNOP/tIXL9Ir44LE/s99-c/photo.jpg",
"given_name": "Test",
"family_name": "User",
"locale": "en"
}
Till here, everything is working good for me.But here I want to create account/login for a the user using above info and when account/login is created then need a key in return response.
below What I had tried
class GoogleClientView(APIView):
permission_classes = [AllowAny]
adapter_class = GoogleOAuth2Adapter
callback_url = 'https://example.com/user/accounts/google/login/callback/'
client_class = OAuth2Client
def post(self, request):
token = {'id_token': request.data.get('id_token')}
print(token)
try:
# Specify the CLIENT_ID of the app that accesses the backend:
idinfo = id_token.verify_oauth2_token(token['id_token'], requests.Request(), CLIENT_ID)
print(idinfo)
if idinfo['iss'] not in ['accounts.google.com', 'https://accounts.google.com']:
raise ValueError('Wrong issuer.')
return Response(idinfo)
except ValueError as err:
# Invalid token
print(err)
content = {'message': 'Invalid token'}
return Response(content)
Again It seems it's not creating any account/login for user and no key is getting in response.
So, for creating account/login, How can I implement the code?
Please ask for more information If I forgot to put any.
I like to print a pdf-version of my mediawikipage using pdfkit.
My mediawiki requires a valid login to see any pages.
I login to mediawiki using requests, and this works, and I get some cookies. However, I am not able to use these cookies with pdfkit.from_url()
My python-script looks like this:
#!/usr/bin/env python2
import pdfkit
import requests
import pickle
mywiki = "http://192.168.0.4/produniswiki/"# URL
username = 'produnis' # Username to login with
password = 'seeeecret#' # Login Password
## Login to MediaWiki
# Login request
payload = {'action': 'query', 'format': 'json', 'utf8': '', 'meta': 'tokens', 'type': 'login'}
r1 = requests.post(mywiki + 'api.php', data=payload)
# login confirm
login_token = r1.json()['query']['tokens']['logintoken']
payload = {'action': 'login', 'format': 'json', 'utf8': '', 'lgname': username, 'lgpassword': password, 'lgtoken': login_token}
r2 = requests.post(mywiki + 'api.php', data=payload, cookies=r1.cookies)
print(r2.cookies)
So, right here I am successfully logged in, and cookies are stored in r2.cookies.
The print()-command gives:
<RequestsCookieJar[<Cookie produniswikiToken=832a1f1da165016fb9d9a107ddb218fc for 192.168.0.4/>, <Cookie produniswikiUserID=1 for 192.168.0.4/>, <Cookie produniswikiUserName=Produnis for 192.168.0.4/>, <Cookie produniswiki_session=oddicobpi1d5af4n0qs71g7dg1kklmbo for 192.168.0.4/>]>
I can save the cookies into a file:
def save_cookies(requests_cookiejar, filename):
with open(filename, 'wb') as f:
pickle.dump(requests_cookiejar, f)
save_cookies(r2.cookies, "cookies")
This file looks like this: http://pastebin.com/yKyCpPTW
Now I want to print a specific page into PDF using pdfkit. Manpage states, that cookies can be set via a cookie-jar file:
options = {
'page-size': 'A4',
'margin-top': '0.5in',
'margin-right': '0.5in',
'margin-bottom': '0.5in',
'margin-left': '0.5in',
'encoding': "UTF-8",
'cookie-jar' : "cookies",
'no-outline': None
}
current_pdf = pdfkit.from_url(pdf_url, the_filename, options=options)
My Problem is:
with this code, the "cookies" file becomes 0KB and the PDF states "You must be logged in to view a page..."
So my question is:
How can I use a requests.cookies in pdfkit.from_url()?
I had the same issue and overcame it with the following:
import requests, pdfkit
# Get login cookie
s = requests.session() # if you're making multiple calls
data = {'username': 'admin', 'password': 'hunter2'}
s.post('http://example.com/login', data=data)
# Get yourself a PDF
options = {'cookie': s.cookies.items(), 'javascript-delay': 1000}
pdfkit.from_url('http://example.com/report', 'report.pdf', options=options)
Depending on how much javascript you're trying to load you might want to set the javascript-delay to something higher or lower; the default is 200ms.
I want to avoid store personal information in database (no last names, no email). This is my approach to achieve it:
Delegate authentication to social networks authentication service ( thanks to python-social-auth )
Change python-social-auth pipeline to anonymize personal information.
Then I replaced social_details step on pipeline by this one:
#myapp/mypipeline.py
def social_details(strategy, response, *args, **kwargs):
import md5
details = strategy.backend.get_user_details(response)
email = details['email']
fakemail = unicode( md5.new(email).hexdigest() )
new_details = {
'username': fakemail[:5],
'email': fakemail + '#noreply.com',
'fullname': fakemail[:5],
'first_name': details['first_name'],
'last_name': '' }
return {'details': new_details }
settings.py
SOCIAL_AUTH_PIPELINE = (
'myapp.mypipeline.social_details',
'social.pipeline.social_auth.social_uid',
...
The question:
Is this the right way to get my purpose?
Looks good.
I'm doing something similar to anonymize IP addresses (hash them).