Skip to content

Instantly share code, notes, and snippets.

@fabian-bouche-liferay
Last active January 3, 2022 14:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fabian-bouche-liferay/7bbc95bf9f6c14ba497ac090d34ed793 to your computer and use it in GitHub Desktop.
Save fabian-bouche-liferay/7bbc95bf9f6c14ba497ac090d34ed793 to your computer and use it in GitHub Desktop.
package com.liferay.samples.fbo.ip.role;
import com.liferay.portal.kernel.audit.AuditRequestThreadLocal;
import com.liferay.portal.kernel.model.Role;
import com.liferay.portal.kernel.security.permission.contributor.RoleCollection;
import com.liferay.portal.kernel.security.permission.contributor.RoleContributor;
import com.liferay.portal.kernel.service.RoleLocalService;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Component(
immediate = true,
service = RoleContributor.class
)
public class IPBasedRoleContributor implements RoleContributor {
private static final String INTERNAL_USER_ROLE_NAME = "IP";
@Override
public void contribute(RoleCollection roleCollection) {
long companyId = roleCollection.getCompanyId();
long internalUserRoleId =
_getInternalUserRoleIdForCompany(companyId);
if (internalUserRoleId == 0) {
return;
}
String clientIPAddress = AuditRequestThreadLocal
.getAuditThreadLocal().getClientIP();
boolean offsite = _isIPAddressOffsite(clientIPAddress);
if (offsite && roleCollection.hasRoleId(internalUserRoleId)) {
roleCollection.removeRoleId(internalUserRoleId);
} else if (!offsite && !roleCollection.hasRoleId(internalUserRoleId)) {
roleCollection.addRoleId(internalUserRoleId);
}
}
private long _getInternalUserRoleIdForCompany(final long companyId) {
long roleId;
Role role = _roleLocalService
.fetchRole(companyId, INTERNAL_USER_ROLE_NAME);
if (role == null) {
return 0;
}
roleId = role.getRoleId();
return roleId;
}
private boolean _isIPAddressOffsite(final String ipAddress) {
return false;
}
@Reference
private RoleLocalService _roleLocalService;
private final static Logger LOG = LoggerFactory.getLogger(IPBasedRoleContributor.class);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment