How to decode SAMLResponse in Django View? - python

I am writing a view to create a user in project that has logged into another site. Whenever the user logins to that site he/she gets redirected to url:https://localhost:127.0.0.1:8000/auth/ad/reply/.
The site sends me an SAMLResponse from which I want to extract the email address, firstname & lastname for the user.
Following is my views.py and urls.py:
views.py
from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
# Create your views here.
#csrf_exempt
def ad_auth(request):
response = request.POST.get('SAMLResponse')
return HttpResponse(response)
urls.py
from django.urls import path
from .views import *
urlpatterns = [
path('auth/ad/reply/', ad_auth, name='ad_auth'),
]
Output:
PHNhbWxwOlJlc3BvbnNlIElEPSJfOTJmYjAyYTMtN2ZiMC00NjZlLTk0NGItNTQxMjhlOGI5NGM2IiBWZXJzaW9uPSIyLjAiIElzc3VlSW5zdGFudD0iMjAyMC0xMS0xMVQxNDowMDoxMi43NzlaIiBEZXN0aW5hdGlvbj0iaHR0cHM6Ly9sb2NhbGhvc3Q6ODAwMC9hdXRoL2FkL3JlcGx5LyIgeG1sbnM6c2FtbHA9InVybjpvYXNpczpuYW1lczp0YzpTQU1MOjIuMDpwcm90b2NvbCI+PElzc3VlciB4bWxucz0idXJuOm9hc2lzOm5hbWVzOnRjOlNBTUw6Mi4wOmFzc2VydGlvbiI+aHR0cHM6Ly9zdHMud2luZG93cy5uZXQvYmYzODg4M2EtOGRlNi00NGFhLWJkYzktODFjMzAzY2YxMDMzLzwvSXNzdWVyPjxzYW1scDpTdGF0dXM+PHNhbWxwOlN0YXR1c0NvZGUgVmFsdWU9InVybjpvYXNpczpuYW1lczp0YzpTQU1MOjIuMDpzdGF0dXM6U3VjY2VzcyIvPjwvc2FtbHA6U3RhdHVzPjxBc3NlcnRpb24gSUQ9Il8wYjExNzMwNi03YTI2LTQ2OGQtYTI5Yy1mYTZkMjk2MTQ3MDAiIElzc3VlSW5zdGFudD0iMjAyMC0xMS0xMVQxNDowMDoxMi43NjlaIiBWZXJzaW9uPSIyLjAiIHhtbG5zPSJ1c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FtZT0iaHR0cDovL3NjaGVtYXMueG1sc29hcC5vcmcvd3MvMjAwNS8wNS9pZGVudGl0eS9jbGFpbXMvbmFtZSI+PEF0dHJpYnV0ZVZhbHVlPmxpbmdheWF0YWpheTI4MTBfZ21haWwuY29tI0VYVCNAa3Jpc3AxNTA2Z21haWwub25taWNyb3NvZnQuY29tPC9BdHRyaWJ1dGVWYWx1ZT48L0F0dHJpYnV0ZT48L0F0dHJpYnV0ZVN0YXRlbWVudD48QXV0aG5TdGF0ZW1lbnQgQXV0aG5JbnN0YW50PSIyMDIwLTExLTExVDA3OjI4OjM1LjAwMFoiIFNlc3Npb25JbmRleD0iXzBiMTE3MzA2LTdhMjYtNDY4ZC1hMjljLWZhNmQyOTYxNDcwMCI+PEF1dGhuQ29udGV4dD48QXV0aG5Db250ZXh0Q2xhc3NSZWY+dXJuOm9hc2lzOm5hbWVzOnRjOlNBTUw6Mi4wOmFjOmNsYXNzZXM6UGFzc3dvcmQ8L0F1dGhuQ29udGV4dENsYXNzUmVmPjwvQXV0aG5Db250ZXh0PjwvQXV0aG5TdGF0ZW1lbnQ+PC9Bc3NlcnRpb24+PC9zYW1scDpSZXNwb25zZT4=
How do I extract information from the following SAMLResponse?
Thanks in Advance.

That is sending you a base64 encoded string.
Decode it and you will find it to be xml.
The email attribute will look something like this
<AttributeValue>xxxxxxxxx2810#gmail.com</AttributeValue>
Some sudo code to get you started
import base64
foo = base64.b64decode("PHNhbWxwOlJlc3BvbnN....") # put your entire string here
print(foo)

You can also use pysaml2 and djangosaml modules to decrypt the SAMLResponse.

Related

