Log in only from certain networks#

The AllowedIPs procedure uses the ALLOW_IP constant to decide whether the user can access the application. In this constant it is necessary to specify the list of networks from which the access to the application is possible, it is acceptable to specify several networks. When entering the application, the user’s IP address will be checked to see if it matches one of the values included in the constant. If it matches, the user will be allowed to enter the application, if it does not match - access will be denied.

public class AllowedIPs implements Strategy {

    private final Logger logger = LoggerFactory.getLogger("com.identityblitz.idp.flow.dynamic");
    private final static String[] ALLOW_IP = {"179.218","180.219"};

    @Override public StrategyBeginState begin(final Context ctx) {
        if ("login".equals(ctx.prompt())){
            List<String> methods = new ArrayList<String>(Arrays.asList(ctx.availableMethods()));
            methods.remove("cls");
            return StrategyState.MORE(methods.toArray(new String[0]), true);
        } else {
            if(ctx.claims("subjectId") != null)
                return StrategyState.ENOUGH();
            else
                return StrategyState.MORE(new String[]{});
        }
    }

    @Override public StrategyState next(final Context ctx) {
        if (!_allowed_ip(ctx.ip())) {
            return StrategyState.DENY("ip_not_allowed", true);
        }
        Integer reqFactor = (ctx.user() == null) ? null : ctx.user().requiredFactor();
        if(reqFactor == null || reqFactor == ctx.justCompletedFactor()) {
            return StrategyState.ENOUGH_BUILDER()
                .build();
        } else
            return StrategyState.MORE(new String[]{});
    }

    private Boolean _allowed_ip(final String IP) {
      int IpListIdx = 0;
      boolean ipAllowed = false;
      while (IpListIdx > -1) {
        String ip_part = ALLOW_IP[IpListIdx];
        if (IP.startsWith(ip_part)) {
            ipAllowed = true;
            IpListIdx = -1;
        } else if (ALLOW_IP.length == (IpListIdx + 1)) {
            IpListIdx = -1;
        } else {
            IpListIdx ++;
        }
      }
        return ipAllowed;
    }
}