Skip to content

Commit

Permalink
Merge branch 'dev' into feat/channel-list
Browse files Browse the repository at this point in the history
  • Loading branch information
Changyu-Ryou committed Nov 26, 2020
2 parents 66e558c + 6d025ba commit b8f17c5
Show file tree
Hide file tree
Showing 33 changed files with 1,453 additions and 187 deletions.
8 changes: 8 additions & 0 deletions .github/CODEOWNERS
Validating CODEOWNERS rules …
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
# This is a comment.
# Each line is a file pattern followed by one or more owners.

# These owners will be the default owners for everything in
# the repo. Unless a later match takes precedence,
# @global-owner1 and @global-owner2 will be requested for
# review when someone opens a pull request.
* @boostcamp-2020/project12-c
8 changes: 8 additions & 0 deletions .github/PULL_REQUEST_TEMPLATE
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
## Linked Issue
close #

## κ³΅μœ ν•  사항
-

## λ…Όμ˜ν•  사항
- μ—†μŠ΅λ‹ˆλ‹€. ❌
12 changes: 10 additions & 2 deletions backend/app.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
require('dotenv').config()
import express from 'express'
import path from 'path'
import cookieParser from 'cookie-parser'
Expand All @@ -6,7 +7,10 @@ import mongoose from 'mongoose'
import controller from './controller'
import statusCode from './util/statusCode'
import resMessage from './util/resMessage'
require('dotenv').config()
import passport from 'passport'
import passportConfig from './config/passport'
import './chatServer'
import cors from 'cors'

const app = express()

Expand All @@ -21,10 +25,14 @@ mongoose
.catch(err => console.error(err))

app.use(logger('dev'))
app.use(cors({ origin: true, credentials: true }))
app.use(express.json())
app.use(express.urlencoded({ extended: false }))
app.use(cookieParser())
app.use(express.static(path.join(__dirname, '../dist')))
app.use(cookieParser(process.env.COOKIE_SECRET))
app.use(passport.initialize())
app.use(cors({ origin: true, credentials: true }))
passportConfig()

app.use('/api', controller)
app.use('/docs', express.static(path.join(__dirname, './docs')))
Expand Down
31 changes: 31 additions & 0 deletions backend/chatServer.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { config as dotenv } from 'dotenv'
import express from 'express'
import { createServer } from 'http'
import createChatServer from 'socket.io'
dotenv()

const server = createServer(express())
const io = createChatServer(server, {
cors: { origin: process.env.FRONTEND_HOST, credentials: true },
})

const namespace = io.of('chat')
namespace.use((socket, next) => {
// TODO jwt 검증 둜직 ν•„μš”
next()
})

namespace.on('connection', socket => {
socket.on('new message', data => {
// TODO νŠΉμ • μ±„λ„λ‘œ μ „μ†‘ν•˜λ„λ‘ λ³€κ²½, db에 μ €μž₯ ν•„μš” (ν˜„μž¬λŠ” μžμ‹  μ œμ™Έ 전체 전솑)
socket.broadcast.emit('new message', {
message: data,
})
})
})

server.listen(process.env.CHAT_PORT, () => {
console.log('chat server created 4000')
})

export default server
87 changes: 87 additions & 0 deletions backend/config/passport.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
const passport = require('passport')
const GitHubStrategy = require('passport-github').Strategy
const JWTStrategy = require('passport-jwt').Strategy
const { User } = require('../model/User')

require('dotenv').config()

const githubStrategyOption = {
clientID: process.env.GITHUB_CLIENT_ID,
clientSecret: process.env.GITHUB_CLIENT_SECRET,
callbackURL: process.env.GITHUB_CALLBACK_URL,
}

async function gitStrategyLogin(profiles) {
try {
let user = await User.findOne({ OAuthId: profiles.id })
if (user === null) {
const data = await User.create({
OAuthId: profiles.id,
fullName: profiles.username,
isDeleted: false,
})
return {
success: true,
id: data._id,
}
}
return {
success: true,
id: user._id,
}
} catch (err) {
return { success: false }
}
}

async function githubVerify(accessToken, refreshToken, profile, done) {
try {
const result = await gitStrategyLogin(profile)
const user = { id: result.id }

if (result.success) {
return done(null, user)
}
return done(null, false, { message: 'κΉƒν—ˆλΈŒ λ‘œκ·ΈμΈμ— μ‹€νŒ¨ν–ˆμŠ΅λ‹ˆλ‹€.' })
} catch (err) {
return done(null, false, { message: 'GitHub verify err λ°œμƒ' })
}
}

const cookieExtractor = req => {
if (req.signedCookies) return req.signedCookies.token
if (req.cookies) return req.cookies
}

