added routing for updating user profile

This commit is contained in:
Aqeeb Imtiaz Harun
2018-08-25 10:41:02 +08:00
parent f64a134407
commit 2e32f06cfe
2 changed files with 36 additions and 3 deletions
+35 -2
View File
@@ -32,6 +32,7 @@ function isAuthenticated({phone, password}){
}
// check if the number already exists in database
//this function's implementation is commented out for the time being because of the token mismatch issue, this will be implemanted later on.
function isInDatabase({phone}){
return userdb.users.findIndex(user => user.phone === phone) !== -1;
}
@@ -56,6 +57,16 @@ function verificationCode(){
// //return userdb.users.reduce((max, b) => Math.max(max, b.id),userdb.users[0].id);
// }
//Function to find a specific id in users.json file
//This function is depricted for the time being, in case we plan to use it in any way
function findUserId(data, id){
for (var i = 0; i<data.length; i++){
if(data[i]['id'] = id){
return i;
}
}
}
server.post('/auth/login', (req, res) => {
const {phone, password} = req.body;
if (isAuthenticated({phone, password}) === false) {
@@ -69,10 +80,10 @@ function verificationCode(){
});
server.post('/send-verification', (req, res)=>{
const {phone, password} = req.body;
const {phone} = req.body;
const id = userdb.users.length + 1;
//if(isInDatabase({phone} === false)){
userdb.users.push({id: id, phone: phone, password: password});
userdb.users.push({id: id, phone: phone, password: null, name: null, role: null});
fs.writeFile('users.json', JSON.stringify(userdb),
function(err){
if(err) throw err;
@@ -89,6 +100,28 @@ function verificationCode(){
res.status(200).json({verification_code});
});
server.post('/update-user', (req, res)=>{
const {name, role, password, id} = req.body;
//var i = findUserId(userdb.users, id);
for (var i = 0; i<userdb.users.length; i++){
if(userdb.users[i]['id'] == id){
userdb.users[i].password = password;
userdb.users[i].name = name;
userdb.users[i].role = role;
}
}
fs.writeFile('users.json', JSON.stringify(userdb),
function(err){
if(err) throw err;
console.log('updated json');
});
const status = 200;
const message = 'Profile Updated';
res.status(status).json({status, message});
});
server.use(/^(?!\/auth).*$/, (req, res, next) => {
if (req.headers.authorization === undefined || req.headers.authorization.split(' ')[0] !== 'Bearer') {
const status = 401;
+1 -1
View File
@@ -1 +1 @@
{"users":[{"id":1,"phone":"01234567891","password":"123456789"},{"id":2,"phone":"01234567892","password":"123456789"},{"id":3,"phone":"01234567893","password":"123456789"}]}
{"users":[{"id":1,"phone":"01234567891","password":"123456789","name":"Forth User","role":"1"},{"id":2,"phone":"01234567892","password":"123456789"},{"id":3,"phone":"01234567893","password":"123456789"},{"id":4,"phone":"01234567894","password":"123456789","name":"Forth User","role":"1"}]}