웹 개발

[포스코X코딩온] Web Session 실습

끊임없이 성장중인 개발자 2023. 12. 14. 20:46
728x90
반응형

포스팅 주제

  • Web Session 실습

Session 실습

 

 

< 서버 - app.js >

const express = require('express');
const session = require('express-session');
const app = express();
const PORT = 8000;

app.set('view engine', 'ejs');
app.use('/static', express.static(__dirname + '/static'));
app.use(express.urlencoded({ extended: true }));
app.use(express.json());

app.use(session({
    secret: 'mySessionSecret',
    resave: false,
    saveUninitialized: false,
    cookie:{
        httpOnly:true,
        maxAge: 60*1000// 1분
    }
}))

userInfo = { id: 'banana', pw:'1234'};

// ============== 실습2 =================

app.get('/', (req,res) => {
    //req.session.user 값이 있는지 검사를 해서 isLogin이라는 변수로 로그인 여부를 보내준다.
    const user = req.session.user;
    console.log('req.session.user >>>> ', user);
    // 값이 없을 때는 undefined가 나온다.
    if(user !== undefined){
        res.render('index', {isLogin: true, user:user});
    }else{
        res.render('index', {isLogin:false})
    }
})
app.get('/login', (req,res)=>{
    res.render('login');
})
app.post('/login', (req,res) =>{
    const {id, pw} = req.body;
    if(id === userInfo.id && pw === userInfo.pw){
        req.session.user = id;
        res.redirect('/');
    }else{
        res.send('로그인 실패!')
    }
})
// 로그아웃 요청
app.get('/logout', (req,res) => {
    const user = req.session.user; //user id
    if(user !== undefined){
        req.session.destroy((err) => {
            res.redirect('/');
        })
    }else{
        // (로그인x) 유저가 잘못 접근했을 떄
        res.send('잘못된 접근입니다.');
    }

})


app.listen(PORT, () => {
    console.log(`http://localhost:${PORT}`);
});

 

미리 지정해둔 userInfo와 로그인 창에서 입력한 값이 같다면 req.session.id에 userid값을 부여한다.

그리고 http://localhost:8000/로 리다이렉트 해준다.

 

만약 req.session.id값이 있다면 isLogin: true와 user값을 index.ejs에 넘겨준다.

만약 값이 없다면 isLogin: false를 반환한다.

 

 

화면 구성

<  views - index.ejs >

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>

  <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>

</head>

<body>
  <h1>실습 Session 연습</h1>
  <p>Home</p>

  <!-- if문으로 isLogin이라는 변수를 통해서 로그인 여부 확인 -->
  <% if(isLogin) { %>
    <form action="/logout" method="get">
      <h3>
        <%= user %>님 환영합니다.
      </h3>

      <button id="logout">로그아웃</button>
    </form>
  <% }else { %>
      <a href="/login">로그인</a>
  <% } %>
  
</body>

</html>

 

isLogin: true가 반횐되면 user 값을 같이 반환하기 때문에 해당하는 유저를 환영한다는 문자가 나올 것이다.

isLogin: false가 반환되면 로그인창 경로에 대한 결과만 화면에 보일 것이다.

 

< views - login.ejs >

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-C6RzsynM9kWDrMNeT87bh95OGNyZPhcTNXj1NW7RuBCsyN/o0jlpcV8Qyq46cDfL" crossorigin="anonymous"></script>

    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous">

</head>
<body>

    <div class="loginBox">
    <h1>로그인</h1>
    <p>참고! 아이디: <b>banana</b> <br>
    비밀번호는 <b>1234</b>
    </p>

    <form action="/login" method="POST">
        <div class="input-group mb-3">
            <spanc class="input-group-text" id="id"></spanc>
            <input type="text" class="form-control" aria-label="id input" aria-describedby="id" name="id">
        </div>
        <div class="input-group mb-3">
            <spanc class="input-group-text" id="pw"></spanc>
            <input type="password" class="form-control" aria-label="pw input" aria-describedby="pw" name="pw">
        </div>

        <button class="btn btn-dark">Login</button>
        <br>
        <a href="/">home 이동하기</a>
    </form>
</div>
</body>
</html>

 

 

 

 

반응형