Esempio n. 1
0
 @Test
 public void testSortedArrayMerge() {
   Json a1 = array(1, 2, 20, 30, 50);
   Json a2 = array(0, 2, 20, 30, 35, 40, 51);
   a1.with(a2, "sort");
   Assert.assertEquals(array(0, 1, 2, 20, 30, 35, 40, 50, 51), a1);
 }
Esempio n. 2
0
 private UserProvider provider(String name) {
   synchronized (providerMap) {
     UserProvider provider = providerMap.get(name);
     if (provider != null) return provider;
     if (!desc.at("hasUserBase").has(name)) return null;
     String classname =
         desc.at("hasUserBase")
             .at(name)
             .at("hasImplementation")
             .at("iri")
             .asString()
             .split("#")[1];
     try {
       provider = (UserProvider) Class.forName(classname).newInstance();
       // Autoconfigure is not part of the object initialisation
       // without synchronization, variables set during autoconfigure might not be readable by
       // other threads.
       synchronized (provider) {
         if (provider instanceof AutoConfigurable)
           ((AutoConfigurable) provider).autoConfigure(desc.at("hasUserBase").at(name));
       }
       providerMap.put(name, provider);
       return provider;
     } catch (Exception ex) {
       throw new RuntimeException(ex);
     }
   }
 }
Esempio n. 3
0
 /**
  * Consumes an array of group names and augments those groups with the corresponding access
  * policies.
  *
  * @param groups An array of names of groups.
  * @return
  */
 @POST
 @Path("/accesspolicies")
 public Json accessPolicies(Json groups) {
   groups = getAccessPolicies(groups);
   if (!groups.asList().isEmpty() && groups.at(0).has("hasAccessPolicy"))
     return ok().set("cirmusergroups", groups);
   else return ko("No Access policies are available for user.");
 }
Esempio n. 4
0
 @Test
 public void testUnsortedArrayMerge() {
   Json a1 = array(4, 35, 1, 65, 2, 456);
   Json a2 = array(65, 5, 3534, 4);
   a1.with(a2, object("sort", false));
   Assert.assertEquals(
       TU.set(a1.asJsonList()), TU.set(array(4, 35, 1, 65, 2, 456, 65, 5, 3534, 4).asJsonList()));
 }
Esempio n. 5
0
 public static Json getReply(Json msg) {
   Json s =
       object(
           ACTIVITY_TYPE, msg.at(ACTIVITY_TYPE),
           CONVERSATION_ID, msg.at(CONVERSATION_ID));
   if (msg.has(PARENT_SCOPE))
     s.set(PARENT_SCOPE, msg.at(PARENT_SCOPE)).set(PARENT_TYPE, msg.at(PARENT_TYPE));
   return msg.has(REPLY_WITH) ? s.set(IN_REPLY_TO, msg.at(REPLY_WITH)) : s;
 }
Esempio n. 6
0
 /**
  * Searches a user by ID. If multiple realms are configured, each will be tried according to their
  * ordinal number configuration. Only the first found is returned.
  */
 public Json searchUserById(String id) {
   if (id == null || id.length() == 0) return Json.array();
   for (String providerName : orderedProviders()) {
     UserProvider P = provider(providerName);
     Json user = P.get(id);
     if (!user.isNull()) return user;
   }
   return Json.nil();
 }
Esempio n. 7
0
 public static Json makeReply(Activity activity, Performative performative, String replyWith) {
   Json s =
       object(
           ACTIVITY_TYPE,
           activity.getType(),
           CONVERSATION_ID,
           activity.getId(),
           PERFORMATIVE,
           performative.toString());
   if (replyWith != null) return s.set(IN_REPLY_TO, replyWith);
   else return s;
 }
Esempio n. 8
0
 @Override
 public Json eval(Json r) {
   for (Json doc : r.at("response").at("docs").asJsonList()) {
     List<Json> o = doc.at("ontology").asJsonList();
     for (int i = 0; i < o.size(); i++) {
       if (o.get(i).asString().startsWith("~")) {
         o.remove(i);
       }
     }
   }
   return r;
 }
 @SuppressWarnings("unchecked")
 public Object from(Json x) {
   Collection<Object> C;
   try {
     C =
         (Collection<Object>)
             HGUtils.loadClass(graph, x.at("javaType").asString()).newInstance();
     for (Json j : x.at("data").asJsonList()) C.add(value(j));
   } catch (Exception e) {
     throw new RuntimeException(e);
   }
   return C;
 }
