Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 52 additions & 0 deletions contributions/Social-media-REST-API/Controllers/AuthController.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import UserModel from "../Models/userModel.js";
import bcrypt from "bcrypt";



//Registering a new user
export const registerUser=async(req,res)=>{
const {username,password,firstname,lastname}=req.body;

const salt=await bcrypt.genSalt(10);
const hashedPass=await bcrypt.hash(password,salt);

const newUser = new UserModel({
username,
password: hashedPass,
firstname,
lastname,
});


try {
await newUser.save();
res.status(200).json(newUser);
} catch (error) {
res.status(500).json({ message: error.message });
}

};

//login user

export const loginUser = async (req, res) => {
const {username, password} = req.body

try {
const user = await UserModel.findOne({username: username})


if(user)
{
const validity = await bcrypt.compare(password, user.password)


validity? res.status(200).json(user): res.status(400).json("Wrong Password")
}
else{
res.status(404).json("User does not exists")
}
} catch (error) {
res.status(500).json({ message: error.message });
}
}
123 changes: 123 additions & 0 deletions contributions/Social-media-REST-API/Controllers/PostController.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
import PostModel from "../Models/postModel.js";
import mongoose from "mongoose";
import UserModel from "../Models/userModel.js";

// Creat new Post
export const createPost = async (req, res) => {
const newPost = new PostModel(req.body);

try {
await newPost.save();
res.status(200).json("Post created!");
} catch (error) {
res.status(500).json(error);
}
};

// Get a post

export const getPost = async (req, res) => {
const id = req.params.id;

try {
const post = await PostModel.findById(id);
res.status(200).json(post);
} catch (error) {
res.status(500).json(error);
}
};

// Update a post
export const updatePost = async (req, res) => {
const postId = req.params.id;
const { userId } = req.body;

try {
const post = await PostModel.findById(postId);
if (post.userId === userId) {
await post.updateOne({ $set: req.body });
res.status(200).json("Post Updated");
} else {
res.status(403).json("Action forbidden");
}
} catch (error) {
res.status(500).json(error);
}
};

// Delete a post
export const deletePost = async (req, res) => {
const id = req.params.id;
const { userId } = req.body;

try {
const post = await PostModel.findById(id);
if (post.userId === userId) {
await post.deleteOne();
res.status(200).json("POst deleted successfully");
} else {
res.status(403).json("Action forbidden");
}
} catch (error) {
res.status(500).json(error);
}
};

// like/dislike a post
export const likePost = async (req, res) => {
const id = req.params.id;
const { userId } = req.body;

try {
const post = await PostModel.findById(id);
if (!post.likes.includes(userId)) {
await post.updateOne({ $push: { likes: userId } });
res.status(200).json("Post liked");
} else {
await post.updateOne({ $pull: { likes: userId } });
res.status(200).json("Post Unliked");
}
} catch (error) {
res.status(500).json(error);
}
};

// Get Timeline POsts
export const getTimelinePosts = async (req, res) => {
const userId = req.params.id;

try {
const currentUserPosts = await PostModel.find({ userId: userId });
const followingPosts = await UserModel.aggregate([
{
$match: {
_id: new mongoose.Types.ObjectId(userId),
},
},
{
$lookup: {
from: "posts",
localField: "following",
foreignField: "userId",
as: "followingPosts",
},
},
{
$project: {
followingPosts: 1,
_id: 0,
},
},
]);

res
.status(200)
.json(currentUserPosts.concat(...followingPosts[0].followingPosts)
.sort((a,b)=>{
return b.createdAt - a.createdAt;
})
);
} catch (error) {
res.status(500).json(error);
}
};
115 changes: 115 additions & 0 deletions contributions/Social-media-REST-API/Controllers/UserController.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
import UserModel from "../Models/userModel.js";
import bcrypt from "bcrypt";
// get a User
export const getUser = async (req, res) => {
const id = req.params.id;

try {
const user = await UserModel.findById(id);

if (user) {
const { password, ...otherDetails } = user._doc;

res.status(200).json(otherDetails);
} else {
res.status(404).json("No such user exists");
}
} catch (error) {
res.status(500).json(error);
}
};

