Commit c215e1be authored by Matija Obreza's avatar Matija Obreza

Using ApplicationStartup

- Ensure 1 admin
- Ensure 1 OAuth client
- Clean up ACL data
- Assign initial permissions for imported Catalog data
parent f9b30825
/**
* Copyright 2014 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.genesys2.server.listener.sample;
import com.google.common.collect.Sets;
import org.genesys.blocks.security.UserException;
import org.genesys.blocks.security.model.BasicUser.AccountType;
import org.genesys.blocks.security.service.PasswordPolicy.PasswordPolicyException;
import org.genesys2.server.listener.RunAsAdminListener;
import org.genesys2.server.model.UserRole;
import org.genesys2.server.model.impl.User;
import org.genesys2.server.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
@Service("createAdminListener")
public class CreateAdminListener extends RunAsAdminListener {
@Autowired
private UserService userService;
@Value("${default.admin.email}")
private String defaultAdminEmail;
@Value("${default.admin.password}")
private String defaultAdminPassword;
@Override
public void init() throws Exception {
LOG.info("Checking for at least one account");
if (userService.listUsers(new PageRequest(0, 2)).getTotalElements() < 2) {
createDefaultAccounts();
}
}
private void createDefaultAccounts() throws UserException, PasswordPolicyException {
createAdmin(defaultAdminEmail, "First Admin", defaultAdminPassword, AccountType.LOCAL);
}
private void createAdmin(String email, String fullName, String password, AccountType accountType) throws UserException, PasswordPolicyException {
final User user = userService.createUser(email, fullName, password, accountType);
userService.setRoles(user, Sets.newHashSet(UserRole.ADMINISTRATOR));
LOG.warn("Admin account for " + email + " has been successfully added.");
}
}
......@@ -19,14 +19,9 @@ package org.genesys2.server.listener.sample;
import java.io.IOException;
import java.io.InputStream;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.genesys.blocks.oauth.model.OAuthClient;
import org.genesys.blocks.oauth.model.OAuthRole;
import org.genesys.blocks.oauth.persistence.OAuthClientRepository;
import org.genesys2.server.listener.RunAsAdminListener;
import org.genesys2.server.model.impl.FaoInstitute;
import org.genesys2.server.persistence.AccessionRepository;
import org.genesys2.server.service.CropService;
import org.genesys2.server.service.GenesysService;
import org.genesys2.server.service.GeoRegionService;
......@@ -39,7 +34,6 @@ import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.data.domain.PageRequest;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
import com.fasterxml.jackson.core.JsonParseException;
......@@ -58,12 +52,6 @@ public class FirstRunListener extends RunAsAdminListener {
// Must **not** be final!
private boolean createContent;
@Value("${default.oauthclient.clientId}")
private String defaultOAuthClientId;
@Value("${default.oauthclient.clientSecret}")
private String defaultOAuthClientSecret;
@Autowired
private GeoService geoService;
......@@ -79,20 +67,11 @@ public class FirstRunListener extends RunAsAdminListener {
@Autowired
private CropService cropService;
@Autowired
private OAuthClientRepository oauthClientRepository;
@Autowired
private AccessionRepository accessionRepository;
@Autowired
private AccessionUploader uploader;
@Autowired
private GenesysService genesysService;
@Autowired
private PasswordEncoder passwordEncoder;
@Override
protected void init() throws Exception {
......@@ -123,12 +102,6 @@ public class FirstRunListener extends RunAsAdminListener {
addCrop("sorghum");
}
if (oauthClientRepository.count() == 0) {
addDefaultOAuthClient();
} else {
LOG.warn("Skipping creation of initial OAuth client");
}
addSomeAccessions();
}
......@@ -137,31 +110,6 @@ public class FirstRunListener extends RunAsAdminListener {
cropService.addCrop(shortName, StringUtils.capitalize(shortName), StringUtils.capitalize(shortName), null);
}
private void addDefaultOAuthClient() {
if (StringUtils.isBlank(defaultOAuthClientId)) {
defaultOAuthClientId = RandomStringUtils.randomAlphanumeric(5) + "." + RandomStringUtils.randomAlphanumeric(20);
}
if (StringUtils.isBlank(defaultOAuthClientSecret)) {
defaultOAuthClientSecret = RandomStringUtils.randomAlphanumeric(32);
}
LOG.warn("Creating default OAuth client id={} secret={}", defaultOAuthClientId, defaultOAuthClientSecret);
final OAuthClient client = new OAuthClient();
client.setClientId(defaultOAuthClientId);
client.setClientSecret(passwordEncoder.encode(defaultOAuthClientSecret));
client.setTitle("Default OAuth client");
client.setDescription("This OAuth client was automatically created by the system.");
client.getAuthorizedGrantTypes().add("authorization_code");
client.getAuthorizedGrantTypes().add("password");
client.getAuthorizedGrantTypes().add("client_credentials");
client.getAuthorizedGrantTypes().add("implicit");
client.getRoles().add(OAuthRole.CLIENT);
client.getScope().add("read");
client.getScope().add("write");
client.getScope().add("trust");
oauthClientRepository.save(client);
}
private void addSomeAccessions() throws IOException {
LOG.warn("Adding some passport data");
......
/*
* 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.genesys2.spring.config;
import javax.transaction.Transactional;
import org.apache.commons.lang3.StringUtils;
import org.genesys.blocks.oauth.model.OAuthClient;
import org.genesys.blocks.oauth.model.OAuthRole;
import org.genesys.blocks.oauth.persistence.OAuthClientRepository;
import org.genesys.blocks.security.NotUniqueUserException;
import org.genesys.blocks.security.UserException;
import org.genesys.blocks.security.model.BasicUser;
import org.genesys.blocks.security.service.CustomAclService;
import org.genesys.blocks.security.service.PasswordPolicy.PasswordPolicyException;
import org.genesys.catalog.persistence.PartnerRepository;
import org.genesys.catalog.persistence.dataset.DatasetRepository;
import org.genesys.catalog.persistence.traits.DescriptorListRepository;
import org.genesys.catalog.persistence.traits.DescriptorRepository;
import org.genesys2.server.model.UserRole;
import org.genesys2.server.model.impl.User;
import org.genesys2.server.persistence.UserRepository;
import org.genesys2.server.security.AsAdminInvoker;
import org.genesys2.server.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
import com.google.common.collect.Sets;
/**
* Run things at startup and after application context is initialized.
*/
@Component
public class ApplicationStartup implements InitializingBean, ApplicationListener<ContextRefreshedEvent> {
private static final Logger LOG = LoggerFactory.getLogger(ApplicationStartup.class);
private static final String DEFAULT_ADMIN_EMAIL = "admin@example.com";
@Value("${default.admin.email}")
private String defaultAdminEmail;
@Value("${default.admin.password}")
private String defaultAdminPassword;
@Value("${default.oauthclient.clientId}")
private String defaultOAuthClientId;
@Value("${default.oauthclient.clientSecret}")
private String defaultOAuthClientSecret;
@Autowired
private UserRepository userRepository;
@Autowired
private UserService userService;
@Autowired
private OAuthClientRepository oauthClientRepository;
@Autowired
private CustomAclService aclService;
@Autowired
protected AsAdminInvoker asAdminInvoker;
/**
* Things to run immediately
*/
@Override
public void afterPropertiesSet() throws Exception {
if (StringUtils.isBlank(defaultAdminEmail)) {
defaultAdminEmail = DEFAULT_ADMIN_EMAIL;
}
if (StringUtils.isBlank(defaultAdminPassword)) {
defaultAdminPassword = "Admin321!#";
}
startup();
asAdminInvoker.invoke(() -> {
aclForCatalog();
// aclParentObject();
return null;
});
}
/**
* Things to run after startup
*/
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
aclService.cleanupAcl();
}
/**
* Startup.
*/
@Transactional
void startup() {
try {
ensure1Admin();
} catch (final UserException e) {
LOG.error("Default admin account could not be created", e);
}
ensure1OAuthClient();
}
@Autowired
private PasswordEncoder passwordEncoder;
/**
* Ensure 1 O auth client.
*/
public void ensure1OAuthClient() {
if (oauthClientRepository.count() == 0) {
LOG.warn("Creating default OAuth client {}", defaultOAuthClientId);
final OAuthClient client = new OAuthClient();
client.setClientId(defaultOAuthClientId);
client.setClientSecret(passwordEncoder.encode(defaultOAuthClientSecret));
client.getAuthorizedGrantTypes().add("authorization_code");
client.getAuthorizedGrantTypes().add("password");
client.getAuthorizedGrantTypes().add("client_credentials");
client.getAuthorizedGrantTypes().add("implicit");
client.getRoles().add(OAuthRole.CLIENT);
client.getScope().add("read");
client.getScope().add("write");
client.getScope().add("trust");
client.setTitle("Default OAuth client");
client.setDescription("This OAuth client was automatically created by the system.");
oauthClientRepository.save(client);
}
}
/**
* Ensure 1 admin.
*
* @throws NotUniqueUserException the not unique user exception
* @throws PasswordPolicyException the password policy exception
* @throws UserException the user exception
*/
public void ensure1Admin() throws NotUniqueUserException, PasswordPolicyException, UserException {
LOG.info("Startup initializer checking stuff");
// The other user is SYSTEM_ADMIN!
if (userRepository.count() <= 1) {
final User admin = userService.createUser(defaultAdminEmail, "Administrator", defaultAdminPassword, BasicUser.AccountType.LOCAL);
userService.setRoles(admin, Sets.newHashSet(UserRole.ADMINISTRATOR));
LOG.warn("Default admin email={} password={}", admin.getEmail(), defaultAdminPassword);
}
LOG.info("Startup initializer done.");
}
@Autowired
private PartnerRepository partnerRepository;
@Autowired
private DatasetRepository datasetRepository;
@Autowired
private DescriptorRepository descriptorRepository;
@Autowired
private DescriptorListRepository descriptorListRepository;
// TODO Remove after first deployment to sandbox
private void aclForCatalog() {
partnerRepository.findAll().stream().forEach(partner -> aclService.addCreatorPermissions(partner));
// datasetRepository.findAll().stream().forEach(dataset ->
// aclService.removeAclAwareModel(dataset));
datasetRepository.findAll().stream().forEach(dataset -> aclService.addCreatorPermissions(dataset));
// descriptorListRepository.findAll().stream().forEach(descriptorList ->
// aclService.removeAclAwareModel(descriptorList));
descriptorListRepository.findAll().stream().forEach(descriptorList -> aclService.addCreatorPermissions(descriptorList));
// descriptorRepository.findAll().stream().forEach(descriptor ->
// aclService.removeAclAwareModel(descriptor));
descriptorRepository.findAll().stream().forEach(descriptor -> aclService.addCreatorPermissions(descriptor));
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment