forked from bibekshhh/wallet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
157 lines (125 loc) · 4.64 KB
/
app.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
require('dotenv').config();
require('./config/database').connect();
// importing user model
const User = require('./model/user')
const bcrypt = require('bcryptjs')
const auth = require('./middleware/auth')
const jwt = require('jsonwebtoken')
const express = require('express');
const PORT = process.env.PORT || 5050;
const app = express()
app.use(express.json());
//register loigic
app.route('/register').post(async(req, res) => {
try {
//get inputs from user
const { phone, email, password } = req.body;
//validating user input
if (!(phone && email && password)) {
res.status(400).send('All the inputs are required')
}
//check if user already existis
const oldUser = await User.findOne({ wallet_id: phone });
if (oldUser) {
return res.status(401).send('User already exists. Please login to continue.')
}
//encrypting password
const encryptedPassword = await bcrypt.hash(password, 10)
//save user in database
const user = await User.create({
wallet_id: phone,
email: email.toLowerCase(),
password: encryptedPassword,
balance: 0
});
res.status(201).json(user)
} catch (error) {
console.log(error)
}
});
//login logic goes here
app.route('/login').post(async(req, res) => {
try {
//get inputs from user
const { email, password } = req.body;
//validating inputs
if (!(email && password)) {
res.status(400).send('All the inputs are required')
}
//checking user credentials
const existingUser = await User.findOne({ email })
console.log(existingUser)
if (existingUser && (await bcrypt.compare(password, existingUser.password))) {
//create a token
const token = jwt.sign({ wallet_id: existingUser.wallet_id, email },
process.env.ACCESS_TOKEN_KEY, {
expiresIn: '1h'
});
//USER
res.status(200).json({ userDetails: existingUser, accessToken: token })
}
res.status(400).send('Invalid Credentials')
} catch (error) {
console.log(error)
}
});
app.route('/welcome').get(auth, async(req, res) => {
const userEmail = req.existingUser.email;
const data = await User.findOne({ email: userEmail })
res.status(200).json({ loggedIn: userEmail, userData: data })
});
app.route('/send').post(auth, async(req, res) => {
try {
//get inputs from user
const { receiver, amount } = req.body;
//validate inputs
if (!(receiver && amount)) {
res.status(400).send('All the inputs are required')
}
// Current logged in userID
const loggedInUserEmail = req.existingUser.email;
const loggedInSender = await User.findOne({ email: loggedInUserEmail })
//check if receiver exists
const receiverExists = await User.findOne({ wallet_id: receiver });
if (!receiverExists) {
res.status(400).send('Receiver does not exists.')
}
//check if user has enoughBalance
const walletBalance = loggedInSender.balance;
const newBalanceForSender = loggedInSender.balance - amount;
const newBalanceForReceiver = receiverExists.balance + amount;
if ((walletBalance >= amount) && receiverExists) {
await User.findOneAndUpdate({ email: loggedInUserEmail }, {
$set: {
balance: newBalanceForSender,
},
$push: {
transactions: {
"receiver": receiverExists.wallet_id,
"amount": amount,
"status": "Sent"
}
}
});
await User.findOneAndUpdate({ wallet_id: receiver }, {
$set: {
balance: newBalanceForReceiver,
},
$push: {
transactions: {
"sender": loggedInSender.wallet_id,
"amount": amount,
"status": "Receieved"
}
}
});
res.status(200).send("Transaction Successful")
}
res.status(400).send('Insufficient Balance')
} catch (error) {
console.log(error)
}
});
app.listen(PORT, () => {
console.log(`Listening on port: ${PORT}`)
})