Redirect From REST_API Response - django

I am using Angular and Django in my stack for a website, and after a user registers it emails them a link to activate their account. As of right now everything is working but the link takes the user to the Django rest framework page.
I've been returning responses in my app like this
data = {'success': True, 'message': 'An account has been activated.', 'response': {}}
return Response(data, status=status.HTTP_201_CREATED)
I am curious on how to redirect a user back to the login page which at the current moment would be a localhost page such as http://localhost:4200/#/authentication/login.
From research I have found methods like
return redirect('http://localhost:4200/#/authentication/login')
but I am wanting to keep my responses consistent. Is there a way to redirect a user while still using the rest api Response object?

After thinking about the comment posted by Muhammad Hassan, I realized I was thinking about this all wrong. Instead of sending a Django url I have change the email to send a URL to an Angular page I made and then I just sent an HTTP request from that page to the Django URL.

Related

How to get POST parameters in a Django view protected by #login_required?

Django's login_required decorator requires a login before proceeding to any functionality in a view function. If a user is not logged in, they will be redirected through a login screen.
If the HTTP request is a GET, Django sometimes puts the GET destination in a parameter ("next"). Or, Django also has a LOGIN_REDIRECT_URL setting that is a URL a user is forwarded to after login.
If the HTTP request is a POST, that POST data is lost during the login process.
What is the best way to preserve the original URL and POST data for the original POST request, and re-post that data after the user is logged in?
I imagine putting something in a session, but I'd have to intercept the POST data and URL on the way through login_required. The best practice is not obvious to me.

Djoser password reset implementation

I am using djosers for my authentication on django backend which eventually i'll be connecting to flutter frontend and i am having trouble implementing the password reset functionality...
from what i have understood, first i need to hit the /users/reset_password/ with email body which will eventually give me the token of authentication which will be used further on confirm reset but the first thing i dont understand is PASSWORD_RESET_CONFIRM_URL field in the settings, like it needs a front end link with uid and token placeholders but what is this token field and what is this PASSWORD_RESET_CONFIRM_URL but i managed to look over a stack overflow question and filled it but now when i hit /users/reset_password/ i get this error:
[WinError 10013] An attempt was made to access a socket in a way forbidden by its access permissions
settings:
DJOSER = {
'PASSWORD_RESET_CONFIRM_URL':'reset/password/reset/confirm/{uid}/{token}',
'LOGIN_FIELD' : 'email',
'USER_CREATE_PASSWORD_RETYPE' : True,
'SERIALIZERS': {
'user_create': 'auth_app.serializers.UseriCreateSerializer',
'user': 'auth_app.serializers.UserCreateSerializer',
}
}
urls.py:
urlpatterns = [
path('',home,name='home'),
path('addInForum/',addInForum,name='addInForum'),
path('addInDiscussion/',addInDiscussion,name='addInDiscussion'),
path('<str:forum_id>/getDiscussion/',getDiscussion,name='getDiscussion'),
path('getDate/',getDate,name='getDate'),
path('reset/password/reset/confirm/<str:uid>/<str:token>/',PasswordResetView,name='PasswordResetView'),
# url(r'^reset/password/reset/confirm/(?P<uid>[\w-]+)/(?P<token>[\w-]+)/$', PasswordResetView.as_view(),),
]
views.py
#api_view(['GET'])
def PasswordResetView(request,uid,token):
post_data = {'uid': uid, 'token': token}
return Response(post_data)
Please remember that djoser should be part of your REST API based on Django REST Framework. You also need to think differently about the url routing in regard of your frontend app..
Usually urls in the form mydomain.com/some_url/whatever are considered "frontend urls" and parsed by routing of your frontend app. On the other hand urls in the form mydomain.com/api/something are considered API urls that are routed via Django's urls.py. I will refer to them as Fronted_URL and API_URL respectively.
So: resetting password works like this. The user that forgot their password and wants to reset it, surely needs to fill some king of form. This form needs to be sent to APIURL returned by resolve('user-reset-password') (by default this returns something like /users/reset_password/)
Here comes PASSWORD_RESET_CONFIRM_URL setting. Because after the body is accepted by the APIURL mentioned above, a mail will be sent to the user with a link that will point to URL entered in that setting. And it has to be FrontendURL! It should be routed by your frontend APP and preferably display some screen. But in the background your frontend app should send the values of uid and token fields to APIURL returned by resolve("user-reset-password-confirm").
This flow allows your frontend app to properly handle the response and display appropriate message to the user and then maybe redirect them to some other screen.
If you don't have a routed frontend app (probably written using REACT, ANGULAR or VUE) then you probably don't need a REST API and should just stick to django-allauth.

