SilvenLEAF의 가장 간단한 등록/로그인 시스템

자바스크립트로 로그인 시스템을 만드는 것은 생각보다 간단합니다!우리 처음부터 하나 하자!

로그인 등록을 만드는 가장 간단한 방법

  • 정책 생성
  • 여권 구성
  • 손잡이 노선
  • 쿠키 사용
  • 프런트엔드 사용
  • 우리 한 명씩 갑시다.

    전체 자습서


    기본 서버와 데이터베이스를 설정하는 방법을 이미 알고 있는 분들은 4단계로 넘어가세요.

    0단계.프로젝트 폴더 설정


    "authDemo"라는 폴더를 만들고 가장 좋아하는 텍스트 편집기에서 엽니다.앱이라는 파일을 만듭니다.js.현재 터미널에 npm init-y를 입력하십시오.패키지는 하나만 생성됩니다.제이슨 파일로 가방을 추적하는 등등. 어쨌든 진정한 모험을 시작합시다!

    첫걸음기본 서버 설정


    우선 터미널에 이걸 입력해서 패키지를 설치하세요.npm i express mongoose passport passport-local cookie-session
    짧은 포장 설명

  • express: 저희 서버 만들기

  • mongoose: 저희 데이터베이스에 연결

  • passport: Google Github 로그인 포함

  • passport local: 로그인 및 등록 폼으로 로그인/등록 만들기
  • 지금 이것들을 응용 프로그램에 써라.js 파일
    // core modules
    const express = require('express');
    const path = require('path'); //it is an in-built node module so no need to install it
    
    const passport = require('passport'); //this is our main package that will help us create the login signup system
    const cookieSession = require('cookie-session'); //this is for using cookies so that our users stay logged in
    
    
    
    
    
    // ------------------------------FIRING EXPRESS APP
    const app = express();
    app.use(express.json()); //it allows us access the data sent from frontend using req.body
    app.use(express.urlencoded({ extended: false })); 
    app.use(express.static(path.join(__dirname, `client`))); //here we are saying that our static files I mean html css etc files will be served from this client file
    
    
    
    
    // -------------------------COOKIE AND PASSPORT
    app.use(cookieSession({
      maxAge: 24*60*60*1000, //it is the total expiration time, here the cookie will be alive for 1 day
      keys: [`abcdefghijklmn`], //here type whatever your want instead of abcdefghijklm, I just typed abcdefghijklm 
    }));
    
    
    
    
    
    
    
    
    /* -------------------------------------------------
    .                    config
    ------------------------------------------------- */
    require('./config/mongodbConfig'); //Here it is firing the mongodbConfig file that has our database configuration, we'll create it soon
    require('./config/passportConfig'); //Here it is firing the passportConfig file that has our login/signup configuration, we'll create it soon
    
    
    
    
    
    
    
    
    
    
    
    
    /* -------------------------------------------------
    .                    routes
    ------------------------------------------------- */
    //                  auth routes
    app.use(require('./routes/authRoute')); //here authRoute has our login signup routes, we'll create it soon
    
    
    
    // CATCH ALL HANDLER, if there is any route that does not match the above routes, send the index.html file
    app.get('*', (req, res, next)=>{
      try {
        res.sendFile(path.join(__dirname, `client/index.html`));
      } catch (err) {
        next(err, req, res)
      }
    })
    
    
    
    
    
    
    // ERRORS HANDLER
    app.use((err, req, res, next)=>{
      console.log(err.message);
    
      console.log(err);
      res.json({ msg: `Server error`, error: err.message })
    });
    // --------------------end of routes------------------------
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    // -----------------------------------------LISTEN
    const PORT = process.env.PORT || 5000;
    app.listen(PORT, ()=>{
      console.log(`Server is running on port ${ PORT }`);
    });
    
    이 코드는 나중에 설명됩니다.우선 데이터베이스 설정과 루트를 설정합니다

    두 번째 단계.기본 데이터베이스 설정


    프로필 폴더를 만듭니다. 모든 프로필을 저장할 것입니다.너는 이렇게 할 필요가 없지만, 나는 그것을 더욱 좋아한다. 왜냐하면 만약 네 프로젝트가 더 커진다면, 그것은 너의 코드 라이브러리를 더욱 깨끗하게 하고, 더욱 쉽게 유지보수할 수 있도록 도와줄 것이다.어쨌든, 현재 몬godbConfig라는 파일을 만듭니다.그 폴더에
    이것들을 몬godbConfig에 써라.js 파일
    const mongoose = require('mongoose');
    
    
    
    
    
    
    
    mongoose.connect(YOUR_DATABASE_STRING,
      {
        useNewUrlParser: true,
        useUnifiedTopology: true,
        useCreateIndex: true,
        useFindAndModify: false,
      },
    
    
    
      (err) =>{
        if(err) throw err;
        console.log('connected to MongoDB');
      }
    )
    
    DATABASE 문자열을 데이터베이스 문자열로 대체하고 없으면 MongoDB Atlas를 사용하여 클러스터를 생성하면 데이터베이스 문자열을 얻을 수 있습니다.

    세 번째.사용자 모델 생성하기


    models 및 Create User라는 폴더를 만듭니다.js
    사용자에 따라 이러한 항목을 입력합니다.js 파일
    const mongoose = require('mongoose');
    
    
    
    /* ----------------------------------
    .           SUB SCHEMAs
    --------------------------------------- */
    const LocalSchema = new mongoose.Schema({
      email: String,
      password: String,
    
    })
    
    
    
    
    
    
    
    
    
    /* ------------------------------------------
    .                MAIN SCHEMA
    ----------------------------------------------- */
    const UserSchema = new mongoose.Schema({
      local: LocalSchema, //I'm using this sub schema now because we will be creating Login with Google Twitter Linkedin Github etc, so it'll help us in the future too.
    
      username: String,
    
    });
    
    
    
    
    
    
    
    /* ------------------------------------------
    .                USER MODEL
    ----------------------------------------------- */
    module.exports = User = mongoose.model('User', UserSchema);
    
    여기에는 모든 것을 간단하게 유지하기 위해 전자 우편, 비밀번호, 사용자 이름만 저장할 것입니다.

    네 번째 단계.실수 인코딩이 시작됐습니다.


    passportConfig 를 만듭니다.폴더의 js 파일을 설정합니다.config 폴더에passportStrategies 하위 폴더를 만들 수도 있습니다.SignupStrategy를 만듭니다.js 및 LoginStrategypassportStrategies 폴더의 js 파일입니다.

    다섯 번째.로그인 및 등록 정책 작성


    이것들을 너의 등록 전략에 써라.js 파일
    const Strategy = require('passport-local'); //this is to create our login signup strategies
    const User = require('../../models/User'); //our User model to save our user data also to retrieve our user data
    const bcrypt = require('bcryptjs'); //we use it to hash our passwords, if you don't know how to use it, go see my prev blog. I already make one on it explaining in detail
    
    
    
    
    
    
    
    
    
    
    
    module.exports = SignupStrategy = new Strategy(
      {
        // overriding the default username with email
        usernameField: 'email',  //passport by default uses username and password  to login and signup, just like My Anime List website. We are here changing it so that users signup with email and password system and not with username and password system
        passwordField: 'password',
        passReqToCallback: true, //this will allow use use req on the following callback function
      },
    
    
    
    
      (req, email, password, done)=>{
        const { username } = req.body; //retrieving username from the data that frontend sent to us. Look here we'll also retrieve other data if it sent us, like first name last name location etc. To keep it simple I'm just using username. One more thing You don't need to retrieve email of password this way because passport will already retrieving it for you
    
    
        User.findOne({ 'local.email': email }, (err, user)=>{ //checking if there is already an user with this email
    
    
          // if there is an error while checking
          if(err) return done(err); //finish this process right here and send back error to our error handler
    
    
    
    
          // if there is already an account with this email, we'll finish the process right here and notify the user that this email is already taken
          if(user) return done({ msg: `This email is already taken` }, null);
    
    
    
    
          // if this email is not already taken, create a new account with this email
          User.create({
            'local.email': email,
            'local.password': bcrypt.hashSync(password, bcrypt.genSaltSync()), //here saving the hashed password, see my prev blog to know in detail
    
    
            username,
    
          }).then(newUser=> done(null, newUser)); // Now when the account has been created, send this data onto the passport middleware on the auth route (we'll create it soon) and that middleware will send this data back to the cookie-fyer which will then cookie-fy our data and store it in a cookie
    
        })
      }
    )
    
    코드를 이해하기 위해 주석을 읽다.나는 이미 한 줄 한 줄 해명했다
    현재 우리는 마찬가지로 로그인 정책을 만들어야 한다.그게 더 쉬워.
    이것들을 Login Strategy에 써라.js 파일
    const Strategy = require('passport-local'); //to create login signup strategy
    const User = require('../../models/User'); //to save or retrieve user data
    const bcrypt = require('bcryptjs'); //to hash or verify passwords, to know more see my prev blog
    
    
    
    
    
    module.exports = LoginStrategy = new Strategy(
      {
        // overriding default username with email
        usernameField: 'email',  //as explained passport uses username and password to login by default, we are overriding it so that it uses email and password for logging in
        passwordField: 'password',
        passReqToCallback: true, //it'll allow us use req on the following callback function
      },
    
    
    
      (req, email, password, done)=>{
        User.findOne({ 'local.email': email }, (err, user)=>{ //finding the user with that email
    
          // if there is any error while finding, finish the process right here and send back the error to our error handler
          if(err) return done(err);
    
    
    
          // if there is no account with that email then let the user know that there is no account with this email
          if(!user) return done({ msg: `No user found`}, null);
    
    
    
          // if password does not match, let the user know that he typed wrong passwords
          const isPasswordValid = bcrypt.compareSync(password, user.local.password); //it is comparing the plain password with the saved hashed password to see if they match, to know more about it see my previous blog, I've explained in detail
          if(!isPasswordValid) return done({ msg: `Invalid Credentials` }, null);
    
    
    
    
          // if everything is OK, send the user data to the password middleware on the auth route that will then send the user data onto the cookie-fyer that will then cookie-fy and store the data on a cookie
          return done(null, user)
    
        })
      }
    )
    
    각 행의 코드를 이해하기 위해 주석을 읽으십시오.

    여섯 번째.여권 설정


    이제 passportConfig를 엽니다.js 파일 및 작성
    const passport = require('passport'); //our main package for creating login signup system
    const User = require('../models/User'); //to save or retrieve 
    user data
    
    
    
    
    const LoginStrategy = require('./passportStrategies/LoginStrategy');
    const SignupStrategy = require('./passportStrategies/SignupStrategy');
    
    
    
    
    
    
    /* ------------------------------------
    .     SERIALIZE AND DESERIALIZE
    ----------------------------------------- */
    //this is our cookie-fyer machine, it'll take the user data and cookie-fy it and store it on a cookie, here we will only cookie-fy the id of the user because we do not want to store his email and password on the cookie because if we do and if hackers find this cookie then it'll be a disaster. ha ha, I think you got my point
    passport.serializeUser((user, done)=>{
      done(null, user.id);
    });
    
    
    //this is the de-cookie-fyer machine. When a user with the cookie comes to our website, it asks them to show him the cookie so that it knows that the user is already logged in. Then it will de-code the cookie and get that id we stored out of the cookie and find the user who has this id, then it will retrieve it's data and store in in a user object and it will attach it on our req object. so now if he is logged in we can access his data with req.user amazing right?
    passport.deserializeUser((id, done)=>{
      User.findById(id).then(user=> done(null, user));
    });
    
    
    
    
    
    /* ------------------------------------
    .               STRATEGIES
    ----------------------------------------- */
    //here we are using those strategies we created
    passport.use('local-signup', SignupStrategy); //we are also giving them name so that we can reference them by name later
    passport.use('local-login', LoginStrategy); //same thing here too
    
    
    
    이제 1부가 완성됐습니다.이제 우리는 노선을 만들고 앞에서 그것을 사용하기만 하면 된다.가자!

    일곱 번째.라우팅 작성


    루트 레벨에routes라는 폴더를 만들고 authRoute라는 파일을 만듭니다.안에 js가 있어요.
    이제 이것들을 authRoute에 쓰세요.js 파일
    const router = require('express').Router(); //this is the router that'll create the routes for us
    const passport = require('passport'); //this is our main package for login signup system
    
    
    
    
    /* --------------------------------------
    .                 LOGOUT
    ------------------------------------------- */
    //this is a route for logging out. It'll log out the users and then send back a message to let them know that they are successfully logged out
    router.get('/logout', (req, res)=>{
      req.logOut();
      res.json({ msg: `Logged out` }); 
    });
    
    
    
    
    /* --------------------------------------
    .          GET LOGGED IN USER 
    ------------------------------------------- */
    //this is a route to get logged in user data 
    router.get('/user', (req, res)=>{
       if(req.user) { //if user is logged in, user data will be stored on req.user
           res.json({ user: req.user });
       } else { //if user is not logged in, req.user will not exist
           res.json({ msg: "Please log in to access this data" });
       }
    });
    
    
    
    
    /* --------------------------------------
    .                 SIGNUP
    ------------------------------------------- */
    router.post('/signup', (req, res, next)=>{
      passport.authenticate('local-signup', (err, user, info)=>{ //this is our passport authenticating middleware I was talking about
        // if there is any error (including the error I defined on the Strategy), send back the error with that error message to the user
        if(err) return res.status(400).json(err);
    
        //if there is no error in sign up, it'll create their account. so now log them in
        req.logIn(user, (err)=>{
          // if there is any error while logging in, send the error message
          if(err) return res.status(500).json({ msg: `Oops, something went wrong` });
    
    
    
          // if everything is OK, return the user onto the Cookie-fyer
          return res.json(user);
        })
    
    
    
      })(req, res, next)
    })
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    /* --------------------------------------
    .                 LOGIN
    ------------------------------------------- */
    router.post('/login', (req, res, next)=>{
      passport.authenticate('local-login', (err, user, info)=>{ //this is the passport middleware I was talking about
        // if there is any error (including the error I defined on the Strategy) send back the error message to the user
        if(err) return res.status(400).json(err);
    
    
      //if there is no error, log them in
       req.logIn(user, (err)=>{
        //  if there is any error while logging in, send back the error message to the user
        if(err) return res.status(500).json({ msg: `Oops, something went wrong`});
    
    
    
        // if everything is OK, send the user data onto the Cookie-fyer
        return res.json(user);
       }) 
      })(req, res, next)
    })
    
    
    
    
    
    module.exports = router;
    
    지금 우리는 거의 완성하지 못했다.아이고.우리는 단지 하나의 전방에서 우리의 로그인 등록 시스템과 상호작용을 할 수 있을 뿐이다.
    기본 HTML을 사용할 것입니다. React,angular, vue, 기타 모든 것을 사용할 수 있습니다.모든 것이 다 같다.

    여덟 번째.프런트엔드 생성


    루트 단계에서 클라이언트라는 폴더를 만듭니다.그런 다음 색인을 만듭니다.html.외부 js와 다른 외부 css 파일을 만들고 색인에서 인용할 수 있습니다.html.나는 별도의 스타일이 아닌 기본 스타일을 간단하게 유지할 것이다.
    색인에 로그인과 등록 폼을 만듭니다.html.
    <!DOCTYPE html>
    <html lang="en">
      <head>
        <meta name="viewport" content="width=device-width, initial-scale=1" />
    
    
        <title>LOGIN SIGNUP</title>
      </head>
      <body>
    
    <form id="signupForm" >
      <input id="signupEmail" type="email" required/>
      <input id="signupPassword" type="password" required/>
      <input id="signupUsername" type="text" />
      <button>Sign up</button>
    </form>
    
    <form id="loginForm" >
      <input id="loginEmail" type="email" required/>
      <input id="loginPassword" type="password" required/>
      <button>Log in</button>
    </form>
    
    
    
    
        <script>
    const signupForm = document.querySelector('#signupForm');
    const loginForm = document.querySelector('#loginForm');
    
    const signupEmail= document.querySelector('#signupEmail');
    const signupPassword= document.querySelector('#signupPassword');
    const signupUsername= document.querySelector('#signupUsername');
    
    const loginEmail= document.querySelector('#loginEmail');
    const loginPassword= document.querySelector('#loginPassword');
    
    
    
    //signup form (if you don't know how fetch works see my prev blog, I explained in detail)
    signupForm.addEventListener('submit', async (e)=>{
       e.preventDefault();
    
       const response = await fetch('/signup', {
             method: 'POST',
             headers: {
                'Content-Type': 'application/json'
             },
             body: JSON.stringify({
                  email: signupEmail.value,
                  password: signupPassword.value,
                  username: signupUsername.value
            })
    
       });
    
       const data = await data.json();
       console.log(data);
    });
    
    
    //login form
    loginForm.addEventListener('submit', async (e)=>{
       e.preventDefault();
    
       const response = await fetch('/login', {
             method: 'POST',
             headers: {
                'Content-Type': 'application/json'
             },
             body: JSON.stringify({
                  email: loginEmail.value,
                  password: loginPassword.value
            })
    
       });
    
       const data = await data.json();
       console.log(data);
    });
        </script>
      </body>
    </html>
    
    
    우리가 방금 완전한 로그인 등록 시스템을 창설한 것을 축하합니다.각 행의 코드를 이해하기 위해 주석을 읽으십시오.이제 다시 한 번 볼게요.

    코드에 무슨 일이 일어났습니까?


    우리는 전자메일, 비밀번호, 사용자 이름을 제공하는 가입 게시물 요청을 앞에서/signup-url에 보냈습니다.너도 더 많은 데이터를 보낼 수 있다.나는 단지 간단함을 유지할 뿐이다.
    현재, 우리 서버는 루트의 요청을 감청/등록하고 있습니다.그녀는 이 요청을 찾아서 나에게 말했다. "헤이, 여권, 이것은 등록에 관한 것이다. 당신이 나를 도와 처리해 주세요."그래서 패스포트가 전자메일과 비밀번호를 캡처해서 (기본 사용자 이름을 전자메일로 덮어쓰지 않으면 사용자 이름과 비밀번호를 캡처해서 보내는 정책) 을 관리하고 있습니다.정책상, 만약 등록 중이라면, 우리는 메일이 이미 수신되었는지 확인하고, 만약 그렇다면, "메일이 이미 수신되었거나 다른 것을 알려 주는 erro 메시지를 보낼 것입니다.너는 너의 앞부분에서 보여줄 수 있다.현재 사용하지 않으면 계정을 성공적으로 만든 후 사용자 id에 대해 쿠키 검증을 하고 쿠키를 저희req 대상에 추가합니다.그래서 우리가 새로운 요청을 할 때마다 우리는 이미 로그인했다.
    현재 로그인 정책도 마찬가지입니다.우리는 이 계정이 존재하는지 확인하고 비밀번호가 일치하는지 검사할 것이다.오류가 있으면 오류 메시지를 되돌려줍니다.만약 없다면, 그것은 그들을 로그인시키고 다운로드하게 할 것이다.
    그들이 취소할 때, 그것은 쿠키를 파괴하고, 너도 취소할 것이다.
    이제 우리 응용 프로그램을 테스트해 봅시다.

    어플리케이션 테스트


    localhost: 5000/user를 등록하고 방문하면 사용자 데이터를 볼 수 있습니다.로그아웃하려면 localhost: 5000/로그아웃으로 이동하십시오.이제 localhost: 5000/사용자로 다시 이동합니다.로그아웃했기 때문에 사용자 데이터가 더 이상 보이지 않습니다.지금 로그인한 다음localhost: 5000/user로 이동하면 사용자 데이터를 볼 수 있습니다.localhost: 5000/logout으로 이동해서 다시 로그아웃하면 로그아웃되고 사용자 데이터가 보이지 않습니다.너무 좋아요, 그렇죠?
    축하합니다, 당신은 방금 당신의 첫 번째 사용자 로그인과 등록 시스템을 창설했습니다!!!아이구!
    지금 더 많이 준비해!!

    하면, 만약, 만약...


    언제든지 연락 주세요.링크드인이나 트위터에 연락 주세요.
    ).
    만약 당신이 나를 더 많이 알고 싶다면, 이것은 나의 투자조합 사이트SilvenLEAF.github.io이다.

    나는 당신의 친구가 되고 싶습니다. 언제든지 저에게 연락 주세요!!


    다음 블로그는 2020년 11월 28일에 발표될 것이다


    Google Github 및 Linkedin Series를 사용하여 등록/로그인할 때**

    다음 데이트

  • 2020년 11월 28일과 11월 5일 구글 Github와 영영 시리즈 사용 **
  • 등록/로그인
  • 2020년 11월 28일, 구글을 어떻게 사용하여 로그인을 만드는가
  • 2020년 11월 28일 Github로 로그인 생성 방법
  • 2020년 11월 28일, 링크드 인 로그인을 만드는 방법
  • 2020년 11월 28일, 트위터로 로그인 만들기 방법
  • 2020년 11월 30일, 비밀번호 리셋 시리즈(Node.js와 React 포함)
  • 만약 이 블로그가 당신에게 도움이 된다면,


    여러분 함께 공유해 주세요.


    이것은 나에게 있어서 매우 큰 의의가 있다.고마워요 고마워요

    이전 블로그


    다음 블로그


    11월 28일

    좋은 웹페이지 즐겨찾기