1
0

More than 1 year has passed since last update.

Webの勉強はじめてみた その36 〜Sequelizeでデータ削除とCSRF脆弱性の対策〜

Posted at

N予備校「プログラミング入門Webアプリ」を受講しています。
今回が最後、第4章20〜24節です。

Sequelizeを利用したデータの削除

テストデータの一括削除。

function deleteScheduleAggregate(scheduleId, done, err) {  
  Availability.findAll({
    where: { scheduleId: scheduleId }
  }).then(availabilities => {
    const promises = availabilities.map(a => { return a.destroy(); });
    return Promise.all(promises);
  }).then(() => {
    return Candidate.findAll({
      where: { scheduleId: scheduleId }
    });
  }).then(candidates => {
    const promises = candidates.map(c => { c.destroy(); });
    promises.push(promiseCommentDestroy);
    return Promise.all(promises);
  }).then(() => {
    return Schedule.findByPk(scheduleId).then(s => { return s.destroy(); });
  }).then(() => {
    if(err) return done(err);
    done();
  });
}

Promise.all
複数のPromiseオブジェクトをまとめたPromiseを作成。
引数で渡したPromiseの処理を待って次の処理を実行する。

data属性

button(class=`availability-toggle-button btn-lg ${buttonStyles[availability]}`
                data-schedule-id=schedule.scheduleId 
                data-user-id=user.userId 
                data-candidate-id=candidate.candidateId 
                data-availability=availability) #{availabilityLabels[availability]}              

data-
プロパティを設定することで、JavaScriptから取得できる。
値渡しという点では、inputhiddenと似てるような気もする。

$('.availability-toggle-button').each((i, e) => {
  const button = $(e);
  button.click(() => {
    const scheduleId = button.data('schedule-id');
    const userId = button.data('user-id');
    const candidateId = button.data('candidate-id');
    const availability = parseInt(button.data('availability'));
    const nextAvailability = (availability + 1) % 3;
    $.post(
      `/schedules/${scheduleId}/users/${userId}/candidates/${candidateId}`,
      { availability: nextAvailability},
      data => {
        button.data('availability', data.availability);
        const availabilityLabels = ['', '?', ''];
        button.text(availabilityLabels[data.availability]);
      }
    );
  });
});

classで検索すると配列が返ってくる。
iはインデックス、eは エレメント。

this

基本的にはthisが書かれた処理の関数が所属するオブジェクトを指す。

entry.js
import $ from 'jquery';
globalThis.jQuery = $;
import bootstrap from 'bootstrap';

globalThis
Node.jsにおいて実行環境のグローバルオブジェクトを参照する。
グローバルオブジェクトのjQueryというプロパティに jQueryを代入している。
こうすることで、BootstrapがjQueryを利用できるようになる。

CSRF脆弱性への対策

ミドルウェアのcsurfをインストール

yarn add csurf@1.8.3
schedule.js
const csrf = require('csurf');
const csrfProtection = csrf({ cookie: true });
// 新規作成画面の前に認証のチェック
router.get('/new', authenticationEnsurer, csrfProtection, (req, res, next) =>{
  res.render('new', {user: req.user, csrfToken: req.csrfToken() });
});
new.pug
input(type="hidden" name="_csrf" value!=csrfToken)

まとめ

今回で「プログラミング入門コース」を終了。修了の方がいいのか。
11月末からはじめて、最後の方は解説動画を参考にしながらでしたが、なんとかここまで進められました。
とはいえ、自分で手打ちしながらではあっても、実際に自分で一から何かを作ってみないと、本当の意味での理解はできないと思ってます。ここからですね。

1
0
1

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