Example usage for org.joda.time DateTime plusSeconds

List of usage examples for org.joda.time DateTime plusSeconds

Introduction

In this page you can find the example usage for org.joda.time DateTime plusSeconds.

Prototype

public DateTime plusSeconds(int seconds) 

Source Link

Document

Returns a copy of this datetime plus the specified number of seconds.

Usage

From source file:org.thingsboard.server.service.security.model.token.JwtTokenFactory.java

License:Apache License

/**
 * Factory method for issuing new JWT Tokens.
 *///  w ww. ja va2s  .  com
public AccessJwtToken createAccessJwtToken(SecurityUser securityUser) {
    if (StringUtils.isBlank(securityUser.getEmail()))
        throw new IllegalArgumentException("Cannot create JWT Token without username/email");

    if (securityUser.getAuthority() == null)
        throw new IllegalArgumentException("User doesn't have any privileges");

    UserPrincipal principal = securityUser.getUserPrincipal();
    String subject = principal.getValue();
    Claims claims = Jwts.claims().setSubject(subject);
    claims.put(SCOPES,
            securityUser.getAuthorities().stream().map(s -> s.getAuthority()).collect(Collectors.toList()));
    claims.put(USER_ID, securityUser.getId().getId().toString());
    claims.put(FIRST_NAME, securityUser.getFirstName());
    claims.put(LAST_NAME, securityUser.getLastName());
    claims.put(ENABLED, securityUser.isEnabled());
    claims.put(IS_PUBLIC, principal.getType() == UserPrincipal.Type.PUBLIC_ID);
    if (securityUser.getTenantId() != null) {
        claims.put(TENANT_ID, securityUser.getTenantId().getId().toString());
    }
    if (securityUser.getCustomerId() != null) {
        claims.put(CUSTOMER_ID, securityUser.getCustomerId().getId().toString());
    }

    DateTime currentTime = new DateTime();

    String token = Jwts.builder().setClaims(claims).setIssuer(settings.getTokenIssuer())
            .setIssuedAt(currentTime.toDate())
            .setExpiration(currentTime.plusSeconds(settings.getTokenExpirationTime()).toDate())
            .signWith(SignatureAlgorithm.HS512, settings.getTokenSigningKey()).compact();

    return new AccessJwtToken(token, claims);
}

From source file:org.thingsboard.server.service.security.model.token.JwtTokenFactory.java

License:Apache License

public JwtToken createRefreshToken(SecurityUser securityUser) {
    if (StringUtils.isBlank(securityUser.getEmail())) {
        throw new IllegalArgumentException("Cannot create JWT Token without username/email");
    }/* ww  w  .  j  a va 2s .c om*/

    DateTime currentTime = new DateTime();

    UserPrincipal principal = securityUser.getUserPrincipal();
    Claims claims = Jwts.claims().setSubject(principal.getValue());
    claims.put(SCOPES, Arrays.asList(Authority.REFRESH_TOKEN.name()));
    claims.put(USER_ID, securityUser.getId().getId().toString());
    claims.put(IS_PUBLIC, principal.getType() == UserPrincipal.Type.PUBLIC_ID);

    String token = Jwts.builder().setClaims(claims).setIssuer(settings.getTokenIssuer())
            .setId(UUID.randomUUID().toString()).setIssuedAt(currentTime.toDate())
            .setExpiration(currentTime.plusSeconds(settings.getRefreshTokenExpTime()).toDate())
            .signWith(SignatureAlgorithm.HS512, settings.getTokenSigningKey()).compact();

    return new AccessJwtToken(token, claims);
}

From source file:org.wannatrak.device.api.TrakApiImpl.java

License:Apache License

@Override
public void post(@PathParam("deviceKey") String deviceKey, Double[][] trak)
        throws EntityNotFoundException, SendPeriodNotElapsedException {
    Subject subject = getSubject(deviceKey);
    DeviceSettings deviceSettings = subject.getDeviceSettings();
    DateTime lastUpdated = subject.getLastUpdated();
    if (deviceSettings != null && lastUpdated != null
            && lastUpdated.plusSeconds(30 * deviceSettings.getSendPeriod()).isAfterNow()) {
        throw new SendPeriodNotElapsedException();
    }//w  w w. ja va 2 s  .c om

    Position[] positions = new Position[trak.length];
    int i = 0;
    for (Double[] point : trak) {
        Position position = new Position();
        position.setGpsTimestamp(new DateTime(point[0].longValue()));
        position.setLongitude(point[1]);
        position.setLatitude(point[2]);
        position.setSpeed(point[3]);
        position.setCourse(point[4] == null ? null : point[4].intValue());
        position.setAltitude(point[5]);
        positions[i++] = position;
    }

    trackingHandler.handlePositions(deviceKey, positions);
}

From source file:org.wso2.carbon.appmgt.gateway.handlers.security.saml2.IDPMessage.java

