const LocalStrategy = require('passport-local').Strategy;
const bcrypt = require('bcrypt');
const User = require('../user/userData');

//初始化passport
const initialize = (passport) => {
    //驗證用戶
    const authenticateUser = async (username, password, done) => {
        const user = await User.get(null, username);
        try {
            if (user == null) {
                return done(null, false, { message: '查無此用戶' });
            }
            if (await bcrypt.compare(password, user.password)) {
                return done(null, user);
            } else {
                return done(null, false, { message: '密碼錯誤' });
            }
        } catch (err) {
            return done(err);
        }
    };

    passport.use(new LocalStrategy(authenticateUser));

    //以userID序列化儲存進session
    passport.serializeUser((user, done) => done(null, user.id));
    passport.deserializeUser(async (id, done) => {
        done(null, await User.get(id));
        // done(null, await getUser.getUserByID(id));
    });
};

module.exports = initialize;