Esempio n. 10
0
  public Json makeTyped(Object anything) {
    boolean isarray = anything.getClass().isArray();
    Class<?> type = isarray ? anything.getClass().getComponentType() : anything.getClass();
    JsonConverter converter = converterMap.get(type.getName());
    String typeName = shortNameMap.getY(type.getName());
    if (typeName == null) typeName = type.getName();
    if (isarray) {
      Json result = Json.array();
      Object[] A = (Object[]) anything;
      for (Object x : A) {
        if (x == null) result.add(Json.nil());
        else result.add(converter != null ? converter.to(x) : make(x));
      }
      return Json.object().set("javaArrayType", typeName).set("array", result);
    } else if (type.isEnum())
      return Json.object().set("java.lang.Enum", type.getName()).set("value", anything.toString());

    for (Class<?> abstractConv : converterFromAbstractMap.keySet())
      if (abstractConv.isAssignableFrom(type))
        return converterFromAbstractMap.get(abstractConv).to(anything);
    Json value = null;
    if (converter != null) value = converter.to(anything);
    else if (Collection.class.isAssignableFrom(type) || Map.class.isAssignableFrom(type))
      value = beanConverter.to(anything);
    else
      try {
        value = f.make(anything);
      } catch (Throwable t) {
        value = beanConverter.to(anything);
      }
    return Json.object().set("javaType", typeName).set("value", value);
  }
Esempio n. 11
0
 private List<String> orderedProviders() {
   ArrayList<String> L =
       new ArrayList<String>(desc.at("hasUserBase", Json.object()).asJsonMap().keySet());
   Collections.sort(
       L,
       new Comparator<String>() {
         public int compare(String left, String right) {
           int x = desc.at("hasUserBase").at(left).at("hasOrdinal", Integer.MAX_VALUE).asInteger();
           int y =
               desc.at("hasUserBase").at(right).at("hasOrdinal", Integer.MAX_VALUE).asInteger();
           return x - y;
         }
       });
   return L;
 }
Esempio n. 12
0
 public Object from(Json x) {
   try {
     return HGUtils.loadClass(graph, x.asString());
   } catch (ClassNotFoundException e) {
     throw new HGException(e);
   }
 }
Esempio n. 13
0
  private Remembered checkSession(
      final String sessionId, HttpServletRequest request, HttpServletResponse response) {
    try {
      SimpleClientHttpRequestFactory tokenExtender =
          new SimpleClientHttpRequestFactory() {
            @Override
            protected void prepareConnection(HttpURLConnection connection, String httpMethod)
                throws IOException {
              super.prepareConnection(connection, httpMethod);

              connection.setRequestProperty("Authorization", "Bearer " + sessionId);
              connection.setRequestProperty("Accept", "application/json");
              connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            }
          };

      String userResponse =
          new RestTemplate(tokenExtender).getForObject(userDetailsUri, String.class);

      return makeNewRemembered(
          Json.read(userResponse).asJsonMap().get("username").asString(), sessionId);
    } catch (RestClientException ex) {
      // TODO: обработать исключение - записать в лог и т.д. - потенциально ошибки соединения с
      // сайтом авторизации, ошибки авторизации
      System.out.println(
          "GOT exception: "
              + ex
                  .toString()); // <-- не делайте так на боевом сервере, используйте
                                // java.util.Logger
      if (ex instanceof HttpClientErrorException)
        System.out.println(
            "response: " + ((HttpClientErrorException) ex).getResponseBodyAsString());
      return null;
    }
  }
Esempio n. 14
0
  @Test
  public void testSendingGetDelta() throws Exception {
    // fill the model with data
    SignalKModel model = SignalKModelFactory.getMotuTestInstance();
    model.putAll(TestHelper.getBasicModel().getFullData());

    // create STOMP connection
    StompConnection connection = new StompConnection();
    connection.open("localhost", 61613);
    logger.debug("Opened STOMP socket, connecting.. ");
    StompFrame connect = connection.connect("system", "manager");
    // StompFrame connect = connection.receive();
    if (!connect.getAction().equals(Stomp.Responses.CONNECTED)) {
      throw new Exception("Not connected");
    }
    logger.debug("connected" + connect.getHeaders());

    // create a private receive queue
    String uuid = UUID.randomUUID().toString();
    connection.subscribe(
        "/queue/signalk." + uuid + "." + vessels_dot_self_dot + env_wind,
        Subscribe.AckModeValues.AUTO);
    latch.await(2, TimeUnit.SECONDS);
    // send list
    Json subMsg =
        getGet("vessels." + SignalKConstants.self, env_wind + ".*", SignalKConstants.FORMAT_DELTA);
    HashMap<String, String> headers = new HashMap<String, String>();
    logger.debug("sending" + subMsg);
    // queue>signalk.3202a939-1681-4a74-ad4b-3a90212e4f33.vessels.motu.navigation
    // set private queue to receive data
    headers.put("reply-to", "/queue/signalk." + uuid + dot + vessels_dot_self_dot + env_wind);
    headers.put(WebsocketConstants.CONNECTION_KEY, uuid);
    connection.send("/queue/signalk.put", subMsg.toString(), null, headers);

    // listen for messages
    StompFrame message = connection.receive();
    logger.debug("Body: " + message.getBody());
    assertNotNull(message);
    Json reply = Json.read(message.getBody());

    assertNotNull(reply.at(SignalKConstants.CONTEXT));
    assertNotNull(reply.at(SignalKConstants.UPDATES));
    // unsubscribe
    connection.unsubscribe("/queue/signalk." + uuid + "." + vessels_dot_self_dot + env_wind);
    // disconnect
    connection.disconnect();
  }
