티스토리 뷰

django 비밀번호 변경

놀랍게도 그동안 비밀번호 변경 기능을 만들지 않고 있었다.

비밀번호를 관리자가 아닌 사용자가 변경할 방법이 없었다.

관리자한테 비밀번호를 바꿔달라고 요청해야 하는데, 관리자에게 비밀번호를 알려주는 상황이 발생한다.

비밀번호는 비밀인데?

 

비밀번호를 변경하는 기능을 넣는 게 엄청 쉬운 일은 아니다.

고려해야 하는 게 좀 있다.

기존 비밀번호가 맞는지 확인하고, 새 비밀번호가 형식에 맞는지 확인하고, 그걸 암호화해서 저장하고, 그 후에 유저 로그인을 다시 해준다.

(생각해보니 엄청 어려울 거 같지는 않기도)

이런 상황은 일어나면 안된다.

 

어쨌든 django에서 기본으로 지원해주는 비밀번호 변경 form이 있다.

그걸 사용하면 매우 간단하므로, 그대로 사용할 거다.

 

참고한 사이트는 여기다.

 

djagno 기본 비밀번호 변경 form

from django.contrib.auth.forms import PasswordChangeForm

얘가 핵심이다.

 

# views.py
from django.contrib import messages
from django.contrib.auth import update_session_auth_hash
from django.contrib.auth.forms import PasswordChangeForm
from django.shortcuts import render, redirect

@login_required
def change_password(request):
    if request.method == 'POST':
        form = PasswordChangeForm(request.user, request.POST)
        if form.is_valid():
            user = form.save()
            update_session_auth_hash(request, user)  # Important!
            messages.success(request, 'Your password was successfully updated!')
            return redirect('index')
        else:
            messages.error(request, 'Please correct the error below.')
    else:
        form = PasswordChangeForm(request.user)
    return render(request, 'taxi/change_password.html', {
        'form': form
    })
    
    
#urls.py
from django.conf.urls import url
from myproject.accounts import views

urlpatterns = [
    url(r'^change_password/$', views.change_password, name='change_password'),
]

딱히 특별한 건 없는데, update_session_auth_hash를 해줘야 비밀번호 변경 후에 자동으로 로그인을 시켜준다고 한다.

이게 없으면 다시 로그인을 해야하는 것이다.

@login_required는 decorator로, 여길 참고하면 된다.

 

이제 taxi/change_password.html을 만들 차례다.

<!--taxi/change_password.html-->

{% extends 'taxi/base.html' %}

{% block content %}

{% include 'taxi/messages.html' %}

<h2 style="text-align:center;">비밀번호 변경</h2>
{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}
<form method="post" style="text-align:center;">
  {% csrf_token %}
  {{ form }}
  <button type="submit">Save changes</button>
</form>

{% endblock %}

기본 base html을 넣고, form을 불러오면 끝이다.

정말 뭐 별로 없다.

 

그래서 taxi/change_password url로 접속해보면 제대로 화면이 뜨는 걸 볼 수 있다.

 

자, 직관적으로 회원정보 수정페이지에서 비밀번호 변경 버튼이 있는 게 자연스럽다.

그러므로 이제 회원정보 수정페이지에 버튼을 넣자

 

{% extends 'taxi/base.html' %}

{% block content %}

{% include 'taxi/messages.html' %}

<h2>회원정보 수정</h2>

<div class="id_box">
  <h3>ID : {{ request.user.username }}</h3>
</div>

<form method="post" action="{% url 'taxi:edit_user' %}" class="form-horizontal">
  <div class="input-group">
    {% csrf_token %}
    {{ user_form.as_p }}
    {{ profile_form.as_p }}

    <input type="button" value="취소" onClick="javascript:history.go(-1);">
    <input type="submit" value="수정" />
    <button type="button" name="change_password" onClick="location.href='{% url 'taxi:change_password'%}'">비밀번호 변경</button>

    {% if request.user.profile.email_confirmed == False %}
    <button type="button" name="resend_mail" onClick="location.href='{% url 'taxi:resend_mail'%}'">인증메일 다시 보내기</button>
    {% endif %}
  </div>

</form>

{% endblock %}

 

<button>에 onClick으로 href를 줬다.

그러면 taxi/urls.py에 있는 change_password url로 연결될 것이다.

 

끝!

댓글