FP6: controllers/users

Charlie·2021년 1월 2일
0

First Project

목록 보기
6/8
post-thumbnail
  • Json Web Token
  • Sequelize
// 'index.js' from 'controllers' Directory
module.exports = {
  usersController: require('./users'),
  postsController: require('./posts'),
  commentsController: require('./comments')
};
// 'index.js' from 'controllers/users' Directory
module.exports = {
  register : require('./register'),
  login : require('./login'),
  logout : require('./logout'),
  mypage : require('./mypage'),
  accessTokenRequest: require('./accessTokenRequest'),
  refreshTokenRequest: require('./refreshTokenRequest'),
};
// 'register.js' from 'controllers/users' Directory
const { User } = require('../../models');

module.exports = {
  
  post: async(req, res) => {
    const {email, username, password, passwordCheck} = req.body;
    if (!email || !password || !username || !passwordCheck) {
      res.status(422).json({
        data: null, 
        message: "insufficient parameters supplied"
      });
    }
    if (password !== passwordCheck) {
      res.status(400).json({
        data: null, 
        message: "passwordCheck does not correspond with password"
      });
    }
    const [newUser, created] = await User.findOrCreate({
      where: {email: email},
      defaults: {
        username: username,
        password: password,
      }
    })
    if (!created) {
      res.status(409).json({
        data: null, 
        message: "email already exists"
      });
    } else {
      const { id, username, email } = newUser;
      res.status(201).json({
        userInfo: { id, username, email }, 
        message: "successfully registered!"
      });
    }
  }
  
};
// 'login.js' from 'controllers/users' Directory
const { User } = require('../../models');
const jwt = require('jsonwebtoken');
require('dotenv').config();

module.exports = {
  
  post: async(req, res) => {
    const { email, password } = req.body;
    if (!email || !password) {
      res.status(422).json({
        data: null, 
        message: "insufficient parameters supplied"});
    }
    const userInfo = await User.findOne({
      where: {
        email:req.body.email, 
        password:req.body.password
      }
    });
    if (!userInfo) {
      res.status(401).json({
        data: null,
        message: "not authorized"
      });
    } else {
      const { id, username, email, profileUrl, nickname } = userInfo;
      const ACCESS_TOKEN = await jwt.sign(
        { id, username, email, profileUrl, nickname },
        process.env.ACCESS_SECRET, 
        {expiresIn: '12h'}
      );
      const REFRESH_TOKEN = await jwt.sign(
        { id, username, email, profileUrl, nickname },
        process.env.REFRESH_SECRET
      );
      res.cookie('refreshToken', REFRESH_TOKEN);
      res.status(200).json({
        accessToken: ACCESS_TOKEN, 
        message: "successfully token issued!"
      });
    }
  }
  
};
// 'logout.js' from 'controllers/users' Directory
module.exports = {
  
  post: (req, res) => {
    if (!req.headers.cookie) {
      res.status(400).json({
        data: null, 
        message: "invalid refresh token"
      });
    }
    const refreshToken = req.headers.cookie.split('=')[1];
    if (!refreshToken) {
      res.status(401).json({
        data: null, 
        message: "not authorized"
      });
    } else {
      delete req.headers.authorization;
      res.clearCookie('refreshToken');
      res.status(200).json({
        data: null, 
        message: "successfully log out!"
      });
    }
  }
  
};
// 'mypage.js' from 'controllers/users' Directory
const { User } = require('../../models')
const jwt = require('jsonwebtoken');
require('dotenv').config();