License:Open Source License

/**
 * Validates the 'Not Before' and 'Not On Or After' conditions of the SAML Assertion.
 *
 *///from ww  w  .j a  v  a2s. com
public boolean validateAssertionValidityPeriod() {

    boolean validateAssertionExpiry = SSOConfiguratorUtil.isValidateAssertionValidityPeriod();

    if (validateAssertionExpiry) {
        Assertion assertion = null;
        Response response = (Response) samlResponse;
        List<Assertion> assertions = response.getAssertions();

        if (CollectionUtils.isEmpty(assertions)) {
            if (log.isDebugEnabled()) {
                log.debug("SAML Response does not have assertions.");
            }
            return false;
        }

        assertion = assertions.get(0);

        DateTime validFrom = assertion.getConditions().getNotBefore();
        DateTime validTill = assertion.getConditions().getNotOnOrAfter();

        //skew time in seconds
        String timeStampSkewInConfig = ServiceReferenceHolder.getInstance().getAPIManagerConfigurationService()
                .getAPIManagerConfiguration()
                .getFirstProperty(AppMConstants.SSO_CONFIGURATION_RESPONSE_VALIDITY_TIME_STAMP_SKEW);

        if (timeStampSkewInConfig != null) {
            timeStampSkewInSeconds = Integer.parseInt(timeStampSkewInConfig);
        }

        if (validFrom != null && validFrom.minusSeconds(timeStampSkewInSeconds).isAfterNow()) {
            log.error("Failed to meet SAML Assertion Condition 'Not Before'");
            return false;
        }

        if (validTill != null && validTill.plusSeconds(timeStampSkewInSeconds).isBeforeNow()) {
            log.error("Failed to meet SAML Assertion Condition 'Not On Or After'");
            return false;
        }

        if (validFrom != null && validTill != null && validFrom.isAfter(validTill)) {
            log.error("SAML Assertion Condition 'Not Before' must be less than the value of 'Not On Or After'");
            return false;
        }
    }

    return true;
}

From source file:org.wso2.carbon.hostobjects.sso.SAMLSSORelyingPartyObject.java

License:Open Source License

/**
 * Validates the 'Not Before' and 'Not On Or After' conditions of the SAML Assertion
 *
 * @param assertion SAML Assertion element
 * @throws ScriptException/*from  w ww  .ja va  2  s .  co m*/
 */
private boolean validateAssertionValidityPeriod(Assertion assertion, int timeStampSkewInSeconds)
        throws ScriptException {
    DateTime validFrom = assertion.getConditions().getNotBefore();
    DateTime validTill = assertion.getConditions().getNotOnOrAfter();

    if (validFrom != null && validFrom.minusSeconds(timeStampSkewInSeconds).isAfterNow()) {
        log.error("Failed to meet SAML Assertion Condition 'Not Before'");
        return false;
    }

    if (validTill != null && validTill.plusSeconds(timeStampSkewInSeconds).isBeforeNow()) {
        log.error("Failed to meet SAML Assertion Condition 'Not On Or After'");
        return false;
    }

    if (validFrom != null && validTill != null && validFrom.isAfter(validTill)) {
        log.error(
                "SAML Assertion Condition 'Not Before' must be less than the " + "value of 'Not On Or After'");
        return false;
    }

    return true;
}

From source file:org.wso2.carbon.identity.application.authenticator.passive.sts.manager.PassiveSTSManager.java

License:Open Source License

/**
 * Validates the 'Not Before' and 'Not On Or After' conditions of the SAML Assertion
 *
 * @param xmlObject parsed SAML entity// w w  w  . j a  va  2 s. c  o m
 * @throws PassiveSTSException
 */
private void validateAssertionValidityPeriod(AuthenticationContext context, XMLObject xmlObject)
        throws PassiveSTSException {

    if (log.isDebugEnabled()) {
        log.debug("Validating SAML Assertion's 'Not Before' and 'Not On Or After' conditions.");
    }

    DateTime validFrom = null;
    DateTime validTill = null;

    if (xmlObject instanceof org.opensaml.saml1.core.Assertion) {
        org.opensaml.saml1.core.Assertion saml1Assertion = (org.opensaml.saml1.core.Assertion) xmlObject;
        if (saml1Assertion.getConditions() != null) {
            validFrom = saml1Assertion.getConditions().getNotBefore();
            validTill = saml1Assertion.getConditions().getNotOnOrAfter();
        }
    } else if (xmlObject instanceof org.opensaml.saml2.core.Assertion) {
        org.opensaml.saml2.core.Assertion saml2Assertion = (org.opensaml.saml2.core.Assertion) xmlObject;
        if (saml2Assertion.getConditions() != null) {
            validFrom = saml2Assertion.getConditions().getNotBefore();
            validTill = saml2Assertion.getConditions().getNotOnOrAfter();
        }
    } else {
        throw new PassiveSTSException(
                "Unknown Security Token. Can process only SAML 1.0 and SAML 2.0 Assertions");
    }

    int clockSkewInSeconds = IdentityUtil.getClockSkewInSeconds();

    if (validFrom != null && validFrom.minusSeconds(clockSkewInSeconds).isAfterNow()) {
        throw new PassiveSTSException("Failed to meet SAML Assertion Condition 'Not Before'");
    }

    if (validTill != null && validTill.plusSeconds(clockSkewInSeconds).isBeforeNow()) {
        throw new PassiveSTSException("Failed to meet SAML Assertion Condition 'Not On Or After'");
    }

    if (validFrom != null && validTill != null && validFrom.isAfter(validTill)) {
        throw new PassiveSTSException(
                "SAML Assertion Condition 'Not Before' must be less than the value of 'Not On Or After'");
    }
}

