Django 1.10.3 Tutorial : 로그인/로그아웃 처리하기


  • 명색이 관리자 화면인데, 아무나 들어와서 조작하면 안되겠지요? 이제는 마지막으로 로그인/로그아웃 처리를 해보겠습니다. 로그인/로그아웃은 세션을 이용해서 구현합니다.
  • 로그인 화면을 구성합니다. $PRJNAME/web/prjname/templates/mgmt/index.html 을 작성합니다.
    <!DOCTYPE html>
    <html lang="ko">
    <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="_xsrf" content="{{.xsrf_token}}" />
    <title>Management</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
    <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
      <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->
    </head>
    <body>
    {% if messages %}
    <div class="alert alert-success alert-dismissible" role="alert">
      <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>
      {% for message in messages %}
      {{ message }}
      {% endfor %}
    </div>
    {% endif %}
     
    <div class="container">
      <div style="text-align:center; margin-top:150px; margin-bottom: 40px"><h1>Management</h1></div>
      <form action="{% url 'mgmt_login' %}" method="post" class="form-horizontal" style="margin: 0 auto; max-width: 360px;">
        {% csrf_token %}
        <div class="form-group">
          <label for="userid" class="col-sm-3 control-label">아이디</label>
          <div class="col-sm-9">
            {{ form.userid }}
          </div>
        </div>
        <div class="form-group">
          <label for="passwd" class="col-sm-3 control-label">비밀번호</label>
          <div class="col-sm-9">
            {{ form.password}}
          </div>
        </div>
        <input type="submit" class="btn btn-primary btn-block" value="로그인" />
      </form>
    </div>
     
    <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
    <!-- Include all compiled plugins (below), or include individual files as needed -->
    <script src="/static/b/js/bootstrap.min.js"></script>
    </body>
    </html>
  • $PRJNAME/web/prjname/forms/mgmt/main.py 를 생성한다.
    # -*- coding: utf-8 -*-
    # ----------------------------------------------------------------------------
    # File : prjname/forms/mgmt/main.py
    # Create Date : 2016-01-26
    # ----------------------------------------------------------------------------
     
    # import re
    # from django.core.exceptions import ObjectDoesNotExist
    from django import forms
    # from ..models.users import UserModel
     
     
    class AdminLoginForm(forms.Form):
        userid   = forms.CharField(max_length=255, widget=forms.TextInput(attrs={'class':'form-control', 'required':True, 'autofocus':True, 'placeholder':'당신의 ID를 입력하세요...', }))
        password = forms.CharField(max_length=255, widget=forms.PasswordInput(attrs={'class':'form-control', 'required':True, 'placeholder':'비밀번호를 입력하세요...', }))
  • $PRJNAME/web/prjname/views/mgmt/main.py 를 생성합니다.
    # -*- encoding: utf-8 -*-
    # prjname/views/mgmt/main.py
     
    import hashlib
     
    from django.utils import timezone
    from django.contrib import messages
    from django.shortcuts import render, redirect
    from django.core.exceptions import ObjectDoesNotExist
     
    from ...models.admin import *
    from ...forms.mgmt.main import *
     
     
    def index(request):
        form = AdminLoginForm(request.POST)
        return render(request, 'mgmt/index.html', {'form': form})
     
     
    def login(request):
        form = AdminLoginForm(request.POST)
        if form.is_valid():
            try:
                hashed_password = hashlib.sha256(form.cleaned_data['password'].encode('utf-8')).hexdigest()
                admin = AdminModel.objects.get(userid=form.cleaned_data['userid'], password=hashed_password)
            except ObjectDoesNotExist:
                messages.add_message(request, messages.INFO, '아이디 또는 비밀번호가 틀렸습니다')
                return redirect('mgmt_index')
        else:
            messages.add_message(request, messages.INFO, '아이디 또는 비밀번호가 올바르지 않습니다.')
            return redirect('mgmt_index')
     
        admin.last_login = timezone.localtime(timezone.now())
        admin.save()
        request.session["admin_login_yn"] = "yes"
        request.session["admin_nick"] = admin.nick
        # request.session.set_expiry(0)
        return redirect('mgmt_admin_index')
     
     
    def logout(request):
        request.session["admin_login_yn"] = "no"
        del request.session["admin_login_yn"]
        return redirect('mgmt_index')
  • $PRJNAME/web/prjname/urls.py 다음을 추가합니다.
    ...
     
    from .views.mgmt import main  as mgmt_main
     
    ...
     
        url(r'^mgmt/$', mgmt_main.index, name='mgmt_index'),
        url(r'^mgmt/login$', mgmt_main.login, name='mgmt_login'),
        url(r'^mgmt/logout$', mgmt_main.logout, name='mgmt_logout'),
     
    ...
  • $PRJNAME/web/prjname/views/mgmt/helper.py 를 생성한다.
    # coding: utf-8
    # ------------------------------------------------------------------------------
    # mgmt/views/mgmt/helper.py
    # ------------------------------------------------------------------------------
     
    import hashlib
    import datetime
    from functools import wraps
     
    from django.shortcuts import redirect
    from django.contrib import messages
     
     
    def login_required(f):
        @wraps(f)
        def decorated_function(request, *args, **kwargs):
            if "admin_login_yn" not in request.session:
                # messages.add_message(request, messages.INFO, '불법적인 접근입니다. 먼저 로그인하세요~!!!')
                return redirect('mgmt_index')
                # return redirect('http://naver.com/')
                return f(request, *args, **kwargs)
            return f(request, *args, **kwargs)
        return decorated_function
  • base.html 의 Logout 부분을 아래와 같이 변경한다.
    <li><a href="{% url 'mgmt_logout' %}">Logout</a></li>
  • 마지막으로 $PRJNAME/web/prjname/views/mgmt/admin.py 에 있는 모든 메소드 위에 @login_required 데코레이터를 추가하고, 상단에 from .helper import login_required 를 추가한다.
  • 이제, http://IP주소:8080/mgmt/admin 으로 접근하면 Naver 로 이동하게 될 것이며, http://IP주소:8080/mgmt 으로 접근하면 로그인화면이 나오고, 로그인 처리도 될 것이다. 아울러, 관리자 화면의 우측 상단에 있는 Logout 을 클릭하면 로그아웃 처리되어서 로그인화면으로 이동할 것이다.


댓글

이 블로그의 인기 게시물

야마하 디지털 피아노 YDP-140

테이블위로 마우스 커서 이동시 색깔 변경하기

피아노 연습