AppBlocksInitializer.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.oauth.util;
import org.apache.commons.lang3.StringUtils;
import org.genesys.blocks.oauth.model.OAuthClient;
import org.genesys.blocks.oauth.persistence.OAuthClientRepository;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionTemplate;
import lombok.extern.slf4j.Slf4j;
/**
* App Blocks utility with handy updates :-).
*
* @author Matija Obreza
*/
@Component
@Slf4j
public class AppBlocksInitializer implements InitializingBean {
@Autowired
private OAuthClientRepository oauthClientRepository;
@Autowired
private PasswordEncoder passwordEncoder;
/** The tx manager. */
@Autowired
@Qualifier("transactionManager")
protected PlatformTransactionManager txManager;
public void afterPropertiesSet() throws Exception {
TransactionTemplate tmpl = new TransactionTemplate(txManager);
tmpl.execute(new TransactionCallbackWithoutResult() {
@Override
protected void doInTransactionWithoutResult(TransactionStatus status) {
encodePasswords();
}
});
}
/**
* Ensure that all clientSecrets are encrypted.
*/
void encodePasswords() {
long count = 0;
for (OAuthClient oauthClient : oauthClientRepository.findAll()) {
if (StringUtils.isNotBlank(oauthClient.getClientSecret()) && !oauthClient.getClientSecret().startsWith("$2a$")) {
count++;
log.warn("Migrating plain-text client secret to bcrypt for {}", oauthClient.getClientId());
oauthClientRepository.setClientSecret(oauthClient.getId(), passwordEncoder.encode(oauthClient.getClientSecret()));
}
}
if (count == 0) {
log.warn("\n\n\t** All OAuth Client secrets are encoded **\n\t You can remove the AppBlocksInitializer.\n\n");
}
}
}