Esempio n. 1
0
  @Override
  public Set<UserRole> getUserRoles(String sessID, String user)
      throws RemoteException, SessionExpiredException, SQLException, SecurityException {
    String thisUser = SessionManager.getInstance().getUserForSession(sessID);
    String thisDatabase = SessionManager.getInstance().getDatabaseForSession(sessID);

    // check that this user ibelongs to this database
    if (!isUserOfThisDatabase(sessID)) {
      LOG.error(
          "User "
              + thisUser
              + " is not a member of the database "
              + thisDatabase
              + ", and can't query roles for user "
              + user);
      throw new SecurityException(
          "Can't get roles for user "
              + user
              + " on this database.  User making request is not a user of this database.");
    }
    // Check that this user is either requesting his own roles, OR is an administrator.
    if (user.equals(thisUser) || isAdmin(sessID)) {
      // ok to proceed
      return getRolesForUser(sessID, user);
    } else {
      String err =
          "User "
              + user
              + " does not have administrative permission to request roles available for user "
              + user;
      LOG.error(err);
      throw new SecurityException(err);
    }
  }
Esempio n. 2
0
 @Override
 public UserLevel getSessionUsersLevel(String sessID)
     throws SQLException, RemoteException, SessionExpiredException {
   // username for this session
   String name = SessionManager.getInstance().getUserForSession(sessID);
   return getUserLevel(sessID, name);
 }
Esempio n. 3
0
 @Override
 public UserRole getRoleByName(String sessID, String roleName)
     throws RemoteException, SessionExpiredException, SQLException {
   String thisDatabase = SessionManager.getInstance().getDatabaseForSession(sessID);
   TableSchema roleTable = MedSavantDatabase.UserRoleTableSchema;
   SelectQuery sq = new SelectQuery();
   sq.addFromTable(roleTable.getTable());
   sq.addAllColumns();
   sq.addCondition(
       BinaryCondition.equalTo(
           roleTable.getDBColumn(MedSavantDatabase.UserRoleTableSchema.COLUMNNAME_OF_ROLENAME),
           roleName));
   ResultSet rs = null;
   try {
     rs = ConnectionController.executeQuery(sessID, sq.toString());
     if (rs.next()) {
       int roleId = rs.getInt(1);
       String name = rs.getString(2);
       String roleDescription = rs.getString(3);
       return new UserRole(roleId, name, roleDescription, thisDatabase);
     }
     return null;
   } finally {
     if (rs != null) {
       rs.close();
     }
   }
 }
Esempio n. 4
0
 @Override
 public Set<UserRole> getAllRoles(String sessID)
     throws RemoteException, SQLException, SecurityException, SessionExpiredException {
   String thisDatabase = SessionManager.getInstance().getDatabaseForSession(sessID);
   TableSchema roleTable = MedSavantDatabase.UserRoleTableSchema;
   SelectQuery sq = new SelectQuery();
   sq.addFromTable(roleTable.getTable());
   sq.addColumns(
       roleTable.getDBColumn(MedSavantDatabase.UserRoleTableSchema.COLUMNNAME_OF_ID),
       roleTable.getDBColumn(MedSavantDatabase.UserRoleTableSchema.COLUMNNAME_OF_ROLENAME),
       roleTable.getDBColumn(
           MedSavantDatabase.UserRoleTableSchema.COLUMNNAME_OF_ROLE_DESCRIPTION));
   sq.setIsDistinct(true);
   ResultSet rs = null;
   try {
     rs = ConnectionController.executeQuery(sessID, sq.toString());
     Set<UserRole> roleSet = new TreeSet<UserRole>();
     while (rs.next()) {
       int roleId = rs.getInt(1);
       String roleName = rs.getString(2);
       String roleDescription = rs.getString(3);
       roleSet.add(new UserRole(roleId, roleName, roleDescription, thisDatabase));
     }
     return roleSet;
   } finally {
     if (rs != null) {
       rs.close();
     }
   }
 }
  @Route(method = HttpRequest.Method.POST, urlPattern = "/register")
  public HttpResponse register(
      HttpRequest request,
      @Param("name") String name,
      @Param("surname") String surname,
      @Param("email") String email,
      @Param("password") String password) {

    User user = new User(DB.getInstance().getNewId(), name, surname, email, password);
    DB.getInstance().addUser(user);

    HttpResponse response = new HttpResponse("Successfully created an user", 200);

    Cookie c = new Cookie("auth", request);
    response.addCookie(c);

    String sessionId = SessionManager.getSessionIdForRequest(request);
    SessionManager.getInstance().addSession(sessionId, new Integer(user.id));

    try {
      String body = TemplateProcessor.process("profile.html", user.getJsonData().build());
      response.setBody(body);
    } catch (IOException e) {
      response.setStatusCode(500);
    }

    return response;
  }