Esempio n. 15
0
 @Test
 public void testObjectMerge() {
   Json o1 =
       object(
           "id",
           2,
           "name",
           "John",
           "address",
           object(
               "streetName", "Main",
               "streetNumber", 20,
               "city", "Detroit"));
   Json o2 = o1.dup().set("age", 20).at("address").delAt("city").up();
   o1.with(o2, "merge");
   Assert.assertTrue(o1.is("age", 20));
   Assert.assertTrue(o1.at("address").is("city", "Detroit"));
 }
Esempio n. 16
0
  public Json make(Object anything) {
    if (anything == null) return Json.nil();
    else if (anything instanceof String) return f.string((String) anything);
    else if (anything instanceof Boolean) return f.bool((Boolean) anything);
    else if (anything instanceof Number) return f.number((Number) anything);
    else if (anything instanceof Json) return (Json) anything;
    else if (anything instanceof Performative) return f.make(anything.toString());

    return makeTyped(anything);
  }
Esempio n. 17
0
 @Override
 protected void onPostExecute(String r) {
   if (r == null) return;
   Log.i("APIRequestResult<" + method + ">", r);
   result = Json.read(r);
   result = result.at(Const.RESPONSE);
   if (callback != null) {
     if (result.isObject() && result.has(Const.ERROR_ID)) callback.onError(new APIError(result));
     else callback.onResult(result);
   }
 }
  public void process(Exchange exchange) throws Exception {

    if (exchange.getIn().getBody() == null) return;
    if (logger.isDebugEnabled())
      logger.debug("Processing, class=" + exchange.getIn().getBody().getClass());
    // TODO: add more filters here
    if (exchange.getIn().getBody() instanceof Json) {
      Json json = (Json) exchange.getIn().getBody();
      // remove _arduino
      try {
        json.at(SignalKConstants.vessels).at(SignalKConstants.self).delAt("_arduino");
      } catch (NullPointerException npe) {
      }
      // remove _config
      try {
        json.at(SignalKConstants.vessels).at(SignalKConstants.self).delAt("_config");
      } catch (NullPointerException npe) {
      }

      exchange.getIn().setBody(json.toString());
    }
    if (exchange.getIn().getBody() instanceof SignalKModel) {
      SignalKModel model = (SignalKModel) exchange.getIn().getBody();
      // remove _arduino
      try {
        model.put(SignalKConstants.vessels_dot_self_dot + "_arduino", null);
      } catch (NullPointerException npe) {
      }
      // remove _config
      try {
        model.put(SignalKConstants.vessels_dot_self_dot + "_config", null);
      } catch (NullPointerException npe) {
      }

      exchange.getIn().setBody(ser.write(model));
    }
    if (logger.isDebugEnabled()) {
      logger.debug("Outputting:" + exchange.getIn().getHeaders());
      logger.debug("Outputting:" + exchange.getIn());
    }
  }
Esempio n. 19
0
 /**
  * Retrieve full user information given a user id (a.k.a. username). If there are multiple user
  * backing stores configured, information from each will be aggregated. The provider with the
  * highest priority will be used to provide based information, but then each separate provider is
  * added as a property.
  *
  * <p>For example, if you have an LDAP provider called "ldap" and a databse provider called "db",
  * with the ldap provider being the default (high priority), you would get something that looks
  * like <code>{ "hasUsername":id, "FirstName":"John",
  * "ldap":{...all LDAP user attributes }, "db":{ all DB user attributes}}</code>
  *
  * @param id
  * @return
  */
 @GET
 @Path("{id}")
 @Produces("application/json")
 public Json getUserById(@PathParam("id") String id) {
   Json user = Json.object("userid", id);
   List<String> plist = orderedProviders();
   for (String providerName : plist) {
     UserProvider P = provider(providerName);
     P.populate(user);
   }
   return ok().set("profile", prepareReturn(user));
 }
