[Node.js] 로그인시 jwt과 session

2022. 8. 9. 23:05·개발/node.js
728x90
반응형

1. HTML

<!DOCTYPE html>
<html lang="en">
  <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>
  </head>
  <link rel="stylesheet" href="src/index.css" />
  <body>
    <canvas class="canvas"></canvas>
    <div id="loginPage">
      <div id="wholeWrapper">
        <form method="post" action="/" id="inputform">
          <div>
            <label for="">아이디</label>
            <input type="text" id="inputId" name="id" />
          </div>
          <div>
            <label for="">비밀번호</label>
            <input type="text" id="inputPw" name="pw" />
          </div>
          <button id="loginBtn" type="submit">로그인</button>
        </form>
        <div id="subdiv">
          <button id="signUp">회원가입</button>
          <button id="findIdPw">아이디/비밀번호 찾기</button>
        </div>
      </div>
      <div id="loginNav">
        <div id="navTop">아이디 슬라이드창</div>
        <button id="logout">로그아웃</button>
      </div>
    </div>
    <div id="adPage">
      <div class="adSection">이것은 광고입니다</div>
      <div id="close">
        <div id="dontLook">
          하루동안 보지않기
          <input type="checkbox" id="checkbox" />
        </div>
        <div id="closeAd">닫기</div>
      </div>
    </div>
  </body>
  <script>
    let createCookie = function (name, value = "광고On", time = 1) {
      let date = new Date();
      date.setTime(date.getTime() + time * 24 * 60 * 60 * 1000);

      document.cookie =
        name + "=" + value + ";expires=" + date.toUTCString() + ";";
    };

    let getCookie = function (name) {
      let value = document.cookie.match("(^|;) ?" + name + "=([^;]*)(;|$)");
      return value ? value[2] : null;
    };

    //온로드 됬을때 로그인상태라면
    window.onload = function () {
      if (sessionStorage.getItem("login") == 1) {
        wholeWrapper.style.display = "none";
        loginNav.style.display = "block";
        navTop.innerHTML = `${sessionStorage.getItem(
          "loggedin"
        )}님 환영합니다!`;
      }
    };
    //로그인 버튼 클릭
    loginBtn.onclick = function () {
      if (!getCookie(inputId.value)) {
        createCookie(inputId.value);
      }
      if (getCookie(inputId.value) == "광고On") {
        adPage.style.display = "flex";
      }
      wholeWrapper.style.display = "none";
      loginNav.style.display = "block";

      sessionStorage.setItem("login", 1);
      sessionStorage.setItem("loggedin", inputId.value);
      navTop.innerHTML = `${sessionStorage.getItem("loggedin")}님 환영합니다!`;
    };
    //하루동안 광고 안보기 클릭
    closeAd.onclick = function () {
      adPage.style.display = "none";
      if (checkbox.checked) {
        createCookie(inputId.value, "광고Off");
      }
      checkbox.checkbox = false;
    };

    //로그아웃 버튼 클릭
    logout.onclick = function () {
      sessionStorage.setItem("login", 0);
      wholeWrapper.style.display = "block";
      loginNav.style.display = "none";
      inputId.value = "";
      inputPw.value = "";
    };
  </script>
</html>

2. JS

const express = require("express");
const app = express();
const fs = require("fs");
const PORT = 3000;
const dot = require("dotenv");
dot.config();
const session = require("express-session");
const FileStore = require("session-file-store")(session);
const jwt = require("jsonwebtoken");
const bodyParser = require("body-parser");
app.listen(PORT, () => {
  console.log("server start");
});

app.use("/src", express.static(__dirname));

// 로그인 했을때 express 세션에 jwt 토큰정보 저장
// .env사용해서 시크릿키는 따로 뺴놓기

const key = process.env.KEY;
let token;
app.use(
  session({
    secret: key,
    resave: false,
    saveUninitialized: true,
    store: new FileStore(),
  }),
  bodyParser.urlencoded({
    extended: true,
  })
);
app.post("/", (req, res) => {
  token = jwt.sign(
    {
      type: "JWT",
      name: req.body.id,
    },
    key,
    {
      expiresIn: "5m",
      issuer: "admin",
    }
  );
});

app.get("/", (req, res) => {
  if (!req.session.key) {
    req.session.key = token;
  }
  fs.readFile("index.html", "utf-8", (err, data) => {
    res.send(data);
  });
});

3. CSS

* {
  padding: 0;
  margin: 0;
}

