AI 본캠프/TIL

24/01/22 TIL(17주차 수요일) - html

impact7608 2025. 1. 22. 22:51
<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>사용자 프로필</title>
</head>
<body>
    {% if user.is_authenticated %}
        <div class="container mt-5">
            <h1 class="mb-4">사용자 프로필</h1>

            <!-- 메시지 출력 -->
            {% if messages %}
                <div>
                    {% for message in messages %}
                        <div class="alert alert-{{ message.tags }} alert-dismissible fade show" role="alert">
                            {{ message }}
                            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                        </div>
                    {% endfor %}
                </div>
            {% endif %}

            <!-- 사용자 정보 -->
            <div class="card mb-4">
                <div class="card-body">
                    <h5 class="card-title">사용자 정보</h5>
                    <p class="card-text">아이디: {{ request.user.username }}</p>
                    <p class="card-text">이메일: {{ request.user.email }}</p>
                </div>
            </div>

            <!-- 비밀번호 변경 -->
<div class="card mb-4">
    <div class="card-body">
        <h5 class="card-title">비밀번호 변경</h5>
        <form id="password-change-form">
            {% csrf_token %}
            <div class="mb-3">
                <label for="id_old_password" class="form-label">현재 비밀번호</label>
                <input type="password" name="old_password" id="id_old_password" class="form-control" required>
            </div>
            <div class="mb-3 position-relative">
                <label for="id_new_password1" class="form-label">새 비밀번호</label>
                <input type="password" name="new_password1" id="id_new_password1" class="form-control" required>
                <small class="form-text text-muted">8자 이상, 숫자 및 특수 문자를 포함해야 합니다.</small>
                <button type="button" class="btn btn-sm btn-outline-secondary position-absolute top-50 end-0 translate-middle-y"
                        onclick="togglePasswordVisibility('id_new_password1')">👁️</button>
            </div>
            <div class="mb-3 position-relative">
                <label for="id_new_password2" class="form-label">새 비밀번호 확인</label>
                <input type="password" name="new_password2" id="id_new_password2" class="form-control" required>
                <button type="button" class="btn btn-sm btn-outline-secondary position-absolute top-50 end-0 translate-middle-y"
                        onclick="togglePasswordVisibility('id_new_password2')">👁️</button>
            </div>
            <button type="submit" class="btn btn-primary w-100">비밀번호 변경</button>
        </form>
    </div>
</div>

<script>
    document.getElementById("password-change-form").addEventListener("submit", function (event) {
    event.preventDefault(); // 기본 폼 제출 방지

    const form = event.target;
    const formData = new FormData(form);

    fetch("{% url 'password_change' %}", {
        method: "POST",
        headers: {
            "X-CSRFToken": document.querySelector('[name=csrfmiddlewaretoken]').value,
        },
        body: formData,
    })
    .then(response => {
        if (!response.ok) {
            // 응답 상태가 실패일 경우 에러 처리
            return response.json().then(errorData => {
                throw new Error(JSON.stringify(errorData.errors));
            });
        }
        return response.json(); // JSON 응답 처리
    })
    .then(data => {
        if (data.success) {
            alert(data.message); // 성공 메시지
            window.location.href = "{% url 'profile' %}"; // 성공 시 리다이렉트
        } else {
            alert("비밀번호 변경에 실패했습니다. 다시 시도해 주세요.");
            console.error("Errors:", data.errors); // 서버에서 반환된 에러 로그
        }
    })
    .catch(error => {
        console.error("Error details:", error);
        alert("서버와의 통신 중 문제가 발생했습니다. 다시 시도해 주세요."); // 실패 시 표시할 메시지
    });
});
</script>

            <!-- 로그아웃 -->
            <div class="card mb-4">
                <div class="card-body">
                    <h5 class="card-title">로그아웃</h5>
                    <form method="post" action="{% url 'logout' %}">
                        {% csrf_token %}
                        <button type="submit" class="btn btn-secondary">로그아웃</button>
                    </form>
                </div>
            </div>

            <!-- 계정 삭제 -->
            <div class="card mb-4">
                <div class="card-body">
                    <h5 class="card-title">회원 탈퇴</h5>
                    <form method="post" action="{% url 'delete_account' %}">
                        {% csrf_token %}
                        <button type="submit" class="btn btn-danger"
                                onclick="return confirm('정말 탈퇴하시겠습니까? 이 작업은 되돌릴 수 없습니다.')">
                            회원 탈퇴
                        </button>
                    </form>
                </div>
            </div>
        </div>
    {% else %}
        <script>
            window.location.href = "{% url 'login' %}";
        </script>
    {% endif %}
   
    <script>
        // 비밀번호 가시성 토글 기능
        function togglePasswordVisibility(inputId) {
            const passwordField = document.getElementById(inputId);
            passwordField.type = passwordField.type === "password" ? "text" : "password";
        }
    </script>
    <script>
        document.getElementById('id_new_password1').addEventListener('input', function () {
            const password = this.value;
            const message = password.length >= 8 ? "사용 가능한 비밀번호입니다." : "비밀번호는 최소 8자 이상이어야 합니다.";
            document.getElementById('password-feedback').textContent = message;
        });
    </script>
</body>
</html>