Esempio n. 20
0
 private Json prepareReturn(Json user) {
   if (user.isArray()) {
     for (Json u : user.asJsonList()) prepareReturn(u);
   } else {
     user.delAt("hasPassword");
     // TODO: can we get rid of this? the fear that somewhere on the client
     // it is being used, but it shouldn't be.
     if (user.has("hasUsername")) user.set("username", user.at("hasUsername"));
   }
   return user;
 }
Esempio n. 21
0
 private Json getAccessPolicies(Json groups) {
   if (!groups.isArray())
     throw new IllegalArgumentException("Expected Array of cirmusergroups. e.g. legacy:311..");
   Json cirmUserGroupsWithAccessPolicies = Json.array();
   for (Json iri : groups.asJsonList()) {
     OWLIndividual group = dataFactory().getOWLNamedIndividual(fullIri(iri.asString()));
     // Here we need to make sure that the serialization stops at e.g.
     // individuals that are the objects of an AccessPolicy!
     Json groupWithAccessPolicies = OWL.toJSON(group, stopExpansionCondition);
     cirmUserGroupsWithAccessPolicies.add(groupWithAccessPolicies);
   }
   // Array of cirm groups with all access policy information serialized.
   return cirmUserGroupsWithAccessPolicies; // userdata.set("cirmusergroups",
                                            // cirmUserGroupsWithAccessPolicies);
 }
Esempio n. 22
0
  private String finishSessionRetrieval(HttpServletRequest request)
      throws UnsupportedEncodingException {
    try {
      String authCode = request.getParameter("code");
      SimpleClientHttpRequestFactory serviceAuthExtender =
          new SimpleClientHttpRequestFactory() {
            @Override
            protected void prepareConnection(HttpURLConnection connection, String httpMethod)
                throws IOException {
              super.prepareConnection(connection, httpMethod);

              String authorization = clientId + ":" + clientSecret;
              byte[] encodedAuthorisation = Base64.encode(authorization.getBytes());
              connection.setRequestProperty(
                  "Authorization", "Basic " + new String(encodedAuthorisation));
              connection.setRequestProperty(
                  "Accept", "application/json, application/x-www-form-urlencoded");
              connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            }
          };

      String tokenRequest =
          "grant_type=authorization_code&code="
              + authCode
              + "&redirect_uri="
              + URLEncoder.encode(request.getRequestURL().toString(), "utf-8");
      String tokenResponse =
          new RestTemplate(serviceAuthExtender)
              .postForObject(URI.create(accessTokenUri), tokenRequest, String.class);

      return Json.read(tokenResponse).asJsonMap().get("access_token").asString();
    } catch (RestClientException ex) {
      // TODO: обработать исключение - записать в лог и т.д. - потенциально ошибки соединения с
      // сайтом авторизации, ошибки авторизации
      System.out.println(
          "GOT exception: "
              + ex
                  .toString()); // <-- не делайте так на боевом сервере, используйте
                                // java.util.Logger
      if (ex instanceof HttpClientErrorException)
        System.out.println(
            "response: " + ((HttpClientErrorException) ex).getResponseBodyAsString());
      return null;
    }
  }
Esempio n. 23
0
 @Test
 public void testCompareEqualsInObject() {
   Json x1 = object("id", 4, "name", "Tom");
   Json x2 = object("id", 4, "name", "Hanna");
   Json a1 = array(object("person", x1));
   Json a2 = array(object("person", x2));
   a1.with(a2, new Json[0]);
   Assert.assertEquals(2, a1.asJsonList().size());
   a1 = array(object("person", x1));
   a1.with(a2, object("compareBy", "id"));
   Assert.assertEquals(1, a1.asJsonList().size());
   Assert.assertEquals(make("Tom"), a1.at(0).at("person").at("name"));
 }
