代码之家  ›  专栏  ›  技术社区  ›  GH00N

我想获得电子邮件身份验证

  •  0
  • GH00N  · 技术社区  · 2 年前

    实现了一个生成八个随机字符的身份验证号函数。

    我输入用户名和邮件。因为我想编写搜索密码html,并用Ajax在视图中请求它。

    当我输入用户名和电子邮件时,我希望将身份验证号码发送到电子邮件。同时,在ajax中创建的代码应该显示“身份验证号”窗口。 但是,什么也没发生。

    我该怎么办。。。? 帮助我!

    错误是 Uncaught SyntaxError: Unexpected token '<' 那是什么。。?

    首先,我纠正了白页。我错过了。”>'

    #html
    {% load static %}
    
    <!DOCTYPE html>
    <html lang="KO">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
    
        <link href="{% static 'users/css/recovery_pw.css' %}" rel="stylesheet">
        <link href="{% static 'users/css/default.css' %}" rel="stylesheet">
        <script
          src="https://kit.fontawesome.com/96379a54a1.js"
          crossorigin="anonymous"
        ></script>
        <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
        <script src="{% static 'users/js/recovery_pw.js' %}" </script>
        <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet">
    
    </head>
    <body>
        {% block content %}
        <form method="get" enctype="multipart/form-data">
            <div class="container">
              <div class="inner-box">
                  <div class="title">
                      <h1>비밀번호 찾기</h1>
                  </div>
                  <div class="input-box">
                      <div class="id">
                        <input type="email" placeholder="등록하신 메일로 인증번호가 발송됩니다." name="email" maxlenth="20" autocomplete="off" value="{{ form.email.value|default_if_none:'' }}" required />
                      </div>
                      <div class="password">
                        <input type="username" placeholder="아이디를 입력하세요" name="username" maxlength="20" value="{{ form.username.value|default_if_none:'' }}" required />
                      </div>
                  </div>
                  <div class="btn">
                      <div class="btn-white" id="btn_white"><button type="submit">임시 비밀번호 발송</button></div>
                  </div>
        
                  <div class="loading-box">
                      <div id="loading"></div>
                  </div>
        
              </div>
        
        </form>
    
        
        {% endblock %}
    </body>
    </html>
    
    #users/js/recovery_pw.js
    $(document).ready(function () {
        $('#find_pw').click(function () {
            $('#loading').replaceWith('<div id="loading_end" class="loading"></div>')
    
            // 걍 임의로 만든것 같음
            var name = $("#pw_form_name").val();
            var email = $("#pw_form_email").val();
    
            $.ajax({
                type: "POST",
                url: "/users/recovery/pw/find/",
                dataType: "json",
                data: {
                    'name': name,
                    'email': email,
                    'csrfmiddlewaretoken': '{{csrf_token}}',
                },
                success: function (response) {
                    // loading_end 이걸 지움
                    $('#loading_end').remove()
                    alert('회원님의 이메일로 인증코드를 발송하였습니다.');
    
                    // 나는 이메일전송버튼이지
                    $('#btn_white').remove()
                    $('#result_pw').replaceWith(
                        '<hr><div class="row justify-content-md-center"><form class="form-inline" style="margin-bottom:-15px; margin-top:-10px;"><div class="md-form md-outline"><label for="input_auth_num">인증번호 입력 (<span id="timeset"></span>)</label><input type="text" id="input_auth_num" class="form-control mx-sm-2" autofocus/></div></form>' +
                        '<button type="submit" name="auth_confirm" id="id_auth_confirm" class="btn btn-red" style="opacity: 90%; height:30%; margin-top:10px; font-size: 12px;"><i class="fas fa-check"></i>&nbsp;&nbsp;인증확인</button></div><hr>'
                    )
                    function countdown(elementName, minutes, seconds) {
                        var elementName, endTime, hours, mins, msLeft, time;
                        function twoDigits(n) {
                            return (n <= 9 ? "0" + n : n);
                        }
                        function updateTimer() {
                            msLeft = endTime - (+new Date);
                            if (msLeft < 1000) {
                                alert("인증시간이 초과되었습니다.");
                                $("" + elementName).remove();
                                cert_ok = false;
                                certificationNum = false;
                                location.href = "{% url 'recovery_pw' %}"
                            } else {
                                time = new Date(msLeft);
                                hours = time.getUTCHours();
                                mins = time.getUTCMinutes();
                                $("" + elementName).html((hours ? hours + ':' + twoDigits(mins) : twoDigits(mins))
                                    + ':' + twoDigits(time.getUTCSeconds()));
                                setTimeout(updateTimer, time.getUTCMilliseconds() + 500);
                            }
                        }
                        endTime = (+new Date) + 1000 * (60 * minutes + seconds) + 500;
                        updateTimer();
                    }
                    countdown("#timeset", 5, 0);
    
                    var user = response.result
    
                    $(document).ready(function () {
                        $('#id_auth_confirm').click(function () {
                            var input_auth_num = $("#input_auth_num").val();
    
                            $.ajax({
                                type: "POST",
                                url: "/users/recovery/pw/auth/",
                                dataType: "json",
                                data: {
                                    'input_auth_num': input_auth_num,
                                    'csrfmiddlewaretoken': '{{csrf_token}}',
                                },
                                success: function (response) {
                                    location.href = "{% url 'recovery_pw_reset' %}";
                                },
                                error: function () {
                                    if ($('#input_auth_num').val() == "") {
                                        alert('회원님의 이메일로 전송된 인증번호를 입력해주세요.');
                                    } else {
                                        alert('인증번호가 일치하지 않습니다.');
                                    }
                                },
                            });
                        })
                    })
                },
                error: function () {
                    $('#loading_end').remove()
                    if (username == "" || email == "") {
                        alert('이름, 이메일을 모두 입력해주세요.');
                    } else {
                        alert('입력하신 정보가 일치하지 않거나 존재하지 않습니다.');
                    }
                },
            });
        })
    });
    
    #views.py
    class RecoveryPwView(View):
        template_name = 'users/recovery_pw.html'
        recovery_pw = RecoveryPwForm
    
        def get(self, request):
            if request.method=='GET':
                form = self.recovery_pw(None)
                return render(request, self.template_name, { 'form':form, })
    
    
    def ajax_find_pw_view(request):
        username = request.POST.get('username')
        email = request.POST.get('email')
        target_user = User.objects.get(username=username, email=email)
    
        if target_user:
            auth_num = email_auth_num()
            target_user.auth = auth_num 
            target_user.save()
    
            send_mail(
                'this is email verify',
                ['email'],
                html=render_to_string('users/recovery_email.html', {
                    'auth_num': auth_num,
                }),
            )
        return HttpResponse(json.dumps({"result": target_user.username}, cls=DjangoJSONEncoder), content_type = "application/json")
    
    
    #urls.py
    path('recovery/pw/', RecoveryPwView.as_view(), name='recovery_pw'),
        path('recovery/pw/find/', views.ajax_find_pw_view, name='ajax_pw'),
        path('recovery/pw/auth/', views.auth_confirm_view, name='recovery_auth'),
        path('recovery/pw/reset/', views.auth_pw_reset_view, name='recovery_pw_reset'),
    
    form
    
    class RecoveryPwForm(forms.Form):
        username = forms.CharField(label='id')
        email = forms.EmailField(label='email')
    
        class Meta:
            fields = ['username', 'email']
    
    
    class CustomSetPasswordForm(forms.Form):
        new_password = forms.CharField(
            max_length=16, 
            min_length=6, 
            label=_('새 비밀번호')
        )
        confirm_password = forms.CharField(
            max_length=16, 
            min_length=6, 
            label=_('새 비밀번호 확인')
        )
    
    0 回复  |  直到 2 年前
        1
  •  1
  •   Abdelhamed Abdin    2 年前

    由于在视图模型中使用get方法,因此可以直接使用它,而无需通过方法进行检查,这就是该函数的作用

    注:-
    现在,通过get方法处理请求方法,但不能在表单中使用csrf_令牌

    现在的问题是,你试图使用get方法来发送数据,然后你想通过Post方法在ajax中获取这些数据,当然除了,您试图在视图中执行单独的函数,这会导致函数永远无法执行的问题,因为表单不知道在创建请求后应该将数据发送到哪里。

    因此,现在您可以删除您使用的附加功能,并尝试在“一个视图”中使用和包含您想要的内容,以防止混淆。因此,请遵循如下解决方案:

    class RecoveryPwView(View):
        template_name = 'users/recovery_pw.html'
        recovery_pw = RecoveryPwForm
    
        def get(self, request):
            form = self.recovery_pw(None)
            return render(request, self.template_name, { 'form':form})
    
        def post(self, request):
            form = self.recovery_pw(request.POST)
            if form.is_valid():
                username = form.cleaned_data.get('username')
                email = form.cleaned_data.get('email')
                target_user = User.objects.get(username=username, email=email)
            
            # do send email here
    
            # return the render that you want to finish by post method here
    

    html

    <form method="post">
        {% csrf_token %}
        <div class="container">
          <div class="inner-box">
              <div class="title">
                  <h1>비밀번호 찾기</h1>
              </div>
              <div class="input-box">
                  {% comment %} <div class="id">
                    <input type="email" placeholder="등록하신 메일로 인증번호가 발송됩니다." name="email" maxlenth="20" autocomplete="off" value="{{ form.email.value|default_if_none:'' }}" required />
                  </div>
                  <div class="username">
                    <input type="username" placeholder="아이디를 입력하세요" name="username" maxlength="20" value="{{ form.username.value|default_if_none:'' }}" required />
                  </div> {% endcomment %}
                  {% for field in form %}
                    <label>{{ field.label }}</label>
                    <div>{{ field }}</div>
                  {% endfor %}
              </div>
              <div class="btn">
                  <div class="btn-white" id="btn_white"><button type="submit">임시 비밀번호 발송</button></div>
              </div>
    
              <div class="loading-box">
                  <div id="loading"></div>
              </div>
    
          </div>
    
    </form>
    

    现在这个解决方案还没有完成,因为我不确定你到底想做什么,但至少你可以看到你的问题出现了一些新的情况,找到了min问题,现在的问题将来自Ajax,让我知道你在那之后面临什么