dockerized the project for dev

This commit is contained in:
QkoSad
2024-09-06 16:27:48 +03:00
parent 8e83b6b8df
commit 04ae8b7be8
47 changed files with 363 additions and 635 deletions
+80
View File
@@ -0,0 +1,80 @@
const express = require("express");
const router = express.Router();
const bcrypt = require("bcryptjs");
const auth = require("../../middleware/auth");
const jwt = require("jsonwebtoken");
const config = require("config");
const { check, validationResult } = require("express-validator");
const User = require("../../models/User");
// @route GET api/auth
// @desc Get user by token
// @access Private
router.get("/", auth, async (req, res) => {
try {
const user = await User.findById(req.user.id).select("-password");
res.json(user);
} catch (err) {
console.error(err.message);
res.status(500).send("Server Error");
}
});
// @route POST api/auth
// @desc Authenticate user & get token
// @access Public
router.post(
"/",
[
check("email", "Please include a valid email").isEmail(),
check("password", "Password is required").exists(),
],
async (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
const { email, password } = req.body;
try {
let user = await User.findOne({ email });
if (!user) {
return res
.status(400)
.json({ errors: [{ msg: "Invalid Credentials" }] });
}
const isMatch = await bcrypt.compare(password, user.password);
if (!isMatch) {
return res
.status(400)
.json({ errors: [{ msg: "Invalid Credentials" }] });
}
const payload = {
user: {
id: user.id,
},
};
jwt.sign(
payload,
config.get("jwtSecret"),
{ expiresIn: 360000 },
(err, token) => {
if (err) throw err;
res.json({ token });
}
);
} catch (err) {
console.error(err.message);
res.status(500).send("Server error");
}
}
);
module.exports = router;
+96
View File
@@ -0,0 +1,96 @@
import express from 'express'
import bcrypt from 'bcryptjs'
import jwt from 'jsonwebtoken';
import auth from '../../middleware/auth'
import config from 'config'
import { check, validationResult } from "express-validator";
import User from '../../models/User'
import type { Request, Response } from 'express';
import { isUserId } from '../../utils';
const router = express.Router();
// @route GET api/auth
// @desc Get user by token
// @access Private
router.get("/", auth, async (req: any, res) => {
try {
let user: unknown = null
if (isUserId(req)) {
user = await User.findById(req.user.id).select("-password");
res.json(user);
}
else {
throw new Error('missing id in request')
}
} catch (err: unknown) {
if (typeof err === 'string')
console.error(err)
else if (err instanceof Error)
console.error(err.message);
res.status(500).send("Server Error");
}
});
// @route POST api/auth
// @desc Authenticate user & get token
// @access Public
router.post(
"/",
[
check("email", "Please include a valid email").isEmail(),
check("password", "Password is required").exists(),
],
async (req: Request, res: Response) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
const { email, password } = req.body;
try {
let user = await User.findOne({ email });
if (!user) {
return res
.status(400)
.json({ errors: [{ msg: "Invalid Credentials" }] });
}
const isMatch = await bcrypt.compare(password, user.password);
if (!isMatch) {
return res
.status(400)
.json({ errors: [{ msg: "Invalid Credentials" }] });
}
const payload = {
user: {
id: user.id,
},
};
const jwtSecret = config.get('jwtSecret')
if (typeof jwtSecret === 'string') jwt.sign(
payload,
jwtSecret,
{ expiresIn: 360000 },
(err, token) => {
if (err) throw err;
res.json({ token });
}
);
else throw new Error('Error signing the jwt token')
} catch (err: unknown) {
if (typeof err === 'string')
console.error(err)
else if (err instanceof Error)
console.error(err.message);
res.status(500).send("Server error");
}
}
);
module.exports = router
+221
View File
@@ -0,0 +1,221 @@
const express = require("express");
const router = express.Router();
const { check, validationResult } = require("express-validator");
const auth = require("../../middleware/auth");
const Post = require("../../models/Post");
const User = require("../../models/User");
const checkObjectId = require("../../middleware/checkObjectId");
// @route POST api/posts
// @desc Create a post
// @access Private
router.post(
"/",
auth,
check("text", "Text is required").notEmpty(),
async (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
try {
const user = await User.findById(req.user.id).select("-password");
const newPost = new Post({
text: req.body.text,
name: user.name,
avatar: user.avatar,
user: req.user.id,
});
const post = await newPost.save();
res.json(post);
} catch (err) {
console.error(err.message);
res.status(500).send("Server Error");
}
}
);
// @route GET api/posts
// @desc Get all posts
// @access Private
router.get("/", auth, async (req, res) => {
try {
const posts = await Post.find().sort({ date: -1 });
res.json(posts);
} catch (err) {
console.error(err.message);
res.status(500).send("Server Error");
}
});
// @route GET api/posts/:id
// @desc Get post by ID
// @access Private
router.get("/:id", auth, checkObjectId("id"), async (req, res) => {
try {
const post = await Post.findById(req.params.id);
if (!post) {
return res.status(404).json({ msg: "Post not found" });
}
res.json(post);
} catch (err) {
console.error(err.message);
res.status(500).send("Server Error");
}
});
// @route DELETE api/posts/:id
// @desc Delete a post
// @access Private
router.delete("/:id", [auth, checkObjectId("id")], async (req, res) => {
try {
const post = await Post.findById(req.params.id);
if (!post) {
return res.status(404).json({ msg: "Post not found" });
}
// Check user
if (post.user.toString() !== req.user.id) {
return res.status(401).json({ msg: "User not authorized" });
}
await post.remove();
res.json({ msg: "Post removed" });
} catch (err) {
console.error(err.message);
res.status(500).send("Server Error");
}
});
// @route PUT api/posts/like/:id
// @desc Like a post
// @access Private
router.put("/like/:id", auth, checkObjectId("id"), async (req, res) => {
try {
const post = await Post.findById(req.params.id);
// Check if the post has already been liked
if (post.likes.some((like) => like.user.toString() === req.user.id)) {
return res.status(400).json({ msg: "Post already liked" });
}
post.likes.unshift({ user: req.user.id });
await post.save();
return res.json(post.likes);
} catch (err) {
console.error(err.message);
res.status(500).send("Server Error");
}
});
// @route PUT api/posts/unlike/:id
// @desc Unlike a post
// @access Private
router.put("/unlike/:id", auth, checkObjectId("id"), async (req, res) => {
try {
const post = await Post.findById(req.params.id);
// Check if the post has not yet been liked
if (!post.likes.some((like) => like.user.toString() === req.user.id)) {
return res.status(400).json({ msg: "Post has not yet been liked" });
}
// remove the like
post.likes = post.likes.filter(
({ user }) => user.toString() !== req.user.id
);
await post.save();
return res.json(post.likes);
} catch (err) {
console.error(err.message);
res.status(500).send("Server Error");
}
});
// @route POST api/posts/comment/:id
// @desc Comment on a post
// @access Private
router.post(
"/comment/:id",
auth,
checkObjectId("id"),
check("text", "Text is required").notEmpty(),
async (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
try {
const user = await User.findById(req.user.id).select("-password");
const post = await Post.findById(req.params.id);
const newComment = {
text: req.body.text,
name: user.name,
avatar: user.avatar,
user: req.user.id,
};
post.comments.unshift(newComment);
await post.save();
res.json(post.comments);
} catch (err) {
console.error(err.message);
res.status(500).send("Server Error");
}
}
);
// @route DELETE api/posts/comment/:id/:comment_id
// @desc Delete comment
// @access Private
router.delete("/comment/:id/:comment_id", auth, async (req, res) => {
try {
const post = await Post.findById(req.params.id);
// Pull out comment
const comment = post.comments.find(
(comment) => comment.id === req.params.comment_id
);
// Make sure comment exists
if (!comment) {
return res.status(404).json({ msg: "Comment does not exist" });
}
// Check user
if (comment.user.toString() !== req.user.id) {
return res.status(401).json({ msg: "User not authorized" });
}
post.comments = post.comments.filter(
({ id }) => id !== req.params.comment_id
);
await post.save();
return res.json(post.comments);
} catch (err) {
console.error(err.message);
return res.status(500).send("Server Error");
}
});
module.exports = router;
+277
View File
@@ -0,0 +1,277 @@
import express, { Request, Response } from 'express'
import { check, validationResult } from "express-validator";
import auth from "../../middleware/auth";
import Post from "../../models/Post";
import User from "../../models/User";
import checkObjectId from "../../middleware/checkObjectId";
import { isUserId } from '../../utils';
const router = express.Router();
// @route POST api/posts
// @desc Create a post
// @access Private
router.post(
"/",
auth,
check("text", "Text is required").notEmpty(),
async (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
try {
if (isUserId(req)) {
const user = await User.findById(req.user.id).select("-password");
if (user) {
const newPost = new Post({
text: req.body.text,
name: user.name,
avatar: user.avatar,
user: req.user.id,
});
const post = await newPost.save();
res.json(post);
}
else {
throw new Error('Error finding the user')
}
}
else {
throw new Error('Error finding the user')
}
} catch (err: unknown) {
if (typeof err === 'string')
console.error(err)
else if (err instanceof Error)
console.error(err.message);
res.status(500).send("Server Error");
}
}
);
// @route GET api/posts
// @desc Get all posts
// @access Private
router.get("/", auth, async (req, res) => {
try {
const posts = await Post.find().sort({ date: -1 });
res.json(posts);
} catch (err: unknown) {
if (typeof err === 'string')
console.error(err)
else if (err instanceof Error)
console.error(err.message);
res.status(500).send("Server Error");
}
});
// @route GET api/posts/:id
// @desc Get post by ID
// @access Private
router.get("/:id", auth, checkObjectId("id"), async (req, res) => {
try {
const post = await Post.findById(req.params.id);
if (!post) {
return res.status(404).json({ msg: "Post not found" });
}
res.json(post);
} catch (err: unknown) {
if (typeof err === 'string')
console.error(err)
else if (err instanceof Error)
console.error(err.message);
res.status(500).send("Server Error");
}
});
// @route DELETE api/posts/:id
// @desc Delete a post
// @access Private
router.delete("/:id", [auth, checkObjectId("id")], async (req: Request, res: Response) => {
try {
const post = await Post.findOne({ _id: req.params.id });
if (!post) {
return res.status(404).json({ msg: "Post not found" });
}
// Check user
if (post.user && isUserId(req)) {
if (post.user.toString() !== req.user.id) {
return res.status(401).json({ msg: "User not authorized" });
}
}
else {
throw new Error('Error in req.user')
}
await post.deleteOne();
res.json({ msg: "Post removed" });
} catch (err: unknown) {
if (typeof err === 'string')
console.error(err)
else if (err instanceof Error)
console.error(err.message);
res.status(500).send("Server Error");
}
});
// @route PUT api/posts/like/:id
// @desc Like a post
// @access Private
router.put("/like/:id", auth, checkObjectId("id"), async (req, res) => {
try {
const post = await Post.findById(req.params.id);
// Check if the post has already been liked
if (post && isUserId(req)) {
if (post.likes.some((like) => like.user?.toString() === req.user.id)) {
return res.status(400).json({ msg: "Post already liked" });
}
const user: any = req.user.id
// can't make string into ObjectID
post.likes.unshift({ user });
await post.save();
return res.json(post.likes)
};
} catch (err: unknown) {
if (typeof err === 'string')
console.error(err)
else if (err instanceof Error)
console.error(err.message);
res.status(500).send("Server Error");
}
});
// @route PUT api/posts/unlike/:id
// @desc Unlike a post
// @access Private
router.put("/unlike/:id", auth, checkObjectId("id"), async (req, res) => {
try {
const post = await Post.findById(req.params.id);
// Check if the post has not yet been liked
if (post && isUserId(req)) {
if (!post.likes.some((like) => like.user?.toString() === req.user.id)) {
return res.status(400).json({ msg: "Post has not yet been liked" });
}
// remove the like
post.likes = post.likes.filter(
({ user }) => {
if (user)
return user.toString() !== req.user.id
return false
}
);
await post.save();
return res.json(post.likes);
}
} catch (err: unknown) {
if (typeof err === 'string')
console.error(err)
else if (err instanceof Error)
console.error(err.message);
res.status(500).send("Server Error");
}
});
// @route POST api/posts/comment/:id
// @desc Comment on a post
// @access Private
router.post(
"/comment/:id",
auth,
checkObjectId("id"),
check("text", "Text is required").notEmpty(),
async (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
try {
if (isUserId(req) && req.params) {
const user = await User.findById(req.user.id).select("-password");
const post = await Post.findById(req.params.id);
if (user) {
const newComment = {
text: req.body.text,
name: user.name,
avatar: user.avatar,
user: req.user.id,
};
if (post) {
post.comments.unshift(newComment as any);
await post.save();
res.json(post.comments);
}
throw new Error('Error in finding post')
}
throw new Error('Error in finding user')
}
throw new Error('Error in parsing the req')
} catch (err: unknown) {
if (typeof err === 'string')
console.error(err)
else if (err instanceof Error)
console.error(err.message);
res.status(500).send("Server Error");
}
}
);
// @route DELETE api/posts/comment/:id/:comment_id
// @desc Delete comment
// @access Private
router.delete("/comment/:id/:comment_id", auth, async (req, res) => {
try {
const post = await Post.findById(req.params.id);
// Pull out comment
if (post) {
const comment = post.comments.find(
(comment: any) => comment.id === req.params.comment_id
);
// Make sure comment exists
if (!comment) {
return res.status(404).json({ msg: "Comment does not exist" });
}
// Check user
if ('user' in comment && comment.user && isUserId(req) && comment.user.toString() !== req.user.id) {
return res.status(401).json({ msg: "User not authorized" });
}
post.comments = post.comments.filter(
({ id }: any) => id !== req.params.comment_id
);
await post.save();
return res.json(post.comments);
}
} catch (err: unknown) {
if (typeof err === 'string')
console.error(err)
else if (err instanceof Error)
console.error(err.message);
return res.status(500).send("Server Error");
}
});
module.exports = router
+330
View File
@@ -0,0 +1,330 @@
import express from 'express';
import axios from 'axios';
import config from 'config';
import auth from '../../middleware/auth';
import { check, validationResult } from 'express-validator';
// bring in normalize to give us a proper url, regardless of what user entered
import normalize from 'normalize-url';
import checkObjectId from '../../middleware/checkObjectId';
import Profile from '../../models/Profile';
import User from '../../models/User';
import Post from '../../models/Post';
import { isUserId } from '../../utils';
const router = express.Router();
// @route GET api/profile/me
// @desc Get current users profile
// @access Private
router.get('/me', auth, async (req, res) => {
try {
if (isUserId(req)) {
const profile = await Profile.findOne({
user: req.user.id
}).populate('user', ['name', 'avatar']);
if (!profile) {
return res.status(400).json({ msg: 'There is no profile for this user' });
}
res.json(profile);
}
} catch (err: unknown) {
if (typeof err === 'string')
console.error(err)
else if (err instanceof Error)
console.error(err.message);
res.status(500).send('Server Error');
}
});
// @route POST api/profile
// @desc Create or update user profile
// @access Private
router.post(
'/',
auth,
check('status', 'Status is required').notEmpty(),
check('skills', 'Skills is required').notEmpty(),
async (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
// destructure the request
const {
website,
skills,
youtube,
twitter,
instagram,
linkedin,
facebook,
// spread the rest of the fields we don't need to check
...rest
} = req.body;
// build a profile
if (isUserId(req)) {
const profileFields = {
user: req.user.id,
website:
website && website !== ''
? normalize(website, { forceHttps: true })
: '',
skills: Array.isArray(skills)
? skills
: skills.split(',').map((skill: string) => ' ' + skill.trim()),
...rest
};
// Build socialFields object
const socialFields: { [key: string]: any } = { youtube, twitter, instagram, linkedin, facebook };
// normalize social fields to ensure valid url
for (const [key, value] of Object.entries(socialFields)) {
if (value && value.length > 0)
socialFields[key] = normalize(value, { forceHttps: true });
}
// add to profileFields
profileFields.social = socialFields;
try {
// Using upsert option (creates new doc if no match is found):
let profile = await Profile.findOneAndUpdate(
{ user: req.user.id },
{ $set: profileFields },
{ new: true, upsert: true, setDefaultsOnInsert: true }
);
return res.json(profile);
} catch (err: unknown) {
if (typeof err === 'string')
console.error(err)
else if (err instanceof Error)
console.error(err.message);
return res.status(500).send('Server Error');
}
}
}
);
// @route GET api/profile
// @desc Get all profiles
// @access Public
router.get('/', async (req, res) => {
try {
const profiles = await Profile.find().populate('user', ['name', 'avatar']);
res.json(profiles);
} catch (err: unknown) {
if (typeof err === 'string')
console.error(err)
else if (err instanceof Error)
console.error(err.message);
res.status(500).send('Server Error');
}
});
// @route GET api/profile/user/:user_id
// @desc Get profile by user ID
// @access Public
router.get(
'/user/:user_id',
checkObjectId('user_id'),
async ({ params: { user_id } }, res) => {
try {
const profile = await Profile.findOne({
user: user_id
}).populate('user', ['name', 'avatar']);
if (!profile) return res.status(400).json({ msg: 'Profile not found' });
return res.json(profile);
} catch (err: unknown) {
if (typeof err === 'string')
console.error(err)
else if (err instanceof Error)
console.error(err.message);
return res.status(500).json({ msg: 'Server error' });
}
}
);
// @route DELETE api/profile
// @desc Delete profile, user & posts
// @access Private
router.delete('/', auth, async (req, res) => {
try {
// Remove user posts
// Remove profile
// Remove user
if (isUserId(req))
await Promise.all([
Post.deleteMany({ user: req.user.id }),
Profile.findOneAndRemove({ user: req.user.id }),
User.findOneAndRemove({ _id: req.user.id })
]);
res.json({ msg: 'User deleted' });
} catch (err: unknown) {
if (typeof err === 'string')
console.error(err)
else if (err instanceof Error)
console.error(err.message);
res.status(500).send('Server Error');
}
});
// @route PUT api/profile/experience
// @desc Add profile experience
// @access Private
router.put(
'/experience',
auth,
check('title', 'Title is required').notEmpty(),
check('company', 'Company is required').notEmpty(),
check('from', 'From date is required and needs to be from the past')
.notEmpty()
.custom((value, { req }) => (req.body.to ? value < req.body.to : true)),
async (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
try {
if (isUserId(req)) {
const profile = await Profile.findOne({ user: req.user.id });
if (profile) {
profile.experience.unshift(req.body);
await profile.save();
}
res.json(profile);
}
} catch (err: unknown) {
if (typeof err === 'string')
console.error(err)
else if (err instanceof Error)
console.error(err.message);
res.status(500).send('Server Error');
}
}
);
// @route DELETE api/profile/experience/:exp_id
// @desc Delete experience from profile
// @access Private
router.delete('/experience/:exp_id', auth, async (req, res) => {
try {
if (isUserId(req)) {
const foundProfile = await Profile.findOne({ user: req.user.id });
if (foundProfile) {
foundProfile.experience = foundProfile.experience.filter(
(exp: any) => exp._id.toString() !== req.params.exp_id
);
await foundProfile.save();
}
return res.status(200).json(foundProfile);
}
} catch (err: unknown) {
if (typeof err === 'string')
console.error(err)
else if (err instanceof Error)
console.error(err.message);
return res.status(500).json({ msg: 'Server error' });
}
});
// @route PUT api/profile/education
// @desc Add profile education
// @access Private
router.put(
'/education',
auth,
check('school', 'School is required').notEmpty(),
check('degree', 'Degree is required').notEmpty(),
check('fieldofstudy', 'Field of study is required').notEmpty(),
check('from', 'From date is required and needs to be from the past')
.notEmpty()
.custom((value, { req }) => (req.body.to ? value < req.body.to : true)),
async (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
try {
if (isUserId(req)) {
const profile = await Profile.findOne({ user: req.user.id });
if (profile) {
profile.education.unshift(req.body);
await profile.save();
}
res.json(profile);
}
} catch (err: unknown) {
if (typeof err === 'string')
console.error(err)
else if (err instanceof Error)
console.error(err.message);
res.status(500).send('Server Error');
}
}
);
// @route DELETE api/profile/education/:edu_id
// @desc Delete education from profile
// @access Private
router.delete('/education/:edu_id', auth, async (req, res) => {
try {
if (isUserId(req)) {
const foundProfile = await Profile.findOne({ user: req.user.id });
if (foundProfile) {
foundProfile.education = foundProfile.education.filter(
(edu: any) => edu._id.toString() !== req.params.edu_id
);
await foundProfile.save();
}
return res.status(200).json(foundProfile);
}
} catch (err: unknown) {
if (typeof err === 'string')
console.error(err)
else if (err instanceof Error)
console.error(err.message);
return res.status(500).json({ msg: 'Server error' });
}
});
// @route GET api/profile/github/:username
// @desc Get user repos from Github
// @access Public
router.get('/github/:username', async (req, res) => {
try {
const uri = encodeURI(
`https://api.github.com/users/${req.params.username}/repos?per_page=5&sort=created:asc`
);
const headers = {
'user-agent': 'node.js',
Authorization: `token ${config.get('githubToken')}`
};
const gitHubResponse = await axios.get(uri, { headers });
return res.json(gitHubResponse.data);
} catch (err: unknown) {
if (typeof err === 'string')
console.error(err)
else if (err instanceof Error)
console.error(err.message);
return res.status(404).json({ msg: 'No Github profile found' });
}
});
module.exports = router
+90
View File
@@ -0,0 +1,90 @@
import express from "express";
import gravatar from "gravatar";
import bcrypt from "bcryptjs";
import jwt from "jsonwebtoken";
import config from "config";
import { check, validationResult } from "express-validator";
import User from "../../models/User";
import normalizeUrl from "normalize-url";
const router = express.Router();
// @route POST api/users
// @desc Register user
// @access Public
router.post(
"/",
check("name", "Name is required").notEmpty(),
check("email", "Please include a valid email").isEmail(),
check(
"password",
"Please enter a password with 6 or more characters"
).isLength({ min: 6 }),
async (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
const { name, email, password } = req.body;
try {
let user = await User.findOne({ email });
if (user) {
return res
.status(400)
.json({ errors: [{ msg: "User already exists" }] });
}
const avatar = normalizeUrl(
gravatar.url(email, {
s: "200",
r: "pg",
d: "mm",
}),
{ forceHttps: true }
);
user = new User({
name,
email,
avatar,
password,
});
const salt = await bcrypt.genSalt(10);
user.password = await bcrypt.hash(password, salt);
await user.save();
const payload = {
user: {
id: user.id,
},
};
const jwtSecret = config.get('jwtSecret')
if (typeof jwtSecret === 'string') jwt.sign(
payload,
jwtSecret,
{ expiresIn: "5 days" },
(err, token) => {
if (err) throw err;
res.json({ token });
}
);
} catch (err: unknown) {
if (typeof err === 'string')
console.error(err)
else if (err instanceof Error)
console.error(err.message);
res.status(500).send("Server error");
}
}
);
module.exports = router