@Override
  public F.Promise<SimpleResult> call(Context ctx) throws Throwable {
    if (Logger.isTraceEnabled()) Logger.trace("Method Start");
    Context.current.set(ctx);

    if (Logger.isDebugEnabled())
      Logger.debug("AnonymousLogin  for resource " + Context.current().request());

    String user = BBConfiguration.getBaasBoxUsername();
    String password = BBConfiguration.getBaasBoxPassword();

    // retrieve AppCode
    String appCode = RequestHeaderHelper.getAppCode(ctx);

    ctx.args.put("username", user);
    ctx.args.put("password", password);
    ctx.args.put("appcode", appCode);

    if (Logger.isDebugEnabled()) Logger.debug("username (defined in conf file): " + user);
    if (Logger.isDebugEnabled()) Logger.debug("password (defined in conf file): " + password);
    if (Logger.isDebugEnabled()) Logger.debug("appcode (from header or querystring): " + appCode);
    if (Logger.isDebugEnabled()) Logger.debug("token: N/A");

    // executes the request
    F.Promise<SimpleResult> tempResult = delegate.call(ctx);

    WrapResponse wr = new WrapResponse();
    // SimpleResult result=wr.wrap(ctx, tempResult);
    F.Promise<SimpleResult> result = wr.wrapAsync(ctx, tempResult);
    if (Logger.isTraceEnabled()) Logger.trace("Method End");
    return result;
  }
Exemple #2
0
    public static void checkPermission(String key, boolean allowSystem) throws NoAccessException {
      long l = 0;
      if (Plugin.logCheckTime && Logger.isDebugEnabled()) {
        Plugin.debug(">>>>>>> [%s]", key);
        l = System.currentTimeMillis();
      }
      if (Boolean.parseBoolean(Play.configuration.getProperty(ConfigConstants.DISABLE, "false"))) {
        return;
      }

      IAuthorizeable a = reg_.get(key);
      if (null == a) {
        throw new RuntimeException("oops, something wrong with enhancer... ?");
      }
      IAccount acc = null;
      try {
        IAccount accFact = AAAFactory.account();
        acc = accFact.getCurrent();
        if (null == acc) {
          if (allowSystem) {
            if (!Boolean.parseBoolean(
                Play.configuration.getProperty(ConfigConstants.SYSTEM_PERMISSION_CHECK, "false"))) {
              // suppress permission check for system account
              return;
            }
            acc = accFact.getSystemAccount();
          }
          if (null == acc) {
            throw new NoAccessException("cannot determine principal account");
          }
        }

        // superuser check
        boolean isSuperUser = false;
        if (Plugin.superuser > 0) {
          IPrivilege p = acc.getPrivilege();
          if (null != p) isSuperUser = p.getLevel() >= Plugin.superuser;
        }
        if (!isSuperUser && !acc.hasAccessTo(a)) {
          throw new NoAccessException("Access denied");
        }
      } catch (NoAccessException nae) {
        throw nae;
      } catch (Exception e) {
        throw new NoAccessException(e);
      } finally {
        if (Plugin.logCheckTime && Logger.isDebugEnabled()) {
          Plugin.debug("<<<<<<< [%s]: %sms", key, System.currentTimeMillis() - l);
        }
      }
    }
  @Override
  public Object authenticate(final Context context, final Object payload) throws AuthException {

    final Request request = context.request();
    final String uri = request.uri();

    if (Logger.isDebugEnabled()) {
      Logger.debug("Returned with URL: '" + uri + "'");
    }

    final Configuration c = getConfiguration();

    final ConsumerKey key =
        new ConsumerKey(
            c.getString(SettingKeys.CONSUMER_KEY), c.getString(SettingKeys.CONSUMER_SECRET));
    final String requestTokenURL = c.getString(SettingKeys.REQUEST_TOKEN_URL);
    final String accessTokenURL = c.getString(SettingKeys.ACCESS_TOKEN_URL);
    final String authorizationURL = c.getString(SettingKeys.AUTHORIZATION_URL);
    final ServiceInfo info =
        new ServiceInfo(requestTokenURL, accessTokenURL, authorizationURL, key);
    final OAuth service = new OAuth(info, true);

    checkError(request);

    if (uri.contains(Constants.OAUTH_VERIFIER)) {

      final RequestToken rtoken =
          (RequestToken) PlayAuthenticate.removeFromCache(context.session(), CACHE_TOKEN);
      final String verifier = Authenticate.getQueryString(request, Constants.OAUTH_VERIFIER);
      final Either<OAuthException, RequestToken> retrieveAccessToken =
          service.retrieveAccessToken(rtoken, verifier);

      if (retrieveAccessToken.isLeft()) {
        throw new AuthException(retrieveAccessToken.left().get().getLocalizedMessage());
      } else {
        final I i = buildInfo(retrieveAccessToken.right().get());
        return transform(i);
      }
    } else {

      final String callbackURL = getRedirectUrl(request);

      final Either<OAuthException, RequestToken> reponse =
          service.retrieveRequestToken(callbackURL);

      if (reponse.isLeft()) {
        // Exception happened
        throw new AuthException(reponse.left().get().getLocalizedMessage());
      } else {
        // All good, we have the request token
        final RequestToken rtoken = reponse.right().get();

        final String token = rtoken.token();
        final String redirectUrl = service.redirectUrl(token);

        PlayAuthenticate.storeInCache(context.session(), CACHE_TOKEN, rtoken);
        return redirectUrl;
      }
    }
  }
