간단한 sns만들기 - 회원가입 및 로그인

passport

index.js

const passport = require('passport');
const User = require('../schemas/user');
const local = require('./localStrategy');

module.exports = ()=>{
  passport.serializeUser((user, done)=>{
    done(null, user.id);
  });

  passport.deserializeUser((id, done)=>{
    User.findOne({
      id : id,
    })
    .then(user=>done(null, user))
    .catch(err=>done(err));
  });
  
  local();

  
}

localStrategy.js

const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
const User = require('../schemas/user');
module.exports = ()=>{
  passport.use(new LocalStrategy({
    usernameField : 'id',
    passwordField : 'password',
  },async(id, password, done)=>{
    try{
      const exUser = await User.findOne({id : id});
      if(exUser){
        if(exUser.password === password){
          done(null, exUser);
        }
        else{
          done(null, false, {message : 'Wrong password'});
        }
      }else{
        done(null, false, {message : 'No such user exists'});
      }

    }catch(error){
      console.error(error);
      done(error);
    }
  }))
}

Schemas

index.js

const mongoose = require('mongoose');

// connect functions 
const connect = ()=>{
  if(process.env.node_ENV !== 'production'){
    mongoose.set('debug', true);
  }
  // show mongoose queries only when not in a production environment

  mongoose.connect('mongodb://localhost:27017/sns', {
    //connnect to sns database
    useNewUrlParser : true,
    useCreateIndex : true,
    useUnifiedTopology: true,
  }, (err)=>{
    if(err){
      console.log('connection error occured', err);
    }
    else{
      console.log('connection success');
    }
  });
};

mongoose.connection.on('error', (err)=>{
  console.error('connection error occured', err);
});

mongoose.connection.on('disconnected', ()=>{
  console.log('the connection has been disrupted. Try connect to it again');
  connect();
});

module.exports = connect;

user.js

const mongoose = require('mongoose');

const {Schema} = mongoose;

const userSchema = new Schema({
  username : {
    type : String,
    required : true,
  },
  id : {
    type : String,
    required : true,
    unique : true,
  },
  password : {
    type : String,
    required : true,
  },
});

module.exports = mongoose.model('User', userSchema);

follower.js

const mongoose = require('mongoose');

const {Schema} = mongoose;

const followerSchema = new Schema({
  followerId : {
    type : [ObjectId],    
  }
});

module.exports = mongoose.model('Follower', followerSchema);

following.js

const mongoose = require('mongoose');

const {Schema} = mongoose;

const followingSchema = new Schema({
  followerId : {
    type : [ObjectId],    
  }
});

module.exports = mongoose.model('Following', followingSchema);

routes

page.js

const passport = require('passport');
const User = require('../schemas/user');
const local = require('./localStrategy');

module.exports = ()=>{
  passport.serializeUser((user, done)=>{
    done(null, user.id);
  });

  passport.deserializeUser((id, done)=>{
    User.findOne({
      id : id,
    })
    .then(user=>done(null, user))
    .catch(err=>done(err));
  });
  
  local();

  
}

auth.js

const express = require('express');
const passport = require('passport');
const User = require('../schemas/user');
const router = express.Router();

router.get('/join', (req, res, next)=>{
  res.render('join', {title : 'my app - join', isLoggedIn :req.user,});
  next();
});

router.get('/join/local', (req, res, next)=>{
  res.render('join_local', {title : 'my app - join', isLoggedIn : req.user,});
  next();
});

router.post('/join/local', async (req, res, next)=>{
  const {username, id, password} = req.body;
  await User.create({
    username : username,
    id : id,
    password : password,
  });
  res.redirect('/');
  next();
});

router.get('/login', (req, res, next)=>{
  res.render('login', {title : 'myapp - login', isLoggedIn : req.user});
  next();
}).post('/login', (req, res, next)=>{
  passport.authenticate('local', (authError, user, info)=>{
    if(authError){
      console.error(authError);
      return next(authError);
    }
    if(!user){
      res.redirect(`/auth/login/Eror=${info.message}`);
    }
    req.logIn(user, (loginError)=>{
      if(loginError){
        console.error(loginError);
        return next(loginError);
      }
      console.log('req :', req);
      return res.redirect('/');
    })
  })(req, res, next);
});

router.get('/logout', async(req, res, next)=>{
  req.logOut();
  req.session.destroy();
  res.redirect('/');
  next();
});

module.exports = router;

passport를 사용해서 local 로그인을 구현했다. 카카오톡 로그인이랑 페이스북도 해야하는데 이건 귀찮아서 나중에...

사실 following이랑 follower기능은 mysql로 해야 깔끔하긴 하지만 mongoDB에 익숙해지기 위해 그냥 mongoose로 디자인했다.

이제 점점 db랑 node.js 감을 잡아가는 것 같다. 그리고 생각보다 프론트엔드가 재밌다... 프론트를 더 재밌어하는 것은 내 착각인감?

좋은 웹페이지 즐겨찾기