Skip to content

Commit 345bfec

Browse files
committed
seed admin user with flyway
1 parent e791377 commit 345bfec

File tree

7 files changed

+87
-66
lines changed

7 files changed

+87
-66
lines changed

backend/spring-boot/src/main/java/org/bugzkit/api/admin/service/impl/UserServiceImpl.java

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -33,21 +33,21 @@ public class UserServiceImpl implements UserService {
3333
private final RoleRepository roleRepository;
3434
private final AccessTokenService accessTokenService;
3535
private final RefreshTokenService refreshTokenService;
36-
private final PasswordEncoder bCryptPasswordEncoder;
36+
private final PasswordEncoder passwordEncoder;
3737
private final UserMapper userMapper;
3838

3939
public UserServiceImpl(
4040
UserRepository userRepository,
4141
RoleRepository roleRepository,
4242
AccessTokenService accessTokenService,
4343
RefreshTokenService refreshTokenService,
44-
PasswordEncoder bCryptPasswordEncoder,
44+
PasswordEncoder passwordEncoder,
4545
UserMapper userMapper) {
4646
this.userRepository = userRepository;
4747
this.roleRepository = roleRepository;
4848
this.accessTokenService = accessTokenService;
4949
this.refreshTokenService = refreshTokenService;
50-
this.bCryptPasswordEncoder = bCryptPasswordEncoder;
50+
this.passwordEncoder = passwordEncoder;
5151
this.userMapper = userMapper;
5252
}
5353

@@ -66,7 +66,7 @@ public UserDTO create(UserRequest userRequest) {
6666
User.builder()
6767
.username(userRequest.username())
6868
.email(userRequest.email())
69-
.password(bCryptPasswordEncoder.encode(userRequest.password()))
69+
.password(passwordEncoder.encode(userRequest.password()))
7070
.active(userRequest.active())
7171
.lock(userRequest.lock())
7272
.roles(new HashSet<>(roleRepository.findAllByNameIn(userRequest.roleNames())))
@@ -186,10 +186,9 @@ private void setEmail(User user, String email) {
186186
}
187187

188188
private void setPassword(User user, String password) {
189-
if (user.getPassword() != null && bCryptPasswordEncoder.matches(password, user.getPassword()))
190-
return;
189+
if (user.getPassword() != null && passwordEncoder.matches(password, user.getPassword())) return;
191190

192-
user.setPassword(bCryptPasswordEncoder.encode(password));
191+
user.setPassword(passwordEncoder.encode(password));
193192
if (user.getId() != null) {
194193
deleteAuthTokens(user.getId());
195194
log.info(

backend/spring-boot/src/main/java/org/bugzkit/api/auth/service/impl/AuthServiceImpl.java

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@
3838
public class AuthServiceImpl implements AuthService {
3939
private final UserRepository userRepository;
4040
private final RoleRepository roleRepository;
41-
private final PasswordEncoder bCryptPasswordEncoder;
41+
private final PasswordEncoder passwordEncoder;
4242
private final AuthenticationManager authenticationManager;
4343
private final AccessTokenService accessTokenService;
4444
private final RefreshTokenService refreshTokenService;
@@ -50,7 +50,7 @@ public class AuthServiceImpl implements AuthService {
5050
public AuthServiceImpl(
5151
UserRepository userRepository,
5252
RoleRepository roleRepository,
53-
PasswordEncoder bCryptPasswordEncoder,
53+
PasswordEncoder passwordEncoder,
5454
AuthenticationManager authenticationManager,
5555
AccessTokenService accessTokenService,
5656
RefreshTokenService refreshTokenService,
@@ -60,7 +60,7 @@ public AuthServiceImpl(
6060
UserMapper userMapper) {
6161
this.userRepository = userRepository;
6262
this.roleRepository = roleRepository;
63-
this.bCryptPasswordEncoder = bCryptPasswordEncoder;
63+
this.passwordEncoder = passwordEncoder;
6464
this.authenticationManager = authenticationManager;
6565
this.accessTokenService = accessTokenService;
6666
this.refreshTokenService = refreshTokenService;
@@ -116,7 +116,7 @@ private User createUser(RegisterUserRequest registerUserRequest) {
116116
return User.builder()
117117
.username(registerUserRequest.username())
118118
.email(registerUserRequest.email())
119-
.password(bCryptPasswordEncoder.encode(registerUserRequest.password()))
119+
.password(passwordEncoder.encode(registerUserRequest.password()))
120120
.roles(Collections.singleton(roles))
121121
.build();
122122
}
@@ -184,7 +184,7 @@ public void resetPassword(ResetPasswordRequest resetPasswordRequest) {
184184
userId);
185185
return new BadRequestException("auth.tokenInvalid");
186186
});
187-
user.setPassword(bCryptPasswordEncoder.encode(resetPasswordRequest.password()));
187+
user.setPassword(passwordEncoder.encode(resetPasswordRequest.password()));
188188
accessTokenService.invalidateAllByUserId(user.getId());
189189
refreshTokenService.deleteAllByUserId(user.getId());
190190
userRepository.save(user);

backend/spring-boot/src/main/java/org/bugzkit/api/shared/config/DataInit.java renamed to backend/spring-boot/src/main/java/org/bugzkit/api/shared/config/InitDevData.java

Lines changed: 9 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,7 @@
22

33
import java.util.Collections;
44
import java.util.List;
5-
import java.util.Set;
65
import net.datafaker.Faker;
7-
import org.bugzkit.api.user.model.Role;
86
import org.bugzkit.api.user.model.Role.RoleName;
97
import org.bugzkit.api.user.model.User;
108
import org.bugzkit.api.user.repository.RoleRepository;
@@ -13,67 +11,38 @@
1311
import org.springframework.boot.ApplicationArguments;
1412
import org.springframework.boot.ApplicationRunner;
1513
import org.springframework.context.annotation.Profile;
16-
import org.springframework.core.env.Environment;
1714
import org.springframework.security.crypto.password.PasswordEncoder;
1815
import org.springframework.stereotype.Component;
1916

20-
@Profile({"dev", "prod"})
17+
@Profile("dev")
2118
@Component
22-
public class DataInit implements ApplicationRunner {
19+
public class InitDevData implements ApplicationRunner {
2320
private final UserRepository userRepository;
2421
private final RoleRepository roleRepository;
25-
private final PasswordEncoder bCryptPasswordEncoder;
26-
private final Environment environment;
22+
private final PasswordEncoder passwordEncoder;
2723
private final Faker faker;
28-
private Role userRole;
29-
private Role adminRole;
3024

3125
@Value("${spring.security.user.password}")
3226
private String password;
3327

34-
public DataInit(
28+
public InitDevData(
3529
UserRepository userRepository,
3630
RoleRepository roleRepository,
37-
PasswordEncoder bCryptPasswordEncoder,
38-
Environment environment) {
31+
PasswordEncoder passwordEncoder) {
3932
this.userRepository = userRepository;
4033
this.roleRepository = roleRepository;
41-
this.bCryptPasswordEncoder = bCryptPasswordEncoder;
42-
this.environment = environment;
34+
this.passwordEncoder = passwordEncoder;
4335
this.faker = new Faker();
4436
}
4537

4638
@Override
4739
public void run(ApplicationArguments args) {
48-
getRoles();
49-
seedUsers();
50-
}
51-
52-
private void getRoles() {
53-
userRole = roleRepository.findByName(RoleName.USER).orElseThrow();
54-
adminRole = roleRepository.findByName(RoleName.ADMIN).orElseThrow();
55-
}
56-
57-
private void seedUsers() {
58-
if (!userRepository.existsByUsername("admin"))
59-
userRepository.save(
60-
User.builder()
61-
.username("admin")
62-
.email("office@bugzkit.com")
63-
.password(bCryptPasswordEncoder.encode(password))
64-
.active(true)
65-
.lock(false)
66-
.roles(Set.of(userRole, adminRole))
67-
.build());
68-
if (environment.getActiveProfiles()[0].equals("dev")) devUsers();
69-
}
70-
71-
private void devUsers() {
40+
final var userRole = roleRepository.findByName(RoleName.USER).orElseThrow();
7241
userRepository.save(
7342
User.builder()
7443
.username("user")
7544
.email("user@localhost")
76-
.password(bCryptPasswordEncoder.encode(password))
45+
.password(passwordEncoder.encode(password))
7746
.active(true)
7847
.lock(false)
7948
.roles(Collections.singleton(userRole))
@@ -85,7 +54,7 @@ private void devUsers() {
8554
User.builder()
8655
.username(faker.credentials().username())
8756
.email(faker.internet().emailAddress())
88-
.password(bCryptPasswordEncoder.encode(password))
57+
.password(passwordEncoder.encode(password))
8958
.active(true)
9059
.lock(false)
9160
.roles(Collections.singleton(userRole))
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
package org.bugzkit.api.shared.config;
2+
3+
import org.springframework.context.annotation.Bean;
4+
import org.springframework.context.annotation.Configuration;
5+
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
6+
import org.springframework.security.crypto.password.PasswordEncoder;
7+
8+
@Configuration
9+
public class PasswordEncoderConfig {
10+
@Bean
11+
public PasswordEncoder passwordEncoder() {
12+
return new BCryptPasswordEncoder(12);
13+
}
14+
}

backend/spring-boot/src/main/java/org/bugzkit/api/shared/config/SecurityConfig.java

Lines changed: 5 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,6 @@
1919
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
2020
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
2121
import org.springframework.security.config.http.SessionCreationPolicy;
22-
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
2322
import org.springframework.security.crypto.password.PasswordEncoder;
2423
import org.springframework.security.web.SecurityFilterChain;
2524
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
@@ -51,31 +50,29 @@ public class SecurityConfig {
5150
private final OAuth2SuccessHandler oAuth2SuccessHandler;
5251
private final OAuth2FailureHandler oAuth2FailureHandler;
5352
private final OAuth2UserService oAuth2UserService;
53+
private final PasswordEncoder passwordEncoder;
5454

5555
public SecurityConfig(
5656
JWTFilter jwtFilter,
5757
UserDetailsServiceImpl userDetailsService,
5858
CustomAuthenticationEntryPoint customAuthenticationEntryPoint,
5959
OAuth2SuccessHandler oAuth2SuccessHandler,
6060
OAuth2FailureHandler oAuth2FailureHandler,
61-
OAuth2UserService oAuth2UserService) {
61+
OAuth2UserService oAuth2UserService,
62+
PasswordEncoder passwordEncoder) {
6263
this.jwtFilter = jwtFilter;
6364
this.userDetailsService = userDetailsService;
6465
this.customAuthenticationEntryPoint = customAuthenticationEntryPoint;
6566
this.oAuth2SuccessHandler = oAuth2SuccessHandler;
6667
this.oAuth2FailureHandler = oAuth2FailureHandler;
6768
this.oAuth2UserService = oAuth2UserService;
68-
}
69-
70-
@Bean
71-
public PasswordEncoder bCryptPasswordEncoder() {
72-
return new BCryptPasswordEncoder(12);
69+
this.passwordEncoder = passwordEncoder;
7370
}
7471

7572
@Bean
7673
public AuthenticationManager authenticationManager() {
7774
DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider(userDetailsService);
78-
authProvider.setPasswordEncoder(bCryptPasswordEncoder());
75+
authProvider.setPasswordEncoder(passwordEncoder);
7976
return new ProviderManager(authProvider);
8077
}
8178

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
package org.bugzkit.api.shared.db.migration;
2+
3+
import org.flywaydb.core.api.migration.BaseJavaMigration;
4+
import org.flywaydb.core.api.migration.Context;
5+
import org.springframework.beans.factory.annotation.Value;
6+
import org.springframework.security.crypto.password.PasswordEncoder;
7+
import org.springframework.stereotype.Component;
8+
9+
@Component
10+
public class V3__seed_admin extends BaseJavaMigration {
11+
12+
private final PasswordEncoder passwordEncoder;
13+
14+
@Value("${spring.security.user.password}")
15+
private String password;
16+
17+
public V3__seed_admin(PasswordEncoder passwordEncoder) {
18+
this.passwordEncoder = passwordEncoder;
19+
}
20+
21+
@Override
22+
public void migrate(Context context) throws Exception {
23+
final var hash = passwordEncoder.encode(password);
24+
try (var stmt =
25+
context
26+
.getConnection()
27+
.prepareStatement(
28+
"INSERT INTO users (username, email, password, active, lock, created_at)"
29+
+ " VALUES ('admin', 'office@bugzkit.com', ?, true, false, NOW())")) {
30+
stmt.setString(1, hash);
31+
stmt.executeUpdate();
32+
}
33+
try (var stmt =
34+
context
35+
.getConnection()
36+
.prepareStatement(
37+
"INSERT INTO user_roles (user_id, role_id)"
38+
+ " SELECT u.user_id, r.role_id FROM users u, roles r"
39+
+ " WHERE u.username = 'admin' AND r.role_name IN ('USER', 'ADMIN')")) {
40+
stmt.executeUpdate();
41+
}
42+
}
43+
}

backend/spring-boot/src/main/java/org/bugzkit/api/user/service/impl/ProfileServiceImpl.java

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@
2424
@Service
2525
public class ProfileServiceImpl implements ProfileService {
2626
private final UserRepository userRepository;
27-
private final PasswordEncoder bCryptPasswordEncoder;
27+
private final PasswordEncoder passwordEncoder;
2828
private final AccessTokenService accessTokenService;
2929
private final RefreshTokenService refreshTokenService;
3030
private final VerificationTokenService verificationTokenService;
@@ -33,14 +33,14 @@ public class ProfileServiceImpl implements ProfileService {
3333

3434
public ProfileServiceImpl(
3535
UserRepository userRepository,
36-
PasswordEncoder bCryptPasswordEncoder,
36+
PasswordEncoder passwordEncoder,
3737
AccessTokenService accessTokenService,
3838
RefreshTokenService refreshTokenService,
3939
VerificationTokenService verificationTokenService,
4040
DeviceService deviceService,
4141
UserMapper userMapper) {
4242
this.userRepository = userRepository;
43-
this.bCryptPasswordEncoder = bCryptPasswordEncoder;
43+
this.passwordEncoder = passwordEncoder;
4444
this.accessTokenService = accessTokenService;
4545
this.refreshTokenService = refreshTokenService;
4646
this.verificationTokenService = verificationTokenService;
@@ -129,12 +129,11 @@ public void changePassword(ChangePasswordRequest changePasswordRequest) {
129129
userId);
130130
return new UnauthorizedException("auth.tokenInvalid");
131131
});
132-
if (!bCryptPasswordEncoder.matches(
133-
changePasswordRequest.currentPassword(), user.getPassword())) {
132+
if (!passwordEncoder.matches(changePasswordRequest.currentPassword(), user.getPassword())) {
134133
log.warn("Password change failed for user '{}': current password is wrong", userId);
135134
throw new BadRequestException("user.currentPasswordWrong");
136135
}
137-
user.setPassword(bCryptPasswordEncoder.encode(changePasswordRequest.newPassword()));
136+
user.setPassword(passwordEncoder.encode(changePasswordRequest.newPassword()));
138137
deleteAuthTokens(userId);
139138
userRepository.save(user);
140139
log.info("Password changed for user '{}', all tokens invalidated", userId);

0 commit comments

Comments
 (0)