module.exports = {
  
  get: async (req, res) => {
    if(!req.headers['authorization']) {
      res.status(400).json({data: null, message: "insufficient parameters supplied"});
    }
   	const ACCESS_TOKEN = token.split(' ')[1];
    payload payload = await jwt.verify(ACCESS_TOKEN, process.env.ACCESS_SECRET);

    const foundUser = await User.findOne({
      where: {
        id: payload.id
      }
    })
    if(!foundUser) {
      res.status(404).json({
        data: null, 
        message: "not found user"
      });
    } else {
      const { id, username, email, profileUrl, githubUrl, introduce, nickname, created_at, updated_at } = foundUser;
      res.status(200).json({
        data: {
          userInfo: {
            id, username, email, profileUrl, githubUrl, introduce, nickname, created_at, updated_at
          }
        },
        message: "ok"
      });
    }

  },
  
  put: async (req, res) => {
    if(!req.headers['authorization']) {
      res.status(400).json({
        data: null, 
        message: "insufficient parameters supplied"
      });
    }
    const ACCESS_TOKEN = token.split(' ')[1];
    const payload = await jwt.verify(ACCESS_TOKEN, process.env.ACCESS_SECRET);
    const { username, profileUrl, githubUrl, introduce, nickname } = req.body;
    await User.update(
      { username, profileUrl, githubUrl, introduce, nickname },
      {
        where: {
        	id: payload.id
        }
      }
    )
    const updatedUser = await User.findOne({
    	where: {
        	id: payload.id
        }
    });
    if(!updatedUser) {
      res.status(401).json({data: null, message: "not authorized"});
    } else {
      const { id, username, email, profileUrl, githubUrl, introduce, nickname, created_at, updated_at } = updatedUser;
      res.status(200).json({
        data: {
          userInfo: {
            id, username, email, profileUrl, githubUrl, introduce, nickname, created_at, updated_at
          }
        },
        message: "ok"
      });
    }
  }
  
};
// 'accessTokenRequest.js' from 'controllers/users' Directory
const { User } = require('../../models');
const jwt = require('jsonwebtoken');
require('dotenv').config();

module.exports = {
  
  get: async (req, res) => {
    if (!req.headers['authorization']) {
      res.status(400).json({
        data: null,
        message: "invalid access token"
      });
    }
    const ACCESS_TOKEN = token.split(' ')[1];
    const payload = await jwt.verify(ACCESS_TOKEN, process.env.ACCESS_SECRET);
    const userInfo = await User.findOne({
      where: {
        id: payload.id
      }
    })
    if (!userInfo) {
      res.status(401).json({
        data:null,
        message:"access token has been tempered"
      });
    } else {
      const { id, username, email, profileUrl, nickname } = userInfo;
        res.status(200).json({
          data: {
            userInfo: { id, username, email, profileUrl, nickname }
          }, 
          message: "ok"
        });
     }
  }
  
};
// 'refreshTokenRequest.js' from 'controllers/users' Directory
const { User } = require('../../models');
const jwt = require('jsonwebtoken');
require('dotenv').config();

module.exports = {
  
  get: async (req, res) => {
    if (!req.headers.cookie) {
      res.status(400).json({
        data: null, 
        message: "invalid refresh token"
      });
    }
    const REFRESH_TOKEN = req.headers.cookie.split('=')[1];
    const refreshTokenData = await jwt.verify(REFRESH_TOKEN, process.env.REFRESH_SECRET);
    if (!refreshTokenData) {
      res.status(401).json({
        data: null,
        message: "invalid refresh token please login again"
      });
    }
    const userInfo = await User.findOne({
      where: {
        id: refreshTokenData.id
      }
    });
    if (!userInfo) {
      res.status(403).json({
        data: null,
        message: "refresh token has been tempered"
      });
    } else {
      const { id, email, username, profileUrl, nickname } = userInfo;
      const newAccessToken = await jwt.sign(
        { id, email, username, profileUrl, nickname }, 
        process.env.ACCESS_SECRET, 
        {expiresIn:'2h'}
      );
      res.status(200).json({
        data:{
          accessToken: newAccessToken,
          userInfo: { id, email, username, profileUrl, nickname },
        },
        message: "ok"
      });
    }
  }
  
};

0개의 댓글