module.exports = (passport, Strategy, crypto, config, client6) => {
    passport.use(new Strategy((username, password, cb) => {
        if (username && password) {
            client6.search({
                index: config.index,
                body: {
                    query: {
                        match: {
                            user: username
                        }
                    }
                }
            }, (err, user) => {
                if (err) {
                    return cb(err)
                }
                if (!user || !user.body) {
                    return cb(null, false)
                }
                if (user.body.hits.total === 1 && user.body.hits.hits[0]._source.verified && !user.body.hits.hits[0]._source.locked
                    && user.body.hits.hits[0]._source.password === crypto.createHash('sha256').update(password).digest('base64')) {
                    return cb(null, {
                        id: user.body.hits.hits[0]._id,
                        user: user.body.hits.hits[0]._source.user,
                        email: user.body.hits.hits[0]._source.email
                    })
                }
                else {
                    return cb(null, false)
                }
            })
        } else {
            return cb(null, false)
        }
    }))

    passport.serializeUser((user, cb) => {
        cb(null, user.user)
    })

    passport.deserializeUser(async (username, cb) => {
        client6.search({
            index: config.index,
            body: {
                query: {
                    match: {
                        user: username
                    }
                }
            }
        }, (err, user) => {
            if (err) {
                return cb(err)
            }
            return cb(null, {
                id: user.body.hits.hits[0]._id,
                user: user.body.hits.hits[0]._source.user,
                email: user.body.hits.hits[0]._source.email
            })
        })
    })
}