Django Automatically Logging Out User , when he goes to Registration Page - django

Thanks In Advance.
I am facing an Issue in one of my Django Website. Here an authenticated user can access the Registration Page. But the client raised it as an issue. So I have tried to rectify that Issue and ended up with the following Solution.
Is it a good solution? Or how can I make it good?
The Process should be like this, when a loginned user try to access the Registration Page, he should be automatically Logged Out from the Site and then redirected to the Registration Page.
My code is
def user_signup(request, template_name='profiles/profile_register_form.html'):
if request.user.is_authenticated():
return custom_logout(request, next_page = "/accounts/register/")
def custom_logout(request, next_page='/'):
try:
language = request.session['django_language']
except:
language = False
response = logout(request, next_page=next_page)
if language:
request.session['django_language'] = language
return response

if i understood your question then
why custom_logout
you can call directly django logout like
if request.user.is_authenticated():
logout(request)
return HttpResponseRedirect('/login/') # whatever you register page

Your method was correct. It will save the current language session and will do the exact process you need

Related

Django Authentication Application

I've just started to the django and got a little lost in between various doumentations and outdated tutorials.
What I want to achieve is to create a simple dashboard application that also contains some backend scripts to integrate various apis most of them are open API's like weather API's , calendar API's etc just for learning.
But I need to create a login page for the application and current tutorials for the authentication mosule of django is a little bit cunfusing as it never gives me how to implemelent a login form to the auth backend. I need a little bir more simple documentation for that.
Is there anyone able to help me on that. I know the question is not code related but still any help will be appriceated. Most of findings from my previous searches are outdated and implementing those methods are often causes errors like non-existent templates etc...
Meanwhile I'll be also checking the offical documentation.
Thank you.
So it depends what view you use to handle login as there are two types of views Class based and function based. I use Function based so I shall explain you with that.
First you should set up an html page that will have the form to take the details of the username and password. I assume you know how to do that and how to handle the form in the html (if not please comment is shall explain you that too). So now the view that will handle the login authentication is below
from django.contrib.auth import login,authenticate
def login_page(request):
if request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('password')
user = authenticate(request, username= username, password= password)
if user is not None:
login(request, user)
return redirect('any_page_you_want_to_send_the_user')
else:
return render(request, 'login.html')
So what the above code does is that it accepts a POST request that you send from your login form and then it gets the username and password from that form. Then it uses the django's authenticate function to authenticate the user. It then checks if the there is actually an user or it is None(doesn't exists). And if the condition is true, it logs in the current user.

Session variable in one route exists, and in other is None

