-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathapp.js
296 lines (247 loc) · 7.82 KB
/
app.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
const express = require('express');
const app = express();
const path = require('path');
const { title } = require('process');
const { MongoClient, ObjectId } = require('mongodb') // mongodb
const session = require('express-session') // passport 라이브러리
const passport = require('passport') // passport 라이브러리
const LocalStrategy = require('passport-local') // passport 라이브러리
const MongoStore = require('connect-mongo')
// socket.io
const { createServer } = require('http')
const { Server } = require('socket.io')
const server = createServer(app)
const io = new Server(server)
app.use(express.json())
app.use(express.urlencoded({extended:true}))
// EJS를 템플릿 엔진으로 설정
app.set('view engine', 'ejs');
// views 디렉토리를 설정
app.set('views', path.join(__dirname, 'views/'));
// 정적 파일 경로 설정 (css, js, images)
app.use(express.static(path.join(__dirname, 'public')));
// DB 연결
let db
const url = 'mongodb+srv://user:[email protected]/?retryWrites=true&w=majority&appName=Cluster0'
new MongoClient(url).connect().then((client)=>{
console.log('DB연결성공')
db = client.db('CodeCookie')
// 서버 시작
const PORT = process.env.PORT || 3000;
server.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
}).catch((err)=>{
console.log(err)
})
// passport
app.use(passport.initialize())
app.use(session({
secret: 'password',
resave : false,
saveUninitialized : false,
cookie : {maxAge : 24 * 60 * 60 * 1000},
store : MongoStore.create({
mongoUrl : 'mongodb+srv://user:[email protected]/?retryWrites=true&w=majority&appName=Cluster0',
dbName : 'CodeCookie'
})
}))
app.use(passport.session())
passport.use(new LocalStrategy(async (username, password, cb) => {
let result = await db.collection('user').findOne({ username : username})
if (!result) {
return cb(null, false, { message: '없는 아이디 입니다' })
}
if (result.password == password) {
return cb(null, result)
} else {
return cb(null, false, { message: '비밀번호 불일치' });
}
}))
passport.serializeUser((user, done) => {
process.nextTick(() => {
done(null, { id: user._id, username: user.username })
})
})
passport.deserializeUser(async (user, done) => {
let result = await db.collection('user').findOne({_id :new ObjectId(user.id)})
if (result){delete result.password}
process.nextTick(() => {
return done(null, result)
})
})
// 라우팅 설정
app.get('/', (req, res) => {
res.render('pages/Main/index'), {title: 'Main page'};
});
// 지도페이지
app.get('/Map', (req, res) => {
res.render('pages/Map', {title: 'Map page'});
});
// 테마1 드라마페이지
app.get('/Thema1', (req, res) => {
res.render('pages/Thema/Thema1', {title: 'Thema page'});
});
// 테마2 계절페이지
app.get('/Thema2', (req, res) => {
res.render('pages/Thema/Thema2', {title: 'Thema2 page'});
});
// 로그인페이지
app.get('/Login', (req, res) => {
console.log(req.user)
res.render('pages/Login', {title: 'Login page'});
});
app.post('/login', async (req, res, next) => {
passport.authenticate('local', (error, user, info) => {
if (error) return res.status(500).json(error)
if (!user) return res.status(401).json(info.message)
req.logIn(user, (err) => {
if (err) return next(err)
res.redirect('/')
})
})(req, res, next)
})
// 로그아웃
app.get('/logout', (req, res, next)=> {
req.logout((err) => {
if (err) { return next(err); }
req.session.save(function() {
res.redirect('/');
});
});
});
// 회원가입 페이지
app.get('/register',async(req,res)=>{
let user = await db.collection('user').find().toArray()
let username = []
for(let i=0; i<user.length; i++) {
username.push(user[i].username)
}
res.render('pages/register',{username: username})
})
app.post('/register',async(req,res)=>{
if(req.body.password == req.body.password2) {
await db.collection('user').insertOne({
username : req.body.username,
password : req.body.password,
name : req.body.name,
friend : [],
request : []
})
res.redirect('/')
} else {
}
})
// 마이페이지
app.get('/Mypage', async(req, res) => {
let result = req.user
let place = await db.collection('place').find().toArray()
if (req.user){
res.render('pages/Mypage', {result : result, place:place })
}else {
res.send('로그인 필요')
}
});
// 유저목록 페이지
app.get('/user',async(req,res)=>{
let result = await db.collection('user').find().toArray()
let user = req.user
res.render('pages/user',{result : result, user:user})
})
// 유저 검색기능
app.get('/usersearch', async(req,res)=>{
let result = await db.collection('user').find({username : {$regex : req.query.search} }).toArray()
let user = req.user
res.render('pages/usersearch.ejs',{result : result, user : user})
})
// 친구추가 기능
app.get('/addfriend', async(req,res)=>{
let user = await db.collection('user').findOne({username : req.user.username})
let filter = user.friend
if (filter.indexOf(req.query.friendname) == -1) {
await db.collection('user').updateOne(
{username : req.query.username},
{$push : {friend : req.query.friendname} }
)
await db.collection('user').updateOne(
{username : req.query.friendname},
{$push : {friend : req.query.username}}
)
await db.collection('user').updateOne(
{username : req.query.username},
{$pull : {request : req.query.friendname}}
)
res.redirect('back')
} else {
res.redirect('back')
}
})
// 친구삭제
app.get('/delete',async(req,res)=>{
await db.collection('user').updateOne(
{username : req.query.username},
{$pull : {friend : req.query.friendname}}
)
await db.collection('user').updateOne(
{username : req.query.friendname},
{$pull : {friend : req.query.username}}
)
res.redirect('/friendlist')
})
// 친구목록 페이지
app.get('/friendlist',async(req,res)=>{
if(req.user) {
let friend = await db.collection('user').findOne({username : req.user.username})
let user = req.user
let array = []
for(let i=0; i<req.user.friend.length; i++) {
array.push(await db.collection('user').find({username : req.user.friend[i]}).toArray())
}
let result =[]
for(let i=0; i<array.length; i++) {
result[i] = array[i][0]._id
}
res.render('pages/friendlist', {friend : friend.friend, user : user, result : result} )
} else {
res.send('로그인 필요')
}
})
// 친구 요청
app.get('/friendrequest',async(req,res)=>{
let user = await db.collection('user').findOne({username : req.query.friendname})
let filter = user.request
if(filter.indexOf(req.query.username) == -1) {
await db.collection('user').updateOne({username : req.query.friendname},{$push : {request : req.query.username}})
res.redirect('back')
}else {
res.send('이미 친구요청 보냈음')
}
})
// 친구요청 거절
app.get('/decline',async(req,res)=>{
await db.collection('user').updateOne(
{username : req.query.username},
{$pull : {request : req.query.friendname}}
)
res.redirect('/friendlist')
})
// 친구 요청 목록 페이지
app.get('/request',async(req,res)=>{
let result = await db.collection('user').findOne({username : req.user.username})
let user = req.user
res.render('pages/request', {result : result, user : user})
})
// 채팅
app.get('/chat/:id',async(req,res)=>{
console.log(req.session.passport.user)
res.render('pages/chat',{id : req.params.id})
})
io.on('connection', (socket)=>{
// const sessionId = socket.request.session.id
// console.log(sessionId)
socket.on('msg',(data)=>{
console.log(data)
socket.join(data.room)
io.to(data.room).emit('broadcast',data.msg)
})
})