Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

week5 completed #5

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
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
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
1 change: 1 addition & 0 deletions controllers/index.js
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
module.exports.UserController = require("./user");
module.exports.ToDoController = require("./todo");
module.exports.middlewareObject = require("./middleware");
37 changes: 37 additions & 0 deletions controllers/middleware.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
const { User, Token } = require("../models");
var middlewareObject = {};

middlewareObject.isLoggedIn= (req,res,next)=>{

const authHeader = req.headers.authorization;
// console.log(authHeader);
if(authHeader.split(' ').length!==2 || authHeader.split(' ')[0]!=='Token'){
res.status(400).send('Invalid Token type! It should be of the form "Token <Token> "!');
}
const token = authHeader.split(' ')[1];
Token.findOne({token: token},(err,foundToken)=>{
if(!err && foundToken){
User.findById(foundToken.user,(err,foundUser)=>{
if(!err && foundUser){
// console.log("User exists!");
// console.log(foundUser);
req.loggedInUser = {
username: foundUser.username,
name: foundUser.name,
id: foundUser._id,
email: foundUser.email,
};

return next();
}
else if(!foundUser) res.status(401).send("User not found!");
else res.send(500).status("Something went wrong!");
})
}
else if(!foundToken) res.status(401).send("Token not found!");
else res.send(500).status("Something went wrong!");
})

}

module.exports = middlewareObject;
178 changes: 174 additions & 4 deletions controllers/todo.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
const { ToDo, Token } = require("../models");
const { ToDo, Token ,User} = require("../models");

// All the given method require token.
// So be sure to check for it before doing any stuff
Expand All @@ -7,34 +7,204 @@ const { ToDo, Token } = require("../models");
const getAllToDo = async (req, res) => {
// Get the token in header.
// Use the token to get all the ToDo's of a user

const token = req.headers.authorization.split(' ')[1];
//token auth is handled by Middleware

ToDo.find({ $or : [{createdBy: req.loggedInUser.id}, {collabedBy: req.loggedInUser.id}]} ,(err,foundTodos)=>{
if(!err){
if(foundTodos){

res.send({
"Created / Collabbed Todos: ": foundTodos.map((todo)=>({
id: todo.id,
title: todo.title,
createdBy: todo.createdBy,
collabedBy: todo.collabedBy
}))
});

}
else res.status(404).send("No todos found!!");
}
else res.status(500).send(err);
});


};

const createToDo = async (req, res) => {
// Check for the token and create a todo
// or throw error correspondingly
const title= req.body.title;
const newtodo = new ToDo ({
title: title,
createdBy: req.loggedInUser.id,
collabedBy: []
})
newtodo.save()
.then(res.status(200).send("Todo created successfully!"))
.catch((err)=>{if(err) res.status(500).send("Something went wrong.")});

};

const getParticularToDo = async (req, res) => {
// Get the Todo of the logged in user with given id.
const todoId = req.params.id;
// console.log(todoId);
ToDo.findById(todoId,(err,foundTodo)=>{
if(!err && foundTodo) {
if(toString(foundTodo.createdBy)!=toString(req.loggedInUser.id)) {
res.status(400).send("Unauthorized to view!!");
}
else res.status(200).json(foundTodo);
}
else if(!foundTodo) res.status(404).send("No such Todo exists!");
else res.status(500).send("Something went wrong.");
})
};

const editToDoPatch = async (req, res) => {
// Change the title of the Todo with given id, and get the new title as response
const todoId = req.params.id;
const newTitle= req.body.title;
ToDo.findById(todoId,(err,foundTodo)=>{
if(!err && foundTodo) {
if(toString(foundTodo.createdBy)!=toString(req.loggedInUser.id)) res.status(400).send("Unauthorized to edit!!")
else {
foundTodo.title=newTitle;
foundTodo.save().then(res.status(200).send("Edited successfully!"));
}
}
else if(!foundTodo) res.status(404).send("No such Todo exists!");
else res.status(500).send("Something went wrong.");
})
};

const editToDo = async (req, res) => {
// Change the title of the Todo with given id, and get the new title as response.
editToDoPatch(req,res);
};

const editToDoPatch = async (req, res) => {
// Change the title of the Todo with given id, and get the new title as response
};


const deleteToDo = async (req, res) => {
// Delete the todo with given id
const todoId = req.params.id;
ToDo.findById(todoId,(err,foundTodo)=>{
if(!err && foundTodo) {
if(toString(foundTodo.createdBy)!=toString(req.loggedInUser.id)) res.status(400).send("Unauthorized to delete!!")
else {
ToDo.findByIdAndDelete(todoId,(err,foundIt)=>{
if(err) res.status(500).send("Something went wrong.");
else {
if(foundIt) res.status(200).send("Deleted successfully!!");
}
})
}
}
else if(!foundTodo) res.status(404).send("No such Todo exists!");
else res.status(500).send("Something went wrong.");
})
};

const addCollaborator = async (req, res) => {
const todoId = req.params.id;
const newCollaborator = req.body.collaborator;
console.log(todoId);
User.findOne({username:newCollaborator},(err,foundUser)=>{
if(!err){
if(foundUser){
console.log(foundUser);
if(toString(foundUser.id)!=toString(req.loggedInUser.id)){
return res.status(400).send("Creater cannot be a collaborator!");
}
ToDo.findById(todoId,(err,foundTodo)=>{
if(!err){
if(foundTodo){
if(toString(foundTodo.createdBy)!=toString(req.loggedInUser.id)){
return res.status(401).send("Unauthorized to add a collaborator!!");
}
console.log(foundUser.id);
if(foundTodo.collabedBy && foundTodo.collabedBy.includes(foundUser.id)){
return res.status(400).send("Given user is already a collaborator!!");
}
if(foundTodo.collabedBy){
foundTodo.collabedBy.push(foundUser.id);
}else{
foundTodo.collabedBy = [foundUser.id];
}

foundTodo.save().then(res.status(200).send("Collaborator added!")).catch(err=>res.status(500).send(err));
}else{
return res.status(404).send("No such Todo Exists!");
}
}else{
res.status(500).send(err);
}
})
}else{
return res.status(404).send("User Not Found!!");
}
}else{
return res.status(500).send(err);
}

})
}

