-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
95 lines (75 loc) · 2.41 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
import express from 'express';
import mongoose from 'mongoose';
import bodyParser from 'body-parser';
import { config } from 'dotenv';
import cors from 'cors';
import bcrypt from 'bcryptjs';
import jwt from 'jsonwebtoken';
import Students from './schemas/studentSchema.js';
import Teachers from './schemas/teacherSchema.js';
import Posts from './schemas/postSchema.js';
const app = express();
app.use(bodyParser.json())
app.use(cors());
config();
const PORT = process.env.PORT || 6969;
const dbURI = process.env.MONGODB_URI;
mongoose.connect(dbURI, { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => console.log('🚁 -> MongoDB Connected'))
.catch(err => console.log(err));
app.post('/api/students-register', async (req, res) => {
const student = new Students(req.body);
try {
const newPassword = await bcrypt.hash(req.body.password, 10);
student.password = newPassword;
student.save()
.then(() => res.send({ status: 'success' }))
.then(() => res.json({ message: 'Student Registered Successfully' }))
.catch(err => res.status(400).json({ message: 'Error : ' + err }));
} catch (err) {
console.log(err);
res.status(500).send(err);
}
});
app.post('/api/login-student', async (req, res) => {
const user = await Students.findOne({ email: req.body.email });
if (!user) {
return res.status(400).json({ message: 'User not found' });
} else {
const isPasswordValid = await bcrypt.compare(req.body.password, user.password);
if (isPasswordValid) {
const token = jwt.sign({
name: user.fullName,
email: user.email,
}, process.env.SECRET_KEY);
return res.json({ status: 'ok', token: token });
} else {
return res.status(400).json({ message: 'Invalid Password' });
}
}
});
app.post('/api/teachers-register', (req, res) => {
const teacher = new Teachers(req.body);
teacher.save()
.then(() => console.log('Teacher saved'))
.then(() => res.send({
status: 'success',
}))
.catch(err => console.log(err))
});
app.post('/api/post', (req, res) => {
const post = new Posts(req.body);
post.save()
.then(() => res.send({
status: 'success',
}))
.catch(err => console.log(err))
});
app.get('/api/posts', (req, res) => {
Posts.find()
.then(posts => res.json(posts))
.catch(err => console.log(err))
});
app.listen(PORT, () =>
console.log('🚂 -> Server is running on port', PORT)
);