LoginSignup
1
0

More than 3 years have passed since last update.

Node.jsとMongoDBを使ったログイン機能の実装をMacのlocalhostで試す

Posted at

Node.jsとMongoDBを使ったログイン機能の実装をMacのlocalhostで試す

Webサービスを作りたいので、ログイン機能をlocalhostで試します。

MongoDBとNode.jsを使います。

Node.jsのインストールの説明は割愛。

MongoDBのインストールから起動まで

インストールの前処理

brew tap mongodb/brew

インストール

brew install mongodb-community

保存場所作成

sudo mkdir /var/lib/mongodb

ログ作成

sudo touch /var/log/mongodb.log

起動

sudo mongod --dbpath /var/lib/mongodb --logpath /var/log/mongodb.log

ログイン機能の実装

まず、モジュールをインストールしておきます。
npm install express
npm install monogodb
下記のコードで sign up と login が出来ると思います。

server.js
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const MongoClient = require('mongodb').MongoClient;
const http = require('http').Server(app);

const url = 'mongodb://localhost:27017';
const dbName = 'myMongo';
const connectOption = {
    useNewUrlParser: true,
    useUnifiedTopology: true,
}

const transactionKururiDownload = async (data, res) => {
  let client;
  let login = false;
  try {
    client = await MongoClient.connect(url, connectOption);
    const db = client.db(dbName);
    const collection = db.collection('account');
      await collection.find({}).toArray( (err, docs) => {
        for (const doc of docs) {
          if (doc.mail == data.mail) {
            if (doc.password == data.password) {
              login = true;
              res.sendFile(__dirname + "/index.html");
            }
          }
        }
        if (!login) {
          res.send("login error");
        }
      });
  } catch (error) {
    console.log(error);
  } finally {
//    client.close();
  }
};

const transactionKururiInsert = async (data, res) => {
  let client;
  data = Object.assign(data, {date: new Date() });
  try {
    client = await MongoClient.connect(url, connectOption);
    const db = client.db(dbName);
    const collection = db.collection('account');
    const a = await collection.updateOne({mail:data.mail, password:data.password, name:data.name, date:data.date}, {$set:data}, true );
    if (a.result.n == 0) {
      await collection.insertOne(data);
    }
  } catch (error) {
    console.log(error);
  } finally {
    client.close();
  }
};



app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

app.get('/', (req, res) => {
  res.sendFile(__dirname + "/login.html");
});
app.get('/signup', (req, res) => {
  res.sendFile(__dirname + "/signup.html");
});

app.post('/signup', async (req, res) => {
  let client;
  let exist = false;
  try {
    client = await MongoClient.connect(url, connectOption);
    const db = client.db(dbName);
    const collection = db.collection('account');
      await collection.find({}).toArray( (err, docs) => {
        console.log(docs);
        for (const doc of docs) {
          if (doc.mail == req.body.mail){
            console.log(req.body.mail);
            exist = true;
          }
        }

        let user = {mail:"", name:"", password:""};

        if (!exist && req.body.mail != "" && req.body.password != "") {
          user["mail"] = req.body.mail;
          user["password"] = req.body.password;
          user["name"] = user.mail.substr(0, user.mail.indexOf("@"));
          transactionKururiInsert(user, res);

          res.sendFile(__dirname + "/signuped.html");
        } else {
          res.sendFile(__dirname + "/signuperror.html");
        }
      });
  } catch (error) {
    console.log(error);
  } finally {
//    client.close();
  }
});


app.post('/', (req, res) => {

  let user = {
    mail:"", name:"", password:""
  };

  user["mail"] = req.body.mail;
  user["password"] = req.body.password;
  user["name"] = user.mail.substr(0, user.mail.indexOf("@"));
  transactionKururiDownload(user, res);

});

http.listen(8080, () => {
  console.log('listening on :8080');
});

login.html
<html>
<head>
    <title>login</title>
</head>
<body style="width: 100%; display: flex; flex-direction: column; justify-content: center; align-items: center;">
    <form action="" method="post">
        <h1>login</h1>
        <table>
            <tr>
                <td>mail</td>
                <td><input id="mail" name="mail" type="mail" /></td>
            </tr>
            <tr>
                <td>password</td>
                <td><input id="password" name="password" type="password" /></td>
            </tr>
        </table>
        <button>send</button>
    </form>
    <br>
    <a href="signup">sign up</a>
</body>
</html>

signup.html
<html>
<head>
    <title>signup</title>
</head>
<body style="width: 100%; display: flex; flex-direction: column; justify-content: center; align-items: center;">
    <form action="" method="post">
        <h1>signup</h1>
        <table>
            <tr>
                <td>mail</td>
                <td><input id="mail" name="mail" type="mail" /></td>
            </tr>
            <tr>
                <td>password</td>
                <td><input id="password" name="password" type="password" /></td>
            </tr>
        </table>
        <button>send</button>
    </form>
</body>
</html>
signuped.html
<!Doctype html>
<html>
  <head>
    <title>logined</title>
  </head>
  <body style="width: 100%; display: flex; flex-direction: column; justify-content: center; align-items: center;">
    <h1>Success signup!</h1>
    <a href="/">please login</a>
  </body>
</html>
signuperror.html
<!Doctype html>
<html>
  <head>
    <title>error</title>
  </head>
  <body style="width: 100%; display: flex; flex-direction: column; justify-content: center; align-items: center;">
    <h1>signup error</h1>
  </body>
</html>
index.html
<!DOCTYPE html>
<html>
    <head>
        <title>test</title>
    </head>
    <body>
        login success!
    </body>
</html>
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0