// update a user
export const updateUser = async (req, res) => {
const id = req.params.id;
const { currentUserId, currentUserAdminStatus, password } = req.body;

if (id === currentUserId || currentUserAdminStatus) {
try {
if (password) {
const salt = await bcrypt.genSalt(10);
req.body.password = await bcrypt.hash(password, salt);
}

const user = await UserModel.findByIdAndUpdate(id, req.body, {
new: true,
});

res.status(200).json(user);
} catch (error) {
res.status(500).json(error);
}
} else {
res.status(403).json("Access Denied! you can only update your own profile");
}
};

// Delete user
export const deleteUser = async (req, res) => {
const id = req.params.id;

const { currentUserId, currentUserAdminStatus } = req.body;

if (currentUserId === id || currentUserAdminStatus) {
try {
await UserModel.findByIdAndDelete(id);
res.status(200).json("User deleted successfully");
} catch (error) {
res.status(500).json(error);
}
} else {
res.status(403).json("Access Denied! you can only delete your own profile");
}
};

// Follow a User
export const followUser = async (req, res) => {
const id = req.params.id;

const { currentUserId } = req.body;

if (currentUserId === id) {
res.status(403).json("Action forbidden");
} else {
try {
const followUser = await UserModel.findById(id);
const followingUser = await UserModel.findById(currentUserId);

if (!followUser.followers.includes(currentUserId)) {
await followUser.updateOne({ $push: { followers: currentUserId } });
await followingUser.updateOne({ $push: { following: id } });
res.status(200).json("User followed!");
} else {
res.status(403).json("User is Already followed by you");
}
} catch (error) {
res.status(500).json(error);
}
}
};

// UnFollow a User
export const UnFollowUser = async (req, res) => {
const id = req.params.id;

const { currentUserId } = req.body;

if (currentUserId === id) {
res.status(403).json("Action forbidden");
} else {
try {
const followUser = await UserModel.findById(id);
const followingUser = await UserModel.findById(currentUserId);

if (followUser.followers.includes(currentUserId)) {
await followUser.updateOne({ $pull: { followers: currentUserId } });
await followingUser.updateOne({ $pull: { following: id } });
res.status(200).json("User Unfollowed!");
} else {
res.status(403).json("User is not followed by you");
}
} catch (error) {
res.status(500).json(error);
}
}
};
16 changes: 16 additions & 0 deletions contributions/Social-media-REST-API/Models/postModel.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import mongoose from "mongoose";

const postSchema = mongoose.Schema(
{
userId: { type: String, required: true },
desc: String,
likes: [],
image: String,
},
{
timestamps: true,
}
);

var PostModel = mongoose.model("Posts", postSchema);
export default PostModel;
38 changes: 38 additions & 0 deletions contributions/Social-media-REST-API/Models/userModel.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import mongoose from "mongoose";

const UserSchema = mongoose.Schema(
{
username: {
type: String,
required: true
},
password : {
type: String,
required: true
},
firstname: {
type: String,
required: true
},
lastname : {
type: String,
required: true
},
isAdmin : {
type: Boolean,
default: false,
},
profilePicture: String,
coverPicture: String,
about: String,
livesin: String,
worksAt: String,
relationship: String,
followers: [] ,
following: []
},
{timestamps: true}
)

const UserModel= mongoose.model("Users", UserSchema);
export default UserModel
12 changes: 12 additions & 0 deletions contributions/Social-media-REST-API/Routes/AuthRoute.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import express from "express";
import { loginUser, registerUser } from "../Controllers/AuthController.js";

const router=express.Router();



router.post('/register', registerUser)
router.post('/login', loginUser)


export default router;
11 changes: 11 additions & 0 deletions contributions/Social-media-REST-API/Routes/PostRoute.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import express from "express";
import { createPost, deletePost, getPost, getTimelinePosts, likePost, updatePost } from "../Controllers/PostController.js";
const router = express.Router()

router.post('/', createPost)
router.get('/:id', getPost)
router.put('/:id', updatePost)
router.delete("/:id", deletePost)
router.put("/:id/like", likePost)
router.get("/:id/timeline", getTimelinePosts)
export default router;
11 changes: 11 additions & 0 deletions contributions/Social-media-REST-API/Routes/UserRoute.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import express from "express";
import { deleteUser, followUser, getUser, UnFollowUser, updateUser } from "../Controllers/UserController.js";

const router = express.Router();

router.get('/:id', getUser)
router.put('/:id', updateUser)
router.delete('/:id', deleteUser)
router.put('/:id/follow', followUser)
router.put('/:id/unfollow', UnFollowUser)
export default router;
Loading