diff --git a/src/main/kotlin/com/wafflestudio/csereal/core/user/database/UserEntity.kt b/src/main/kotlin/com/wafflestudio/csereal/core/user/database/UserEntity.kt index a7e1e1d9..731375ca 100644 --- a/src/main/kotlin/com/wafflestudio/csereal/core/user/database/UserEntity.kt +++ b/src/main/kotlin/com/wafflestudio/csereal/core/user/database/UserEntity.kt @@ -14,7 +14,7 @@ class UserEntity( val studentId: String, @Enumerated(EnumType.STRING) - val role: Role? + var role: Role? ) : BaseTimeEntity() diff --git a/src/main/kotlin/com/wafflestudio/csereal/core/user/service/CustomOidcUserService.kt b/src/main/kotlin/com/wafflestudio/csereal/core/user/service/CustomOidcUserService.kt index 3a0609a4..f0954e18 100644 --- a/src/main/kotlin/com/wafflestudio/csereal/core/user/service/CustomOidcUserService.kt +++ b/src/main/kotlin/com/wafflestudio/csereal/core/user/service/CustomOidcUserService.kt @@ -25,6 +25,7 @@ class CustomOidcUserService( private val restTemplate: RestTemplate ) : OAuth2UserService { + @Transactional override fun loadUser(userRequest: OidcUserRequest): OidcUser { val oidcUser = DefaultOidcUser( userRequest.clientRegistration.scopes.map { SimpleGrantedAuthority("SCOPE_$it") }, @@ -32,13 +33,26 @@ class CustomOidcUserService( ) val username = oidcUser.idToken.getClaim("username") - val user = userRepository.findByUsername(username) + var user = userRepository.findByUsername(username) if (user == null) { val userInfoAttributes = fetchUserInfo(userRequest) - createUser(username, userInfoAttributes) + user = createUser(username, userInfoAttributes) + } + + val groups = oidcUser.idToken.getClaim>("groups") + val role = if ("staff" in groups) { + Role.ROLE_STAFF + } else if ("professor" in groups) { + Role.ROLE_PROFESSOR + } else if ("graduate" in groups) { + Role.ROLE_GRADUATE + } else { + null } + user.role = role + return oidcUser } @@ -67,31 +81,21 @@ class CustomOidcUserService( return userInfoResponse.body ?: emptyMap() } - @Transactional - fun createUser(username: String, userInfo: Map) { + private fun createUser(username: String, userInfo: Map): UserEntity { val name = userInfo["name"] as String val email = userInfo["email"] as String val studentId = userInfo["student_id"] as String - val groups = userInfo["groups"] as List - val role = if ("staff" in groups) { - Role.ROLE_STAFF - } else if ("professor" in groups) { - Role.ROLE_PROFESSOR - } else if ("graduate" in groups) { - Role.ROLE_GRADUATE - } else { - null - } - val newUser = UserEntity( username = username, name = name, email = email, studentId = studentId, - role = role + role = null ) userRepository.save(newUser) + + return newUser } }