import com.mongodb.DBCollection; //導入方法依賴的package包/類
/**
* Update an existing user.
*
* @param id The ID of the user to update.
* @param payload The fields of the user that should be updated.
* @return Nothing.
*/
@PUT
@Path("/{id}")
@Consumes("application/json")
public Response updateUser(@PathParam("id") String id, JsonObject payload) {
// Validate the JWT. The JWT should be in the 'users' group. We do not
// check to see if the user is modifying their own profile.
try {
validateJWT(new HashSet(Arrays.asList("users")));
} catch (JWTException jwte) {
return Response.status(Status.UNAUTHORIZED)
.type(MediaType.TEXT_PLAIN)
.entity(jwte.getMessage())
.build();
}
// Retrieve the user from the database.
DB database = mongo.getMongoDB();
DBCollection dbCollection = database.getCollection(User.DB_COLLECTION_NAME);
DBObject oldDbUser = dbCollection.findOne(new ObjectId(id));
if (oldDbUser == null) {
return Response.status(Status.BAD_REQUEST).entity("The user was not Found.").build();
}
// If the input object contains a new password, need to hash it for use in the database.
User newUser = null;
if (payload.containsKey("password")) {
try {
String rawPassword = payload.getString("password");
String saltString = (String) (oldDbUser.get(User.JSON_KEY_USER_PASSWORD_SALT));
PasswordUtility pwUtil = new PasswordUtility(rawPassword, saltString);
JsonObject newJson =
createJsonBuilder(payload)
.add(User.JSON_KEY_USER_PASSWORD_HASH, pwUtil.getHashedPassword())
.add(User.JSON_KEY_USER_PASSWORD_SALT, pwUtil.getSalt())
.build();
newUser = new User(newJson);
} catch (Throwable t) {
return Response.serverError().entity("Error updating password").build();
}
} else {
newUser = new User(payload);
}
// Create the updated user object. Only apply the fields that we want the
// client to change (skip the internal fields).
DBObject updateObject = new BasicDBObject("$set", newUser.getDBObjectForModify());
dbCollection.findAndModify(oldDbUser, updateObject);
return Response.ok().build();
}