Skip to content

Commit 28cd260

Browse files
code changes
1 parent 778a1fd commit 28cd260

File tree

925 files changed

+206937
-33
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

925 files changed

+206937
-33
lines changed

auth-service.js

Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
var mongoose = require("mongoose");
2+
var Schema = mongoose.Schema;
3+
const bcrypt = require('bcryptjs');
4+
var userSchema = new Schema({
5+
"userName": String,
6+
"password": String,
7+
"email": String,
8+
"loginHistory": [ {
9+
"dateTime": Date,
10+
"userAgent": String,
11+
}]
12+
});
13+
let User;
14+
function initialize(){
15+
let db = mongoose.createConnection(`mongodb+srv://rajatkumar:[email protected]/myFirstDatabase?retryWrites=true&w=majority`);;
16+
return new Promise((resolve,reject)=>{
17+
18+
db.on('error', (err)=>{
19+
reject(Error("Db not Connected"));
20+
});
21+
db.once('open', ()=>{
22+
User = db.model("users", userSchema);
23+
resolve("db1 success!");
24+
});
25+
})
26+
}
27+
28+
function registerUser(userData) {
29+
return new Promise((resolve,reject)=>{
30+
if(userData.password != userData.password2){
31+
reject("Password do not match");
32+
}
33+
34+
bcrypt.hash(userData.password, 10).then((hash)=>{
35+
userData.password=hash;
36+
let newUser= new User(userData);
37+
newUser.save((err)=>{
38+
if(err){
39+
reject(Error("User Name Already Taken "))
40+
}
41+
else if(err){
42+
reject("There was an error creating the user:"+err);
43+
}
44+
else{
45+
resolve();
46+
}
47+
})
48+
})
49+
.catch(err=>{
50+
console.log(err); // Show any errors that occurred during the process
51+
});
52+
53+
})
54+
}
55+
56+
function checkUser(userData){
57+
return new Promise((resolve,reject)=>{
58+
User.find({userName: userData.userName})
59+
.exec().then((data)=>{
60+
if(data.length==0){
61+
reject("Unable to Find user"+userData.userName)
62+
}
63+
bcrypt.compare(userData.password, data[0].password).then((result) => {
64+
if(!result){
65+
reject("Incorrect Password for user : "+ userData.userName);
66+
}
67+
else{
68+
data[0].loginHistory.push({dateTime: (new Date()).toString(), userAgent: userData.userAgent})
69+
User.updateOne(
70+
{userName: data[0].userName},
71+
{$set : { loginHistory : data[0].loginHistory}}
72+
).exec().then(()=>{
73+
resolve(data[0])
74+
}).catch(function(error){
75+
reject("There was an error verifying the user : "+err)
76+
});
77+
}
78+
})
79+
80+
}).catch(function(error){
81+
reject("unable to find the user : "+ userData.userName +error)
82+
});
83+
})
84+
}
85+
86+
module.exports={initialize,registerUser,checkUser }

0 commit comments

Comments
 (0)