Esempio n. 24
0
  @Override
  public String resolve(String variableName, Json sr, Properties properties) {
    String activityLegacyCode;

    OWLLiteral variableLegacyCode =
        OWL.dataProperty(
            MessageManager.findIndividualFromVariable(variableName), "legacy:hasLegacyCode");
    if (variableLegacyCode != null && variableLegacyCode.getLiteral().length() > 0)
      activityLegacyCode =
          variableLegacyCode
              .getLiteral(); // look for a specific activity as defined with the variable
    else activityLegacyCode = properties.getProperty("LEGACY_CODE");
    Json activity = SRJsonActivityUtil.getMostRecentActivityByLegacyCode(sr, activityLegacyCode);
    if (activity == null || activity.isNull()) {
      System.out.println(
          "Messaging - ActivityResolver: unable to find activity "
              + properties.getProperty("LEGACY_CODE")
              + " in SR "
              + sr);
      return null;
    }
    String result = null;
    if (VAR_SR_ACTIVITY_TYPE.equals(variableName))
      result = SRJsonActivityUtil.getActivityTypeLabel(activity);
    else {
      if (variableName.contains("_OUTCOME")) {
        result = SRJsonActivityUtil.getHasOutcomeLabel(activity);
      } else if (variableName.contains("_DETAILS") || variableName.contains("_DTLS$$")) {
        result = SRJsonActivityUtil.getHasDetails(activity);
      } else if (variableName.contains("_DUE_DTE")) {
        result = SRJsonActivityUtil.getHasDueDate(activity, DATE_PATTERN);
      } else if (variableName.equals("$$SR_ACTIVITY_DATE_TIME$$")) {
        result = SRJsonActivityUtil.getHasDateCreated(activity, DATE_PATTERN);
      } else if (variableName.equals("$$SR_ACTIVITY_DUEDATE_SWR$$")) {
        result = SRJsonActivityUtil.getDueDate90Days(activity, DATE_PATTERN);
      } else if (variableName.contains("SR_ACTIVITY_CALLCREATED_D")) {
        result = SRJsonActivityUtil.getIsCreatedByName(activity);
      } else if (variableName.equals("$$SR_ASSIGNED_STAFF$$")) {
        result = SRJsonActivityUtil.getAssignedStaffName(activity);
      } else {
        System.out.println(
            "Messaging - ActivityResolver: unable to resolve variable" + variableName);
      }
      // Just a check if we already know the variable.
      if (VALIDATE_VARS_POST_RESOLUTION && !ActivityVariableValidator.isKnown(variableName))
        System.err.println(
            "ActivityResolver resolved an unknown variable: "
                + variableName
                + " to value "
                + result);
    }
    if (DBG) {
      System.out.println(
          "ActivityResolver: Var "
              + variableName
              + " Result: "
              + result
              + " Act: "
              + activity
              + " Code: "
              + activityLegacyCode);
    }
    return result;
  }
Esempio n. 25
0
 /**
  * Return the network identity of the sender of a given message.
  *
  * @param msg
  * @return
  */
 public static Object getSender(Json msg) {
   return Messages.fromJson(msg.at(Messages.REPLY_TO));
 }
Esempio n. 26
0
 public static <T> T content(Json j) {
   return HGPeerJsonFactory.getInstance().value(j.at(CONTENT));
 }
Esempio n. 27
0
 /**
  * Authenticate within a given realm (user provider).
  *
  * @param form
  * @return
  */
 @POST
 @Path("/authenticate")
 public Json authenticate(Json form) {
   if (!form.has("provider") || form.is("provider", ""))
     form.set("provider", desc.at("authenticatesWith").at("hasName"));
   if (form.is("provider", authenticateProvider())) {
     if (!form.has("password") || form.is("password", "")) return ko("Please provide a password.");
     Json userdata = userProfile(form);
     if (userdata.is("error", "No profile")) return ko("User not found or invalid password.");
     else if (!userdata.is("ok", true)) return userdata;
     else if (!StartUp.getConfig().is("ignorePasswords", true)) {
       if (!provider(form.at("provider").asString())
           .authenticate(
               userdata.at("profile").at("hasUsername").asString(),
               form.at("password").asString())) return ko("User not found or invalid password.");
     }
     if (dbg()) {
       String msg =
           (userdata.at("profile").has("hasUsername"))
               ? userdata.at("profile").at("hasUsername").asString()
               : "Unknown";
       msg += " | lastname: " + (userdata.at("profile").at("lastName", " no lastname")).toString();
       msg +=
           "\r\n | groups: "
               + (userdata.at("profile").at("groups", " no groups")).toString()
               + "\r\n";
       ThreadLocalStopwatch.getWatch().time("Auth success: " + msg);
       ThreadLocalStopwatch.dispose();
     }
     return ok().set("user", prepareReturn(userdata.at("profile")));
   }
   // other realms/providers...
   else return ko("Unknown realm");
 }
Esempio n. 28
0
/**
 * Main entry point for user management - authentication, profile retrieval, access policies.
 *
 * @author Syed Abbas
 * @author Tom Hilpold
 * @author Borislav Iordanov
 */
