Skip to content

Commit

Permalink
Addition of user update apis and CI tests
Browse files Browse the repository at this point in the history
  • Loading branch information
AO-StreetArt committed Dec 26, 2018
1 parent 84777d8 commit 5621e7b
Show file tree
Hide file tree
Showing 4 changed files with 406 additions and 40 deletions.
6 changes: 6 additions & 0 deletions src/main/java/com/ao/adrestia/AdrestiaMongoConfiguration.java
Original file line number Diff line number Diff line change
Expand Up @@ -136,4 +136,10 @@ public MongoClient mongoClient() {
protected String getDatabaseName() {
return "_adrestia";
}

// Definition for accessing underlying Mongo Driver
@Bean
public MongoDatabase mongoDatabase() {
return mongoDbFactory().getDb();
}
}
138 changes: 131 additions & 7 deletions src/main/java/com/ao/adrestia/controller/UsersController.java
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,24 @@
import com.ao.adrestia.model.ApplicationUser;
import com.ao.adrestia.repo.ApplicationUserRepository;

import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.mongodb.async.SingleResultCallback;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Sorts;
import com.mongodb.client.model.UpdateOptions;
import com.mongodb.client.result.UpdateResult;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import javax.annotation.PostConstruct;

import org.bson.Document;
import org.bson.types.ObjectId;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
Expand All @@ -31,6 +46,8 @@
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
Expand All @@ -53,13 +70,26 @@
@RequestMapping("users")
public class UsersController {
private static Logger log = LoggerFactory.getLogger("adrestia.UserController");
private String mongoCollectionName = "applicationUser";

@Autowired
ApplicationUserRepository applicationUserRepository;

@Autowired
MongoDatabase mongoDb;
MongoCollection<Document> mongoCollection = null;

@Autowired
BCryptPasswordEncoder bCryptPasswordEncoder;

/**
* Use the Mongo Client to access the database and collection.
*/
@PostConstruct
public void init() {
mongoCollection = mongoDb.getCollection(mongoCollectionName);
}

/**
* Sign-up a new user.
*/
Expand Down Expand Up @@ -91,22 +121,114 @@ public ResponseEntity<ApplicationUser> signUp(@RequestBody ApplicationUser user)
return new ResponseEntity<ApplicationUser>(user, responseHeaders, returnCode);
}

private BasicDBObject genUpdateQuery(String attrKey, String attrVal, String opType) {
BasicDBObject update = new BasicDBObject();
update.put(attrKey, attrVal);
return new BasicDBObject(opType, update);
}

private BasicDBObject genIdQuery(String id) {
BasicDBObject query = new BasicDBObject();
query.put("_id", new ObjectId(id));
return query;
}

/**
* Update an existing user.
*/
@PutMapping("/{key}")
public ResponseEntity<ApplicationUser> updateUser(
@RequestBody ApplicationUser user,
@PathVariable("key") String key) {
user.setId(key);
user.password = bCryptPasswordEncoder.encode(user.getPassword());
applicationUserRepository.save(user);
// Set up a success response code
log.info("Updating Existing User");
BasicDBObject updateQuery = new BasicDBObject();
if (user.getUsername() != null && !(user.getUsername().isEmpty())) {
updateQuery.put("username", user.getUsername());
}
if (user.getUsername() != null && !(user.getUsername().isEmpty())) {
updateQuery.put("password", bCryptPasswordEncoder.encode(user.getPassword()););
}
if (user.getEmail() != null && !(user.getEmail().isEmpty())) {
updateQuery.put("email", user.getEmail());
}
if (user.getIsAdmin() != null) {
updateQuery.put("isAdmin", user.getIsAdmin());
}
if (user.getIsActive() != null) {
updateQuery.put("isActive", user.getIsActive());
}

UpdateResult result = mongoCollection.updateOne(genIdQuery(key),
new BasicDBObject("$set", updateQuery), new UpdateOptions());

// Set the http response code
HttpStatus returnCode = HttpStatus.OK;
if (result.getModifiedCount() < 1) {
returnCode = HttpStatus.REQUESTED_RANGE_NOT_SATISFIABLE;
logger.debug("No documents modified for user update");
}
HttpHeaders responseHeaders = new HttpHeaders();
return new ResponseEntity<String>("", responseHeaders, returnCode);
}