body {
  width: 100%;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
}
.canvas {
  position: absolute;
  z-index: -1;
}
#loginPage {
  width: 400px;
  height: 400px;
  background-color: greenyellow;
  position: relative;
  overflow: hidden;
}
#wholeWrapper {
  position: absolute;
  width: 100%;
  height: 100%;
}
#inputform > div {
  transform: translateX(17%) translateY(200%);
  margin-bottom: 30px;
  display: flex;
  justify-content: space-between;
  width: 300px;
  font-size: 20px;
}
#inputform > div input {
  height: 30px;
  padding-left: 10px;
}
#loginBtn {
  position: absolute;
  top: 60%;
  left: 50%;
  transform: translate(-50%, -50%);
  height: 50px;
  width: 300px;
  border-radius: 10px;
  border: none;
  cursor: pointer;
}
#subdiv {
  position: absolute;
  bottom: 20%;
  border-radius: 5px;
  left: 12%;
  width: 300px;
  display: flex;
  justify-content: space-between;
}
#loginNav {
  position: absolute;
  width: 100%;
  height: 100%;
  display: none;
}
#navTop {
  width: 100%;
  height: 50px;
  background-color: green;
  display: flex;
  justify-content: center;
  align-items: center;
  overflow: hidden;
  position: absolute;
  animation: slideAnimation 5s linear infinite;
}
@keyframes slideAnimation {
  from {
    left: -100%;
  }
  to {
    left: 100%;
  }
}
#logout {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 80px;
  height: 30px;
}
#adPage {
  width: 330px;
  height: 300px;
  position: absolute;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: white;
  z-index: 999;
  display: none;
}
#adSection {
  width: 100%;
  height: 100%;
}
#close {
  position: absolute;
  bottom: 10px;
  width: 300px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
#dontLook {
  font-size: 12px;
  display: flex;
  justify-content: center;
  align-items: center;
}
#closeAd {
  cursor: pointer;
}

4. 코드

 

로그인시 아이디와 비밀번호를 form태그를 통해 post방식으로 데이터를 전송한다.

 

js에서 post방식으로 데이터를 받아 jwt를 만들어줄때 id를 넣어준다.

 

다시 그 토큰을 express-session을 만들때 key값으로 token을 넣어준다.

 

로그인시 광고팝업을 띄어 하루동안 보지않기를 클릭하면 쿠키의 value를 광고Off 로 설정하여

광고가 하루동안 나오지 않게 한다.

 

로그인상태를 유지시키기 위해 세션을 사용하여 onload이벤트에서 세션을 검사 후 로그인 되어있으면 로그인을 

유지시킨다.

728x90
반응형

'개발 > node.js' 카테고리의 다른 글

[Node.js] 로그인 Access Token, Refresh Token  (0) 2022.08.16
[Node.js] exports router  (0) 2022.08.10
[Node.js] 로그인시 JWT생성  (0) 2022.08.09
[Node.js] 채팅, 귓속말 기능 만들기  (0) 2022.07.29
[Node.js, jquery] 비행기 예약 시스템 만들기  (0) 2022.07.29
'개발/node.js' 카테고리의 다른 글
  • [Node.js] 로그인 Access Token, Refresh Token
  • [Node.js] exports router
  • [Node.js] 로그인시 JWT생성
  • [Node.js] 채팅, 귓속말 기능 만들기
TeTedo.
TeTedo.
  • TeTedo.
    TeTedo 개발 일기
    TeTedo.
  • 전체
    오늘
    어제
    • 분류 전체보기 (319)
      • 개발 (274)
        • Article (4)
        • 정리 (21)
        • Spring Boot (17)
        • JPA (2)
        • JAVA (6)
        • Database (4)
        • 자료구조 (11)
        • 알고리즘 (32)
        • React (20)
        • Docker (10)
        • node.js (18)
        • Devops (11)
        • Linux (4)
        • TypeScript (3)
        • Go (10)
        • HyperLedger (4)
        • BlockChain (43)
        • html, css, js (48)
        • CS (3)
        • AWS (3)
      • 모아두고 나중에 쓰기 (3)
      • 팀프로젝트 (18)
        • SNS(키보드워리어) (9)
        • close_sea (9)
      • 개인프로젝트 (1)
        • Around Flavor (1)
        • CHAM (13)
        • ethFruitShop (5)
      • 독서 (0)
        • 스프링부트와 AWS로 혼자 구현하는 웹 서비스 (0)
  • 블로그 메뉴

    • 홈
    • 개발일기
    • CS
    • 실습
    • 코딩테스트
    • 웹
    • Go
    • node.js
    • 팀플
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    도커
    프로그래머스
    node.js
    html
    30일 챌린지
    명령어
    ERC721
    mysql
    erc20
    React
    go언어
    nodejs
    go
    node
    js
    블록체인
    CSS
    하이퍼레저
    30일챌린지
    컨테이너
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.1
TeTedo.
[Node.js] 로그인시 jwt과 session
상단으로

티스토리툴바