Skip to content

Commit

Permalink
Sample data creation and user management (#31)
Browse files Browse the repository at this point in the history
  • Loading branch information
haiphucnguyen authored Dec 15, 2024
1 parent e98ac5e commit dbbeb33
Show file tree
Hide file tree
Showing 31 changed files with 303 additions and 399 deletions.
6 changes: 1 addition & 5 deletions gradle/profile_prod.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,7 @@ dependencies {
}

ext {
springProfiles = "prod" + springProfiles

if (project.hasProperty("api-docs")) {
springProfiles += ",api-docs"
}
springProfiles = "prod"
}

springBoot {
Expand Down
25 changes: 9 additions & 16 deletions server/src/main/java/io/flexwork/FlexworkApp.java
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
Expand All @@ -40,13 +39,13 @@
@EntityScan("io.flexwork")
@EnableAspectJAutoProxy
@Order(1)
public class FlexworkApp implements CommandLineRunner {
public class FlexworkApp {

private static final Logger LOG = LoggerFactory.getLogger(FlexworkApp.class);

private TenantService tenantService;
private final TenantService tenantService;

private LiquibaseService liquibaseService;
private final LiquibaseService liquibaseService;

private final Environment env;

Expand All @@ -72,12 +71,7 @@ public void initApplication() {
"You have misconfigured your application! It should not run "
+ "with both the 'dev' and 'prod' profiles at the same time.");
}
if (activeProfiles.contains(FlexworkProfiles.SPRING_PROFILE_DEVELOPMENT)
&& activeProfiles.contains(FlexworkProfiles.SPRING_PROFILE_CLOUD)) {
LOG.error(
"You have misconfigured your application! It should not "
+ "run with both the 'dev' and 'cloud' profiles at the same time.");
}
migrateDatabases(activeProfiles);
}

/**
Expand All @@ -86,11 +80,11 @@ public void initApplication() {
* @param args the command line arguments.
*/
public static void main(String[] args) {
SpringApplication app = new SpringApplication(FlexworkApp.class);

loadEnvVariablesFromEnvFile(".");
loadEnvVariablesFromEnvFile("..");

SpringApplication app = new SpringApplication(FlexworkApp.class);

DefaultProfileUtil.addDefaultProfile(app);
Environment env = app.run(args).getEnvironment();
logApplicationStartup(env);
Expand Down Expand Up @@ -138,12 +132,11 @@ private static void logApplicationStartup(Environment env) {
}

@Transactional
@Override
public void run(String... args) throws Exception {
liquibaseService.updateMasterDbSchema(MASTER_SCHEMA);
void migrateDatabases(Collection<String> activeProfiles) {
liquibaseService.updateMasterDbSchema(MASTER_SCHEMA, activeProfiles);
Tenant defaultTenant = tenantService.getDefaultTenant();
LOG.debug("Default tenant: {}", defaultTenant);
liquibaseService.createTenantDbSchema(defaultTenant.getName());
liquibaseService.createTenantDbSchema(defaultTenant.getName(), activeProfiles);
TenantContext.setCurrentTenant(defaultTenant.getName());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,4 @@
public class FlexworkProfiles {
public static final String SPRING_PROFILE_DEVELOPMENT = "dev";
public static final String SPRING_PROFILE_PRODUCTION = "prod";
public static final String SPRING_PROFILE_CLOUD = "cloud";
}
Original file line number Diff line number Diff line change
Expand Up @@ -58,8 +58,6 @@ public SecurityFilterChain filterChain(HttpSecurity http, MvcRequestMatcher.Buil
.permitAll()
.requestMatchers(mvc.pattern("/content/**"))
.permitAll()
.requestMatchers(mvc.pattern("/swagger-ui/**"))
.permitAll()
.requestMatchers(mvc.pattern(HttpMethod.POST, "/api/login"))
.permitAll()
.requestMatchers(
Expand All @@ -84,8 +82,6 @@ public SecurityFilterChain filterChain(HttpSecurity http, MvcRequestMatcher.Buil
.hasAuthority(AuthoritiesConstants.ADMIN)
.requestMatchers(mvc.pattern("/api/**"))
.authenticated()
.requestMatchers(mvc.pattern("/v3/api-docs/**"))
.hasAuthority(AuthoritiesConstants.ADMIN)
.requestMatchers(mvc.pattern("/management/health"))
.permitAll()
.requestMatchers(mvc.pattern("/management/health/**"))
Expand Down
2 changes: 0 additions & 2 deletions server/src/main/java/io/flexwork/config/WebConfigurer.java
Original file line number Diff line number Diff line change
Expand Up @@ -88,8 +88,6 @@ public CorsFilter corsFilter() {
LOG.debug("Registering CORS filter");
source.registerCorsConfiguration("/api/**", config);
source.registerCorsConfiguration("/management/**", config);
source.registerCorsConfiguration("/v3/api-docs", config);
source.registerCorsConfiguration("/swagger-ui/**", config);
}
return new CorsFilter(source);
}
Expand Down
16 changes: 10 additions & 6 deletions server/src/main/java/io/flexwork/db/service/LiquibaseService.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package io.flexwork.db.service;

import java.sql.Connection;
import java.util.Collection;
import javax.sql.DataSource;
import liquibase.Contexts;
import liquibase.LabelExpression;
Expand Down Expand Up @@ -31,7 +32,8 @@ public LiquibaseService(DataSource dataSource) {
}

@SneakyThrows
private void updateLiquibaseSchema(String classpathChangeset, String schema) {
private void updateLiquibaseSchema(
String classpathChangeset, String schema, Collection<String> activeProfiles) {
try (Connection connection = dataSource.getConnection()) {
LOG.info("Going to create a schema {}", schema);
connection.prepareCall("CREATE SCHEMA IF NOT EXISTS " + schema).execute();
Expand All @@ -42,18 +44,20 @@ private void updateLiquibaseSchema(String classpathChangeset, String schema) {
database.setDefaultSchemaName(schema);
Liquibase liquibase =
new Liquibase(classpathChangeset, new ClassLoaderResourceAccessor(), database);
liquibase.update(new Contexts(), new LabelExpression());
Contexts contexts = new Contexts();
activeProfiles.forEach(contexts::add);
liquibase.update(contexts, new LabelExpression());
liquibase.close();
}
}

@Transactional
public void createTenantDbSchema(String schema) {
updateLiquibaseSchema(TENANT_CHANGESET, schema);
public void createTenantDbSchema(String schema, Collection<String> activeProfiles) {
updateLiquibaseSchema(TENANT_CHANGESET, schema, activeProfiles);
}

@Transactional
public void updateMasterDbSchema(String schema) {
updateLiquibaseSchema(MASTER_CHANGESET, schema);
public void updateMasterDbSchema(String schema, Collection<String> activeProfiles) {
updateLiquibaseSchema(MASTER_CHANGESET, schema, activeProfiles);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,9 @@

@Getter
public class RemoveUserOutOfTeamEvent extends ApplicationEvent {
private Long teamId;
private final Long teamId;

private Long userId;
private final Long userId;

public RemoveUserOutOfTeamEvent(Object source, Long teamId, Long userId) {
super(source);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package io.flexwork.modules.teams.service.listener;

import io.flexwork.modules.teams.service.TeamService;
import io.flexwork.modules.teams.service.dto.TeamDTO;
import io.flexwork.modules.usermanagement.service.event.DeleteUserEvent;
import java.util.List;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

@Component
public class DeleteUserEventListener {

private final TeamService teamService;

public DeleteUserEventListener(TeamService teamService) {
this.teamService = teamService;
}

@Async("auditLogExecutor")
@Transactional
@EventListener
public void onDeleteUserEvent(DeleteUserEvent event) {
List<TeamDTO> teams = teamService.findAllTeamsByUserId(event.getUserId());
for (TeamDTO team : teams) {
teamService.removeUserFromTeam(event.getUserId(), team.getId());
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -54,8 +54,11 @@ public class User extends AbstractAuditingEntity<Long> implements Serializable {
private String email;

@NotNull @Column(nullable = false)
@Builder.Default
private boolean activated = false;
@Enumerated(EnumType.STRING)
private UserStatus status = UserStatus.PENDING;

@Column(name = "is_deleted", nullable = false)
private Boolean isDeleted = false;

@Size(min = 2, max = 10)
@Column(name = "lang_key", length = 10)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
package io.flexwork.modules.usermanagement.domain;

public enum UserStatus {
ACTIVE,
PENDING
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import io.flexwork.modules.usermanagement.UserNotActivatedException;
import io.flexwork.modules.usermanagement.domain.Authority;
import io.flexwork.modules.usermanagement.domain.User;
import io.flexwork.modules.usermanagement.domain.UserStatus;
import io.flexwork.modules.usermanagement.repository.UserRepository;
import io.flexwork.modules.usermanagement.service.dto.FwUserDetails;
import java.util.List;
Expand Down Expand Up @@ -49,7 +50,7 @@ public UserDetails loadUserByUsername(final String email) {
}

private FwUserDetails createSpringSecurityUser(String lowercaseLogin, User user) {
if (!user.isActivated()) {
if (!user.getStatus().equals(UserStatus.ACTIVE)) {
throw new UserNotActivatedException("User " + lowercaseLogin + " was not activated");
}
List<SimpleGrantedAuthority> grantedAuthorities =
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,11 @@

import static io.flexwork.db.DbConstants.DEFAULT_TENANT;

import io.flexwork.config.FlexworkProfiles;
import io.flexwork.db.service.LiquibaseService;
import io.flexwork.modules.usermanagement.domain.Tenant;
import io.flexwork.modules.usermanagement.repository.TenantRepository;
import java.util.Optional;
import java.util.Random;
import java.util.UUID;
import java.util.*;
import lombok.SneakyThrows;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
Expand Down Expand Up @@ -60,7 +59,8 @@ public Tenant registerNewTenant(Tenant tenant) {
tenant.setNameId(uuid);

tenantRepository.save(tenant);
liquibaseService.createTenantDbSchema(tenant.getNameId());
liquibaseService.createTenantDbSchema(
tenant.getNameId(), List.of(FlexworkProfiles.SPRING_PROFILE_PRODUCTION));
return tenant;
}

Expand Down
Loading

0 comments on commit dbbeb33

Please sign in to comment.