From source file:org.wso2.carbon.identity.authenticator.saml2.sso.SAML2SSOAuthenticator.java

License:Open Source License

/**
 * Validates the 'Not Before' and 'Not On Or After' conditions of the SAML Assertion
 *
 * @param xmlObject SAML Assertion element
 * @throws SAML2SSOAuthenticatorException
 *//* w  w  w.  ja v a2  s .  c o  m*/
private void validateAssertionValidityPeriod(XMLObject xmlObject) throws SAML2SSOAuthenticatorException {

    Assertion assertion;
    if (xmlObject instanceof Response) {
        assertion = getAssertionFromResponse((Response) xmlObject);
    } else if (xmlObject instanceof Assertion) {
        assertion = (Assertion) xmlObject;
    } else {
        throw new SAML2SSOAuthenticatorException(
                "Only Response and Assertion objects are validated in this authenticator");
    }

    if (assertion == null) {
        throw new SAML2SSOAuthenticatorException("Cannot find a SAML Assertion");
    }

    if (assertion.getConditions() != null) {
        DateTime validFrom = assertion.getConditions().getNotBefore();
        DateTime validTill = assertion.getConditions().getNotOnOrAfter();
        int timeStampSkewInSeconds = getTimeStampSkewInSeconds();

        if (validFrom != null && validFrom.minusSeconds(timeStampSkewInSeconds).isAfterNow()) {
            throw new SAML2SSOAuthenticatorException("Failed to meet SAML Assertion Condition 'Not Before'");
        }

        if (validTill != null && validTill.plusSeconds(timeStampSkewInSeconds).isBeforeNow()) {
            throw new SAML2SSOAuthenticatorException(
                    "Failed to meet SAML Assertion Condition 'Not On Or After'");
        }

        if (validFrom != null && validTill != null && validFrom.isAfter(validTill)) {
            throw new SAML2SSOAuthenticatorException(
                    "SAML Assertion Condition 'Not Before' must be less than the "
                            + "value of 'Not On Or After'");
        }
    }
}

From source file:org.wso2.carbon.identity.sso.saml.validators.SPInitSSOAuthnRequestValidator.java

License:Open Source License

/**
 * Validating issueInstant time//w w w . jav  a  2  s .com
 * @return
 */
private String validateRequestIssueInstant() {

    DateTime validFrom = authnReq.getIssueInstant();
    if (validFrom == null) {
        return "IssueInstant time is not valid.";
    }
    DateTime validTill = validFrom.plusSeconds(SAMLSSOUtil.getSAMLAuthenticationRequestValidityPeriod());
    int timeStampSkewInSeconds = IdentityUtil.getClockSkewInSeconds();

    if (validFrom.minusSeconds(timeStampSkewInSeconds).isAfterNow()) {
        return "The request IssueInstant time is 'Not Before'";
    }

    if (validTill != null && validTill.plusSeconds(timeStampSkewInSeconds).isBeforeNow()) {
        return "The request IssueInstant time is  'Not On Or After'";
    }

    if (validTill != null && validFrom.isAfter(validTill)) {
        return "The request IssueInstant time is  'Not On Or After'";
    }

    return null;
}

From source file:se.inera.certificate.web.security.BrowserClosedInterceptor.java

License:Open Source License

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
        throws IOException {

    HttpSession session = request.getSession();
    DateTime then = (DateTime) session.getAttribute(BROWSER_CLOSED_TIMESTAMP);

    if (then != null) {
        if (then.plusSeconds(timeoutSeconds).isBefore(DateTime.now())) {
            LOG.warn("Browser closed and protected page revisited, user logged out");
            // log out user
            logoutHandler.logout(request, response, null);
            response.sendRedirect(redirectLocation);
            return false;
        } else {//from w w  w . ja  v  a2s  .c o m
            // valid reqest remove timestamp
            session.removeAttribute(BROWSER_CLOSED_TIMESTAMP);
            LOG.debug("Valid refresh of browser");
            return true;
        }
    }
    // normal request
    return true;
}