-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathapp.js
More file actions
111 lines (96 loc) · 2.55 KB
/
app.js
File metadata and controls
111 lines (96 loc) · 2.55 KB
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
const express = require('express');
const app = express();
const fs = require('fs');
const bluebird = require('bluebird');
const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');
require('dotenv').config()
// Connecting to mongodb
const mongoose = require('mongoose');
mongoose.connect(process.env.MONGODB_URI, {useNewUrlParser: true, useUnifiedTopology: true});
mongoose.connection.on('error', console.error.bind(console, 'connection error:'));
mongoose.connection.once('open', function() {
console.log('Connected to MongoDB');
});
app.use(express.json());
// Auhtorization Middleware
const auth = (req, res, next) => {
try {
jwt.verify(req.get('Authorization'), 'anysecret');
next();
} catch (error) {
res.send('You are not authorized');
}
}
// Defining the students Schema
const StudentSchema = new mongoose.Schema({
fistName: String,
lastName: String,
email: String,
password: String,
age: Number,
skills: [String]
});
const StudentsModel = mongoose.model('Student', StudentSchema);
app.post('/students', async (req, res) => {
try {
req.body.password = await bcrypt.hash(req.body.password, 12);
const student = await StudentsModel.create(req.body);
res.json({
message: 'Student Added Successfully',
student
})
} catch (error) {
res.send('You have Validation Error')
}
});
app.get('/students', async (req, res) => {
try {
const students = await StudentsModel.find();
res.json(students);
} catch (error) {
res.send(error)
}
});
app.get('/students/:id', async (req, res) =>{
try {
const student = await StudentsModel.findById(req.params.id);
res.json(student);
} catch (error) {
res.send(error);
}
});
app.delete('/students/:id', async (req, res) =>{
try {
await StudentsModel.findByIdAndRemove(req.params.id);
res.send('Student Deleted');
} catch (error) {
res.send(error);
}
});
app.delete('/students', async (req, res) =>{
try {
await StudentsModel.deleteMany();
res.send('Students Deleted');
} catch (error) {
res.send(error);
}
});
app.post('/login', async (req, res) => {
try {
const student = await StudentsModel.findOne({email: req.body.email});
if(!student){
res.send('Email Does Not Exist')
}
const match = await bcrypt.compare(req.body.password, student.password);
if(!match){
res.send('Incorrect Password')
}
res.json({token: jwt.sign({id: student._id}, 'anysecret')})
} catch (error) {
res.send(error)
}
});
app.listen(3001, () => {
console.log('Listening on port 3001');
});