본문 바로가기

프로그래밍/Back-end

Django 유저 인증 시스템

참고:

https://docs.djangoproject.com/ko/4.2/topics/auth/default/

 

Django

The web framework for perfectionists with deadlines.

docs.djangoproject.com

사용자 생성하기

>>> from django.contrib.auth.models import User
>>> user = User.objects.create_user("john", "lennon@thebeatles.com", "johnpassword")

# At this point, user is a User object that has already been saved
# to the database. You can continue to change its attributes
# if you want to change other fields.
>>> user.last_name = "Lennon"
>>> user.save()

패스워드 변경하기

>>> from django.contrib.auth.models import User
>>> u = User.objects.get(username="john")
>>> u.set_password("new password")
>>> u.save()

사용자 인증하기

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

패스워드 변경시 세션 무효화

# update_session_auth_hash(request, user)
# 이 함수는 현재 요청과 새 세션 해시가 파생될 업데이트된 사용자 객체를 가져오고 세션 해시를 적절하게 업데이트한다. 또한 도난당한 세션 쿠키가 무효화되도록 세션 키를 교체한다.

from django.contrib.auth import update_session_auth_hash


def password_change(request):
    if request.method == "POST":
        form = PasswordChangeForm(user=request.user, data=request.POST)
        if form.is_valid():
            form.save()
            update_session_auth_hash(request, form.user)
    else:
        ...