Bladeren bron

Added check to prevent inserting user with same userName

Michal Kepka 4 jaren geleden
bovenliggende
commit
39399bc220
1 gewijzigde bestanden met toevoegingen van 34 en 7 verwijderingen
  1. 34 7
      src/main/java/cz/hsrs/rest/provider/UserRest.java

+ 34 - 7
src/main/java/cz/hsrs/rest/provider/UserRest.java

@@ -18,6 +18,7 @@ import javax.ws.rs.core.Response;
 
 import org.mortbay.jetty.HttpStatus;
 
+import cz.hsrs.db.model.NoItemFoundException;
 import cz.hsrs.db.util.UserUtil;
 import cz.hsrs.rest.beans.ExceptionBean;
 import cz.hsrs.rest.beans.UserBean;
@@ -78,13 +79,20 @@ public class UserRest {
         try {
             LoginUser loggedUser = AuthUtil.getAuthenticatedLoginUser(req);
             if(loggedUser.getRightsID() == 0) {
-                UserUtil.insertUser(userJSON.getString("userName"),
-                        userJSON.getString("userPass"),
-                        userJSON.getString("userRealName"),
-                        userJSON.getInt("groupId"),
-                        userJSON.getInt("rightsId"));
-            return Response.ok()
-                    .build();
+            	if(!checkDuplicity(userJSON.getString("userName"))) {
+            		UserUtil.insertUser(userJSON.getString("userName"),
+                            userJSON.getString("userPass"),
+                            userJSON.getString("userRealName"),
+                            userJSON.getInt("groupId"),
+                            userJSON.getInt("rightsId"));
+            		return Response.ok()
+                            .build();
+            	} else {
+                    return Response.status(HttpStatus.ORDINAL_409_Conflict)
+                            .entity(new ExceptionBean("Exception", "User with given name cannot be created!"))
+                            .build();
+            	}
+            
             }
             else {
                 return Response.status(HttpStatus.ORDINAL_403_Forbidden)
@@ -103,6 +111,25 @@ public class UserRest {
     }
     
     /**
+     * Function check if user with same userName already exists in DB
+     * @param userName - name of user
+     * @return true if userName is already used
+     * 			false if userName is not used
+     * @throws SQLException
+     */
+    private boolean checkDuplicity(String userName) throws SQLException {
+		UserUtil uUtil = new UserUtil();
+		try {
+			uUtil.getUserId(userName);
+			return true;
+		} catch (NoItemFoundException e) {
+			return false;
+		} catch (SQLException e) {
+			throw new SQLException(e);
+		}
+	}
+
+	/**
      * 
      * URL: /rest/user/rights
      * @param req