· 5 years ago · May 15, 2020, 07:24 AM
1/// app.js //
2const express = require('express');
3const jwt = require('jsonwebtoken');
4const bcrypt = require('bcryptjs')
5
6const app = express();
7
8// connecting to mongoDB in here. I am not including the code for it //
9
10const User = require('./models/User')
11
12app.post('/api/posts', verifyToken, (req, res) => {
13 jwt.verify(req.token, 'secretkey', (err, authData) => {
14 if(err) {
15 res.sendStatus(403);
16 } else {
17 res.json({
18 message: 'Post created...',
19 authData
20 });
21 }
22 });
23});
24
25//THIS RIGHT HERE IS THE PROBLEM !!
26app.post('/api/login', async(req, res) => {
27 // Mock user
28 const user = await User.findOne({ username: 'nice'})
29 bcrypt.compare('nice123', user.password, function(err, res){
30 if (err){ return next(err); }
31 if (res){
32 jwt.sign({user}, 'cat', { expiresIn: '30s' }, (err, token) => {
33 res.json({
34 token
35 });
36 });
37 }
38 })
39
40});
41
42// Verify Token
43function verifyToken(req, res, next) {
44 // Get auth header value
45 const bearerHeader = req.headers['authorization'];
46 // Check if bearer is undefined
47 if(typeof bearerHeader !== 'undefined') {
48 // Split at the space
49 const bearer = bearerHeader.split(' ');
50 // Get token from array
51 const bearerToken = bearer[1];
52 // Set the token
53 req.token = bearerToken;
54 // Next middleware
55 next();
56 } else {
57 // Forbidden
58 res.sendStatus(403);
59 }
60}
61
62app.listen(5000, () => console.log('Server started on port 5000'));
63
64
65
66// User Model //
67const mongoose = require('mongoose')
68
69const Schema = mongoose.Schema
70
71UserSchema = new Schema({
72 username: { type: String, maxLength: 70, required: true, unique: true},
73 password: { type: String, maxLength: 50, required: true},
74})
75
76module.exports = mongoose.model('User', UserSchema);