Testing redirects to parameterized URLs when creating object

I have a view for creating blog posts which redirects the user to a form to fill the blog post content like this:
from django.views import View
from app.models import BlogPost
class CreateBlogPost(View):
def post():
new_post = BlogPost.objects.create()
return redirect(reverse('post_edit'), args=[new_post.id])
class EditBlogPost(View):
...
And my urls are the following:
from django.urls import path
from app.views import CreateBlogPost
urlpatterns = [
path('post', CreateBlogPost.as_view(), name='post_create'),
path('post/<int:pk>/edit', EditBlogPost.as_view(), name='post_edit')
]
I would like to: test the CreateBlogPost by asserting that it redirects to post/<some_id>/edit.
I've tried: using the method assertRedirects from django's SimpleTestCase, but couldn't find a way to make this work.
I'm also using pytest-django, in case that's relevant.

'function' object has no attribute 'get' error in django

greetings dear django experts,
i am having an issue with my website i am using the defualt login view in django from
from django.contrib.auth import views as auth_views
the code is working
like this inside the urls.py file :
from django.contrib.auth import views as auth_views
path('login/',auth_views.LoginView.as_view(template_name='website/login.html'), name='login-page'),
but using this methode i don't have a view inside my views.py file. the problem is i need to define a view inside my viwes.py to record logs for any one accessing this page the problem is when i tried the following code i get the error "'function' object has no attribute 'get'"
the code that gives me the error is as the following:
views.py
from django.contrib.auth import views as auth_views
def login(request):
ip = get_client_ip(request)
logger.info(f'user access: {request.user} via ip:{ip}')
return auth_views.LoginView.as_view(template_name='website/login.html')
urls.py
path('login/',views.login, name='login-page'),
.LoginView.as_view() does not process the request, it simply returns a function that will dispatch the request, you thus need to call the function that is the result of .as_view(…) with the request as parameter:
from django.contrib.auth import views as auth_views
def login(request):
ip = get_client_ip(request)
logger.info(f'user access: {request.user} via ip:{ip}')
return auth_views.LoginView.as_view(template_name='website/login.html')(request)
That being said, it looks a bit odd to do this. Why not just subclass the LoginView and register that view?
You thus can do this with:
# appname/views.py
from django.contrib.auth.views import LoginView
class MyLoginView(LoginView):
template_name='website/login.html'
def setup(self, request, *args, **kwargs):
super().setup(request, *args, **kwargs)
ip = get_client_ip(request)
logger.info(f'user access: {request.user} via ip:{ip}')
and then register your MyLoginView instead:
from appname.views import MyLoginView
path('login/', MyLoginView.as_view(), name='login-page'),

How can i make a post request to a rest api endpoint and the request to save my form in a view file in django?

So i am trying to send a JSON file to a rest API endpoint and i am trying to use the requests library and it doesn't work.
Also in the function i have a return render to another page, because when i save a form i want also to send a request to the rest api to send an email and they only send emails via the endpoint.
from django.shortcuts import render
from django.views.generic import View
from Upload_Page import models
from django.core.files.storage import FileSystemStorage
from Upload_Page.forms import Upload_Document
from django.shortcuts import redirect
#from django.core.mail import send_mail
from Upload_Page.mail import mail_class
import requests
import json
def upload_doc(request):
if request.method == 'POST':
form = Upload_Document(request.POST, request.FILES)
if form.is_valid():
form.save()
mail=mail_class()
jsonmail=mail.createSimpleMail()
requests.post("http://mail.internal.de1.bosch-iot-cloud.com:80/email",data=json.dumps(jsonmail))
#send_mail('Title','Body','DigitalLibrary.BoschECC#bosch.com',['fixed-term.Razvan.Sabou#ro.bosch.com'],fail_silently=False)
return render(request,'Upload_Page/upload_successful.html')
else:
form = Upload_Document(auto_id=True,label_suffix='')
return render(request, 'Upload_Page/upload_page.html', {'form':form})
So this is the code, and i do not know why it doesn't send the post request, i checked the terminal to see what requests are made and the request from the requests it doesn't appear.
I've searched but i am new in django and Rest API and i didn't find the answer for my problem, if you need any more information i can provide it to you.
So thank you for the answer and have a good day.

Django AllAuth - How to manually send a reset-password email?