private ResponseEntity<String> updateArrayAttr(String userKey,
String attrKey, String attrVal, String updType) {
BasicDBObject updateQuery = genUpdateQuery(attrKey, attrVal, updType);
BasicDBObject query = genIdQuery(userKey);
UpdateResult result = mongoCollection.updateOne(query, updateQuery, new UpdateOptions());
// Set the http response code
HttpStatus returnCode = HttpStatus.OK;
if (result.getModifiedCount() < 1) {
returnCode = HttpStatus.REQUESTED_RANGE_NOT_SATISFIABLE;
log.debug("No documents modified for array attribute update");
}
// Set up a response header to return a valid HTTP Response
HttpHeaders responseHeaders = new HttpHeaders();
user.password = "";
return new ResponseEntity<ApplicationUser>(user, responseHeaders, returnCode);
return new ResponseEntity<String>("", responseHeaders, returnCode);
}

/**
* Add a favorite project to an existing user.
*/
@PutMapping("/{key}/projects/{projectKey}")
public ResponseEntity<String> addUserFavProject(
@PathVariable("key") String key,
@PathVariable("projectKey") String projectKey) {
log.info("Adding Favorite Project to user");
return updateArrayAttr(key, "favoriteProjects", projectKey, "$push");
}

/**
* Remove a favorite project from an existing user.
*/
@DeleteMapping("/{key}/projects/{projectKey}")
public ResponseEntity<String> removeUserFavProject(
@PathVariable("key") String key,
@PathVariable("projectKey") String projectKey) {
log.info("Removing Favorite Project from user");
return updateArrayAttr(key, "favoriteProjects", projectKey, "$pull");
}

/**
* Add a favorite scene to an existing user.
*/
@PutMapping("/{key}/scenes/{sceneKey}")
public ResponseEntity<String> addUserFavScene(
@PathVariable("key") String key,
@PathVariable("sceneKey") String sceneKey) {
log.info("Adding Favorite Scene to user");
return updateArrayAttr(key, "favoriteScenes", sceneKey, "$push");
}

/**
* Remove a favorite scene from an existing user.
*/
@DeleteMapping("/{key}/scenes/{sceneKey}")
public ResponseEntity<String> removeUserFavScene(
@PathVariable("key") String key,
@PathVariable("sceneKey") String sceneKey) {
log.info("Remove Favorite Scene from user");
return updateArrayAttr(key, "favoriteScenes", sceneKey, "$pull");
}

/**
Expand Down Expand Up @@ -164,7 +286,9 @@ public ResponseEntity<List<ApplicationUser>> findUser(
returnCode = HttpStatus.NOT_FOUND;
}
// Return the response
returnUser.password = "";
for (ApplicationUser user : existingUsers) {
user.password = "";
}
return new ResponseEntity<List<ApplicationUser>>(existingUsers, responseHeaders, returnCode);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,7 @@ private UsernamePasswordAuthenticationToken getAuthentication(HttpServletRequest

if (user != null) {
log.debug("User retrieved from JWT {}", user);
log.debug("Validating Request URL: {}", request.getRequestURL().toString());
// Validate user access
List<ApplicationUser> requestUsers = this.userRepository.findByUsername(user);
if (requestUsers.size() > 0) {
Expand All @@ -123,8 +124,8 @@ private UsernamePasswordAuthenticationToken getAuthentication(HttpServletRequest
// Non-admin users can only acces user endpoints for themselves
if (!(requestUsers.get(0).getIsAdmin())) {
if (request.getRequestURI().contains("users")
&& !(request.getRequestURI().contains(requestUsers.get(0).getId())
|| request.getRequestURI().contains(requestUsers.get(0).getUsername()))) {
&& !(request.getRequestURI().contains(requestUsers.get(0).getId())
|| request.getQueryString().contains(requestUsers.get(0).getUsername()))) {
log.warn("Rejecting access to user endpoint for non-matching user {}", user);
return null;
}
Expand Down

0 comments on commit 5621e7b

Please sign in to comment.