request.user
속성과 request.auser
비동기 속성을 제공한다. 만약 현재 사용자가 로그인하지 않은 경우 이 속성은 AnonymousUser의 인스턴스로 설정이 되고 그렇지 않으면 User의 인스턴스가 된다.is_authenticated
로 구분할 수 있다.if request.user.is_authenticated:
# Do something for authenticated users.
...
else:
# Do something for anonymous users.
...
login()
함수를 사용하여 수행한다.from django.contrib.auth import authenticate, login
def my_view(request):
username = request.POST["username"]
password = request.POST["password"]
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
# Redirect to a success page.
...
else:
# Return an 'invalid login' error message.
...
from django.shortcuts import render, redirect
from django.http import HttpResponse, HttpResponseRedirect
from django.contrib.auth.models import User
from django.contrib import auth
from django.contrib import messages
from .forms import RegisterForm, LoginForm, ApplicationForm
from django.db.models import ObjectDoesNotExist
from .models import Application
def login(request):
if request.method == "POST":
form = LoginForm(request.POST)
if form.is_valid():
email = form.cleaned_data['email']
password = form.cleaned_data['password']
user = auth.authenticate(username=email, password=password)
# 로그인 성공한 경우
if user:
# 세션에 로그인을 처리 후 첫 페이지로 리다이렉트
auth.login(request, user)
return HttpResponseRedirect('/')
# 로그인 실패한 경우
else:
messages.warning(request, "이메일 혹은 패스워드를 다시 확인하세요.")
else:
form = LoginForm()
context = {
'form' : form,
}
return render(request, 'Myapp/login.html', context)
authenticate()
을 사용하여 일련의 자격 증명을 확인한다.raise
를 이용해서 PermissionDenied
에러를 발생시킨 경우라면 None을 반환한다.from django.contrib.auth import authenticate
user = authenticate(username="john", password="secret")
if user is not None:
# A backend authenticated the credentials
...
else:
# No backend authenticated the credentials
...
messages.warning(request, "이메일 혹은 패스워드를 다시 확인하세요.")
views.py
에서 이와 같이 작성을 한 다음 출력하고자하는 템플릿에서 템플릿 Syntax를 사용해 작성하면 된다.{% if messages %}
<div class="mt-2">
<ul class="message">
{% for message in messages %}
<div class="alert alert-{{ message.tags }}" role="alert">
{{ message }}
</div>
{% endfor %}
</ul>
</div>
{% endif %}
django.contrib.auth.login()
을 통해 로그인한 사용자를 로그아웃하려면 뷰 내에서 django.contrib.auth.logout()
을 사용하면 되며 반환값이 따로 없다.logout()
을 호출하면 현재 요청에 대한 세션 데이터가 완전히 지워진다. 기존의 데이터가 모두 지워진다는 것이다. 이는 다른 사람이 동일한 웹 브라우저로 로그인하여 이전 사용자의 세션 데이터에 접근하는 것을 방지하기 위한 것이다. from django.contrib.auth import logout
def logout_view(request):
logout(request)
# Redirect to a success page.
def logout(request):
auth.logout(request)
return HttpResponseRedirect('/')
LOGIN_REDIRECT_URL
LOGIN_URL
LOGOUT_REDIRECT_URL
django-allauth
방식은 각각 차이점이 존재한다. 이는 나중에...