-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
147 lines (132 loc) · 4.06 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
const express = require('express');
const admin = require('firebase-admin');
const path = require('path');
try {
const serviceAccount = require('./serviceAccountKey.json');
admin.initializeApp({
credential: admin.credential.cert(serviceAccount)
});
} catch (error) {
console.error('Failed to initialize Firebase Admin:', error);
process.exit(1);
}
const app = express();
app.use(express.json());
app.use(express.static('public'));
const errorHandler = (err, req, res, next) => {
console.error('Error:', err);
res.status(500).json({
success: false,
message: 'Internal server error',
error: process.env.NODE_ENV === 'development' ? err.message : undefined
});
};
const validateRole = (req, res, next) => {
const { role } = req.body;
const validRoles = ['admin', 'moderator'];
if (role && !validRoles.includes(role)) {
return res.status(400).json({
success: false,
message: `Invalid role. Must be one of: ${validRoles.join(', ')}`
});
}
next();
};
const validateUID = (req, res, next) => {
const { uid } = req.body;
if (!uid || typeof uid !== 'string') {
return res.status(400).json({
success: false,
message: 'Valid user ID is required'
});
}
next();
};
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'index.html'));
});
app.get('/api/users-with-claims', async (req, res, next) => {
try {
const listUsersResult = await admin.auth().listUsers();
const usersWithClaims = listUsersResult.users
.filter(user => user.customClaims && Object.keys(user.customClaims).length > 0)
.map(user => ({
uid: user.uid,
email: user.email,
displayName: user.displayName,
claims: user.customClaims
}));
res.json({ success: true, users: usersWithClaims });
} catch (error) {
next(error);
}
});
app.get('/api/all-users', async (req, res, next) => {
try {
const listUsersResult = await admin.auth().listUsers();
const users = listUsersResult.users.map(user => ({
uid: user.uid,
email: user.email,
displayName: user.displayName,
claims: user.customClaims
}));
res.json({ success: true, users });
} catch (error) {
next(error);
}
});
app.post('/api/setRole', [validateUID, validateRole], async (req, res, next) => {
const { uid, role } = req.body;
try {
await admin.auth().getUser(uid);
const claims = { [role]: true };
await admin.auth().setCustomUserClaims(uid, claims);
res.json({
success: true,
message: `Role ${role} set for user ${uid}`,
timestamp: new Date().toISOString()
});
} catch (error) {
if (error.code === 'auth/user-not-found') {
res.status(404).json({
success: false,
message: 'User not found'
});
} else {
next(error);
}
}
});
app.post('/api/removeRole', validateUID, async (req, res, next) => {
const { uid } = req.body;
try {
await admin.auth().getUser(uid);
await admin.auth().setCustomUserClaims(uid, null);
res.json({
success: true,
message: `Role removed for user ${uid}`,
timestamp: new Date().toISOString()
});
} catch (error) {
if (error.code === 'auth/user-not-found') {
res.status(404).json({
success: false,
message: 'User not found'
});
} else {
next(error);
}
}
});
app.use(errorHandler);
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});
process.on('SIGTERM', () => {
console.log('SIGTERM received. Shutting down gracefully...');
server.close(() => {
console.log('Server closed');
process.exit(0);
});
});