FtpRunAs.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.filerepository.service.ftp;

import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

import lombok.extern.slf4j.Slf4j;

/**
 * RunAs for FTP.
 *
 * @author Matija Obreza
 */
@Slf4j
public class FtpRunAs {

	/**
	 * NoArgMethod.
	 *
	 * @param <R> the return type
	 * @param <T> the exception type
	 */
	public static interface NoArgMethod<R, T extends Throwable> {
		
		/**
		 * Run.
		 *
		 * @return the r
		 * @throws T the t
		 */
		R run() throws T;
	}

	/**
	 * Run method as the ftp user. Switches Spring security context to
	 * {@link FtpUser#user} and back to what it was.
	 *
	 * @param <R> method return type
	 * @param <T> exception type
	 * @param ftpUser the ftp user
	 * @param runnable the code to execute as FTP user
	 * @return the result of runnable
	 * @throws T the exception
	 */
	public static <R, T extends Throwable> R asFtpUser(FtpUser ftpUser, NoArgMethod<R, T> runnable) throws T {
		final Authentication prevAuth = SecurityContextHolder.getContext().getAuthentication();

		if (ftpUser != null && ftpUser.user != null) {
			log.trace("Switching to {}", ftpUser.user.getUsername());
			SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(ftpUser.user, ftpUser.getPassword(), ftpUser.user.getAuthorities()));
		}

		try {
			return runnable.run();
		} catch (Throwable e) {
			throw e;
		} finally {
			if (ftpUser != null && ftpUser.user != null) {
				log.trace("Switching back from {}", ftpUser.user.getUsername());
			}
			SecurityContextHolder.getContext().setAuthentication(prevAuth);
		}
	}
}