Esempio n. 6
0
  // verifies the user is assigned the given role.
  public boolean checkAllRoles(String sessID, Set<UserRole> roles)
      throws RemoteException, SQLException, SessionExpiredException {
    if (roles.isEmpty()) {
      throw new IllegalArgumentException("Can't check empty role");
    }

    Set<UserRole> assignedRoles =
        getRolesForUser(sessID, SessionManager.getInstance().getUserForSession(sessID));
    return !assignedRoles.isEmpty() && assignedRoles.containsAll(roles);
  }
Esempio n. 7
0
 public boolean isUserOfThisDatabase(String sessID)
     throws SQLException, SessionExpiredException, RemoteException {
   String thisUser = SessionManager.getInstance().getUserForSession(sessID);
   String[] users = getUserNames(sessID);
   for (String user : users) {
     if (user.equalsIgnoreCase(thisUser)) {
       return true;
     }
   }
   return false;
 }
Esempio n. 8
0
  private boolean checkAdmin(String sessID)
      throws SecurityException, RemoteException, SessionExpiredException, SQLException {
    String thisUser = SessionManager.getInstance().getUserForSession(sessID);
    String thisDatabase = SessionManager.getInstance().getDatabaseForSession(sessID);
    if (!isAdmin(sessID)) {
      String err =
          "Cannot add role to user.  This requires "
              + thisUser
              + " to have administrative privileges";
      LOG.error(err);
      throw new SecurityException(err);
    }

    if (!isUserOfThisDatabase(sessID)) {
      String err =
          "Cannot add role to user.  The current user "
              + thisUser
              + " is not a user of "
              + thisDatabase;
      LOG.error(err);
      throw new SecurityException(err);
    }
    return true;
  }
Esempio n. 9
0
  @Override
  public UserRole addRole(String sessID, String roleName, String roleDescription)
      throws RemoteException, SessionExpiredException, SQLException, SecurityException {
    String thisDatabase = SessionManager.getInstance().getDatabaseForSession(sessID);
    checkAdmin(sessID);

    // Check if role already exists, and if so, return it.
    Set<UserRole> roles = getAllRoles(sessID);
    for (UserRole r : roles) {
      if (r.getDatabase().equals(thisDatabase) && r.getRoleName().equals(roleName)) {
        return r;
      }
    }

    TableSchema roleTable = MedSavantDatabase.UserRoleTableSchema;
    InsertQuery iq = new InsertQuery(roleTable.getTableName());
    iq.addColumn(
        roleTable.getDBColumn(MedSavantDatabase.UserRoleTableSchema.COLUMNNAME_OF_ROLENAME),
        roleName);
    iq.addColumn(
        roleTable.getDBColumn(MedSavantDatabase.UserRoleTableSchema.COLUMNNAME_OF_ROLE_DESCRIPTION),
        roleDescription);

    PooledConnection conn = ConnectionController.connectPooled(sessID);
    PreparedStatement stmt = null;
    ResultSet res = null;
    int roleId = -1;
    try {
      stmt = conn.prepareStatement(iq.toString(), Statement.RETURN_GENERATED_KEYS);
      stmt.execute();
      res = stmt.getGeneratedKeys();
      res.next();
      roleId = res.getInt(1);

      return new UserRole(roleId, roleName, roleDescription, thisDatabase);
    } finally {
      if (stmt != null) {
        stmt.close();
      }
      if (res != null) {
        res.close();
      }
      if (conn != null) {
        conn.close();
      }
    }
  }
Esempio n. 10
0
  public boolean checkAnyRole(String sessID, Set<UserRole> roles)
      throws RemoteException, SQLException, SessionExpiredException {
    if (roles.isEmpty()) {
      throw new IllegalArgumentException("Can't check empty role");
    }
    Set<UserRole> assignedRoles =
        getRolesForUser(sessID, SessionManager.getInstance().getUserForSession(sessID));

    if (!assignedRoles.isEmpty()) {
      for (UserRole role : roles) {
        if (assignedRoles.contains(role)) {
          return true;
        }
      }
    }
    return false;
  }
