node/express + mongodb, ユーザー認証、CSRF対応、CRUDなど #node #express #mongo #javascript

■ 概要:

node/express +mongo DB関連で、
ユーザー認証、CSRF対応 のメモとなります

■ 環境

node 14
mongoDb : 3.6.3
・npm
mongodb: 3.6.3
express : 4.16.1
ejs : 2.6.2

■ 参考のコード

■ npm 追加

npm install mongodb --save

■ 実装など

mongo操作の部分は、なるべく await/ async を使用
コールバック処理を。少な目にしました

・ログイン
routes/login.js


/******************************** 
* 
*********************************/
router.get('/', function(req, res) {
 try{
   LibCsrf.set_token(req, res) 
   res.render('login', { user : "" });
 } catch (e) {
     console.log(e);
 }
});
/******************************** 
* 
*********************************/
router.post('/',async function(req, res){
   try{
       var data = req.body
console.log( data  )  
       var valid_user = await LibAuth.validUserAuth(res ,data.email, data.password )
       if (valid_user){
           req.flash('success', 'Welcom, Login completed.');  
           res.redirect('/')
       }else{
           req.flash('err', 'Error Login, authrize NG');
           console.log("error, login");
           res.clearCookie('user');
           res.redirect('/login')
       }        
   } catch (e) {
       console.log(e);
       res.status(500).send();
   }

});

・ユーザー追加
routes/users.js

パスワード暗号化、mongo登録


/******************************** 
* 
*********************************/
router.get('/add', function(req, res, next) {
 LibCsrf.set_token(req, res) 
 res.render('users/add', {});
});
/******************************** 
* 
*********************************/
router.post('/add', async function(req, res, next){
   try{ 
       if(LibCsrf.valid_token(req, res)== false){ return false; }
       let data = req.body
       console.log( data );
       let hashed_password = bcrypt.hashSync(data.password, 10);
       var item = {
           name: "",
           mail: data.email ,  
           password: hashed_password ,
           created_at: new Date()
       };        
       const collection = await LibMongo.get_collection("users" )
       await collection.insertOne(item);
       req.flash('success', 'Complete, save User'); 
       res.redirect('/')          
   } catch (e) {
       console.log(e);
       req.flash('err', 'Error ,save User');
       res.redirect('/')        
   }    
});

・ CRUDサンプル ( /tasks )
routes/api.js

/******************************** 
* 
*********************************/
router.get('/tasks_index', async function(req, res) {
   try{
       const collection = await LibMongo.get_collection("tasks" )
       collection.find().sort({created_at: -1}).toArray(function(err, result) {
           if (err) throw err;
//            console.log(result);
           var param = {"docs": result };
           res.json(param)            
       });
   } catch (err) {
       console.log(err);
       res.status(500).send();    
   }   
});
/******************************** 
* 
*********************************/
router.post('/tasks_new', async function(req, res){
   try{
       var data = req.body;
       const collection = await LibMongo.get_collection("tasks" )
       var item = { 
           "title": data.title,
           "content": data.content,
           "created_at" : new Date()
       };        
       await collection.insertOne(item);
       res.json(req.body);
   } catch (err) {
       console.log(err);
       res.status(500).send();    
   }    
}); 

■ 関連のページ

・node/express認証の例、password暗号化 / CSRF対応 / Redis 認証情報
https://note.com/knaka0209/n/ncf4282b8f3c2

■ Update

・2020/11/14

mongo登録速度の測定値を、追記しました。
1,000 件で。 0.89 msec
(1件あたり、0.00089msec / 0.89ナノ秒)

・redisが、同件数で。 35msec程で。
 mongoが高速のようです

■ 参考git
https://github.com/kuc-arc-f/app11_2mongo_post/


この記事が気に入ったらサポートをしてみませんか?