Exemple #4
0
 public void send(String message, String username)
     throws PushNotInitializedException, UserNotFoundException, SqlInjectionException,
         InvalidRequestException, IOException, UnknownHostException {
   if (Logger.isDebugEnabled())
     Logger.debug("Try to send a message (" + message + ") to " + username);
   UserDao udao = UserDao.getInstance();
   ODocument user = udao.getByUserName(username);
   if (user == null) {
     if (Logger.isDebugEnabled()) Logger.debug("User " + username + " does not exist");
     throw new UserNotFoundException("User " + username + " does not exist");
   }
   ODocument userSystemProperties = user.field(UserDao.ATTRIBUTES_SYSTEM);
   if (Logger.isDebugEnabled()) Logger.debug("userSystemProperties: " + userSystemProperties);
   List<ODocument> loginInfos = userSystemProperties.field(UserDao.USER_LOGIN_INFO);
   if (Logger.isDebugEnabled()) Logger.debug("Sending to " + loginInfos.size() + " devices");
   for (ODocument loginInfo : loginInfos) {
     String pushToken = loginInfo.field(UserDao.USER_PUSH_TOKEN);
     String vendor = loginInfo.field(UserDao.USER_DEVICE_OS);
     if (Logger.isDebugEnabled()) Logger.debug("push token: " + pushToken);
     if (Logger.isDebugEnabled()) Logger.debug("vendor: " + vendor);
     if (!StringUtils.isEmpty(vendor) && !StringUtils.isEmpty(pushToken)) {
       VendorOS vos = VendorOS.getVendorOs(vendor);
       if (Logger.isDebugEnabled()) Logger.debug("vos: " + vos);
       if (vos != null) {
         IPushServer pushServer = Factory.getIstance(vos);
         pushServer.setConfiguration(getPushParameters());
         pushServer.send(message, pushToken);
       } // vos!=null
     } // (!StringUtils.isEmpty(vendor) && !StringUtils.isEmpty(deviceId)
   } // for (ODocument loginInfo : loginInfos)
 } // send
Exemple #5
0
 private void setUsernameCaseInsensitive(ODatabaseRecordTx db) {
   Logger.info("..updating ouser.name collate CI..:");
   DbHelper.execMultiLineCommands(
       db,
       Logger.isDebugEnabled(),
       "drop index ouser.name;",
       "alter property ouser.name collate ci;",
       "create index ouser.name unique;");
   Logger.info("...done...");
 }
  /**
   * Gets the string content of a node via xpath
   *
   * @param nodeObj
   * @param xpath
   * @return
   */
  private static String getNodeContent(final Object nodeObj, final String xpath) {
    Node node = XPath.selectNode(xpath, nodeObj);
    if (node == null) {
      if (Logger.isDebugEnabled() == true) {
        Logger.debug("Could not find node by xpath: " + xpath + " in node: " + nodeObj.toString());
      }
      return StringUtils.EMPTY;
    }

    return StringUtils.trimToEmpty(node.getTextContent());
  }
