Coding Is My Life

코딩은 인생

파이썬

[Django Project][community 만들기 - 세션과 로그인]

산기대 컴공 2021. 12. 12. 13:21
728x90

세션이란?

클라이언트에는 쿠키라는 저장소가 있고 서버에는 데이터 베이스가 있다. 클라이언트가 서버에 요청을하게 되면 서버에서는 쿠키로 사용할 키를 만든다. 서버는 데이터 베이스에  키를 저장하고 쿠키를 클라이언트로 보낸다. 그리고 클라이언트도 쿠키를 저장한다. 브라우저마다 쿠키를 저장하는 저장공간이 다르다. 그리고 다음 요청부터 클라이언트가 쿠키를 같이 보내고 데이터베이스에서는 쿠키를 가지고 클라이언트의 사용자를 구분할 수 있다. 이러한 방식으로 로그인하는 것을 구현 할 수 있다.

 

로그인 페이지 html

<html>
    <head>
        <meta charset="utf-8">
        <style>
            .html{
                box-sizing: border-box;
                background-color: powderblue;
            }
            .wrap{
                width: 100%;
                height:100vh;
                display: flex;
                align-items: center;
                justify-content: center;

                background: rgba(0,0,0,0.1);
            }
            .logo{
                color:skyblue;
                text-align: center;
            }
            .container{
                background-color:snow;
                display: flex;
                flex-direction: column;
                border: 1px solid gray;
                border-radius: 20px;

                width: 30%;
                height:600px;

                justify-content: center;
                align-items: center;
            }
            .input_1, .input_2{
                border:1px solid gray;
                height: 30px;
                border-radius: 10px;
            }
            .button{
                border:1px solid gray;
                width: 100%;
                border-radius: 10px;
                background-color: powderblue;
            }
        </style>
    </head>
    <body>
        <div class="wrap">
            <div class="container">
                <div class="logo">
                    <h1>Log-in</h1>
                </div>
                <form action="." class="form" method="post">
                    {% csrf_token %}
                    <p>
                        {{error}}
                    </p>
                    <p>
                        <div class="id">
                             <strong>ID</strong><br>
                             <input type="text" name = "id" placeholder="id" class = "input_1">
                        </div>
                    </p>
                    <p>
                        <div class="password">
                            <strong>Password</strong><br>
                            <input type="password" name = "password" placeholder="password" class="input_2">
                        </div>
                    </p>
                    <p>
                        <button type="submit" class = "button">Login</button>
                    </p>
                </form>
            </div>
        </div>
    </body>
</html>

로그인 페이지는 저번에 만들었던 회원가입 html을 재활용하였다.

 

view코드

def login(request):
    if request.method == 'GET':
        return render(request,'login.html')
    else:
        user_id = request.POST.get('id',None)
        password = request.POST.get('password',None)

        res_data = {}
        if not(user_id and password):
            res_data['error'] = '모든 값을 입력해주세요'
        else:
            user_data = user.objects.get(user_id = user_id)
            if password == user_data.password:
                request.session['user'] = user_data.id
                return redirect('/')
            else:
                res_data['error'] = '비밀번호가 틀렸습니다'
                return render(request,'login.html',res_data)
        return render(request,'login.html',res_data)

회원가입의 view코드랑 유사하다. 다른 곳만 살펴보도록 하겠다. 

            user_data = user.objects.get(user_id = user_id)
            if password == user_data.password:
                request.session['user'] = user_data.id
                return redirect('/')

여기서 user_data라는 객체를 생성해서 데이터 베이스에서 user_id가 같은 객체를 가져왔다.

그리고 password가 같은지 확인해주고 같으면 session에 user_data의 id를 넣고 홈으로 redirect해주었다.

home은 간단히 임시로 만들었다. 코드는 다음과 같다.

<html>
    <head>
        <meta charset="utf-8">
        <style>
            .nav{
                height: 80px;
                border-bottom: 1px solid snow;
                display: flex;
                flex-direction: column;
                justify-content: center;
                background-color: gray;
            }
            .container{
                text-align: right;
                width:90%;
            }
            .item{
                font-size:1.2rem;
                margin:10px;
                color:lightblue;
                text-decoration: none;
            }
        </style>
    </head>
    <body>
        <header>
            <nav class="nav">
                <div class="container">
                    <a href = "/user/login" class = "item">Log-in</a>
                    <a href = "/user/sigh_up" class = "item">sigh-in</a>
                </div>   
            </nav>
        </header>
    </body>
</html>

이제 만들어진 view와 home의 url을 설정해보겠다. 

path('login/',views.login)

user디렉토리안에 urls.py안에 해당코드를 작성하였고

from user.views import home
path('',home)

프로젝트 urls.py 안에 해당코드를 추가로 작성해서 저장해주었다. home은 처음 화면으로 하고 싶어서 urls.py에 작성하였다.

그리고 다음으로는 직접 로그인해서 쿠키를 확인해 보겠다.

세션 확인해보기

처음에 홈페이지에 들어갔을때는 아무것도 저장되어있지 않았다. 그럼 이제 로그인을 해보겠다.

다시 크롬 개발자 도구에 들어가서 보니 세션이라는 value값이 생겼다. 다른 클라이언트에서 실행해보면 value값이 달라지는것까지 확인하였다.

회원가입과 로그인을 구현해보았다. 다음 글에서는 드디어 게시판을 만들어보겠다.

728x90