-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
201 lines (170 loc) · 6.03 KB
/
server.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
const express = require('express');
const mongoose = require('mongoose');
const path = require('path');
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
const session = require('express-session');
const User = require('./models/user');
const Category = require('./models/category');
const Quiz = require('./models/quizz');
const MyQuiz = require('./models/project');
const projectRoutes = require('./routes/projectRoutes');
const authRoutes = require('./routes/auth');
const profileRoutes = require('./routes/profile');
const quizRoutes = require('./routes/quiz');
const isAuthenticated = require('./middleware/auth');
const app = express();
mongoose.connect('mongodb+srv://mamadoulcisse9236:2wOI5WMcV1cP19fC@quizzine.3q907.mongodb.net/', {
useNewUrlParser: true,
useUnifiedTopology: true
})
.then(() => console.log('Connecté à MongoDB Atlas'))
.catch((error) => console.error('Erreur de connexion à MongoDB:', error));
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
// Middleware pour les sessions
app.use(session({
secret: 'quizzine',
resave: false,
saveUninitialized: true
}));
app.use(passport.initialize());
app.use(passport.session());
// Configuration de la stratégie locale pour Passport
passport.use(new LocalStrategy({
usernameField: 'email',
passwordField: 'password'
}, async (email, password, done) => {
try {
const user = await User.findOne({ email });
if (!user) {
return done(null, false, { message: 'Utilisateur non trouvé' });
}
const isMatch = await user.matchPassword(password);
if (!isMatch) {
return done(null, false, { message: 'Mot de passe incorrect' });
}
return done(null, user);
} catch (err) {
return done(err);
}
}));
passport.serializeUser((user, done) => {
done(null, user.id);
});
passport.deserializeUser(async (id, done) => {
try {
const user = await User.findById(id);
done(null, user);
} catch (err) {
done(err);
}
});
// Middleware pour le parsing des requêtes POST
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
// Configuration des dossiers statiques
app.use(express.static(path.join(__dirname, 'public')));
app.use('/ressource', express.static(path.join(__dirname, 'ressource')));
app.use('/script', express.static(path.join(__dirname, 'script')));
app.use('/css', express.static(path.join(__dirname, 'css')));
app.use('/views', express.static(path.join(__dirname, 'views')));
app.use('/uploads', express.static(path.join(__dirname, 'uploads')));
app.use('/auth', authRoutes);
app.use('/profile', profileRoutes);
app.use('/quizzes', quizRoutes);
app.use('/projects', projectRoutes);
app.get('/creer_page', isAuthenticated, async (req, res) => {
try {
const projects = await MyQuiz.find({ creator: req.user._id })
.select('name createdAt lastModified')
.sort({ lastModified: -1 });
res.render('creer_page', {
user: req.user,
projects: projects
});
} catch (error) {
console.error('Erreur lors de la récupération des projets:', error);
res.render('creer_page', {
user: req.user,
projects: []
});
}
});
app.get('/api/projects', isAuthenticated, async (req, res) => {
try {
const projects = await MyQuiz.find({ creator: req.user._id })
.select('name createdAt lastModified')
.sort({ lastModified: -1 });
res.json(projects);
} catch (error) {
console.error('Erreur lors de la récupération des projets:', error);
res.status(500).json({ message: 'Erreur lors de la récupération des projets' });
}
});
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'index.html'));
});
app.get('/quiz', (req, res) => {
res.render('play_quiz', { user: req.user });
});
// Route pour parametre
app.get('/index', (req, res) => {
res.render('index', { user: req.user });
});
// Ro
app.get('/parametres', (req, res) => {
res.render('parametres', { user: req.user });
});
app.get('/profile', (req, res) => {
res.render('profile', { user: req.user });
});
app.get('/jouer_page', (req, res) => {
res.render('jouer_page', { user: req.user });
});
app.get('/connexion', (req, res) => {
res.render('connexion', { user: req.user });
});
app.get('/inscription', (req, res) => {
res.render('inscription', { user: req.user });
});
app.get('/quiz_creation', isAuthenticated, (req, res) => {
res.render('quiz_creation', { user: req.user });
});
app.get('/api/categories', async (req, res) => {
try {
const categories = await Category.find();
res.json(categories);
} catch (error) {
res.status(500).json({ message: 'Erreur lors de la récupération des catégories' });
}
});
app.get('/api/quiz/category/:categoryId', async (req, res) => {
const { categoryId } = req.params;
try {
const quizzes = await Quiz.find({ category: categoryId }).limit(10);
if (!quizzes || quizzes.length === 0) {
return res.status(404).json({ message: 'Aucun quiz disponible pour cette catégorie' });
}
res.json(quizzes);
} catch (error) {
res.status(500).json({ message: 'Erreur serveur' });
}
});
app.get('/api/quiz/quick', async (req, res) => {
const { count, difficulty } = req.query;
try {
const quizzes = await Quiz.find({ 'questions.difficulty': difficulty })
.limit(parseInt(count, 10));
if (!quizzes || quizzes.length === 0) {
return res.status(404).json({ message: 'Aucun quiz disponible pour cette sélection' });
}
res.json(quizzes);
} catch (error) {
res.status(500).json({ message: 'Erreur lors de la récupération des quizzes' });
}
});
const PORT = process.env.PORT || 3001;
app.listen(PORT, () => {
console.log(`Serveur démarré sur le port ${PORT}, connectez-vous sur http://localhost:${PORT}`);
});