const removeCollaborator = async (req,res) => {
const todoId = req.params.id;
const collaborator = req.body.collaborator;
console.log(collaborator);
User.findOne({username:collaborator},(err,foundUser)=>{
if(!err){
if(foundUser){
console.log(foundUser);
if(toString(foundUser.id)!=toString(req.loggedInUser.id)){
return res.status(400).send("Creater was'nt a Collaborator!!");
}
ToDo.findById(todoId,(err,foundTodo)=>{
if(!err){
if(foundTodo){
console.log(foundUser.id)
if(toString(foundTodo.createdBy)!=toString(req.loggedInUser.id)){
return res.status(401).send("Unauthorized to remove collaborators!!");
}
if(foundTodo.collabedBy && foundTodo.collabedBy.includes(foundUser.id)){
foundTodo.collabedBy.splice(foundTodo.collabedBy.findIndex((user)=>{user==foundUser.id}));
}else{
return res.status(404).send("No such collaborator exists!");
}

foundTodo.save().then(res.status(200).send("Succesfully removed the collaborator!!")).catch(err=>res.status(500).send(err));
}
else{
return res.status(404).send("No such Todo exists!");
}
}
else{
res.status(500).send(err);
}
})
}else{
return res.status(404).send("User Not Found!!");
}
}else{
return res.status(500).send(err);
}

})

}

module.exports = {
createToDo,
deleteToDo,
editToDo,
editToDoPatch,
getAllToDo,
getParticularToDo,
addCollaborator,
removeCollaborator
};
85 changes: 85 additions & 0 deletions controllers/user.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
const { User, Token } = require("../models");
const { randomBytes } = require("crypto");
const bcrypt = require("bcrypt");

const createToken = (user) => {
return Token({
Expand All @@ -13,20 +14,104 @@ const login = async (req, res) => {
// Check if data is valid
// Return correct status codes: https://en.wikipedia.org/wiki/List_of_HTTP_status_codes
// If the user is verified, then return a token along with correct status code
const username = req.body.username;
const password= req.body.password;

if(username && password){
User.findOne({username: username},(err,foundUser)=>{
if(err) console.log(err);
else if(foundUser) {
const validPass = bcrypt.compare(password,foundUser.password);
if(validPass) {
Token.findOne({user: foundUser._id},(err,foundToken)=>{
if(!err){
if(foundToken) {
console.log("Token "+foundToken);
res.status(200).send("Login Successfull!!");
}
else res.status(401).send("Token not found!");
}
else console.log(err);

})

}
else res.status(400).send("Invalid Password!!");
}
else {
res.status(401).send("User does'nt exist. :(");
}
})
}
else res.send("Please fill the credentials first!");
};

const signup = async (req, res) => {
// TODO: Read username, email, name, pwd from the req object
// Hash the password
// Return with appropriate status code in case of an error
// If successful, return with an appropriate token along with correct status code
const username=req.body.username;
const email=req.body.email;
const name=req.body.name;
const password= req.body.password;

if (!(username && name && email && password)) {
return res.status(400).send({ error: "Please enter valid credentials!!" });
}

var validRegex = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/;

if (!(validRegex.test(email))) {
return res.status(400).send("Email Address not valid :(");

}
const saltRounds=10;

User.findOne({$or: [{username:username},{email: email}]},(err,foundUser)=>{
if(err) console.log(err);
else{
if(foundUser) res.status(400).send({error: "User already exists!!"});
else {
bcrypt.genSalt(saltRounds, function(err, salt) {
if(!err){
bcrypt.hash(password, salt, function(err, hash) {
if(err) console.log(err);
else {
console.log("Hash "+hash);
const newUser= new User({
name: name,
email: email,
username: username,
password: hash,

})
newUser.save();
const newToken = createToken(newUser);
newToken.save();

res.status(200).send("Succesfully registered!!");
}
});
} else console.log(err);

});

}
}
})
};

const profile = async (req, res) => {
// TODO:
// Implement the functionality to retrieve the details
// of the logged in user.
// Check for the token and then use it to get user details

//Token checked by Middleware
// Just printing out the json object of loggedInUser
console.log(req.loggedInUser);
res.send(req.loggedInUser);
};

module.exports = { login, signup, profile };
2 changes: 1 addition & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ app.use("/api/auth", UserRoutes);
app.use("/api/todo", ToDoRoutes);

const PORT = process.env.PORT || 8000;
const mongoDB = "mongodb://127.0.0.1/my_database";
const mongoDB = "mongodb+srv://yash6318:[email protected]/week5";

mongoose.set("useFindAndModify", false);
mongoose.set("useCreateIndex", true);
Expand Down
1 change: 1 addition & 0 deletions models/todo.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ const todoSchema = new Schema(
{
title: { type: String, required: true },
createdBy: { type: Schema.Types.ObjectId, ref: "User" },
collabedBy: [{ type: Schema.Types.ObjectId, ref: "User" }]
},
{ timestamps: true }
);
Expand Down
1 change: 1 addition & 0 deletions node_modules/.bin/color-support

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions node_modules/.bin/is-ci

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions node_modules/.bin/mime

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions node_modules/.bin/mkdirp

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading