Created
February 28, 2020 07:02
-
-
Save Raja0sama/984c9095955ac75804de4f8495930bca to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const express = require('express') | |
const app = express() | |
const bcrypt = require('bcrypt') | |
const mongoose = require('mongoose') | |
var bodyParser = require('body-parser') | |
app.use(bodyParser.json()) | |
mongoose.connect('mongodb://localhost/my_database', { | |
useNewUrlParser: true, | |
useUnifiedTopology: true | |
}); | |
const Schema = mongoose.Schema; | |
const ObjectId = Schema.ObjectId; | |
const UserSchema = new Schema({ | |
id: ObjectId, | |
name: {type:String,required: true,unique: true}, | |
password: {type:String,required: true}, | |
email: {type:String,required: true,unique: true}, | |
}); | |
var User = mongoose.model('User', UserSchema); | |
const users = [] | |
app.get('/users', (req, res) => { | |
res.json(users) | |
}) | |
app.post('/users', async (req, res, next) => { | |
const check = await User.find({ email: req.body.email }) | |
if (check.length == 0) { | |
try { | |
const hashedpw = await bcrypt.hash(req.body.password, 10) | |
const user = { name: req.body.name, password: hashedpw, email: req.body.email } | |
User.create(user, (err, user) => { | |
if (err) { | |
return next(err.message) | |
} else { | |
res.status(201).send(users) | |
} | |
}) | |
} catch (e) { | |
res.status(500).send(e) | |
} | |
} else { | |
res.status(200).send("User already Exist") | |
} | |
}) | |
app.post('/users/login', async (req, res) => { | |
const user = await User.find({name:req.body.name}) | |
if(user.length == 0 ){ | |
return res.status(400).send('cannot find user') | |
} | |
try { | |
if (await bcrypt.compare(req.body.password, user[0].password)) { | |
res.status(201).send(user[0]) | |
} else { | |
res.status(201).send("not allowed") | |
} | |
} catch (e) { | |
res.status(500).send("failed") | |
} | |
}) | |
app.listen(3000) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment