Django 유저 인증 시스템

2023. 9. 20. 09:43·프로그래밍/Back-end

참고:

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:
        ...

'프로그래밍 > Back-end' 카테고리의 다른 글

docker + postgresql 파헤치기  (0) 2022.08.26
윈도우 배치 파일 만들기  (0) 2022.08.25
[Django] Do it 장고 파헤치기 - 2 # ListView  (0) 2022.08.22
[Django] Do it 장고 파헤치기 - 1 # admin  (0) 2022.08.19
[Python] venv 설정하기  (0) 2022.08.19
'프로그래밍/Back-end' 카테고리의 다른 글
  • docker + postgresql 파헤치기
  • 윈도우 배치 파일 만들기
  • [Django] Do it 장고 파헤치기 - 2 # ListView
  • [Django] Do it 장고 파헤치기 - 1 # admin
블루풀
블루풀
  • 블루풀
    [ IT] Be Dreamer
    블루풀
  • 전체
    오늘
    어제
    • 분류 전체보기 (35)
      • 프로그래밍 (33)
        • ChatGPT Q&A (0)
        • 안드로이드 스튜디오 (1)
        • 알고리즘(자바) (23)
        • GitHub (0)
        • Front-end (2)
        • Back-end (6)
        • 개발자 Basic English (1)
      • 취업정보 (0)
      • 일상 (1)
  • 블로그 메뉴

    • 홈
    • 태그
    • 미디어로그
    • 위치로그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    admin
    emmet
    ListView
    여행
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
블루풀
Django 유저 인증 시스템
상단으로

티스토리툴바