Running django admin command via curl or request.post - django

I have a special Django admin action called "run_test".
I would like to start that action from a Jenkins job on some items.
Something like this was my idea
import json
import requests
url = "http://localhost:8000/admin/app/model/"
item = { "user": "jenkins",
"password": "password",
"action": "run_test",
"index": 0
}
headers = {"Content-Type":"application/json","Accept": "application/json"}
resp = requests.post(url,data=json.dumps(item),headers=headers)
print(resp)
403 is the answer I got as a response.
Is there a way to run Django admin command with curl or request.post?
How can I include a queryset?
Note: manage.py command is not an option

This requires a bit of stateful shell scripting -- login to admin area, obtain a magic cookie and then shoot your custom requests with the magic cookie included. Details in this answer.

Related

Using telethon with a django application

I want to watch updates on telegram messages in an django application and interact with django orm.
I found telethon library, it works with user api which is what I want.
Below code simply works on its own.
from telethon import TelegramClient
from telethon import events
api_id = 231232131
api_hash = '32131232312312312edwq'
client = TelegramClient('anon', api_id, api_hash)
#client.on(events.NewMessage)
async def my_event_handler(event):
if 'hello' in event.raw_text:
await event.reply('hi!')
client.start()
But telethon requires phone message verification and it needs to work in a seperate thread.
I couldn't find a way to put this code in a django application. And when django starts, I dont know how to bypass phone verification.
It should always work in an seperate loop and interact with django orm. Which is very confusing for me.
You can simply use django-telethon and use the API endpoints for signing bot and user session.
run the following command to start the server:
python manage.py runserver
run the following command to start telegram client:
python manage.py runtelegram
go to admin panel and telegram app section. create a new app. get data from the your Telegram account.
request code from telegram:
import requests
import json
url = "127.0.0.1:8000/telegram/send-code-request/"
payload = json.dumps({
"phone_number": "+12345678901",
"client_session_name": "name of the client session"
})
headers = {
'Content-Type': 'application/json'
}
response = requests.request("POST", url, headers=headers, data=payload)
print(response.text)
send this request for sign in:
import requests
import json
url = "127.0.0.1:8000/telegram/login-user-request/"
payload = json.dumps({
"phone_number": "+12345678901",
"client_session_name": "name of the client session",
"code": "1234",
"password": "1234"
})
headers = {
'Content-Type': 'application/json'
}
response = requests.request("POST", url, headers=headers, data=payload)
print(response.text)
It's not the answer I wanted initially.
But, I think this is better approach.
Instead of trying to put all of this in django application. It's better to run it seperately and let django application communicate this with rest framework.

Add API key to a header in a DRF browsable API page

I am enabling token/api-key authentication on my API. But once I enable it, I can no longer use the browsable API page of the DRF. I know I can disable the authentication while developing, but this is a question of curiosity: Can I add an api-key to the header of each request sent to the browsable API page? Can I do that by tweaking the Browser settings? Or is it possible to tweak the Browsable API page itself and hardcode the api-key into it?
The better way to handle the situation is to add the SessionAuthentication to the DEFAULT_AUTHENTICATION_CLASSES section in your settings
# settings.py
REST_FRAMEWORK = {
"DEFAULT_AUTHENTICATION_CLASSES": [
"rest_framework.authentication.TokenAuthentication",
"rest_framework.authentication.SessionAuthentication",
],
}
More precisely,
# settings.py
REST_FRAMEWORK = {
"DEFAULT_AUTHENTICATION_CLASSES": [
"rest_framework.authentication.TokenAuthentication",
],
}
if DEBUG:
REST_FRAMEWORK["DEFAULT_AUTHENTICATION_CLASSES"].append(
"rest_framework.authentication.SessionAuthentication"
)
By doing this, you can either use your APIKey or session key to authenticate the requests.

Django Microsoft AD Authentication

