Django PreCourse 3-3) Login & Logout

Turtle·2023년 12월 21일
0
post-thumbnail

📌Authentication in web requests

  • Django는 세션과 미들웨어를 사용하여 인증 시스템을 요청 개체에 연결한다.
  • 이는 현재 사용자를 나타내는 모든 요청에 대해 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(request=None, **credentials)

  • authenticate()을 사용하여 일련의 자격 증명을 확인한다.
  • 기본적으로 사용자 이름과 비밀번호를 사용하여 각 인증 백엔드에 대해 체크하고 만약 자격 증명이 유효한 경우 User 개체를 반환한다. 만약 자격 증명이 유효하지 않거나 백엔드가 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
    ...

📌Displaying messages

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 %}

  • 위와 같이 에러 메시지가 템플릿에 잘 출력되는 것을 확인할 수 있다.

📌How to log a user out

  • 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('/')

📌Django Settings

  • 우리가 일반적으로 로그인이나 로그아웃을 하면 메인 페이지로 돌아오는 경우를 보았을 것이다. Django에서도 로그인이나 로그아웃 후의 URL을 지정할 수 있다.

LOGIN_REDIRECT_URL

LOGIN_URL

LOGOUT_REDIRECT_URL

  • 추후 뒤에서도 배우겠지만 Authentication in web requests 방식과 pip를 통해 설치할 수 있는 django-allauth 방식은 각각 차이점이 존재한다. 이는 나중에...

0개의 댓글