Get token from URL in Django. TDAmeritrade API Call

Ok,
I'm developing a website where I'm using Django. The website is for creating and keep track of stock portfolios. I have the database and the basics of the website set up but I would like to use the TDAmeritrade API in order to get the stock information. How it works is the user is redirected to TD where they enter there Login and Password they accept the terms and get transferred to a redirect page of the local host (until it goes live). Which looks a little like this
"https://127.0.0.1:8000/?code=" with a huge code after the equals sign.
Finally, how would one create the URL destination in Django url.py file and store the code for AUTH Token
I've tried something like this: path('?code=', test_view, name='test'),
but had no luck but that could be because of this error (You're accessing the development server over HTTPS, but it only supports HTTP.)
Thanks in advance!
Side note: I've tried looking up how Paypal does there send back confirmation but all I could find were packages Pre-build for Django
I figured out the solution with the help of Moha369 in the comments, So shout out to him/her!
def home_view(request):
context= {}
user = request.user
if user.is_authenticated:
token = request.GET.get('code')
print(token)
return render(request, "home.html", context)
Django Docs that helped

Django session authentication failed sometimes

I'm having very weird issue with session authentication.
I'm using session authentication over DRF APIs for some legacy django views. And login process implemented with DRF and react app.
The server code for sign-in looks like this:
class AuthViewSet(viewsets.ViewSet):
def create(self, request, *args, **kwargs):
is_session_auth = request.data.get('session_auth', False)
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
token = serializer.save()
if is_session_auth is True:
login(request, token.user)
return Response(dict(token=token.key))
So, as far as I expected, the response should has set-cookie header which makes browser to set sessionid and csrftoken cookies. And it works well most of times.
But rarely, some users experiencing login failures. I'm faild to reproduce it, but this is what they describe:
When user submit sign in form, the request sent to the server and got response successfully.
Then the javascript app push url to login/complete, as expected.
But in login complete view, the request failed to authenticate. And the view redirect request to the original login view.
User retry login, but got same result.
I have no idea how this happened so rarely, to the so small amount of users. Am I miss something?
Thanks for help.
==============
Add some more information.
I dig into this problem, and find out that users' sessions are not decodable.
session.get_decoded() for session in Session.objects.all() returns Session data corrupted error. Is it relevant to login failure?

Django API for login/logout with S3 site is not creating cookies

I'm working with a static webpage hosted on S3 and I'm using a Django as my api for session management.
I have my JS code on S3 POSTing to django when users sign in to my web site but I'm not getting any cookies saved on my browser.
I'm not sure if it's the jQuery $.post that is not accepting cookies or if it's Django that's not allowing the sending of cookies. How would I overcome this?
I currently also have a url endpoint on my django app where I can check if cookies are working but when I hit the url I get the standard message
Please enable cookies and try again.
Although my browser accepts cookies.
I get these urls to work fine when I use a Django rendered page to interact with them.
Any help would be greatly appreciated - thanks
Edit - showing code:
I use Janrain to allow user to login via facebook, twitter, etc..
how Janrain works
user clicks sign in button, uses facebook/wtv to login
Janrain get's user data on their servers and gives you a token which I post to django via this function
janrain.events.onProviderLoginToken.addHandler(function(tokenResponse) {
$.ajax({
type: "POST",
url: post_form_url,
data: formdata + "&token=" + tokenResponse.token,
success: function(res, textStatus, jqXHR) {
//do stuff now that we are logged in ...
console.log(jqXHR.getResponseHeader('Set-Cookie')); //returns null
//$('#redirect').submit();
},
});
In Django
def login_via_janrain(request):
if request.method == "POST":
janrain_token = request.POST.get('token')
// communicate w/janrain api to get info from this token (i.e. who just logged in via this token)
#create (or pull) user based on data returned from janrain api and do a Django login
auth.login(request, user)
#return success msg to $.post (session cookies should be automatically included in the response)
return HttpResponse("success")
Using S3
I currently have a static site hosted on S3. I tested these urls using django rendered views but ultimately I want the S3 site to render the views and just use django as an api endpoint.
I can currently login from the S3 site but after a successful login I have no cookies to show for it... I think django isn't sending back cookies...