SpringSecurityAuditorAware.java

/*
 * Copyright 2018 Global Crop Diversity Trust
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.genesys.blocks.security;

import java.util.Optional;

import org.genesys.blocks.security.model.AclSid;
import org.genesys.blocks.security.service.CustomAclService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.AuditorAware;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.core.oidc.user.DefaultOidcUser;
import org.springframework.stereotype.Component;

import lombok.extern.slf4j.Slf4j;

/**
 * The Class SpringSecurityAuditorAware.
 */
@Component
@Slf4j
public class SpringSecurityAuditorAware implements AuditorAware<Long> {

	@Autowired
	private CustomAclService aclService;

	/*
	 * (non-Javadoc)
	 * @see org.springframework.data.domain.AuditorAware#getCurrentAuditor()
	 */
	@Override
	public Optional<Long> getCurrentAuditor() {
		final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

		if (authentication != null) {
			Object principal = authentication.getPrincipal();
			if (principal instanceof AclSid) {
				return Optional.of(((AclSid) principal).getId());
			} else if (principal instanceof String) {
				return Optional.ofNullable(aclService.getSidId((String) principal));
			} else if (principal instanceof DefaultOidcUser) {
				Long userId = ((DefaultOidcUser)principal).getClaim(AclSid.OIDC_SID_ID);
				return Optional.ofNullable(userId);
			} else {
				log.warn("Principal {} is not AclSid, but type {}. Auth of type {}", principal, principal.getClass(), authentication.getClass());
			}
		}
		
		log.info("No security principal available.");
		return Optional.empty();
	}

}