Esempio n. 11
0
  private Set<UserRole> getRolesForUser(String sessID, String user)
      throws RemoteException, SQLException, SessionExpiredException {
    String database = SessionManager.getInstance().getDatabaseForSession(sessID);
    TableSchema roleTable = MedSavantDatabase.UserRoleTableSchema;
    TableSchema roleATable = MedSavantDatabase.UserRoleAssignmentTableSchema;

    SelectQuery sq = new SelectQuery();
    sq.addColumns(
        roleTable.getDBColumn(MedSavantDatabase.UserRoleTableSchema.COLUMNNAME_OF_ID),
        roleTable.getDBColumn(MedSavantDatabase.UserRoleTableSchema.COLUMNNAME_OF_ROLENAME),
        roleTable.getDBColumn(
            MedSavantDatabase.UserRoleTableSchema.COLUMNNAME_OF_ROLE_DESCRIPTION));
    Condition joinCondition =
        BinaryCondition.equalTo(
            roleTable.getDBColumn(MedSavantDatabase.UserRoleTableSchema.COLUMNNAME_OF_ID),
            roleATable.getDBColumn(
                MedSavantDatabase.UserRoleAssignmentTableSchema.COLUMNNAME_OF_ROLE_ID));
    sq.addJoin(
        SelectQuery.JoinType.INNER, roleTable.getTable(), roleATable.getTable(), joinCondition);
    sq.addCondition(
        BinaryCondition.equalTo(
            roleATable.getDBColumn(
                MedSavantDatabase.UserRoleAssignmentTableSchema.COLUMNNAME_OF_USERNAME),
            user));

    ResultSet rs = null;
    try {
      rs = ConnectionController.executeQuery(sessID, sq.toString());
      Set<UserRole> roleSet = new HashSet<UserRole>();
      while (rs.next()) {
        int roleId = rs.getInt(1);
        String roleName = rs.getString(2);
        String roleDescription = rs.getString(3);
        roleSet.add(new UserRole(roleId, roleName, roleDescription, database));
      }
      return roleSet;
    } finally {
      if (rs != null) {
        rs.close();
      }
    }
  }
Esempio n. 12
0
 public void stop() {
   subscriber.stop();
   SessionManager.getInstance().removeSession(this);
 }
Esempio n. 13
0
 public void start() {
   SessionManager.getInstance().addSession(this);
 }
Esempio n. 14
0
 public String registerUserHandling(String userName) throws MageException {
   this.isAdmin = false;
   if (userName.equals("Admin")) {
     return "User name Admin already in use";
   }
   if (userName.length() > ConfigSettings.getInstance().getMaxUserNameLength()) {
     return new StringBuilder("User name may not be longer than ")
         .append(ConfigSettings.getInstance().getMaxUserNameLength())
         .append(" characters")
         .toString();
   }
   if (userName.length() < ConfigSettings.getInstance().getMinUserNameLength()) {
     return new StringBuilder("User name may not be shorter than ")
         .append(ConfigSettings.getInstance().getMinUserNameLength())
         .append(" characters")
         .toString();
   }
   Pattern p =
       Pattern.compile(
           ConfigSettings.getInstance().getUserNamePattern(), Pattern.CASE_INSENSITIVE);
   Matcher m = p.matcher(userName);
   if (m.find()) {
     return new StringBuilder("User name '")
         .append(userName)
         .append("' includes not allowed characters: use a-z, A-Z and 0-9")
         .toString();
   }
   User user = UserManager.getInstance().createUser(userName, host);
   boolean reconnect = false;
   if (user == null) { // user already exists
     user = UserManager.getInstance().findUser(userName);
     if (user.getHost().equals(host)) {
       user.updateLastActivity(null); // minimizes possible expiration
       this.userId = user.getId();
       if (user.getSessionId().isEmpty()) {
         logger.info("Reconnecting session for " + userName);
         reconnect = true;
       } else {
         // disconnect previous session
         logger.info("Disconnecting another user instance: " + userName);
         SessionManager.getInstance()
             .disconnect(user.getSessionId(), DisconnectReason.ConnectingOtherInstance);
       }
     } else {
       return new StringBuilder("User name ")
           .append(userName)
           .append(" already in use (or your IP address changed)")
           .toString();
     }
   }
   if (!UserManager.getInstance().connectToSession(sessionId, user.getId())) {
     return new StringBuilder("Error connecting ").append(userName).toString();
   }
   this.userId = user.getId();
   if (reconnect) { // must be connected to receive the message
     UUID chatId =
         GamesRoomManager.getInstance()
             .getRoom(GamesRoomManager.getInstance().getMainRoomId())
             .getChatId();
     if (chatId != null) {
       ChatManager.getInstance().joinChat(chatId, userId);
     }
     ChatManager.getInstance().sendReconnectMessage(userId);
   }
   return null;
 }
Esempio n. 15
0
 @Override
 public Set<UserRole> getRolesForUser(String sessID)
     throws SQLException, SessionExpiredException, RemoteException {
   return getRolesForUser(sessID, SessionManager.getInstance().getUserForSession(sessID));
 }
Esempio n. 16
0
 public boolean checkRole(String sessID, UserRole role)
     throws RemoteException, SQLException, SessionExpiredException {
   Set<UserRole> assignedRoles =
       getRolesForUser(sessID, SessionManager.getInstance().getUserForSession(sessID));
   return assignedRoles.contains(role);
 }