Exemple #7
0
 public static void changePassword(String username, String newPassword)
     throws SqlInjectionException, UserNotFoundException {
   ODatabaseRecordTx db = DbHelper.getConnection();
   db = DbHelper.reconnectAsAdmin();
   UserDao udao = UserDao.getInstance();
   ODocument user = udao.getByUserName(username);
   if (user == null) {
     if (Logger.isDebugEnabled()) Logger.debug("User " + username + " does not exist");
     throw new UserNotFoundException("User " + username + " does not exist");
   }
   db.getMetadata().getSecurity().getUser(username).setPassword(newPassword).save();
 }
  @Override
  public void delete(String name) throws Exception {
    if (!existsCollection(name))
      throw new InvalidCollectionException("Collection " + name + " does not exists");

    // get the helper class
    GenericDao gdao = GenericDao.getInstance();

    // begin transaction
    DbHelper.requestTransaction();

    try {
      // delete all vertices linked to objects in this class
      String deleteVertices = "delete vertex _bb_nodevertex where _node.@class=?";
      Object[] params = {name};
      gdao.executeCommand(deleteVertices, params);

      // delete vertices linked to the collection entry in the _bb_collection class
      // note: the params are equals to the previous one (just the collection name)
      String deleteVertices2 =
          "delete vertex _bb_nodevertex where _node.@class='_bb_collection' and _node.name=?";
      gdao.executeCommand(deleteVertices2, params);

      // delete this collection from the list of declared collections
      // note: the params are equals to the previous one (just the collection name)
      String deleteFromCollections = "delete from _bb_collection where name =?";
      gdao.executeCommand(deleteFromCollections, params);

      // delete all records belonging to the dropping collection....
      // it could be done dropping the class, but in this case we not should be able to perform a
      // rollback
      String deleteAllRecords = "delete from " + name;
      gdao.executeCommand(deleteAllRecords, new Object[] {});

      // commit
      DbHelper.commitTransaction();

      // drop the collection class outside collection
      String dropCollection = "drop class " + name;
      gdao.executeCommand(dropCollection, new Object[] {});

    } catch (Exception e) {
      // rollback in case of error
      DbHelper.rollbackTransaction();
      if (Logger.isDebugEnabled())
        Logger.debug("An error occured deleting the collection " + name, e);
      throw e;
    }
  } // delete
Exemple #9
0
 public static void removeSocialLoginTokens(ODocument user, String socialNetwork)
     throws ODatabaseException {
   DbHelper.requestTransaction();
   try {
     ODocument systemProps = user.field(UserDao.ATTRIBUTES_SYSTEM);
     Map<String, ODocument> ssoTokens = systemProps.field(UserDao.SOCIAL_LOGIN_INFO);
     if (ssoTokens == null) {
       throw new ODatabaseException(socialNetwork + " is not linked with this account");
     } else {
       ssoTokens.remove(socialNetwork);
       systemProps.field(UserDao.SOCIAL_LOGIN_INFO, ssoTokens);
       user.field(UserDao.ATTRIBUTES_SYSTEM, systemProps);
       systemProps.save();
       user.save();
       if (Logger.isDebugEnabled()) Logger.debug("saved tokens for user ");
       DbHelper.commitTransaction();
     }
   } catch (Exception e) {
     e.printStackTrace();
     DbHelper.rollbackTransaction();
     throw new ODatabaseException("unable to add tokens");
   }
 }
Exemple #10
0
  public static void addSocialLoginTokens(ODocument user, UserInfo userInfo)
      throws ODatabaseException {
    DbHelper.requestTransaction();
    try {
      ODocument systemProps = user.field(UserDao.ATTRIBUTES_SYSTEM);
      Map<String, ODocument> ssoTokens = systemProps.field(UserDao.SOCIAL_LOGIN_INFO);
      if (ssoTokens == null) {
        ssoTokens = new HashMap<String, ODocument>();
      }

      String jsonRep = userInfo.toJson();
      ssoTokens.put(userInfo.getFrom(), (ODocument) new ODocument().fromJSON(jsonRep));
      systemProps.field(UserDao.SOCIAL_LOGIN_INFO, ssoTokens);
      user.field(UserDao.ATTRIBUTES_SYSTEM, systemProps);
      systemProps.save();
      user.save();
      if (Logger.isDebugEnabled()) Logger.debug("saved tokens for user ");
      DbHelper.commitTransaction();

    } catch (Exception e) {
      DbHelper.rollbackTransaction();
      throw new ODatabaseException("unable to add tokens");
    }
  }
