{"size": 1768, "ext": "js", "max_stars_repo_path": "server/passport.js", "max_stars_repo_name": "miladbonakdar/ICMP-server", "max_stars_repo_stars_event_min_datetime": "2018-12-29T09:03:38.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-13T17:26:10.000Z", "max_issues_repo_path": "server/passport.js", "max_issues_repo_name": "miladbonakdar/ICMP-rai", "max_issues_repo_issues_event_min_datetime": "2019-12-28T07:22:40.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-26T09:12:25.000Z", "max_forks_repo_path": "server/passport.js", "max_forks_repo_name": "miladbonakdar/ICMP-rai", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": 14, "max_issues_count": 5, "max_forks_count": null, "avg_line_length": 30.4827586207, "max_line_length": 82, "alphanum_fraction": 0.5707013575}
const passport = require('passport');
const passportJWT = require('passport-jwt');
const User = require('./repositories/mongoModels/user.model');
const LocalStrategy = require('passport-local').Strategy;
const jwt_secret = require('./app.config').get().jwt_secret;
const ExtractJWT = passportJWT.ExtractJwt;
const JWTStrategy = passportJWT.Strategy;

module.exports = () => {
    const localStrategyMiddleware = async function(username, password, done) {
        let user;
        try {
            user = await User.findOne({ username });
            if (!user) {
                return done(null, false, { message: 'No user by that username' });
            }
        } catch (e) {
            return done(e);
        }

        let match = await user.comparePassword(password);
        if (!match) {
            return done(null, false, { message: 'Not a matching password' });
        }
        delete user.password;
        return done(null, user);
    };

    passport.use(
        new LocalStrategy({
            usernameField: 'username',
            passwordField: 'password'
        },
        localStrategyMiddleware)
    );

    const JWTStrategyMiddleware = async function(jwtPayload, done) {
        try {
            const user = await User.findById(jwtPayload.id).select('-password');
            if (!user) {
                return done(null, false, { message: 'cannot fine the user' });
            }
            delete user.password;
            return done(null, user);
        } catch (error) {
            return done(error);
        }
    };

    passport.use(
        new JWTStrategy({
            jwtFromRequest: ExtractJWT.fromAuthHeaderAsBearerToken(),
            secretOrKey: jwt_secret
        },
        JWTStrategyMiddleware)
    );
};
