Create admin user only if it does not yet exist

Fixes #28
This commit is contained in:
Simon Bruder 2023-11-23 12:28:15 +01:00
parent a795fc99aa
commit 391ddaf03b
Signed by: simon
GPG key ID: 8D3C82F9F309F8EC
2 changed files with 50 additions and 3 deletions

View file

@ -1,6 +1,7 @@
package catering.users;
import org.salespointframework.core.DataInitializer;
import org.salespointframework.useraccount.UserAccountManagement;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
@ -13,15 +14,19 @@ class UserDataInitializer implements DataInitializer {
private static final Logger LOG = LoggerFactory.getLogger(UserDataInitializer.class);
private final UserManagement userManagement;
private final UserAccountManagement userAccountManagement;
UserDataInitializer(UserManagement userManagement) {
UserDataInitializer(UserManagement userManagement, UserAccountManagement userAccountManagement) {
Assert.notNull(userManagement, "UserRepository must not be null!");
this.userManagement = userManagement;
this.userAccountManagement = userAccountManagement;
}
@Override
public void initialize() {
LOG.info("Creating default user.");
userManagement.createAdmin("admin", "admin", "admin");
if (userAccountManagement.findByUsername("admin").isEmpty()) {
LOG.info("Creating default user.");
userManagement.createAdmin("admin", "admin", "admin");
}
}
}

View file

@ -0,0 +1,42 @@
package catering.users;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.salespointframework.useraccount.UserAccount.UserAccountIdentifier;
import org.salespointframework.useraccount.UserAccountManagement;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class UserDataInitializerIntegrationTests {
@Autowired
UserManagement userManagement;
@Autowired
UserAccountManagement userAccountManagement;
UserDataInitializer userDataInitializer;
@BeforeEach
void init() {
userDataInitializer = new UserDataInitializer(userManagement, userAccountManagement);
}
/**
* Test if the administrators account is only created once.
*
* If the admin is either replaced or attempted to be created a second time,
* the test will fail or throw an {@link IllegalArgumentException} respectively.
*
* @throws Exception
*/
@Test
void onlyCreateAdminOnce() throws Exception {
UserAccountIdentifier idBefore = userAccountManagement.findByUsername("admin").get().getId();
userDataInitializer.initialize();
UserAccountIdentifier idAfter = userAccountManagement.findByUsername("admin").get().getId();
assertThat(idAfter).isEqualTo(idBefore);
}
}