index.js 2.39 KB
var express = require('express')

var app = express()

var mysql = require('mysql')

var router = express.Router();

var path = require('path')

var passport = require('passport')
var LocalStrategy = require('passport-local').Strategy;


var connection = mysql.createConnection({
    host: 'localhost',
    port: 3306,
    user: 'root',
    password: 'ksmhjh88',
    database: 'nodetest'
})

connection.connect()


router.get('/', function (req, res) {
    //get : req.param('email')
    //console.log(req.body.email)
    //res.send("<h1>Welcome!</h1>" + req.body.email)

    //res.render('email.ejs',{'email' : req.body.email })
    console.log('get join url')
    //res.sendFile(path.join(__dirname, '../../public/join.html'))

    var msg;
    var errMsg = req.flash('error')
    if (errMsg)
        msg = errMsg;

    res.render('join/join.ejs', {'message': msg});
})

passport.serializeUser(function (user, done) {
    console.log('passport session save : ', user.id)
    done(null, user.id)
})

passport.deserializeUser(function (id, done) {
    console.log('passport session get id : ', id)
    done(null, id)
})


passport.use('local-join', new LocalStrategy({
        usernameField: 'email',
        passwordField: 'password',
        passReqToCallback: true
    }, function (req, email, password, done) {
        var query = connection.query('select * from user where email=?', [email], function (err, rows) {
            if (err) {
                console.log('error')
                return done(err)
            }
            //console.log(req)
            //console.log(email)
            //console.log(password)
            //console.log(rows.length)

            //중복 가입 방지
            if (rows.length) {
                console.log('existed user')
                return done(null, false, {message: 'your email is already used'})
            } else {
                var sql = {email: email, password: password};
                var query = connection.query('insert into user set ?', sql, function (err, rows) {
                    if (err) throw err
                    return done(null, {'email': email, 'id': rows.insertId})
                })
            }
        })
        console.log('local-join callback called');
    }
))

router.post('/', passport.authenticate('local-join', {
        successRedirect: '/main',
        failureRedirect: '/join',
        failureFlash: true
    })
)


module.exports = router;