Currently I'm working on a project where I'm using React as frontend and Django as backend. In react i created a login page, where I through axios send files to django, and in this route index i sent all the information from the login page, and define a session variable reqeuset.session['id']=150 in it. But when i call reqeust.session['id'] in a diffrent route, it says that it is type None.
This is the code:
#api_view(['POST'])
def index(request):
data=request.data.get('data')
korisnik = Korisnik.objects.filter(korisnicko_ime=data.get('user'),
if korisnik.exists():
korisnik_json=serializers.serialize('json',korisnik)
request.session['id']=150
print(request.session['id'])
# if not request.session.session_key:
# request.session.create()
return HttpResponse(korisnik_json)
else: return HttpResponse(status=404)
#api_view(['GET'])
def korisnik(request,id):
print(request.session.get('id'))
korisnik=Korisnik.objects.filter(pk=id)
korisnik_json=serializers.serialize('json',korisnik)
return HttpResponse(korisnik_json)
This is the output from python console
Image
Also note, I'm using django restframework. Did anyone, have this problem before, any help is appreciated.
I had faced a similar issue. Please check my answer here.
React Django REST framework session is not persisting/working

Flask: Clear session from admin prospective

In my flask app, logout can clear the session.
#app.route('/logout')
def logout():
session.clear()
return redirect(url_for('index'))
But logout is called only when user click logout on my website.
I am implementing a functionality where i can block a mysterious user. So, i need to force logout the user without his consent. My logic would also work if i can clear his session. Please guide.
Note: someone suggested to change app.secret_key. But that would clear session for all users and not a particular user only.
So you have to check out if user is banned or not before each request!
#app.before_request
def before_request():
user = findUser()
if user.isBanned():
return redirect(url_for('logout'))
Something like this would work,
Ofc you have to implant findUser and isBanned, findUser should return a User object, and isBanned should return True or False

Django process_view middleware resulting in 403 forbidden

I've written a small bit of middleware that catches if a user is using a temporary password and, if so, redirects them to a page that forces them to create a new password. My problem is that the page works fine when the user is logged in and NOT using a temp password (i.e. they go to the change password URL manually), but when they ARE using a temp password the redirect from the middleware yields a 403 Forbidden page.
The middleware does one other thing in process_view after the temp password check, but this is the relevant code:
class MyMiddleware( object ):
def process_view( self, request, view_func, view_args, view_kwargs ):
if request.user.is_authenticated( ):
try:
if request.user.get_profile( ).using_temp:
return HttpResponseRedirect( reverse( 'change_password' ) )
except Object.DoesNotExist:
pass
# Not using temp password, let the request process
return None
Note that rendering the template directly could be used, with something like render_to_response, to fix the problem but that will cause the browser's URL to not follow as well as it not being able to really exit the page it renders.
First, I think your indenting is off in the example, but how about the following as a solution to detect when the current path is the change_password URL? This should get rid of that infinite redirect you have going on.
class MyMiddleware( object ):
def process_view( self, request, view_func, view_args, view_kwargs ):
if request.user.is_authenticated( ):
try:
if request.user.get_profile( ).using_temp and request.path != reverse('change_password'):
return HttpResponseRedirect( reverse( 'change_password' ) )
except Object.DoesNotExist:
pass
# Not using temp password, let the request process
return None
Which version of django are you using ?
If your are using the latest beta, setting the logging may be helpful
http://docs.djangoproject.com/en/dev/topics/logging/
Django Debug Toolbar might be helpful here. It can trap redirects and show you where it's redirecting before actually going there. This helps run down broken redirects.
That said, I'd recommend using a different "change password" page for users with temporary passwords, so it can handle permissions checking differently. The page you have might have a #login_required decorator, and a temporary password might not be considered "really" logged in.

Django, restrict access to registration success page

This is something I've wondered about in a couple of frameworks that I've messed around with. Assuming I don't want to automatically log a user in when they register (I want them to activate) how can I make it so a user can't just visit the "register-success" page? Right now, here's what I have:
def register(request):
if request.method == 'POST':
rf = forms.RegisterForm(request.POST)#register form
pf = forms.ProfileForm(request.POST)#profile form (additional info)
lf = forms.LoginForm()#login form is also on this page but is empty when registering
if rf.is_valid() and pf.is_valid():
newuser = User(username=rf.cleaned_data['username'],email=rf.cleaned_data['email'])
newuser.set_password(rf.cleaned_data['password'])
newuser.save()
#need to mark newuser as inactive still
profile = pf.save(commit=False)
profile.user = newuser
profile.save()
return HttpResponseRedirect("/register-success/")
return render_to_response("authentication/index.html", {'rform': rf, 'pform':pf,'lform':lf})
return main(request)
def register_success(request):
return render_to_response("authentication/register-success.html")
My url-conf:
(r'^register-success/$','register_success'),
The other way I thought to do it was to just render_to_response("authentication/register-success.html") and not do the redirect. The benefit is, no one can access the register-success.html page, the downside is if the user refreshes the page it will try and resubmit the POST. What's the best practice?
I would stick with the redirect, getting duplicate users is a fairly large risk. What is the risk of someone seeing your register success page who hasn't registered? If there is a risk, you could always generate a random token, put it in session and pass it to your register-success page and then in your view check that the token matches. But that seems like a lot of work for what typical success pages are.
My recommendation would be to not worry about people being able to get to that page without registering. If it is just static HTML, there can't be any risk with showing to to everybody, right?
You can set the cookie, a session key in register view that you can check for in the register_success view only on its presence render the page, else redirect to main register.