const isExist = async userId => {
try {
let user = await User.findOne({ _id: userId })
return {
success: true,
id: user._id,
}
} catch (err) {
return { success: false }
}
}

const jwtStrategyOption = {
jwtFromRequest: cookieExtractor,
secretOrKey: process.env.JWT_SECRET,
}
async function jwtVerify(payload, done) {
try {
const result = await isExist(payload.id)
if (!result.success) {
return done(null, false, { message: 'JWT 토큰 인증에 μ‹€νŒ¨ν–ˆμŠ΅λ‹ˆλ‹€.' })
}
return done(null, result)
} catch (err) {
return done(null, false, { message: 'JWT verify err λ°œμƒ' })
}
}

module.exports = () => {
passport.use(new GitHubStrategy(githubStrategyOption, githubVerify))
passport.use(new JWTStrategy(jwtStrategyOption, jwtVerify))
}
15 changes: 14 additions & 1 deletion backend/controller/channel/channel.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import { asyncWrapper } from '../../util'
import service from '../../service/channel'

const { WorkspaceUserInfo } = require('../../model/WorkspaceUserInfo')
const { Channel } = require('../../model/Channel')
const { ChannelConfig } = require('../../model/ChannelConfig')
const { Chat } = require('../../model/Chat')

/* GET /api/channle get channel list */
const getChannelList = async (req, res, next) => {
try {
const workspaceUserInfoId = req.query.workspaceUserInfoId
Expand Down Expand Up @@ -116,9 +118,20 @@ const muteChannel = async (req, res, next) => {
}
}


const createChannel = asyncWrapper(async (req, res) => {
const { code, success, data } = await service.createChannel({
...req.body,
creator: req.user,
})
return res.status(code).json({ success, data })
})

module.exports = {
getChannelList,
getChannelHeaderInfo,
inviteUser,
muteChannel,
createChannel
}

13 changes: 8 additions & 5 deletions backend/controller/channel/index.js
Original file line number Diff line number Diff line change
@@ -1,17 +1,20 @@
const express = require('express')
const router = express.Router()
const channelController = require('./channel')
const controller = require('./channel')

/* GET /api/channle get channel list */
router.get('/', channelController.getChannelList)
router.get('/', controller.getChannelList)


router.post('/', controller.createChannel)

/* GET /api/channle/{channelId}/info get channel header info */
router.get('/:channelId/info', channelController.getChannelHeaderInfo)
router.get('/:channelId/info', controller.getChannelHeaderInfo)

/* POST /api/channle/invite invite user to channel */
router.post('/invite', channelController.inviteUser)
router.post('/invite', controller.inviteUser)

/* PATCH /api/channle/mute mute channel */
router.patch('/mute', channelController.muteChannel)
router.patch('/mute', controller.muteChannel)

module.exports = router
3 changes: 3 additions & 0 deletions backend/controller/index.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
import express from 'express'

import channelCotroller from './channel'
import searchCotroller from './search'
import userController from './user'

const router = express.Router()

router.use('/channel', channelCotroller)
router.use('/search', searchCotroller)
router.use('/user', userController)

module.exports = router
9 changes: 9 additions & 0 deletions backend/controller/user/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import express from 'express'
const router = express.Router()
const controller = require('./userController')

router.get('/sign-in/github', controller.githubLogin)
router.get('/sign-in/github/callback', controller.githubCallback)
router.get('/auth', controller.authCheck)

module.exports = router
40 changes: 40 additions & 0 deletions backend/controller/user/userController.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
const passport = require('passport')
const jwt = require('jsonwebtoken')

exports.githubLogin = passport.authenticate('github')

exports.githubCallback = async (req, res, next) => {
const frontHost = process.env.FRONTEND_HOST
passport.authenticate('github', (err, id) => {
if (err || !id) {
return res.status(200).redirect(frontHost)
}
req.login(id, { session: false }, err => {
if (err) {
res.send(err)
}

const token = jwt.sign(id, process.env.JWT_SECRET, { expiresIn: '1H' })
res.cookie('token', token, {
maxAge: 1000 * 60 * 60,
httpOnly: true,
signed: true,
})
return res.status(200).redirect(frontHost)
})
})(req, res)
}

exports.authCheck = (req, res) => {
let token = req.signedCookies.token
if (token) {
try {
let decoded = jwt.verify(token, process.env.JWT_SECRET)
return res.json({ verify: true })
} catch (err) {
return res.json({ verify: false })
}
} else {
return res.json({ verify: false, message: 'token does not exist' })
}
}
Loading

0 comments on commit b8f17c5

Please sign in to comment.