NODEJSとMongoDBによる認証-パート3


これはnodejsとmongodbの認証シリーズの第3部です.前の部分をチェックアウトしていない場合は、チェックアウトしてください.
チュートリアルのこの部分では、ログインをカバーします jasonwebtoken (JWT) . 最後に、我々はどのようにクロスチェックユーザーと一致する見ているhashed passwordplain text password .
いつでも無駄にせずに、それにジャンプしましょう.

スタータープロジェクト


あなたが前のチュートリアルから来ていないならば、あなたはスタータープロジェクトをhere

ログイン終了点

  • JWTをインストール
  • 
    npm i jsonwebtoken -s
    
    
  • 輸入JWT すぐ下にconst bcrypt = require("bcrypt"); 線の上の行app.js ファイル:
  • 
    const jwt = require("jsonwebtoken");
    
    
  • すぐ下にregister endポイント、次の関数を入力します
  • 
    app.post("/login", (request, response) => {
    
    })
    
    
  • ログイン時にユーザーが入力したメールが次のコード行で存在するかどうかを確認します.
  • 
      User.findOne({ email: request.body.email })
    
    
    次に、私たちはthen...catch... 上記のメール検索が成功したかどうかチェックするブロック
  • それが失敗したら、我々はそれをキャプチャしますcatch ブロック:
  • 
    User.findOne({ email: request.body.email })
        .then()
        .catch((e) => {
          response.status(404).send({
            message: "Email not found",
            e,
          });
        });
    
    
  • 成功した場合、我々はパスワードをデータベース内のハッシュされたパスワードに対して入力を比較します.我々は、このthen... ブロック:
  • 
       .then((user)=>{
          bcrypt.compare(request.body.password, user.password)
       })
    
    
    それから、私たちはthen...catch... 比較が成功したかどうかをチェックするブロック
  • 比較が失敗した場合、エラーメッセージをcatch ブロック:
  • 
        .then((user)=>{
          bcrypt.compare(request.body.password, user.password)
          .then()
          .catch((error) => {
            response.status(400).send({
              message: "Passwords does not match",
              error,
            });
          })
        })
    
    
  • パスワードが正しいかどうかチェックしましょうthen ブロック
  • 
          .then((passwordCheck) => {
    
              // check if password matches
              if(!passwordCheck) {
                return response.status(400).send({
                  message: "Passwords does not match",
                  error,
                });
              }
            })
    
    
  • パスワードが一致した場合、jwt.sign() 関数.それは3パラメータを取るかjwt.sign(payload, secretOrPrivateKey, [options, callback]) . もっと読むことができますhere
  • 
    bcrypt.compare(request.body.password, user.password)
          .then((passwordCheck) => {
    
              // check if password matches
              if(!passwordCheck) {
                return response.status(400).send({
                  message: "Passwords does not match",
                  error,
                });
              }
    
            //   create JWT token
            const token = jwt.sign(
              {
                userId: user._id,
                userEmail: user.email,
              },
              "RANDOM-TOKEN",
              { expiresIn: "24h" }
            );
          })
    
    
  • 最後に、成功したトークンを持つ成功メッセージを返します
  • 
    .then((user)=>{
          bcrypt.compare(request.body.password, user.password)
          .then((passwordCheck) => {
    
              // check if password matches
              if(!passwordCheck) {
                return response.status(400).send({
                  message: "Passwords does not match",
                  error,
                });
              }
    
            //   create JWT token
            const token = jwt.sign(
              {
                userId: user._id,
                userEmail: user.email,
              },
              "RANDOM-TOKEN",
              { expiresIn: "24h" }
            );
    
             //   return success response
             response.status(200).send({
              message: "Login Successful",
              email: user.email,
              token,
            });
          })
    
    
  • ログインエンドポイントは次のようになります.
  • 
    // login endpoint
    app.post("/login", (request, response) => {
      // check if email exists
      User.findOne({ email: request.body.email })
    
        // if email exists
        .then((user) => {
          // compare the password entered and the hashed password found
          bcrypt
            .compare(request.body.password, user.password)
    
            // if the passwords match
            .then((passwordCheck) => {
    
              // check if password matches
              if(!passwordCheck) {
                return response.status(400).send({
                  message: "Passwords does not match",
                  error,
                });
              }
    
              //   create JWT token
              const token = jwt.sign(
                {
                  userId: user._id,
                  userEmail: user.email,
                },
                "RANDOM-TOKEN",
                { expiresIn: "24h" }
              );
    
              //   return success response
              response.status(200).send({
                message: "Login Successful",
                email: user.email,
                token,
              });
            })
            // catch error if password do not match
            .catch((error) => {
              response.status(400).send({
                message: "Passwords does not match",
                error,
              });
            });
        })
        // catch error if email does not exist
        .catch((e) => {
          response.status(404).send({
            message: "Email not found",
            e,
          });
        });
    });
    
    
    

    テスト

  • 最後のチュートリアルで登録した資格情報でログインしてみましょう.ランダム参照token ログイン成功
  • If email が正しくないか、存在しないか
  • If password が間違っている

  • この時点で、あなたは自分自身のために一緒に手を置くことができます
    👏🏼👏🏼👏🏼👏🏼👏🏼

    結論


    私たちは、この認証シリーズを始めました、パート1でデータベースをセットアップすることによってuser コレクションとregister パート2の最終点と最終的に、この部分では、我々は首尾よくlogin ユーザが存在するかどうかのエンドポイントチェック.
    おめでとう!🍾🍾🍾
    次に調べましょう.私はあなたをそこにキャッチしたい.
    一方、すべてのコードはhere

    エベゲット / Authバックエンド


    このチュートリアルでは、NodeJsとMongoDBを使用してユーザーの認証を作成する方法を教えています