Skip to content

Commit 1af7496

Browse files
committed
initial commit
0 parents  commit 1af7496

File tree

13 files changed

+2907
-0
lines changed

13 files changed

+2907
-0
lines changed

.DS_Store

6 KB
Binary file not shown.

.gitignore

+4
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
*.env
2+
.idea
3+
node_modules
4+
api/uploads/*

api/config/database.js

+13
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
const mongoose = require('mongoose')
2+
3+
const connectDB = async () => {
4+
try {
5+
const conn = await mongoose.connect(process.env.DB_STRING)
6+
console.log(`MongoDB Connected: ${conn.connection.host}`)
7+
} catch (err) {
8+
console.error(err)
9+
process.exit(1)
10+
}
11+
}
12+
13+
module.exports = connectDB

api/config/jwt.js

+3
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
const jwt = require('jsonwebtoken');
2+
3+
module.exports = { jwt };

api/controllers/auth.js

+75
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
const User = require('../models/User')
2+
const { jwt } = require('../config/jwt');
3+
require('dotenv').config({path: './config/.env'})
4+
5+
// const validator = require('validator')
6+
const bcrypt = require('bcryptjs');
7+
const salt = bcrypt.genSaltSync(10);
8+
9+
exports.postLogin = async (req, res, next) => {
10+
const {username,password} = req.body;
11+
const userDoc = await User.findOne({username});
12+
const passOk = bcrypt.compareSync(password, userDoc.password);
13+
if (passOk) {
14+
// logged in
15+
jwt.sign({username,id:userDoc._id}, process.env.jwtSecret, {}, (err,token) => {
16+
if (err) throw err;
17+
res.cookie('token', token).json({
18+
id:userDoc._id,
19+
username,
20+
});
21+
});
22+
} else {
23+
res.status(400).json('wrong credentials');
24+
}
25+
}
26+
27+
exports.postRegister = async (req, res, next) => {
28+
const {username,password} = req.body;
29+
30+
const checkUserExists = (req) => {
31+
const existingUser = User.findOne(//{$or: [
32+
// {email: req.body.email},
33+
{username: req.body.username}
34+
// ]}
35+
);
36+
return existingUser;
37+
};
38+
39+
try{
40+
checkUserExists(req).then(user => {
41+
if(user){
42+
console.log(user)
43+
res.status(400).json('username is taken')
44+
} else {
45+
User.create({
46+
username: username.toLowerCase(),
47+
password:bcrypt.hashSync(password,salt),
48+
}).then(userDoc => res.json(userDoc));
49+
}
50+
})
51+
} catch(e) {
52+
console.log(e);
53+
res.status(400).json(e);
54+
}
55+
}
56+
57+
exports.profileAuth = function(req, res, next){ //should be async
58+
const {token} = req.cookies;
59+
if(!token){
60+
res.json({msg: 'no user'})
61+
}else {
62+
try {
63+
jwt.verify(token, process.env.jwtSecret, {}, (err,info) => {
64+
if (err) throw err;
65+
res.json(info);
66+
});
67+
} catch (error) {
68+
console.log(error)
69+
}
70+
}
71+
}
72+
73+
exports.logout = function(req, res, next){
74+
res.cookie('token', '').json('ok');
75+
}

api/controllers/home.js

+74
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
const User = require('../models/User')
2+
const Post = require('../models/Post')
3+
const fs = require('fs');
4+
const { jwt } = require('../config/jwt');
5+
require('dotenv').config({path: './config/.env'})
6+
7+
exports.createPost = async (req, res, next) => {
8+
const {originalname,path} = req.file;
9+
const parts = originalname.split('.');
10+
const ext = parts[parts.length - 1];
11+
const newPath = path+'.'+ext;
12+
fs.renameSync(path, newPath);
13+
14+
const {token} = req.cookies;
15+
jwt.verify(token, process.env.jwtSecret, {}, async (err,info) => {
16+
if (err) throw err;
17+
const {title,summary,content} = req.body;
18+
const postDoc = await Post.create({
19+
title,
20+
summary,
21+
content,
22+
cover:newPath,
23+
author:info.id,
24+
});
25+
res.json(postDoc);
26+
});
27+
}
28+
29+
exports.updatePost = async (req, res, next) => {
30+
let newPath = null;
31+
if (req.file) {
32+
const {originalname,path} = req.file;
33+
const parts = originalname.split('.');
34+
const ext = parts[parts.length - 1];
35+
newPath = path+'.'+ext;
36+
fs.renameSync(path, newPath);
37+
}
38+
39+
const {token} = req.cookies;
40+
jwt.verify(token, process.env.jwtSecret, {}, async (err,info) => {
41+
if (err) throw err;
42+
const {id,title,summary,content} = req.body;
43+
let postDoc = await Post.findById(id);
44+
const isAuthor = JSON.stringify(postDoc.author) === JSON.stringify(info.id);
45+
if (!isAuthor) {
46+
return res.status(400).json('you are not the author');
47+
}
48+
postDoc = {
49+
title,
50+
summary,
51+
content,
52+
cover: newPath ? newPath : postDoc.cover,
53+
}
54+
55+
await Post.updateOne({_id: id}, postDoc);
56+
57+
res.json(postDoc);
58+
});
59+
}
60+
61+
exports.getPosts = async (req, res, next) => {
62+
res.json(
63+
await Post.find()
64+
.populate('author', ['username'])
65+
.sort({createdAt: -1})
66+
.limit(20)
67+
);
68+
}
69+
70+
exports.getPost = async (req, res, next) => {
71+
const {id} = req.params;
72+
const postDoc = await Post.findById(id).populate('author', ['username']);
73+
res.json(postDoc);
74+
}

api/index.js

+22
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
const express = require('express');
2+
const cors = require('cors');
3+
const connectDB = require('./config/database')
4+
const app = express();
5+
const mainRoutes = require('./routes/main')
6+
const cookieParser = require('cookie-parser');
7+
const logger = require('morgan')
8+
require('dotenv').config({path: './config/.env'})
9+
10+
connectDB()
11+
12+
app.use(cors({credentials:true,origin:'http://localhost:3000'}));
13+
app.use(express.json());
14+
app.use(cookieParser());
15+
app.use('/uploads', express.static(__dirname + '/uploads'));
16+
app.use(logger('dev'))
17+
18+
app.use('/', mainRoutes)
19+
20+
app.listen(process.env.PORT, ()=>{
21+
console.log('Server is running, you better catch it!')
22+
})

api/models/Post.js

+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
const mongoose = require('mongoose');
2+
const {Schema,model} = mongoose;
3+
4+
const PostSchema = new Schema({
5+
title:String,
6+
summary:String,
7+
content:String,
8+
cover:String,
9+
author:{type:Schema.Types.ObjectId, ref:'User'},
10+
}, {
11+
timestamps: true,
12+
});
13+
14+
const PostModel = model('Post', PostSchema);
15+
16+
module.exports = PostModel;

api/models/User.js

+11
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
const mongoose = require('mongoose');
2+
const {Schema, model} = mongoose;
3+
4+
const UserSchema = new Schema({
5+
username: {type: String, required: true, min: 4, unique: true},
6+
password: {type: String, required: true},
7+
});
8+
9+
const UserModel = model('User', UserSchema);
10+
11+
module.exports = UserModel;

0 commit comments

Comments
 (0)