I noticed that this question was repeated few times, but still, from all the resources, I couldn't manage to make it work properly.
I'm simply trying to use Azure Active Directory authentication with my Django app.
I am using this module, and I configured everything as noted in the docs.
The thing is - I can't figure out where should user enter the credentials - since the module has only
one url ('auth-callback/'). I can't find out how to jump to Microsoft login html page. Should I use my login.html or?
Also, I guess that 'auth-callback/' url is obviously a callback URL, which comes after the login page.
I am using django auth.views LoginView for login, and custom login.html page.
In terms of Redirect URI's I configured redirect URI to match directly the 'http://localhost:8000/microsoft/auth-callback/' url, which is also how it needs to be I guess.
Main problem is - where can I enter the credentials for login? :)
Also, when I try this - I get invalid credentials error on my Admin login page :
Start site and go to /admin and logout if you are logged in.
Login as Microsoft/Office 365/Xbox Live user. It will fail. This will automatically create your new user.
Login as a Password user with access to change user accounts.
Quick Edit :
I noticed that when i go to django/admin page '..../admin/login' inside the console i have this error :
https://static/microsoft/css/login.css Failed to load resource (404)
https://static/microsoft/js/login.js Failed to load resource (404)
Where can i get those files?
Let's jump to my code :
settings.py
INSTALLED_APPS = [
...
'django.contrib.sites',
'microsoft_auth',
...
]
#Choped from templates
'context_processors': [
...
'microsoft_auth.context_processors.microsoft',
],
AUTHENTICATION_BACKENDS = [
'microsoft_auth.backends.MicrosoftAuthenticationBackend',
'django.contrib.auth.backends.ModelBackend',
]
SITE_ID = 1
LOGIN_REDIRECT_URL = 'main:index'
LOGOUT_REDIRECT_URL = 'main:index'
LOGIN_URL = '/'
LOGOUT_URL = '/'
# AZURE AUTH CONFIG
MICROSOFT_AUTH_CLIENT_ID = 'THIS IS MY CLIENT KEY'
MICROSOFT_AUTH_CLIENT_SECRET = 'THIS IS MY SECRET KEY'
MICROSOFT_AUTH_TENANT_ID = 'THIS IS MY TENANT KEY'
# include Microsoft Accounts, Office 365 Enterpirse and Azure AD accounts
MICROSOFT_AUTH_LOGIN_TYPE = 'ma'
And my urls.py
...
path('microsoft/', include('microsoft_auth.urls', namespace='microsoft')),
...
Thank you all in advance.
django-microsoft-auth uses the standard django login page and extends that. My guess is that your custom login page is interfering with that. You could try removing that view and test again to see if the login appears at /admin.
The files should be coming from the django-microsoft-auth package. You could try uninstalling and reinstalling it again with pip

Trouble getting Salesforce login working with dj-rest-auth + django-allauth

My app has a Django 3.1 backend with django-allauth and dj-rest-auth (actively supported fork of django-rest-auth).
My mobile and web frontends can already sign in using Facebook and Google via REST. I'm now trying to add Salesforce as a 3rd REST social login method, but am running into issues.
I've followed the django-allauth instructions for Salesforce:
Created a Salesforce Connected App with id and openid scopes (along with some others), and set the callback URL to https://www.mywebdomain.com/accounts/salesforce/login/callback/
Created a SocialApplication in Django with client ID, secret, and login URL in the "Key" field (https://login.salesforce.com/)
Included allauth.socialaccount.providers.salesforce in INSTALLED_APPS
I've been using client-side JSforce to kick off the Salesforce auth request in the frontend, but I'm open to other methods if they are simpler/better/etc.
Running jsforce.browser.login() in my clients' JS code opens a Salesforce login popup. After entering Salesforce login credentials, the Salesforce system redirected to my defined callback URL, resulting in a page that shows the following text:
Social Network Login Failure
An error occurred while attempting to login via your social network account.
The URL in the address bar on that page looks something like this:
https://www.mywebdomain.com/accounts/salesforce/login/callback/#access_token=00D3t000004QWRm%21ARwAQPfHWiM6jdB43dlyW6qjEw._34mjzGi_Jv6YCXp0QssT.9F9lCge5_YaH8gqTy3Od6SywCs8X9zOGv145SyviBVeGdn0&instance_url=https%3A%2F%2Fna123.salesforce.com&id=https%3A%2F%2Flogin.salesforce.com%2Fid%2F00D3t000004QWRmEAO%2F0053t000008QBetAAG&issued_at=1606802917608&signature=KvxAX0WBCFQYY%2BO25id9%2FXxpbh2q2d2vWdQ%2FFV5FCBw%3D&state=jsforce0.popup.c0ockgct29g&scope=id+api+web+refresh_token+openid&token_type=Bearer
I tried to debug and print the error in my backend, but both auth_error.code and auth_error.exception were blank/empty.
I also tried sending the access_token from that URL's hash to my Salesforce API endpoint (see below), but that resulted in a 400 error ("Incorrect value").
Here is how I've defined my SocialLoginViews in my views.py, based on dj-rest-auth's social auth documentation:
from dj_rest_auth.registration.views import SocialLoginView
from allauth.socialaccount.providers.facebook.views import FacebookOAuth2Adapter
from allauth.socialaccount.providers.google.views import GoogleOAuth2Adapter
from allauth.socialaccount.providers.salesforce.views import SalesforceOAuth2Adapter
class FacebookLogin(SocialLoginView):
adapter_class = FacebookOAuth2Adapter
class GoogleLogin(SocialLoginView):
adapter_class = GoogleOAuth2Adapter
class SalesforceLogin(SocialLoginView):
adapter_class = SalesforceOAuth2Adapter
My urls.py:
from .views import FacebookLogin, GoogleLogin, SalesforceLogin
urlpatterns = [
...
# Sending access_token to the Facebook and Google REST endpoints works,
# but doing the same for the Salesforce REST endpoint does not (400 error: "Incorrect value")
url(r'^api/rest-auth/facebook/$', FacebookLogin.as_view(), name='fb_login'),
url(r'^api/rest-auth/google/$', GoogleLogin.as_view(), name='google_login'),
url(r'^api/rest-auth/salesforce/$', SalesforceLogin.as_view(), name='salesforce_login'),
...
]
How can Salesforce social auth be made to work in this app?
I figured it out and got it working: when posting to my dj-rest-auth Salesforce API endpoint, I was only including access_token in my POST body. I actually need both access_token and key, where key is the Salesforce login URL ("https://login.salesforce.com").
It was indeed in the django-allauth instructions for Salesforce, but I misinterpreted the wording. I now know that it says to require both access_token and key in the POST body.

unable to make a successful call from android using retrofit with csrf token

I'm new to django and got struck with csrf tokens. I'm making a post request from android using retrofit to my django server which is using csrf protection. I had obtained the csrf token by making a get request first and then I'm passing this csrftoken from the body of POST request. However, my server is showing 'CSRF cookie not set' error. The server is responding well to the calls from POSTMAN but when I make calls from android, I get this error. I think there is some simple thing I'm missing, but I'm not able to figure it out.
Session based authorization is usually used in web-apps. In case of android apps which are backed by API.
So rather than you can do Token Based Authorization using rest_framework in Django.
In your settings.py
INSTALLED_APPS = [
...
'rest_framework',
]
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.TokenAuthentication', # <-- And here
],
}
Now migrate the migrations to the database.
python manage.py migrate
Run this command to generate token for the specific user.
python manage.py drf_create_token <username>
Now add this line to urls.py.
from rest_framework.authtoken.views import obtain_auth_token
urlpatterns = [
#Some other urls.
path('api-token-auth/', obtain_auth_token, name='api_token_auth'),
]
Using this you can obtain token for any user by using its username & password by just passing them in request body.
So this will be our protected api. Add this class based view in your views.py
from rest_framework.permissions import IsAuthenticated,AllowAny # <-- Here
from rest_framework.views import APIView
from rest_framework.response import Response
class DemoData(APIView):
permission_classes = (IsAuthenticated,)
def post(self, request):
content = {'data': 'Hello, World!'}
return Response(content)
Now pass a header with the api name as 'Authorization' & value be like something 'Token 5a2b846d267f68be68185944935d1367c885f360'
This is how we implement Token Authentication/Authorization in Django.
For more info, click here to see official documentation.