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


で、我々はMongoDBデータベースを設定し、我々のnodejsアプリに接続します.
この部分では、モデルを設定し、Aを作りますregister 入力を受け入れ、パスワードでハッシュを使用する bcrypt . 始めましょう.

スタータープロジェクト


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

ユーザーモデルの作成

  • ファイルを作成するdb フォルダと名前userModel
  • ファイルにmongoose
  • 
    const mongoose = require("mongoose");
    
    
  • 定数を作成するUserSchema ) そして、それのようにマングーススキーマをそれに割り当ててください
  • 
    const UserSchema = new mongoose.Schema({})
    
    
  • スキーマで、必要な2つのフィールドを入力しますemail and password ) のように空のオブジェクトを割り当てます:
  • const UserSchema = new mongoose.Schema({
      email: {},
    
      password: {},
    })
    
    
  • では、どのようにフィールドがどのように見えるかを指定しましょうmongoose option
  • 
    email: {
        type: String,
        required: [true, "Please provide an Email!"],
        unique: [true, "Email Exist"],
      },
    
      password: {
        type: String,
        required: [true, "Please provide a password!"],
        unique: false,
      },
    
    
  • 最後に輸出しましょうUserSchema 次のコード
  • 
    module.exports = mongoose.model.Users || mongoose.model("Users", UserSchema);
    
    
    上のコードは次のように言います

    Now we have completed our model for the user, the user collection is now ready to receive the data we will pass in.


    登録ユーザ終了点

  • インストールbcrypt . これはユーザから受け取るパスワードをハッシュするために使用されます
  • 
    npm install --save bcrypt
    
    
  • 必要bcrypt の上部にapp.js ファイル
  • 
    const bcrypt = require("bcrypt");
    
    
  • 必要とするuserModel 我々のデータベースを必要とする行のすぐ下に
  • 
    const User = require("./db/userModel");
    
    
  • 私たちはregister 直前のエンドポイントmodule.exports = app; ライン
  • 
    app.post("/register", (request, response) => {
    
    });
    
    
  • データベースにメールとパスワードを保存する前にパスワードをハッシュします.パスワードを次のコードでハッシュしましょう.
  • 
    bcrypt.hash(request.body.password, 10)
      .then()
      .catch()
    
    
    上記のコードはbcrypt ハッシュするpassword 受信request body 10回または塩ラウンド
    ハッシュが成功するならば、我々はthen ブロックと保存email and hashed password 他のデータベースではcatch ブロック
  • catch ブロックを返します.
  • 
       .catch((e) => {
          response.status(500).send({
            message: "Password was not hashed successfully",
            e,
          });
        });
    
    
  • then ブロックは、我々が今持っているデータを保存してみましょう.の新しいインスタンスを作成しますuserModel などの更新データを収集します
  • 
    .then((hashedPassword) => {
          const user = new User({
            email: request.body.email,
            password: hashedPassword,
          });
    });
    
    
  • 次に、データを保存します.まだthen ブロックします.
  • 
    user.save()
    
    
    そしてそれです.あなたがこの点で止まるならば、それはすべてよいです.それは、フィードバックを保存します.
  • フィードバックを得るためにthen...catch... ブロック
  • 
         user.save().then((result) => {
            response.status(201).send({
              message: "User Created Successfully",
              result,
            });
          })
          .catch((error) => {
            response.status(500).send({
              message: "Error creating user",
              error,
            });
          });
    
    
    最後にregister エンドポイントは次のようになります.
    
    // register endpoint
    app.post("/register", (request, response) => {
      // hash the password
      bcrypt
        .hash(request.body.password, 10)
        .then((hashedPassword) => {
          // create a new user instance and collect the data
          const user = new User({
            email: request.body.email,
            password: hashedPassword,
          });
    
          // save the new user
          user
            .save()
            // return success if the new user is added to the database successfully
            .then((result) => {
              response.status(201).send({
                message: "User Created Successfully",
                result,
              });
            })
            // catch erroe if the new user wasn't added successfully to the database
            .catch((error) => {
              response.status(500).send({
                message: "Error creating user",
                error,
              });
            });
        })
        // catch error if the password hash isn't successful
        .catch((e) => {
          response.status(500).send({
            message: "Password was not hashed successfully",
            e,
          });
        });
    });
    
    

    エンドポイントのテスト

  • あなたがそうしないならば、ターミナルであなたのサーバーを始めてください
  • あなたの郵便配達人に行って、以下のようにテストしてください
  • あなたのMongoDBアトラスに移動します.クリックCollections そして、あなたはちょうど以下のように追加されたデータを見る必要があります

  • この足を達成おめでとう

    結論


    これは、この認証シリーズのパート2でした.パスワードをハッシュした後、MongoDBデータベースにユーザーを追加することがいかに簡単かを明らかにしました.
    全コードhere

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


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


    次に、その方法を見ていきます.
    私と連絡しなさい.すぐに会いましょう.