Skip to content
Merged
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
1 change: 1 addition & 0 deletions .env
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@

PORT=2000
JWT_SECRET=askfeed1234

12 changes: 9 additions & 3 deletions app.js
Original file line number Diff line number Diff line change
@@ -1,16 +1,22 @@
const express = require("express");

const mongoose = require("mongoose");
const cors = require("cors");
const bcryptjs = require("bcryptjs");
const app = express();
require("dotenv").config();
require("./db/connectionDB");

require('./models/User')
require('./models/Survey')

const authRoutes = require("./routes/auth");
const surveyRoutes = require("./routes/survey");

const app = express();

app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.use(cors());

app.use("/survey", surveyRoutes);
app.use("/api", authRoutes);

app.listen(process.env.PORT || 2000, () => {
Expand Down
86 changes: 37 additions & 49 deletions controllers/auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ const { User } = require("../models/user");
const nodemailer = require("nodemailer");
const bcryptjs = require("bcryptjs");
const jwt = require("jsonwebtoken");
JWT_SECRET = "askfeed1234";

const transporter = nodemailer.createTransport({
service: "gmail",
Expand All @@ -17,7 +16,7 @@ const signup = async (req, res) => {
const userexist = await User.findOne({ email });
if (!userexist) {
const hashedPass = await bcryptjs.hashSync(password, 10);
const token = jwt.sign({ username, email }, JWT_SECRET, {
const token = jwt.sign({ username, email }, process.env.JWT_SECRET, {
expiresIn: "30m",
});
const newUser = {
Expand All @@ -35,7 +34,7 @@ const signup = async (req, res) => {
to: email,
subject: "Account activation link",
html: `<h2>PLease click on given link to activate your account</h2>
<p>http://localhost:2000/api/activate/?token=${token}</p>
<p>http://localhost:2000/api/activate/${token}</p>
`,
};
try {
Expand All @@ -53,8 +52,8 @@ const signup = async (req, res) => {

const verifyAccount = async (req, res) => {
try {
const token = req.query.token;
const decodedUser = jwt.verify(token, JWT_SECRET);
const token = req.params.token;
const decodedUser = jwt.verify(token, process.env.JWT_SECRET);

const user = await User.findOne({ email: decodedUser.email, token: token });
if (user) {
Expand All @@ -81,7 +80,7 @@ const resetlink = async (req, res) => {
const user = await User.findOne({ email });
// console.log("user", user, email);
if (user) {
const token = jwt.sign({ email }, JWT_SECRET, {
const token = jwt.sign({ email }, process.env.JWT_SECRET, {
expiresIn: "30m",
});

Expand Down Expand Up @@ -112,52 +111,41 @@ const resetlink = async (req, res) => {
}
};


const changepassword = async(req,res) =>{
const { password}=req.body;
const changepassword = async (req, res) => {
const { password } = req.body;
const token = req.query.token;
const decodedtoken = jwt.verify(token,JWT_SECRET)
const decodedtoken = jwt.verify(token, process.env.JWT_SECRET);
const hashedPass = await bcryptjs.hashSync(password, 10);
const user= await User.findOneAndUpdate({email:decodedtoken.email, resetToken:token },
{$set:
{
password: hashedPass,
resetToken:null
}
}
)
if(user)
const user = await User.findOneAndUpdate(
{ email: decodedtoken.email, resetToken: token },
{
res.send("Password updated successfully!")
}
else
{
res.send("Unable to reset password!")
$set: {
password: hashedPass,
resetToken: null,
},
}
);
if (user) {
res.send("Password updated successfully!");
} else {
res.send("Unable to reset password!");
}
const login=async(req,res)=>{
const {email,password}=req.body
const user=await User.findOne({email})
const {_id}=user
if(user)

{
console.log("user",user)
const matchpassword= await bcryptjs.compare(password,user.password)
if(matchpassword && user.isVarified)
{
const token=jwt.sign({email ,_id},JWT_SECRET)
res.send({token})

}
else
{
res.send("Login unsuccessful!")
}
}
else
{
res.send("Incorrect Email or password!")
};
const login = async (req, res) => {
const { email, password } = req.body;
const user = await User.findOne({ email });
const { _id } = user;
if (user) {
console.log("user", user);
const matchpassword = await bcryptjs.compare(password, user.password);
if (matchpassword && user.isVarified) {
const token = jwt.sign({ email, _id }, process.env.JWT_SECRET);
res.send({ token });
} else {
res.send("Login unsuccessful!");
}
}
module.exports = { signup, verifyAccount, resetlink ,changepassword,login};
} else {
res.send("Incorrect Email or password!");
}
};
module.exports = { signup, verifyAccount, resetlink, changepassword, login };
8 changes: 8 additions & 0 deletions controllers/survey.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
const mongoose = require("mongoose");
const { Survey } = require("../models/survey");

const createSurvey = async (req, res) => {
const survey = await Survey.create(req.body);
res.send(survey);
};
module.exports = { createSurvey };
16 changes: 10 additions & 6 deletions db/connectionDB.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
const mongoose = require("mongoose");

mongoose.connect("mongodb+srv://santan:*Saheb13*@cluster0.cnnl3.mongodb.net/myFirstDatabase?retryWrites=true&w=majority", {
useNewUrlParser: true,
useUnifiedTopology: true,

}) .then(() => console.log("DB connected established"))
.catch(err => console.log("DB Connection error: " , err));
mongoose
.connect(
"mongodb+srv://santan:*Saheb13*@cluster0.cnnl3.mongodb.net/myFirstDatabase?retryWrites=true&w=majority",
{
useNewUrlParser: true,
useUnifiedTopology: true,
}
)
.then(() => console.log("DB connected established"))
.catch((err) => console.log("DB Connection error: ", err));
6 changes: 6 additions & 0 deletions middlewares/requireCredits.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
module.exports = (req, res, next) => {
if (!req.user.credits <1) {
return res.status(403).send({ error: " You do Not have enough Credits!" });
}
next();
};
8 changes: 8 additions & 0 deletions middlewares/requireLogin.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
module.exports = (req, res, next) => {
if (!req.user) {
return res.status(401).send({ error: 'You must log in!' });
}

next();
};

9 changes: 9 additions & 0 deletions models/recipient.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
const mongoose = require('mongoose');
const { Schema } = mongoose;

const recipientSchema = new Schema({
email: String,
responded: { type: Boolean, default: false }
});

module.exports = recipientSchema;
61 changes: 35 additions & 26 deletions models/survey.js
Original file line number Diff line number Diff line change
@@ -1,26 +1,35 @@

const mongoose=require('mongoose')

const surveySchema=mongoose.Schema({
title:{
type:String
},
type:{
type:String
},

questionsSet:[
{
ques:{
type: String
},
ans:{
type: [Boolean]
}
}
]

})
//created the survey api now
const Survey = mongoose.model("Survey",surveySchema)
module.exports={Survey}
const mongoose = require("mongoose");
const recipientSchema= require('./recipient')
const surveySchema = mongoose.Schema({
title: {
type: String,
},
category: {
type: String,
},
body: {
type: String,
},
subject: {
type: String,
},
recipients:[
recipientSchema
],
yes: {
type: Number,
default: 0,
},
No: {
type: Number,
default: 0,
},
_user:{
type:mongoose.Schema.Types.ObjectId,
ref:'User'
},
dateSent: Date,
lastResponded: Date
});
const Survey = mongoose.models.Survey||mongoose.model("Survey", surveySchema);
module.exports = { Survey };
30 changes: 12 additions & 18 deletions models/user.js
Original file line number Diff line number Diff line change
@@ -1,38 +1,32 @@
const mongoose = require("mongoose");
// const crypto = require ('crypto')


const userSchema = mongoose.Schema({

username: {
type: String,
required:true,
max:64,
required: true,
},
password: {
type: String,
required:true,
required: true,
},
email: {
type: String,
unique:true,
unique: true,
lowercase: true,
},
phoneNo: {
type: Number,
},
isVarified:{
isVarified: {
type: Boolean,
default:false
default: false,
},
token:{
type: String
token: {
type: String,
},
resetToken: {
type: String,
default: null,
},
resetToken:{
type: String ,
default:null
}

});
const User = mongoose.model("User", userSchema);
const User = mongoose.models.User || mongoose.model("User", userSchema);
module.exports = { User };
23 changes: 15 additions & 8 deletions routes/auth.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,18 @@
const express =require("express")
const express = require("express");
const router = express.Router();

const {signup, verifyAccount,resetlink,changepassword,login} = require("../controllers/auth")
const {
signup,
verifyAccount,
resetlink,
changepassword,
login,
} = require("../controllers/auth");

router.post('/signup', signup)
router.post('/activate', verifyAccount)
router.post('/resetlink', resetlink)
router.post('/changepassword',changepassword)
router.post('/login',login)
module.exports = router;
router.post("/signup", signup);
router.post("/activate", verifyAccount);
router.post("/resetlink", resetlink);
router.post("/changepassword", changepassword);
router.post("/login", login);

module.exports = router;
26 changes: 26 additions & 0 deletions routes/survey.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
const express = require("express");
const mongoose = require("mongoose");
const requireLogin = require("../middlewares/requireLogin");
const requireCredits = require("../middlewares/requireCredits");
const {Survey} = require('../models/survey')
// const { createSurvey } = require("../controllers/survey");
// const router = express.Router();
// router.post("/createsurvey", createSurvey);
//first need to cheak user is actually logged in

module.exports = (app) => {
app.post("api/surveys", requireLogin, requireCredits, (req, res) => {
const { title, category, body, recipients } = req.body;
const survey = new Survey({
title,
category,
subject,
body,
recipients: recipients.split(',').map(email => ({ email: email.trim() })),
_user: req.user.id,
dateSent: Date.now()
});
survey.save()
});
};
// module.exports = router;