Following the tutorial at http://docs.appery.io/tutorials/build..., I modified the code so that it would change the username. When I tested, the code successfully sends out email and a success alert - but the username is not changed.
The code also sends out email when the password is wrong and there are no errors in the console.
My changeUserService accepts three request params, username, newUsername and password.
code
var responseBody = {},
requestParams = {},
paramKeys = request.keys();
for (var key = 0; key < paramKeys.length; key++) {
requestParams[paramKeys[key]] = request.get(paramKeys[key]);
}
// Declare database ID and Master key
var dbId = "***********"
var masterKey = "*************"
// Get username, new password and secret code from request parameters
var username = requestParams['username'];
var newUsername = requestParams['newUsername'];
var password = requestParams['password'];
try {
// Get the user with a given username from the database
var XHRResponse = XHR.send("GET", "https://api.appery.io/rest/1/db/users/", {
"headers": {
"X-Appery-Database-Id": dbId,
"X-Appery-Master-Key": masterKey
},
"parameters": {
"where": '{"username":"' + username + '"}'
}
});
// If the user exists, get his id and password from response
if (XHRResponse.body.length) {
Code: Select all
var userId = XHRResponse.body[0]["_id"];
var passwordDB = XHRResponse.body[0]["password"];
// If the password from the database matches the password received from user,
// update the username with the new value
if (password == passwordDB) {
var XHRResponse = XHR.send("PUT", "https://api.appery.io/rest/1/db/users/" + userId, {
"headers": {
"X-Appery-Database-Id": dbId,
"X-Appery-Master-Key": masterKey,
"Content-Type": "application/json"
},
// Update user's username with a new value
"body": {
"username": newUsername
}
});
}
// If the username update was successful, send an email to the user
if (XHRResponse.status == 200) {
var XHRResponse = XHR.send("POST", "https://api.sendgrid.com/api/mail.send.json", {
"parameters": {
"api_user": "*****",
"api_key": "*****",
"to": "*****",
"toname": "",
"subject": "Username Change Complete",
"text": "You have successfully changed your username ",
"from": "no-reply@test.com"
}
});
if (XHRResponse.status == 200) {
// If the email was successfully sent, inform the user about it
responseBody.message = "Your username was successfully changed. A confirmation email has been sent to your address"
} else {
// Email was not sent, but the user change was still successful
responseBody.message = "Your username was successfully changed"
}
} else {
responseBody.message = "Database error"
} } else {
responseBody.message = "User not found"
}
response.success(responseBody, "application/json");
} catch (e) {
response.success("message: " + e.message + "\ncode: " + e.code); //If something goes wrong error message will appear
}
/code