-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
116 lines (93 loc) · 3.19 KB
/
server.js
File metadata and controls
116 lines (93 loc) · 3.19 KB
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
const express = require("express");
const mongoose = require("mongoose");
const session = require("express-session");
const MongoStore = require("connect-mongo");
// Подключаемся к базе данных MongoDB
mongoose.connect("mongodb://localhost/authentication", {
useNewUrlParser: true,
useUnifiedTopology: true,
});
const app = express();
// Заводим сессию и хранилище для сессий в базе данных
const sessionStore = MongoStore.create({
mongoUrl: "mongodb://localhost/authentication",
collectionName: "sessions",
});
app.use(
session({
secret: "your-secret-key",
resave: false,
saveUninitialized: false,
store: sessionStore,
})
);
// Модель пользователя
const User = mongoose.model("User", {
username: String,
password: String,
});
// Регистрация пользователя
app.post("/register", async (req, res) => {
const { username, password } = req.body;
try {
const existingUser = await User.findOne({ username });
if (existingUser) {
// Пользователь с таким именем уже существует
return res.status(400).send("Username already exists");
}
const user = new User({ username, password });
await user.save();
// Устанавливаем ID пользователя в сессию
req.session.userId = user._id;
res.send("Registration successful");
} catch (error) {
console.error(error);
res.status(500).send("Internal Server Error");
}
});
// Вход пользователя
app.post("/login", async (req, res) => {
const { username, password } = req.body;
try {
const user = await User.findOne({ username });
if (!user || user.password !== password) {
// Неверное имя пользователя или пароль
return res.status(401).send("Invalid username or password");
}
// Устанавливаем ID пользователя в сессию
req.session.userId = user._id;
res.send("Login successful");
} catch (error) {
console.error(error);
res.status(500).send("Internal Server Error");
}
});
// Защищенный маршрут для проверки аутентификации
app.get("/protected", (req, res) => {
if (!req.session.userId) {
// Пользователь не аутентифицирован
return res.status(401).send("Unauthorized");
}
// Получаем информацию о текущем пользователе, например по его ID
User.findById(req.session.userId, (err, user) => {
if (err) {
console.error(err);
return res.status(500).send("Internal Server Error");
}
if (!user) {
// Пользователь не найден
return res.status(401).send("Unauthorized");
}
res.send(`Hello, ${user.username}!`);
});
});
// Завершение сессии
app.post("/logout", (req, res) => {
// Очищаем ID пользователя из сессии
req.session.userId = null;
res.send("Logout successful");
});
// Запуск сервера
app.listen(3000, () => {
console.log("Server listening on port 3000");
});