@Path("users")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class UserService extends RestService implements AutoConfigurable {
  public static final IRI DEFAULT_STOP_EXPANSION_CONDITION_IRI1 = Model.upper("Department");
  public static final IRI DEFAULT_STOP_EXPANSION_CONDITION_IRI2 = Model.upper("Divison");
  public static final IRI DEFAULT_STOP_EXPANSION_CONDITION_IRI3 = Model.upper("hasDivision");
  public static final IRI DEFAULT_STOP_EXPANSION_CONDITION_IRI4 = Model.upper("hasObject");
  public static final String CIRM_ADMIN = Model.upper("CirmAdmin").toString();

  private final OWLObjectPropertyCondition stopExpansionCondition = getStopExpansionCondition();

  private OWLObjectPropertyCondition getStopExpansionCondition() {
    Set<OWLObjectProperty> stopExpansionProps = new HashSet<OWLObjectProperty>();
    stopExpansionProps.add(OWL.objectProperty(DEFAULT_STOP_EXPANSION_CONDITION_IRI1));
    stopExpansionProps.add(OWL.objectProperty(DEFAULT_STOP_EXPANSION_CONDITION_IRI2));
    stopExpansionProps.add(OWL.objectProperty(DEFAULT_STOP_EXPANSION_CONDITION_IRI3));
    stopExpansionProps.add(OWL.objectProperty(DEFAULT_STOP_EXPANSION_CONDITION_IRI4));
    return new OWLObjectPropertyCondition(stopExpansionProps);
  }

  private Json desc = Json.object();
  private static volatile Map<String, UserProvider> providerMap =
      new HashMap<String, UserProvider>();

  private List<String> orderedProviders() {
    ArrayList<String> L =
        new ArrayList<String>(desc.at("hasUserBase", Json.object()).asJsonMap().keySet());
    Collections.sort(
        L,
        new Comparator<String>() {
          public int compare(String left, String right) {
            int x = desc.at("hasUserBase").at(left).at("hasOrdinal", Integer.MAX_VALUE).asInteger();
            int y =
                desc.at("hasUserBase").at(right).at("hasOrdinal", Integer.MAX_VALUE).asInteger();
            return x - y;
          }
        });
    return L;
  }

  private String authenticateProvider() {
    return desc.at("authenticatesWith").at("hasName").asString();
  }

  private UserProvider provider(String name) {
    synchronized (providerMap) {
      UserProvider provider = providerMap.get(name);
      if (provider != null) return provider;
      if (!desc.at("hasUserBase").has(name)) return null;
      String classname =
          desc.at("hasUserBase")
              .at(name)
              .at("hasImplementation")
              .at("iri")
              .asString()
              .split("#")[1];
      try {
        provider = (UserProvider) Class.forName(classname).newInstance();
        // Autoconfigure is not part of the object initialisation
        // without synchronization, variables set during autoconfigure might not be readable by
        // other threads.
        synchronized (provider) {
          if (provider instanceof AutoConfigurable)
            ((AutoConfigurable) provider).autoConfigure(desc.at("hasUserBase").at(name));
        }
        providerMap.put(name, provider);
        return provider;
      } catch (Exception ex) {
        throw new RuntimeException(ex);
      }
    }
  }

  private Json getAccessPolicies(Json groups) {
    if (!groups.isArray())
      throw new IllegalArgumentException("Expected Array of cirmusergroups. e.g. legacy:311..");
    Json cirmUserGroupsWithAccessPolicies = Json.array();
    for (Json iri : groups.asJsonList()) {
      OWLIndividual group = dataFactory().getOWLNamedIndividual(fullIri(iri.asString()));
      // Here we need to make sure that the serialization stops at e.g.
      // individuals that are the objects of an AccessPolicy!
      Json groupWithAccessPolicies = OWL.toJSON(group, stopExpansionCondition);
      cirmUserGroupsWithAccessPolicies.add(groupWithAccessPolicies);
    }
    // Array of cirm groups with all access policy information serialized.
    return cirmUserGroupsWithAccessPolicies; // userdata.set("cirmusergroups",
                                             // cirmUserGroupsWithAccessPolicies);
  }

  private Json prepareReturn(Json user) {
    if (user.isArray()) {
      for (Json u : user.asJsonList()) prepareReturn(u);
    } else {
      user.delAt("hasPassword");
      // TODO: can we get rid of this? the fear that somewhere on the client
      // it is being used, but it shouldn't be.
      if (user.has("hasUsername")) user.set("username", user.at("hasUsername"));
    }
    return user;
  }

  public void autoConfigure(Json config) {
    this.desc = config;
  }

  /**
   * This is a general method to retrieve information about a particular user. Because it's
   * expensive to fill out all information we can get about a user, the request is a more complex
   * object that specifies what is to be provided. In this way, a client can request all that is
   * needed and only that which is needed in a single network round-trip.
   *
   * <p>The basic profile (first name, email etc.) is returned regardless. Here are the expected
   * properties of the JSON <code>request</code> parameter that control what else is returned:
   *
   * <ul>
   *   <li>username - mandatory...of course
   *   <li>groups - true/false whether to include the list of groups the user belongs to
   *   <li>access - true/false whether to include the access policies for this user
   * </ul>
   *
   * @param request
   * @return
   */
  @POST
  @Path("/profile")
  public Json userProfile(Json request) {
    try {
      if (!request.isObject() || !request.has("username")) return ko("bad request.");
      if (!request.has("provider") || request.is("provider", ""))
        request.set("provider", desc.at("authenticatesWith").at("hasName"));
      UserProvider providerImpl = provider(request.at("provider").asString());
      Json profile = providerImpl.get(request.at("username").asString());
      if (profile.isNull()) return ko("No profile");
      if (request.is("groups", true) || request.is("access", true))
        profile.set("groups", providerImpl.findGroups(request.at("username").asString()));
      if (request.is("access", true))
        profile.set("access", getAccessPolicies(profile.at("groups")));
      return ok().set("profile", prepareReturn(profile));
    } catch (Throwable t) {
      if (!"unavailable"
          .equals(t.getMessage())) // error would have already been reported in the logs
      t.printStackTrace(System.err);
      return ko(t.getMessage());
    }
  }

  /**
   * Authenticate within a given realm (user provider).
   *
   * @param form
   * @return
   */
  @POST
  @Path("/authenticate")
  public Json authenticate(Json form) {
    if (!form.has("provider") || form.is("provider", ""))
      form.set("provider", desc.at("authenticatesWith").at("hasName"));
    if (form.is("provider", authenticateProvider())) {
      if (!form.has("password") || form.is("password", "")) return ko("Please provide a password.");
      Json userdata = userProfile(form);
      if (userdata.is("error", "No profile")) return ko("User not found or invalid password.");
      else if (!userdata.is("ok", true)) return userdata;
      else if (!StartUp.getConfig().is("ignorePasswords", true)) {
        if (!provider(form.at("provider").asString())
            .authenticate(
                userdata.at("profile").at("hasUsername").asString(),
                form.at("password").asString())) return ko("User not found or invalid password.");
      }
      if (dbg()) {
        String msg =
            (userdata.at("profile").has("hasUsername"))
                ? userdata.at("profile").at("hasUsername").asString()
                : "Unknown";
        msg += " | lastname: " + (userdata.at("profile").at("lastName", " no lastname")).toString();
        msg +=
            "\r\n | groups: "
                + (userdata.at("profile").at("groups", " no groups")).toString()
                + "\r\n";
        ThreadLocalStopwatch.getWatch().time("Auth success: " + msg);
        ThreadLocalStopwatch.dispose();
      }
      return ok().set("user", prepareReturn(userdata.at("profile")));
    }
    // other realms/providers...
    else return ko("Unknown realm");
  }

  /**
   * Consumes an array of group names and augments those groups with the corresponding access
   * policies.
   *
   * @param groups An array of names of groups.
   * @return
   */
  @POST
  @Path("/accesspolicies")
  public Json accessPolicies(Json groups) {
    groups = getAccessPolicies(groups);
    if (!groups.asList().isEmpty() && groups.at(0).has("hasAccessPolicy"))
      return ok().set("cirmusergroups", groups);
    else return ko("No Access policies are available for user.");
  }

  @GET
  @Path("search")
  public Json search(
      @QueryParam("id") String id,
      @QueryParam("name") String searchString,
      @QueryParam("providers") String providers) {
    if (id != null && !id.isEmpty()) {
      return Json.array().add(searchUserById(id));
    }
    Json resultList = Json.array();
    final int maxResults = 15;
    try {
      if (searchString == null || searchString.length() == 0) return null;
      else searchString = searchString.trim();
      Json user = Json.object();
      String name = searchString;
      name = name.trim();
      int idx;
      // Parse search string
      if ((idx = name.indexOf(',')) > -1) { // Miller, Bob
        user.set("LastName", name.substring(0, idx).trim());
        user.set("FirstName", name.substring(idx + 1).trim());
      } else if ((idx = name.indexOf(' ')) > -1) { // Bob Miller
        user.set("LastName", name.substring(idx + 1).trim());
        user.set("FirstName", name.substring(0, idx).trim());
      } else { // Miller
        user.set("LastName", name);
      }
      if (user.is("FirstName", "")) user.delAt("FirstName");
      if (user.is("LastName", "")) user.delAt("LastName");
      if (user.asJsonMap().size() > 0) {
        Collection<String> P =
            providers != null ? Arrays.asList(providers.split(",")) : orderedProviders();
        for (String providerName : P)
          resultList.with(searchProvider(providerName, user, maxResults));
      }
    } catch (Exception e) {
      e.printStackTrace();
      return ko(e);
    }
    return prepareReturn(resultList);
  }

  /**
   * Searches a user by ID. If multiple realms are configured, each will be tried according to their
   * ordinal number configuration. Only the first found is returned.
   */
  public Json searchUserById(String id) {
    if (id == null || id.length() == 0) return Json.array();
    for (String providerName : orderedProviders()) {
      UserProvider P = provider(providerName);
      Json user = P.get(id);
      if (!user.isNull()) return user;
    }
    return Json.nil();
  }

  public Json searchProvider(String name, Json prototype, int maxResults) {
    UserProvider provider = provider(name);
    if (provider == null) throw new RuntimeException("Unknown user realm " + name);
    return provider.find(prototype, maxResults);
  }

  @GET
  @Path("{provider}/{id}")
  @Produces("application/json")
  public Json getUserJson(
      @PathParam(value = "provider") String provider, @PathParam(value = "id") String id) {
    UserProvider providerImpl = provider(provider);
    if (providerImpl == null) return ko("Unknown realm " + provider);
    return prepareReturn(providerImpl.get(id));
  }

  /**
   * Retrieve full user information given a user id (a.k.a. username). If there are multiple user
   * backing stores configured, information from each will be aggregated. The provider with the
   * highest priority will be used to provide based information, but then each separate provider is
   * added as a property.
   *
   * <p>For example, if you have an LDAP provider called "ldap" and a databse provider called "db",
   * with the ldap provider being the default (high priority), you would get something that looks
   * like <code>{ "hasUsername":id, "FirstName":"John",
   * "ldap":{...all LDAP user attributes }, "db":{ all DB user attributes}}</code>
   *
   * @param id
   * @return
   */
  @GET
  @Path("{id}")
  @Produces("application/json")
  public Json getUserById(@PathParam("id") String id) {
    Json user = Json.object("userid", id);
    List<String> plist = orderedProviders();
    for (String providerName : plist) {
      UserProvider P = provider(providerName);
      P.populate(user);
    }
    return ok().set("profile", prepareReturn(user));
  }

  public String getFullName(String userid) {
    if (userid == null || userid.isEmpty()) return "";
    Json user = searchUserById(userid);
    if (user.isNull()) return "";
    else return user.at("FirstName", "").asString() + " " + user.at("LastName", "").asString();
  }

  public UserService() {
    autoConfigure(Refs.owlJsonCache.resolve().individual(OWL.fullIri("UserService")).resolve());
  }
}
Esempio n. 29
0
 public String getFullName(String userid) {
   if (userid == null || userid.isEmpty()) return "";
   Json user = searchUserById(userid);
   if (user.isNull()) return "";
   else return user.at("FirstName", "").asString() + " " + user.at("LastName", "").asString();
 }
