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

feat:backend added #6

Closed
wants to merge 6 commits into from
Closed
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 .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
/node_modules
37 changes: 37 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
# Club Collabaration Backend

Languages Used

- Node.js
- Express
- MongoDB
Expand All @@ -14,8 +15,44 @@ git clone https://github.com/iiitv/Club-Collabaration-backend/
cd Club-Collabaration-backend
yarn install
```

## Running

```bash
yarn start
```

## DEPLOYMENT

```
The app is deployed at https://club-collab.herokuapp.com

The following are the routes that are available

## GET https://club-collab.herokuapp.com/users
## POST https://club-collab.herokuapp.com/signup

the body must include
{
name: (min length:3)
email: valid one and unique
password:(min length:6)
}
sample one
{
"name":"vadodara",
"email":"[email protected]",
"password":"rybaopd"

}

##POST https://club-collab.herokuapp.com/login

The body must include
{
email:
password:
}


```
93 changes: 16 additions & 77 deletions app.js
Original file line number Diff line number Diff line change
@@ -1,81 +1,20 @@
var express = require("express");
var app = express();
var bodyParser = require("body-parser");

//mongodb packages
var mongoose = require("mongoose");

//routes
const usersRoutes = require('./routes/users-routes');

//passport packages
var LocalStrategy = require("passport-local");
var passport = require("passport");
var passportLocalMongoose = require("passport-local-mongoose");


var User = require("./models/user");
var Admin = require("./models/admin");

//encryting password
app.use(require("express-session")({
secret: "kuch bhi likh do",
resave: false,
saveUninitialized: false
}));

//Connecting to mongodb server and storing ip_data
mongoose.connect("mongodb://localhost:27017/club_collaboration", { useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex: true});

app.use(bodyParser.urlencoded({extended: true}));

//Passport Configuration
app.use(passport.initialize());
app.use(passport.session());
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
passport.use(new LocalStrategy(User.authenticate()));

//passing current user to every route
app.use(function(req, res, next){
res.locals.currentUser = req.user;
next();
});

//to pass data to react
app.use(bodyParser.json());

app.use((req, res, next) => {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader(
'Access-Control-Allow-Headers',
'Origin, X-Requested-With, Content-Type, Accept, Authorization'
);
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PATCH, DELETE');

next();
const express = require("express");
const mongoose = require("mongoose");
const app = express();
app.use(express.json());
const usersRoutes = require("./routes/users-routes");

//Connecting to mongodb server
const dbURI =
"mongodb+srv://rohith:[email protected]/clubcollab";
mongoose.connect(dbURI, {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true,
});

app.use("/", usersRoutes);

//get requests
app.get("/checkAuthentication", isLoggedIn, (req, res){
const authenticated: boolean = typeof req.user !== 'undefined';
res.status(200).json({
authenticated,
});
});


//middleware
function isLoggedIn(req, res, next){
if(req.isAuthenticated()){
return next();
}
res.redirect("/l");
}

//PORT
app.listen(5000, function(){
console.log("Serving app on port 3000");
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => {
console.log(`Serving app on port ${PORT}`);
});
56 changes: 56 additions & 0 deletions controllers/users-controllers.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
const Users = require("../models/user");
const bcrypt = require("bcrypt");

const { checkErrors, checkUserExist } = require("../utils/auth");

const signUp = async (req, res) => {
const { name, email, password } = req.body;
const errors = checkErrors(req.body);
const user = await checkUserExist(email);
if (errors) return res.status(300).send(errors);
if (user) return res.status(400).send("The user with email allready exists");
try {
const user = await Users.create({
name,
email,
password,
});
res.status(200).send(user);
} catch (error) {
res.status(400).send(error.message);
}
};
const getAllUsers = async (req, res) => {
try {
const users = await Users.find().sort({ name: 1 });
res.status(200).send(users);
} catch (error) {
res.status(400).send(error.message);
}
};
const userLogin = async (req, res) => {
const { email, password } = req.body;
try {
const user = await Users.findOne({ email });
if (!user) return res.status(400).send("the user with email doesn't exist");
bcrypt
.compare(password, user.password)
.then((result) => {
if (result)
return res.status(200).send("You have logged in successfully");
else return res.status(400).send("password doesn't match");
})
.catch((err) => {
return res.status(400).send("bad credintials");
});
} catch (error) {
res.status(400).send(error.message);
}
};
const handleNotFound = (req, res) => {
res.status(404).send("sorry this page doeesn't exist");
};
module.exports.signUp = signUp;
module.exports.userLogin = userLogin;
module.exports.getAllUsers = getAllUsers;
module.exports.handleNotFound = handleNotFound;
25 changes: 25 additions & 0 deletions models/Schema.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
var mongoose = require("mongoose");
const { isEmail, isAlphanumeric } = require("validator");
const bcrypt = require("bcrypt");
const Schema = new mongoose.Schema({
name: { type: String, required: true, trim: true, min: 3 },
email: {
type: String,
required: true,
trim: true,
validate: [isEmail, "please enter a valid email"],
},
isAdmin: { type: Boolean, default: false },
password: {
type: String,
required: true,
trim: true,
min: 6,
},
});
Schema.pre("save", async function (next) {
const salt = await bcrypt.genSalt();
this.password = await bcrypt.hash(this.password, salt);
next();
});
module.exports = Schema;
17 changes: 3 additions & 14 deletions models/admin.js
Original file line number Diff line number Diff line change
@@ -1,15 +1,4 @@
var mongoose = require("mongoose");
var passportLocalMongoose = require("passport-local-mongoose");

var AdminSchema = new mongoose.Schema({
username: String,
name: String,
gender: String,
email: String,
mobile: Number,
password: String
});

AdminSchema.plugin(passportLocalMongoose);

const mongoose = require("mongoose");
const passportLocalMongoose = require("passport-local-mongoose");
const AdminSchema = require("./Schema");
module.exports = mongoose.model("Admin", AdminSchema);
18 changes: 3 additions & 15 deletions models/user.js
Original file line number Diff line number Diff line change
@@ -1,15 +1,3 @@
var mongoose = require("mongoose");
var passportLocalMongoose = require("passport-local-mongoose");

var UserSchema = new mongoose.Schema({
username: String,
name: String,
gender: String,
email: String,
mobile: Number,
password: String
});

UserSchema.plugin(passportLocalMongoose);

module.exports = mongoose.model("User", UserSchema);
const mongoose = require("mongoose");
const UserSchema = require("./Schema");
module.exports = mongoose.model("users", UserSchema);
Loading