Skip to content

Instantly share code, notes, and snippets.

@bewarusman
Last active December 1, 2020 13:55
Show Gist options
  • Save bewarusman/5d6721802a770ae69ac0f131e7855ebf to your computer and use it in GitHub Desktop.
Save bewarusman/5d6721802a770ae69ac0f131e7855ebf to your computer and use it in GitHub Desktop.
// npm install -S express jsonwebtoken body-parser bcrypt mongoose
// npm install -D nodemon
// adding "start": "nodemon" to start script
// npm start
// CONSTANTS
const PORT = 3000;
const SECRET_KEY = "a_secret_key_to_sign_jwt";
const SALT_ROUNDS = 10;
// required packages
const express = require("express");
const bodyParser = require("body-parser");
const jwt = require("jsonwebtoken");
const bcrypt = require("bcrypt");
const mongoose = require("mongoose");
// connect to mongodb
mongoose.connect("mongodb://localhost:27017/blog", {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true,
useFindAndModify: false,
});
// mongoose schemas
const userSchema = new mongoose.Schema({
firstName: { type: String, required: true },
lastName: { type: String, required: true },
username: { type: String, required: true },
hash: { type: String, required: true },
});
const blogSchema = new mongoose.Schema({
title: { type: String, required: true },
content: { type: String, required: true },
author: {
type: mongoose.Schema.Types.ObjectId,
ref: "User",
required: false,
},
});
// mongoose models
var User = mongoose.model("User", userSchema);
var Blog = mongoose.model("Blog", blogSchema);
// seeding data
const firstName = "Bewar";
const lastName = "Salah";
const username = "bewar";
const password = "12345";
bcrypt.hash(password, SALT_ROUNDS, async (err, hash) => {
var user = await User.findOne({ username });
if (user == null) {
var user = new User({ firstName, lastName, username, hash });
await user.save();
}
});
// express application
const app = express();
app.use(bodyParser.json());
// authenticates
const authenticateMiddleware = (req, res, next) => {
const { authorization } = req.headers;
const token = authorization && authorization.split(" ")[1];
if (token == null) return res.sendStatus(401);
jwt.verify(token, SECRET_KEY, (err, user) => {
if (err) return res.sendStatus(403);
req.user = user;
console.log(user);
next();
});
};
// API Routes
// POST /api/user/login
app.post("/api/users/login", async (req, res) => {
const { username, password } = req.body;
const user = await User.findOne({ username });
console.log(user);
if (user == null) {
res.sendStatus(401);
return;
}
bcrypt.compare(password, user.hash, (err, result) => {
if (err) res.sendStatus(401);
else if (!result) res.sendStatus(401);
else {
jwt.sign({ id: user._id }, SECRET_KEY, (err, token) => {
if (err) res.sendStatus(500);
else
res.json({
success: true,
user: { username: user.username },
token,
});
});
}
});
});
app.get("/api/users", authenticateMiddleware, async (req, res) => {
const users = await User.find({});
console.log(users);
res.json(users);
});
// GET /api/blogs
app.get("/api/blogs", async (req, res) => {
var users = await Blog.find({}).populate({
path: "author",
select: ["firstName", "lastName"],
});
res.json(users);
});
// GET /api/blogs/:id
app.get("/api/blogs/:id", async (req, res) => {
const { id } = req.params;
var users = await Blog.findById(id).populate({
path: "author",
select: ["firstName", "lastName"],
});
res.json(users);
});
// POST /api/blogs
app.post("/api/blogs", authenticateMiddleware, async (req, res) => {
const { title, content } = req.body;
const user = req.user.id;
const blog = new Blog({ title, content, author: user });
await blog.save();
res.json({
success: true,
blog,
});
});
// PUT /api/blogs/:id
app.put("/api/blogs/:id", authenticateMiddleware, async (req, res) => {
const { id } = req.params;
const { title, content } = req.body;
var blog = await Blog.findByIdAndUpdate(id, { title, content }).populate({
path: "author",
select: ["firstName", "lastName"],
});
res.json({
success: true,
blog,
});
});
// DELETE /api/blogs/:id
app.delete("/api/blogs/:id", authenticateMiddleware, async (req, res) => {
const { id } = req.params;
await Blog.findByIdAndDelete(id);
res.json({ success: true });
});
app.listen(PORT, (err) => {
if (err) {
console.log(err);
} else {
console.log(`app started successfully on port ${PORT}!`);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment