-
Notifications
You must be signed in to change notification settings - Fork 0
/
insp.html
496 lines (441 loc) · 13.6 KB
/
insp.html
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
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
// Import necessary modules and dependencies
import React, { useState, useEffect } from 'react';
import { BrowserRouter as Router, Route, Switch, Redirect } from 'react-router-dom';
import axios from 'axios';
import bcrypt from 'bcryptjs';
import { v4 as uuidv4 } from 'uuid';
import { DndProvider } from 'react-dnd';
import { HTML5Backend } from 'react-dnd-html5-backend';
import SignatureCanvas from 'react-signature-canvas';
import { ToastContainer, toast } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
// Styles
import styled from 'styled-components';
const AppContainer = styled.div`
font-family: 'Roboto', Arial, sans-serif;
color: #333;
background-color: #f0f8ff;
min-height: 100vh;
`;
const Header = styled.header`
background-color: #003366;
color: white;
padding: 1rem;
text-align: center;
`;
const Logo = styled.img`
max-width: 200px;
margin-bottom: 1rem;
`;
const Button = styled.button`
background-color: #0056b3;
color: white;
border: none;
padding: 0.5rem 1rem;
font-size: 1rem;
cursor: pointer;
transition: background-color 0.3s;
&:hover {
background-color: #003d82;
}
`;
const Form = styled.form`
display: flex;
flex-direction: column;
max-width: 400px;
margin: 2rem auto;
padding: 2rem;
background-color: white;
border-radius: 8px;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
`;
const Input = styled.input`
margin-bottom: 1rem;
padding: 0.5rem;
font-size: 1rem;
border: 1px solid #ccc;
border-radius: 4px;
`;
const ErrorMessage = styled.p`
color: red;
font-size: 0.875rem;
`;
// Components
const PrivateRoute = ({ component: Component, ...rest }) => {
const [isAuthenticated, setIsAuthenticated] = useState(false);
const [loading, setLoading] = useState(true);
useEffect(() => {
const checkAuth = async () => {
try {
const response = await axios.get('/api/auth/check', { withCredentials: true });
setIsAuthenticated(response.data.isAuthenticated);
} catch (error) {
console.error('Error checking authentication:', error);
} finally {
setLoading(false);
}
};
checkAuth();
}, []);
if (loading) {
return <div>Loading...</div>;
}
return (
<Route
{...rest}
render={(props) =>
isAuthenticated ? (
<Component {...props} />
) : (
<Redirect to={{ pathname: '/login', state: { from: props.location } }} />
)
}
/>
);
};
const LoginPage = () => {
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const [error, setError] = useState('');
const handleSubmit = async (e) => {
e.preventDefault();
try {
const response = await axios.post('/api/auth/login', { username, password });
if (response.data.success) {
window.location.href = '/home';
} else {
setError('Invalid credentials');
}
} catch (error) {
setError('An error occurred. Please try again.');
}
};
return (
<Form onSubmit={handleSubmit}>
<Logo src="/path/to/government-logo.png" alt="Government Logo" />
<Input
type="text"
placeholder="Username"
value={username}
onChange={(e) => setUsername(e.target.value)}
required
/>
<Input
type="password"
placeholder="Password"
value={password}
onChange={(e) => setPassword(e.target.value)}
required
/>
{error && <ErrorMessage>{error}</ErrorMessage>}
<Button type="submit">Login</Button>
<Button type="button" onClick={() => window.location.href = '/register'}>Register</Button>
<a href="/forgot-password">Forgot Password?</a>
</Form>
);
};
const RegisterPage = () => {
const [formData, setFormData] = useState({
idNumber: '',
username: '',
email: '',
password: '',
confirmPassword: '',
});
const [signature, setSignature] = useState(null);
const [errors, setErrors] = useState({});
const handleChange = (e) => {
setFormData({ ...formData, [e.target.name]: e.target.value });
};
const validateForm = () => {
const newErrors = {};
if (!/^\d{10}$/.test(formData.idNumber)) {
newErrors.idNumber = 'ID number must be 10 digits';
}
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(formData.email)) {
newErrors.email = 'Invalid email format';
}
if (!/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$/.test(formData.password)) {
newErrors.password = 'Password must contain at least 8 characters, including uppercase, lowercase, number, and special character';
}
if (formData.password !== formData.confirmPassword) {
newErrors.confirmPassword = 'Passwords do not match';
}
if (!signature) {
newErrors.signature = 'Signature is required';
}
setErrors(newErrors);
return Object.keys(newErrors).length === 0;
};
const handleSubmit = async (e) => {
e.preventDefault();
if (validateForm()) {
try {
const hashedPassword = await bcrypt.hash(formData.password, 10);
const userData = {
...formData,
password: hashedPassword,
signature: signature.toDataURL(),
};
const response = await axios.post('/api/auth/register', userData);
if (response.data.success) {
toast.success('Registration successful! Please log in.');
window.location.href = '/login';
} else {
toast.error('Registration failed. Please try again.');
}
} catch (error) {
toast.error('An error occurred. Please try again.');
}
}
};
return (
<Form onSubmit={handleSubmit}>
<h2>Register</h2>
<Input
type="text"
name="idNumber"
placeholder="ID Number"
value={formData.idNumber}
onChange={handleChange}
required
/>
{errors.idNumber && <ErrorMessage>{errors.idNumber}</ErrorMessage>}
<Input
type="text"
name="username"
placeholder="Username"
value={formData.username}
onChange={handleChange}
required
/>
<Input
type="email"
name="email"
placeholder="Email"
value={formData.email}
onChange={handleChange}
required
/>
{errors.email && <ErrorMessage>{errors.email}</ErrorMessage>}
<Input
type="password"
name="password"
placeholder="Password"
value={formData.password}
onChange={handleChange}
required
/>
{errors.password && <ErrorMessage>{errors.password}</ErrorMessage>}
<Input
type="password"
name="confirmPassword"
placeholder="Confirm Password"
value={formData.confirmPassword}
onChange={handleChange}
required
/>
{errors.confirmPassword && <ErrorMessage>{errors.confirmPassword}</ErrorMessage>}
<SignatureCanvas
penColor="black"
canvasProps={{ width: 300, height: 150, className: 'signature-canvas' }}
onEnd={() => setSignature(signatureCanvas.current)}
/>
<Button type="button" onClick={() => signatureCanvas.current.clear()}>Clear Signature</Button>
{errors.signature && <ErrorMessage>{errors.signature}</ErrorMessage>}
<Button type="submit">Register</Button>
</Form>
);
};
const HomePage = () => {
const [user, setUser] = useState(null);
useEffect(() => {
const fetchUser = async () => {
try {
const response = await axios.get('/api/user', { withCredentials: true });
setUser(response.data);
} catch (error) {
console.error('Error fetching user data:', error);
}
};
fetchUser();
}, []);
const handleLogout = async () => {
try {
await axios.post('/api/auth/logout', {}, { withCredentials: true });
window.location.href = '/login';
} catch (error) {
console.error('Error logging out:', error);
}
};
return (
<div>
<Header>
<h1>Welcome, {user ? user.username : 'Inspector'}</h1>
<Button onClick={handleLogout}>Logout</Button>
</Header>
<main>
<h2>Inspection Forms</h2>
<div className="form-grid">
{['Form A', 'Form B', 'Form C', 'Form D', 'Form E'].map((formName) => (
<Button key={formName} onClick={() => window.location.href = `/form/${formName.toLowerCase()}`}>
{formName}
</Button>
))}
</div>
</main>
</div>
);
};
const DraggableElement = ({ id, type, content, index, moveElement }) => {
const [{ isDragging }, drag] = useDrag({
type: 'form-element',
item: { id, type, index },
collect: (monitor) => ({
isDragging: monitor.isDragging(),
}),
});
const [, drop] = useDrop({
accept: 'form-element',
hover(item, monitor) {
if (!drag) {
return;
}
if (item.index === index) {
return;
}
moveElement(item.index, index);
item.index = index;
},
});
return (
<div ref={(node) => drag(drop(node))} style={{ opacity: isDragging ? 0.5 : 1 }}>
{renderFormElement(type, content)}
</div>
);
};
const renderFormElement = (type, content) => {
switch (type) {
case 'text':
return <Input type="text" placeholder={content} />;
case 'checkbox':
return (
<label>
<input type="checkbox" /> {content}
</label>
);
case 'date':
return <Input type="date" />;
case 'signature':
return <SignatureCanvas penColor="black" canvasProps={{ width: 300, height: 150 }} />;
default:
return null;
}
};
const InspectionForm = ({ formName }) => {
const [formElements, setFormElements] = useState([]);
const [formData, setFormData] = useState({});
useEffect(() => {
// Fetch form structure from the server
const fetchFormStructure = async () => {
try {
const response = await axios.get(`/api/forms/${formName}`);
setFormElements(response.data.elements);
} catch (error) {
console.error('Error fetching form structure:', error);
}
};
fetchFormStructure();
}, [formName]);
const moveElement = (fromIndex, toIndex) => {
const updatedElements = [...formElements];
const [movedElement] = updatedElements.splice(fromIndex, 1);
updatedElements.splice(toIndex, 0, movedElement);
setFormElements(updatedElements);
};
const handleInputChange = (id, value) => {
setFormData({ ...formData, [id]: value });
};
const handleSubmit = async (e) => {
e.preventDefault();
try {
await axios.post(`/api/forms/${formName}/submit`, formData, { withCredentials: true });
toast.success('Form submitted successfully');
} catch (error) {
toast.error('Error submitting form. Please try again.');
}
};
return (
<DndProvider backend={HTML5Backend}>
<Form onSubmit={handleSubmit}>
<h2>{formName} Inspection Form</h2>
{formElements.map((element, index) => (
<DraggableElement
key={element.id}
id={element.id}
type={element.type}
content={element.content}
index={index}
moveElement={moveElement}
/>
))}
<Button type="submit">Save</Button>
</Form>
</DndProvider>
);
};
const App = () => {
return (
<Router>
<AppContainer>
<ToastContainer position="top-right" autoClose={5000} />
<Switch>
<Route exact path="/" component={LoginPage} />
<Route path="/login" component={LoginPage} />
<Route path="/register" component={RegisterPage} />
<PrivateRoute path="/home" component={HomePage} />
<PrivateRoute path="/form/:formName" component={InspectionForm} />
</Switch>
</AppContainer>
</Router>
);
};
export default App;
// Backend code (Node.js with Express)
const express = require('express');
const mongoose = require('mongoose');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const cors = require('cors');
const helmet = require('helmet');
const rateLimit = require('express-rate-limit');
const app = express();
// Middleware
app.use(express.json());
app.use(cors({ origin: process.env.FRONTEND_URL, credentials: true }));
app.use(helmet());
const limiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100 // limit each IP to 100 requests per windowMs
});
app.use(limiter);
// Connect to MongoDB
mongoose.connect(process.env.MONGODB_URI, { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => console.log('Connected to MongoDB'))
.catch((err) => console.error('MongoDB connection error:', err));
// User model
const UserSchema = new mongoose.Schema({
idNumber: { type: String, required: true, unique: true },
username: { type: String, required: true, unique: true },
email: { type: String, required: true, unique: true },
password: { type: String, required: true },
signature: { type: String, required: true },
});
const User = mongoose.model('User', UserSchema);
// Form model
const FormSchema = new mongoose.Schema({
name: { type: String, required: true },
elements: [{ type: Object }],
});
const Form = mongoose.model('Form', FormSchema);
// Authentication middleware