Node js 8일차 - bcrypto, JWT

00_8_3·2020년 11월 18일
0

간단 Node

목록 보기
9/27

Node js 8일차

bcrypt 패스워드 암호화 하기

bcrypt

공식문서

벨로퍼트

UserSchema.pre('save', function (next) {
    let user = this;
    if (user.isModified('password')) {
        bcrypt.genSalt(10, function (err, salt) {
            if (err) return next(err);
            bcrypt.hash(user.password, salt, function (err, hash) {
                if (err) return next(err);
                user.password = hash;
                next();
            });
        });
    } else {
        next();
    }
});

패스워드 대조하기

UserSchema.methods.comparePassword = function (candidatePassword) {
    return bcrypt.compare(candidatePassword, this.password);
};

JWT 적용하기

routes/Users.js

user.generateToken()
            .then(user => {
                res.cookie('x_auth', user.token)
                    .status(200)
                    .json({
                        loginSuccess: true,
                        userId: user._id,
                    })
                    .catch(err => {
                        res.status(400).send(err);
                    });
            })
            .catch(err => {
                res.json({ loginSuccess: false, err });
            });

models/Users.js

UserSchema.methods.generateToken = function () {
    const token = jwt.sign(this._id.toHexString(), 'secretToken');
    this.token = token;
    return this.save()
        .then(user => user)
        .catch(err => err);
};

0개의 댓글