Esempio n. 30
0
 @GET
 @Path("search")
 public Json search(
     @QueryParam("id") String id,
     @QueryParam("name") String searchString,
     @QueryParam("providers") String providers) {
   if (id != null && !id.isEmpty()) {
     return Json.array().add(searchUserById(id));
   }
   Json resultList = Json.array();
   final int maxResults = 15;
   try {
     if (searchString == null || searchString.length() == 0) return null;
     else searchString = searchString.trim();
     Json user = Json.object();
     String name = searchString;
     name = name.trim();
     int idx;
     // Parse search string
     if ((idx = name.indexOf(',')) > -1) { // Miller, Bob
       user.set("LastName", name.substring(0, idx).trim());
       user.set("FirstName", name.substring(idx + 1).trim());
     } else if ((idx = name.indexOf(' ')) > -1) { // Bob Miller
       user.set("LastName", name.substring(idx + 1).trim());
       user.set("FirstName", name.substring(0, idx).trim());
     } else { // Miller
       user.set("LastName", name);
     }
     if (user.is("FirstName", "")) user.delAt("FirstName");
     if (user.is("LastName", "")) user.delAt("LastName");
     if (user.asJsonMap().size() > 0) {
       Collection<String> P =
           providers != null ? Arrays.asList(providers.split(",")) : orderedProviders();
       for (String providerName : P)
         resultList.with(searchProvider(providerName, user, maxResults));
     }
   } catch (Exception e) {
     e.printStackTrace();
     return ko(e);
   }
   return prepareReturn(resultList);
 }