In my application I am using Django Allauth. I don't have any registration form for users. The admin is going to register users by uploading an excel file that contains user info. I have done all of this and users are saved in the user table by auto generating passwords. After I upload user lists and save them in database, I want to send a reset password email to each user.
In allauth to reset password you first need to go to reset page account/password/reset/ and type your email. then an email is send which directs you to change your password account/password/reset/key/(?P<uidb36>[0-9A-Za-z]+)-(?P<key>.+)/
Is it possible to send the email directly within the app? The url contains a key that I don't know how to generate!! Or is there any better way to do that?
It's possible. My solution implements a User model post_save signal to call the Allauth Password reset view which will send the user the email. The first thing to consider is to make the user email address mandatory in the admin user create form (as explained here). And then use this code:
from allauth.account.views import PasswordResetView
from django.conf import settings
from django.dispatch import receiver
from django.http import HttpRequest
from django.middleware.csrf import get_token
#receiver(models.signals.post_save, sender=settings.AUTH_USER_MODEL)
def send_reset_password_email(sender, instance, created, **kwargs):
if created:
# First create a post request to pass to the view
request = HttpRequest()
request.method = 'POST'
# add the absolute url to be be included in email
if settings.DEBUG:
request.META['HTTP_HOST'] = '127.0.0.1:8000'
else:
request.META['HTTP_HOST'] = 'www.mysite.com'
# pass the post form data
request.POST = {
'email': instance.email,
'csrfmiddlewaretoken': get_token(HttpRequest())
}
PasswordResetView.as_view()(request) # email will be sent!
You can try to get URL for specific user using something like this:
from allauth.account.forms import EmailAwarePasswordResetTokenGenerator
from allauth.account.utils import user_pk_to_url_str
token_generator = EmailAwarePasswordResetTokenGenerator()
user = User.objects.get(email='example#example.com')
temp_key = token_generator.make_token(user)
path = reverse("account_reset_password_from_key",
kwargs=dict(uidb36=user_pk_to_url_str(user), key=temp_key))
Following from #davecaputo's answer, you can also directly submit the form instead of creating and calling the view:
from allauth.account.forms import ResetPasswordForm
from django.conf import settings
from django.http import HttpRequest
def send_password_reset(user: settings.AUTH_USER_MODEL):
request = HttpRequest()
request.user = user
request.META["HTTP_HOST"] = "www.mysite.com"
form = ResetPasswordForm({"email": user.email})
if form.is_valid():
form.save(request)

Python/Django - How to get the page URL before navigating to a new view

I have a link that links to a url, like so:
Sign in
This links to a new view in Django, my URL pattern looks like this:
url(r'^sign-in/', sign_in, name="sign_in")
In my sign_in view, I would like to have access to the URL where the user originally clicked the link. Specifically, I would like to add this URL has a parameter called returnUrl to a new URL. My sign_in view can then redirect to this new URL, and the corresponding view will have access to the returnUrl parameter.
For example:
The user clicks 'Sign in'
The website navigates to example.com/sign-in/
The sign_in view redirects to sign_in_page adding the URL from step 1 as a parameter.
sign_in_page has access to the URL parameter.
How can I achieve this in Django? My views look like this...
from django.http import HttpResponse
from django.shortcuts import render, redirect
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from django.core.urlresolvers import resolve
def sign_in(request):
# I need the original URL the user came from here
# to add it as `returnUrl` below:
return HttpResponseRedirect(reverse('sign_in_page') + '?returnUrl=example.com/whatever')
def sign_in_page(request):
return render(request, 'sign-in.html')
Please let me know if I'm going down a wrong and dark path by using a redirect. To me it seemed like the only way to add a URL parameter - which is important for my implementation. If you know of a way to do it without the redirect - let me know!
If you want to pass data between views, you may use either POST data or GET. In your case GET data is what you want.
So you should use the following URL.
"{% url 'sign_in' %}?returnUrl={{request.path}}"
Then after in your view:
check if GET variable 'returnUrl' was sent
redirect to the next URL
else redirect to the default page
In the following example I am using Class based View inherited from FormView
def get_success_url(self):
if self.request.GET.get('next', ''):
return (self.request.GET.get('next', ''))
return reverse_lazy('experiment_list')
Note: make sure you include the following in your settings, to make sure you get the request.path variable in each template:
## example: settings.py
TEMPLATE_CONTEXT_PROCESSORS = (
# other items...
'django.core.context_processors.request',
# other items...
)
If you want to redirect to referer, Then you can try like this
from django.http import HttpResponseRedirect
def sign_in(request):
# Do your logic here
return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
referer = self.request.META.get('HTTP_REFERER')
try this in the view where you need to get the previous url, hope this is what you are looking for

Categories

Resources