Hallo evrey one , i am trying to authenticate the user like if he registerd before cant register again and wanna to authenticate the password if it the same one , here iam using just a jason file to save the data but when i save the data its save it just like objects , i puted them in array but its still putting evrey user in array , i want all users be in array!! here is my Code::
What I have tried:
1 import express, { json } from 'express';
2 import path from 'path';
3 import { fileURLToPath } from 'url';
4 import bcrypt, { hash } from 'bcrypt';
5 import fs from 'fs';
6 import bodyParser from 'body-parser';
7 import Jwt from 'jsonwebtoken';
8
9 const __filename = fileURLToPath(import.meta.url);
10 const __dirname = path.dirname(__filename);
11
12 const app = express();
13 const port = 3005;
14
15 app.use(bodyParser.json());
16 app.set("views", "./views")
17 app.set('view engine', 'ejs')
18 app.use(express.static('public'))
19 app.use(bodyParser.urlencoded({ extended: true }));
20
21
22 let secretkey = "12342423";
23
24
25 async function createToken(req, res, next) {
26 const salt = await bcrypt.genSalt();
27 const hashedPassword = await bcrypt.hash(req.body.password, salt);
28 const user = { email: req.body.email, password: hashedPassword };
29 Jwt.sign(user, secretkey, (err, result) => {
30 if (err) {
31 res.json({ error: err });
32 } else {
33 console.log(({ token: result }));
34
35 res.status(200).send(` <h1>your data is </h1>${JSON.stringify(user)} <h1>logged in at </h1> ${new Date().toUTCString()} `)
36 }
37 });
38 next();
39 }
40
41 app.post('/login', createToken, async (req, res) => {
42 try {
43 const salt = await bcrypt.genSalt();
44 const hashedPassword = await bcrypt.hash(req.body.password, salt);
45 const user = { email: req.body.email, password: hashedPassword };
46
47 fs.appendFile('output.json', JSON.stringify(user), function (err) {
48 if (err) throw err;
49 console.log('Saved!');
50 res.status(200).send(` <h1>your data is </h1>${JSON.stringify(user)} <h1> at time </h1> ${new Date().toUTCString()} ` )
51 });
52 } catch {
53 res.status(500).send()
54 }
55 });
56
57 app.post('/register', async (req, res) => {
58 try {
59 const salt = await bcrypt.genSalt();
60 const hashedPassword = await bcrypt.hash(req.body.password, salt);
61 const user = { email: req.body.email, password: hashedPassword };
62 const users = [];
63 users.push(user);
64
65 fs.appendFile('output.json', JSON.stringify(users), function (err) {
66 if (err) throw err;
67 console.log('Saved!');
68 res.status(200).send(` <h1>your data is </h1>${JSON.stringify(user)} <h1> at time </h1> ${new Date().toUTCString()} `)
69
70 });
71 } catch {
72 res.status(500).send()
73 }
74
75 });