Exemple #11
0
  public static void sendResetPwdMail(String appCode, ODocument user) throws Exception {
    final String errorString = "Cannot send mail to reset the password: "******" invalid user object");

    // initialization
    String siteUrl = Application.NETWORK_HTTP_URL.getValueAsString();
    int sitePort = Application.NETWORK_HTTP_PORT.getValueAsInteger();
    if (StringUtils.isEmpty(siteUrl))
      throw new PasswordRecoveryException(errorString + " invalid site url (is empty)");

    String textEmail = PasswordRecovery.EMAIL_TEMPLATE_TEXT.getValueAsString();
    String htmlEmail = PasswordRecovery.EMAIL_TEMPLATE_HTML.getValueAsString();
    if (StringUtils.isEmpty(htmlEmail)) htmlEmail = textEmail;
    if (StringUtils.isEmpty(htmlEmail))
      throw new PasswordRecoveryException(errorString + " text to send is not configured");

    boolean useSSL = PasswordRecovery.NETWORK_SMTP_SSL.getValueAsBoolean();
    boolean useTLS = PasswordRecovery.NETWORK_SMTP_TLS.getValueAsBoolean();
    String smtpHost = PasswordRecovery.NETWORK_SMTP_HOST.getValueAsString();
    int smtpPort = PasswordRecovery.NETWORK_SMTP_PORT.getValueAsInteger();
    if (StringUtils.isEmpty(smtpHost))
      throw new PasswordRecoveryException(errorString + " SMTP host is not configured");

    String username_smtp = null;
    String password_smtp = null;
    if (PasswordRecovery.NETWORK_SMTP_AUTHENTICATION.getValueAsBoolean()) {
      username_smtp = PasswordRecovery.NETWORK_SMTP_USER.getValueAsString();
      password_smtp = PasswordRecovery.NETWORK_SMTP_PASSWORD.getValueAsString();
      if (StringUtils.isEmpty(username_smtp))
        throw new PasswordRecoveryException(errorString + " SMTP username is not configured");
    }
    String emailFrom = PasswordRecovery.EMAIL_FROM.getValueAsString();
    String emailSubject = PasswordRecovery.EMAIL_SUBJECT.getValueAsString();
    if (StringUtils.isEmpty(emailFrom))
      throw new PasswordRecoveryException(errorString + " sender email is not configured");

    try {
      String userEmail =
          ((ODocument) user.field(UserDao.ATTRIBUTES_VISIBLE_ONLY_BY_THE_USER))
              .field("email")
              .toString();

      String username = (String) ((ODocument) user.field("user")).field("name");

      // Random
      String sRandom = appCode + "%%%%" + username + "%%%%" + UUID.randomUUID();
      String sBase64Random = new String(Base64.encodeBase64(sRandom.getBytes()));

      // Save on DB
      ResetPwdDao.getInstance().create(new Date(), sBase64Random, user);

      // Send mail
      HtmlEmail email = null;

      URL resetUrl =
          new URL(
              Application.NETWORK_HTTP_SSL.getValueAsBoolean() ? "https" : "http",
              siteUrl,
              sitePort,
              "/user/password/reset/" + sBase64Random);

      // HTML Email Text
      ST htmlMailTemplate = new ST(htmlEmail, '$', '$');
      htmlMailTemplate.add("link", resetUrl);
      htmlMailTemplate.add("user_name", username);

      // Plain text Email Text
      ST textMailTemplate = new ST(textEmail, '$', '$');
      textMailTemplate.add("link", resetUrl);
      textMailTemplate.add("user_name", username);

      email = new HtmlEmail();

      email.setHtmlMsg(htmlMailTemplate.render());
      email.setTextMsg(textMailTemplate.render());

      // Email Configuration
      email.setSSL(useSSL);
      email.setSSLOnConnect(useSSL);
      email.setTLS(useTLS);
      email.setStartTLSEnabled(useTLS);
      email.setStartTLSRequired(useTLS);
      email.setSSLCheckServerIdentity(false);
      email.setSslSmtpPort(String.valueOf(smtpPort));
      email.setHostName(smtpHost);
      email.setSmtpPort(smtpPort);

      if (PasswordRecovery.NETWORK_SMTP_AUTHENTICATION.getValueAsBoolean()) {
        email.setAuthenticator(new DefaultAuthenticator(username_smtp, password_smtp));
      }
      email.setFrom(emailFrom);
      email.addTo(userEmail);

      email.setSubject(emailSubject);

      if (Logger.isDebugEnabled()) {
        StringBuilder logEmail =
            new StringBuilder()
                .append("HostName: ")
                .append(email.getHostName())
                .append("\n")
                .append("SmtpPort: ")
                .append(email.getSmtpPort())
                .append("\n")
                .append("SslSmtpPort: ")
                .append(email.getSslSmtpPort())
                .append("\n")
                .append("SSL: ")
                .append(email.isSSL())
                .append("\n")
                .append("TLS: ")
                .append(email.isTLS())
                .append("\n")
                .append("SSLCheckServerIdentity: ")
                .append(email.isSSLCheckServerIdentity())
                .append("\n")
                .append("SSLOnConnect: ")
                .append(email.isSSLOnConnect())
                .append("\n")
                .append("StartTLSEnabled: ")
                .append(email.isStartTLSEnabled())
                .append("\n")
                .append("StartTLSRequired: ")
                .append(email.isStartTLSRequired())
                .append("\n")
                .append("SubType: ")
                .append(email.getSubType())
                .append("\n")
                .append("SocketConnectionTimeout: ")
                .append(email.getSocketConnectionTimeout())
                .append("\n")
                .append("SocketTimeout: ")
                .append(email.getSocketTimeout())
                .append("\n")
                .append("FromAddress: ")
                .append(email.getFromAddress())
                .append("\n")
                .append("ReplyTo: ")
                .append(email.getReplyToAddresses())
                .append("\n")
                .append("BCC: ")
                .append(email.getBccAddresses())
                .append("\n")
                .append("CC: ")
                .append(email.getCcAddresses())
                .append("\n")
                .append("Subject: ")
                .append(email.getSubject())
                .append("\n")
                .append("Message: ")
                .append(email.toString())
                .append("\n")
                .append("SentDate: ")
                .append(email.getSentDate())
                .append("\n");
        Logger.debug("Password Recovery is ready to send: \n" + logEmail.toString());
      }
      email.send();

    } catch (EmailException authEx) {
      Logger.error("ERROR SENDING MAIL:" + ExceptionUtils.getStackTrace(authEx));
      throw new PasswordRecoveryException(
          errorString
              + " Could not reach the mail server. Please contact the server administrator");
    } catch (Exception e) {
      Logger.error("ERROR SENDING MAIL:" + ExceptionUtils.getStackTrace(e));
      throw new Exception(errorString, e);
    }
  }
  /**
   * Searches the amazon ws for a movie by the given id.
   *
   * @param params
   * @return
   */
  private static List<AmazonResult> search(Map<String, String> params) {

    String awsEndPoint = ConfigFactory.load().getString("dvddb.amazon.endPoint");
    if (StringUtils.isEmpty(awsEndPoint) == true) {
      if (Logger.isErrorEnabled() == true) {
        Logger.error("No AWS endPoint set in the configuration.");
      }
      return null;
    }
    String awsKeyId = ConfigFactory.load().getString("dvddb.amazon.aws.keyid");
    if (StringUtils.isEmpty(awsKeyId) == true) {
      if (Logger.isErrorEnabled() == true) {
        Logger.error("No AWS keyID set in the configuration.");
      }
      return null;
    }
    String awsSecretKey = ConfigFactory.load().getString("dvddb.amazon.aws.secretkey");
    if (StringUtils.isEmpty(awsSecretKey) == true) {
      if (Logger.isErrorEnabled() == true) {
        Logger.error("No AWS keySecretKey set in the configuration.");
      }
      return null;
    }

    try {
      SignedRequestsHelper helper =
          SignedRequestsHelper.getInstance(awsEndPoint, awsKeyId, awsSecretKey);

      if (params == null) {
        params = new HashMap<>();
      }

      params.put("Service", "AWSECommerceService");
      params.put("Version", "2011-08-02");
      params.put("ResponseGroup", "ItemAttributes,Images");
      params.put("AssociateTag", "aztag-20");

      String requestUrl = helper.sign(params);
      if (Logger.isDebugEnabled() == true) {
        Logger.debug("Signed AWS request: " + requestUrl);
      }

      DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
      DocumentBuilder db = dbf.newDocumentBuilder();
      Document doc = db.parse(requestUrl);

      final List<AmazonResult> result = new ArrayList<>();
      NodeList itemNodes = XPath.selectNodes("//Items/Item", doc);
      for (int i = 0; i < itemNodes.getLength(); i++) {
        Node item = itemNodes.item(i);
        final AmazonResult resultFromNode = getResultFromNode(item);
        if (resultFromNode != null) {
          result.add(resultFromNode);
        }
      }

      return result;

    } catch (Exception e) {
      if (Logger.isErrorEnabled() == true) {
        Logger.error("An error happend while looking in the aws.", e);
      }
      return null;
    }
  }