-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
294 lines (246 loc) · 8.34 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
// app.js
console.log('Hello, world!');
// app.js
require('dotenv').config();
// Import required modules
const express = require('express');
const app = express();
const secretKey = process.env.SECRET_KEY;
app.get('/', (req, res) => {
res.send(`Your secret key is: ${secretKey}`);
});
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
// Define a route handler for the root path
app.get('/', (req, res) => {
res.send(`Your secret key is: ${secretKey}`);
});
// Start the server on port 3000
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${5432}`);
});
// Import required modules
const mongoose = require('mongoose');
// MongoDB connection URI (replace with your MongoDB connection string)
const MONGODB_URI = 'mongodb://localhost:27017/mydatabase';
// Connect to MongoDB
mongoose.connect(MONGODB_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
const db = mongoose.connection;
// Check MongoDB connection
db.on('error', console.error.bind(console, 'MongoDB connection error:'));
db.once('open', () => {
console.log('Connected to MongoDB database');
});
// Define a mongoose schema and model example
const Schema = mongoose.Schema;
const UserSchema = new Schema({
username: String,
email: String,
});
// Example usage: create a new user
const newUser = new mongoose.model('User', UserSchema)({ username: 'john_doe', email: 'john@example.com' });
newUser.save((err) => {
if (err) return console.error(err);
console.log('User saved successfully');
});
// Import required modules
const axios = require('axios');
// Example: Fetch data from an API
axios.get('https://api.example.com/data')
.then(response => {
console.log('API Response:', response.data);
})
.catch(error => {
console.error('Error fetching data:', error);
});
// Import required modules
const bodyParser = require('body-parser'); // For parsing JSON request bodies
// Middleware to parse JSON request bodies
app.use(bodyParser.json());
// Example route handler for GET request
app.get('/', (req, res) => {
res.send('Hello, world! This is your Express server.');
});
// Example route handler for POST request
app.post('/api/users', (req, res) => {
const { username, email } = req.body;
// Validate input
if (!username || !email) {
return res.status(400).json({ error: 'Username and email are required' });
}
// Save to database or perform other actions
// Example: Creating a new user (assuming you have a User model)
const newUser = new User({ username, email });
newUser.save()
.then(user => {
res.status(201).json(user); // Respond with created user object
})
.catch(err => {
console.error('Error saving user:', err);
res.status(500).json({ error: 'Server error' });
});
});
// Example route handler for PUT request
app.put('/api/users/:userId', (req, res) => {
const { userId } = req.params;
const { username, email } = req.body;
// Update user in database based on userId
// Example: Updating user details
User.findByIdAndUpdate(userId, { username, email }, { new: true })
.then(updatedUser => {
if (!updatedUser) {
return res.status(404).json({ error: 'User not found' });
}
res.json(updatedUser); // Respond with updated user object
})
.catch(err => {
console.error('Error updating user:', err);
res.status(500).json({ error: 'Server error' });
});
});
// Example route handler for DELETE request
app.delete('/api/users/:userId', (req, res) => {
const { userId } = req.params;
// Delete user from database based on userId
// Example: Deleting a user
User.findByIdAndDelete(userId)
.then(deletedUser => {
if (!deletedUser) {
return res.status(404).json({ error: 'User not found' });
}
res.json({ message: 'User deleted successfully' });
})
.catch(err => {
console.error('Error deleting user:', err);
res.status(500).json({ error: 'Server error' });
});
});
// Start the server on port 3000
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
// Import required modules
const bodyParser = require('body-parser');
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
const users = [
{ id: 1, username: 'john', password: 'password' },
{ id: 2, username: 'jane', password: 'password' },
];
// Passport.js setup
passport.use(new LocalStrategy(
(username, password, done) => {
// Mock user authentication (replace with actual logic)
const user = users.find(u => u.username === username && u.password === password);
if (!user) {
return done(null, false, { message: 'Incorrect username or password' });
}
return done(null, user);
}
));
// Serialize and deserialize user (session management)
passport.serializeUser((user, done) => {
done(null, user.id);
});
passport.deserializeUser((id, done) => {
const user = users.find(u => u.id === id);
done(null, user);
});
// Initialize Passport and restore authentication state, if any, from the session
app.use(passport.initialize());
app.use(passport.session());
// Example route handler for login (POST /login)
app.post('/login',
passport.authenticate('local', { failureRedirect: '/login-failure' }),
(req, res) => {
res.redirect('/dashboard'); // Successful login redirect
}
);
// Example route handler for logout (GET /logout)
app.get('/logout', (req, res) => {
req.logout();
res.redirect('/');
});
// Example route handler for authenticated route (GET /dashboard)
app.get('/dashboard', isAuthenticated, (req, res) => {
res.send(`Welcome, ${req.user.username}! This is your dashboard.`);
});
// Middleware function to check if user is authenticated
function isAuthenticated(req, res, next) {
if (req.isAuthenticated()) {
return next();
}
res.redirect('/login'); // Redirect to login if not authenticated
}
// Start the server on port 3000
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
// Error handling middleware (must be defined last)
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).json({ error: 'Internal Server Error' });
});
const passport = require('passport');
const GoogleStrategy = require('passport-google-oauth20').Strategy;
passport.use(new GoogleStrategy({
clientID: GOOGLE_CLIENT_ID,
clientSecret: GOOGLE_CLIENT_SECRET,
callbackURL: '/auth/google/callback'
},
(accessToken, refreshToken, profile, done) => {
// Check if user exists in database or create a new user
// Example:
User.findOrCreate({ googleId: profile.id }, (err, user) => {
return done(err, user);
});
}
));
// Routes for OAuth authentication
app.get('/auth/google',
passport.authenticate('google', { scope: ['profile', 'email'] }));
app.get('/auth/google/callback',
passport.authenticate('google', { failureRedirect: '/login' }),
(req, res) => {
// Successful authentication, redirect to dashboard or profile
res.redirect('/dashboard');
}
);
passport.serializeUser((user, done) => {
done(null, user.id);
});
passport.deserializeUser((id, done) => {
User.findById(id, (err, user) => {
done(err, user);
});
});
// Example middleware for role-based access control
function isAdmin(req, res, next) {
if (req.user && req.user.role === 'admin') {
return next();
}
res.status(403).json({ error: 'Unauthorized' });
}
// Example route with role-based access control
app.get('/admin/dashboard', isAdmin, (req, res) => {
res.send(`Your secret key is: ${secretKey}`);
});
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/myapp', {
useNewUrlParser: true,
useUnifiedTopology: true
});
const userSchema = new mongoose.Schema({
username: String,
email: String,
role: { type: String, default: 'user' }
});
const User = mongoose.model('User', userSchema);
mongoose.model('User', userSchema);