Skip to content

Commit

Permalink
Hide AuthenticationDetails from BL
Browse files Browse the repository at this point in the history
### What's done:
- small refactoring to hide AuthenticationDetails to get userId and identitySource

It's part of #2336
  • Loading branch information
nulls committed Jul 20, 2023
1 parent 480574c commit e347939
Show file tree
Hide file tree
Showing 17 changed files with 54 additions and 57 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -41,19 +41,19 @@ fun Authentication.username(): String = when (principal) {
* @return identitySource
* @throws BadCredentialsException
*/
fun Authentication.identitySource(): String {
val identitySource = (this.details as AuthenticationDetails).identitySource
if (identitySource == null || !this.name.startsWith("$identitySource:")) {
throw BadCredentialsException(this.name)
}
return identitySource
}
fun Authentication.identitySource(): String? = (this.details as AuthenticationDetails).identitySource

/**
* @return pair of username and identitySource from this [Authentication].
* @throws BadCredentialsException
*/
fun Authentication.extractUserNameAndIdentitySource(): Pair<String, String> = this.username() to this.identitySource()
fun Authentication.extractUserNameAndIdentitySource(): Pair<String, String> = this.username() to run {
val identitySource = this.identitySource()
if (identitySource == null || !this.name.startsWith("$identitySource:")) {
throw BadCredentialsException(this.name)
}
identitySource
}

/**
* Convert [Authentication] to [User] based on convention in backend.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

package com.saveourtool.save.backend.controllers

import com.saveourtool.save.authservice.utils.AuthenticationDetails
import com.saveourtool.save.authservice.utils.userId
import com.saveourtool.save.backend.service.*
import com.saveourtool.save.configs.ApiSwaggerSupport
import com.saveourtool.save.configs.RequiresAuthorizationSourceHeader
Expand Down Expand Up @@ -111,7 +111,7 @@ class LnkContestProjectController(
@PathVariable contestName: String,
authentication: Authentication,
): Mono<List<String>> = Mono.fromCallable {
lnkUserProjectService.getProjectsByUserIdAndStatuses((authentication.details as AuthenticationDetails).id).filter { it.public }
lnkUserProjectService.getProjectsByUserIdAndStatuses(authentication.userId()).filter { it.public }
}
.map { userProjects ->
userProjects to lnkContestProjectService.getProjectsFromListAndContest(contestName, userProjects).map { it.project }
Expand Down Expand Up @@ -295,7 +295,7 @@ class LnkContestProjectController(
"Contest with name $contestName was not found."
}
.map { contest ->
contest to lnkUserProjectService.getProjectsByUserIdAndStatuses((authentication.details as AuthenticationDetails).id).map { it.requiredId() }
contest to lnkUserProjectService.getProjectsByUserIdAndStatuses(authentication.userId()).map { it.requiredId() }
}
.flatMapMany { (contest, projectIds) ->
blockingToFlux {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@

package com.saveourtool.save.backend.controllers

import com.saveourtool.save.authservice.utils.AuthenticationDetails
import com.saveourtool.save.authservice.utils.toUser
import com.saveourtool.save.authservice.utils.userId
import com.saveourtool.save.backend.security.OrganizationPermissionEvaluator
import com.saveourtool.save.backend.service.LnkUserOrganizationService
import com.saveourtool.save.backend.service.OrganizationService
Expand Down Expand Up @@ -244,7 +244,7 @@ class LnkUserOrganizationController(
fun getAllUsersOrganizationsThatCanCreateContests(
authentication: Authentication,
): Flux<Organization> = Flux.fromIterable(
lnkUserOrganizationService.getSuperOrganizationsWithRole((authentication.details as AuthenticationDetails).id)
lnkUserOrganizationService.getSuperOrganizationsWithRole(authentication.userId())
)

@PostMapping("/by-filters")
Expand All @@ -265,7 +265,7 @@ class LnkUserOrganizationController(
@RequestBody organizationFilter: OrganizationFilter,
authentication: Authentication,
): Flux<OrganizationWithUsers> = Mono.justOrEmpty(
lnkUserOrganizationService.getUserById((authentication.details as AuthenticationDetails).id)
lnkUserOrganizationService.getUserById(authentication.userId())
)
.switchIfEmptyToNotFound()
.flatMapIterable {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

package com.saveourtool.save.backend.controllers

import com.saveourtool.save.authservice.utils.AuthenticationDetails
import com.saveourtool.save.authservice.utils.userId
import com.saveourtool.save.backend.security.ProjectPermissionEvaluator
import com.saveourtool.save.backend.service.LnkUserProjectService
import com.saveourtool.save.backend.service.ProjectService
Expand Down Expand Up @@ -58,16 +58,13 @@ class LnkUserProjectController(
)
@PreAuthorize("permitAll()")
@ApiResponse(responseCode = "200", description = "Successfully fetched users from project.")
fun getProjectsOfCurrentUser(authentication: Authentication): Flux<ProjectDto> {
val userIdFromAuth = (authentication.details as AuthenticationDetails).id
return Flux.fromIterable(
lnkUserProjectService.getProjectsByUserIdAndStatuses(userIdFromAuth)
)
.filter {
it.public
}
.map { it.toDto() }
}
fun getProjectsOfCurrentUser(authentication: Authentication): Flux<ProjectDto> = Flux.fromIterable(
lnkUserProjectService.getProjectsByUserIdAndStatuses(authentication.userId())
)
.filter {
it.public
}
.map { it.toDto() }

@GetMapping(path = ["/{organizationName}/{projectName}/users"])
@RequiresAuthorizationSourceHeader
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
package com.saveourtool.save.backend.controllers

import com.saveourtool.save.authservice.utils.AuthenticationDetails
import com.saveourtool.save.authservice.utils.userId
import com.saveourtool.save.backend.configs.ConfigProperties
import com.saveourtool.save.backend.security.OrganizationPermissionEvaluator
import com.saveourtool.save.backend.service.*
Expand Down Expand Up @@ -136,7 +136,7 @@ internal class OrganizationController(
authentication: Authentication?,
): Flux<OrganizationDto> = authentication.toMono()
.map { auth ->
(auth.details as AuthenticationDetails).id
auth.userId()
}
.flatMapMany {
lnkUserOrganizationService.findAllByAuthenticationAndStatuses(it)
Expand Down Expand Up @@ -239,7 +239,7 @@ internal class OrganizationController(
}
.map { (organizationId, organizationStatus) ->
lnkUserOrganizationService.setRoleByIds(
(authentication.details as AuthenticationDetails).id,
authentication.userId(),
organizationId,
Role.OWNER,
)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
package com.saveourtool.save.backend.controllers

import com.saveourtool.save.authservice.utils.AuthenticationDetails
import com.saveourtool.save.authservice.utils.userId
import com.saveourtool.save.backend.security.ProjectPermissionEvaluator
import com.saveourtool.save.backend.service.LnkUserProjectService
import com.saveourtool.save.backend.service.OrganizationService
Expand Down Expand Up @@ -169,7 +169,7 @@ class ProjectController(
))
}
.map { (projectId, status) ->
lnkUserProjectService.setRoleByIds((authentication.details as AuthenticationDetails).id, projectId, Role.OWNER)
lnkUserProjectService.setRoleByIds(authentication.userId(), projectId, Role.OWNER)
ResponseEntity.ok(status.message)
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
package com.saveourtool.save.backend.controllers

import com.saveourtool.save.authservice.utils.AuthenticationDetails
import com.saveourtool.save.authservice.utils.userId
import com.saveourtool.save.backend.repository.OriginalLoginRepository
import com.saveourtool.save.backend.repository.UserRepository
import com.saveourtool.save.backend.service.UserDetailsService
Expand Down Expand Up @@ -105,8 +105,7 @@ class UsersDetailsController(
fun saveUser(@RequestBody newUserInfo: UserInfo, authentication: Authentication): Mono<StringResponse> = Mono.just(newUserInfo)
.map {
val user: User = userRepository.findByName(newUserInfo.oldName ?: newUserInfo.name).orNotFound()
val userId = (authentication.details as AuthenticationDetails).id
val response = if (user.id == userId) {
val response = if (user.id == authentication.userId()) {
userDetailsService.saveUser(user.apply {
name = newUserInfo.name
email = newUserInfo.email
Expand Down Expand Up @@ -142,7 +141,7 @@ class UsersDetailsController(
@PreAuthorize("isAuthenticated()")
fun saveUserToken(@PathVariable userName: String, @RequestBody token: String, authentication: Authentication): Mono<StringResponse> {
val user = userRepository.findByName(userName).orNotFound()
val userId = (authentication.details as AuthenticationDetails).id
val userId = authentication.userId()
val response = if (user.id == userId) {
userRepository.save(user.apply {
password = "{bcrypt}${BCryptPasswordEncoder().encode(token)}"
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
package com.saveourtool.save.backend.security

import com.saveourtool.save.authservice.utils.AuthenticationDetails
import com.saveourtool.save.authservice.utils.userId
import com.saveourtool.save.backend.service.LnkUserOrganizationService
import com.saveourtool.save.backend.utils.hasRole
import com.saveourtool.save.domain.Role
Expand All @@ -27,7 +27,7 @@ class OrganizationPermissionEvaluator(
*/
fun hasOrganizationRole(authentication: Authentication?, organization: Organization, role: Role): Boolean {
authentication ?: return false
val userId = (authentication.details as AuthenticationDetails).id
val userId = authentication.userId()
if (authentication.hasRole(Role.SUPER_ADMIN)) {
return true
}
Expand Down Expand Up @@ -59,7 +59,7 @@ class OrganizationPermissionEvaluator(
*/
fun hasPermission(authentication: Authentication?, organization: Organization, permission: Permission): Boolean {
authentication ?: return permission == Permission.READ
val userId = (authentication.details as AuthenticationDetails).id
val userId = authentication.userId()
if (authentication.hasRole(Role.SUPER_ADMIN)) {
return true
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
package com.saveourtool.save.backend.security

import com.saveourtool.save.authservice.utils.AuthenticationDetails
import com.saveourtool.save.authservice.utils.userId
import com.saveourtool.save.backend.repository.LnkUserProjectRepository
import com.saveourtool.save.backend.service.LnkUserOrganizationService
import com.saveourtool.save.backend.service.LnkUserProjectService
Expand Down Expand Up @@ -59,7 +59,7 @@ class ProjectPermissionEvaluator(
return true
}

val userId = (authentication.details as AuthenticationDetails).id
val userId = authentication.userId()
val organizationRole = lnkUserOrganizationService.findRoleByUserIdAndOrganization(userId, project.organization)
val projectRole = lnkUserProjectService.findRoleByUserIdAndProject(userId, project)

Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
package com.saveourtool.save.backend.security

import com.saveourtool.save.authservice.utils.AuthenticationDetails
import com.saveourtool.save.authservice.utils.userId
import com.saveourtool.save.backend.service.vulnerability.VulnerabilityService
import com.saveourtool.save.backend.utils.hasRole
import com.saveourtool.save.domain.Role
Expand Down Expand Up @@ -48,6 +48,6 @@ class VulnerabilityPermissionEvaluator(
val vulnerability = vulnerabilityService.findByName(vulnerabilityName).orNotFound { "Not found vulnerability $vulnerabilityName" }
val linkUsers = vulnerabilityService.getUsers(vulnerability.requiredId()).map { it.user.name }

return vulnerability.userId == (authentication.details as AuthenticationDetails).id || authentication.name in linkUsers
return vulnerability.userId == authentication.userId() || authentication.name in linkUsers
}
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
package com.saveourtool.save.backend.service

import com.saveourtool.save.authservice.utils.AuthenticationDetails
import com.saveourtool.save.authservice.utils.userId
import com.saveourtool.save.backend.repository.CommentRepository
import com.saveourtool.save.backend.repository.UserRepository
import com.saveourtool.save.entities.Comment
Expand Down Expand Up @@ -28,7 +28,7 @@ class CommentService(
*/
@Transactional
fun saveComment(comment: CommentDto, authentication: Authentication) {
val userId = (authentication.details as AuthenticationDetails).id
val userId = authentication.userId()
val user = userRepository.getByIdOrNotFound(userId)

val newComment = Comment(
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
package com.saveourtool.save.backend.service

import com.saveourtool.save.authservice.utils.AuthenticationDetails
import com.saveourtool.save.authservice.utils.userId
import com.saveourtool.save.backend.repository.UserRepository
import com.saveourtool.save.backend.repository.contest.ContestSampleFieldRepository
import com.saveourtool.save.backend.repository.contest.ContestSampleRepository
Expand Down Expand Up @@ -34,7 +34,7 @@ class ContestSampleService(
contestSampleDto: ContestSampleDto,
authentication: Authentication,
) {
val userId = (authentication.details as AuthenticationDetails).id
val userId = authentication.userId()
val user = userRepository.getByIdOrNotFound(userId)
val contestSample = ContestSample(
name = contestSampleDto.name,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
package com.saveourtool.save.backend.service

import com.saveourtool.save.authservice.utils.AuthenticationDetails
import com.saveourtool.save.authservice.utils.userId
import com.saveourtool.save.backend.repository.LnkUserOrganizationRepository
import com.saveourtool.save.backend.repository.UserRepository
import com.saveourtool.save.domain.Role
Expand Down Expand Up @@ -171,7 +171,7 @@ class LnkUserOrganizationService(
* @return the highest of two roles: the one in [organization] and global one.
*/
fun getGlobalRoleOrOrganizationRole(authentication: Authentication, organization: Organization): Role {
val selfId = (authentication.details as AuthenticationDetails).id
val selfId = authentication.userId()
val selfGlobalRole = userDetailsService.getGlobalRole(authentication)
val selfOrganizationRole = findRoleByUserIdAndOrganization(selfId, organization)
return getHighestRole(selfOrganizationRole, selfGlobalRole)
Expand All @@ -183,7 +183,7 @@ class LnkUserOrganizationService(
* @return the highest of two roles: the one in organization with name [organizationName] and global one.
*/
fun getGlobalRoleOrOrganizationRole(authentication: Authentication, organizationName: String): Role {
val selfId = (authentication.details as AuthenticationDetails).id
val selfId = authentication.userId()
val selfGlobalRole = userDetailsService.getGlobalRole(authentication)
val selfOrganizationRole = findRoleByUserIdAndOrganizationName(selfId, organizationName)
return getHighestRole(selfOrganizationRole, selfGlobalRole)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
package com.saveourtool.save.backend.service

import com.saveourtool.save.authservice.utils.AuthenticationDetails
import com.saveourtool.save.authservice.utils.userId
import com.saveourtool.save.backend.repository.LnkUserProjectRepository
import com.saveourtool.save.backend.repository.UserRepository
import com.saveourtool.save.domain.Role
Expand Down Expand Up @@ -129,7 +129,7 @@ class LnkUserProjectService(
* @return the highest of two roles: the one in [project] and global one.
*/
fun getGlobalRoleOrProjectRole(authentication: Authentication, project: Project): Role {
val selfId = (authentication.details as AuthenticationDetails).id
val selfId = authentication.userId()
val selfGlobalRole = userDetailsService.getGlobalRole(authentication)
val selfOrganizationRole = findRoleByUserIdAndProject(selfId, project)
return getHighestRole(selfOrganizationRole, selfGlobalRole)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
package com.saveourtool.save.backend.service

import com.saveourtool.save.authservice.utils.AuthenticationDetails
import com.saveourtool.save.authservice.utils.userId
import com.saveourtool.save.backend.repository.ProjectProblemRepository
import com.saveourtool.save.backend.repository.ProjectRepository
import com.saveourtool.save.backend.repository.UserRepository
Expand Down Expand Up @@ -51,7 +51,7 @@ class ProjectProblemService(
fun saveProjectProblem(problem: ProjectProblemDto, authentication: Authentication) {
val vulnerability = problem.vulnerabilityName?.let { vulnerabilityRepository.findByName(it) }
val project = projectRepository.findByNameAndOrganizationName(problem.projectName, problem.organizationName).orNotFound()
val userId = (authentication.details as AuthenticationDetails).id
val userId = authentication.userId()
val user = userRepository.getByIdOrNotFound(userId)

val projectProblem = ProjectProblem(
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
package com.saveourtool.save.backend.service.vulnerability

import com.saveourtool.save.authservice.utils.AuthenticationDetails
import com.saveourtool.save.authservice.utils.userId
import com.saveourtool.save.backend.repository.OrganizationRepository
import com.saveourtool.save.backend.repository.UserRepository
import com.saveourtool.save.backend.repository.vulnerability.LnkVulnerabilityUserRepository
Expand Down Expand Up @@ -116,7 +116,7 @@ class VulnerabilityService(
}

val ownerPredicate = authentication?.let {
val userId = (authentication.details as AuthenticationDetails).id
val userId = authentication.userId()
if (isOwner) {
cb.equal(root.get<Vulnerability>("userId"), userId)
} else {
Expand Down Expand Up @@ -198,7 +198,7 @@ class VulnerabilityService(
vulnerabilityDto: VulnerabilityDto,
authentication: Authentication,
) {
val userId = (authentication.details as AuthenticationDetails).id
val userId = authentication.userId()
val user = userRepository.getByIdOrNotFound(userId)
val organizationNew = vulnerabilityDto.organization?.name?.let { organizationRepository.findByName(it) }
val vulnerability = Vulnerability(
Expand Down Expand Up @@ -360,7 +360,7 @@ class VulnerabilityService(
vulnerabilityDateDto: VulnerabilityDateDto,
authentication: Authentication,
) {
val userId = (authentication.details as AuthenticationDetails).id
val userId = authentication.userId()
val user = userRepository.getByIdOrNotFound(userId)

vulnerabilityRepository.findByName(vulnerabilityDateDto.vulnerabilityName)?.let { vulnerability ->
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package com.saveourtool.save.backend.security

import com.saveourtool.save.authservice.security.CustomAuthenticationBasicConverter
import com.saveourtool.save.authservice.utils.AuthenticationDetails
import com.saveourtool.save.authservice.utils.identitySource
import com.saveourtool.save.utils.AUTHORIZATION_SOURCE
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.Test
Expand All @@ -28,7 +29,7 @@ class ConverterTest {
Assertions.assertInstanceOf(UsernamePasswordAuthenticationToken::class.java, authentication)
Assertions.assertInstanceOf(AuthenticationDetails::class.java, authentication.details)
Assertions.assertEquals("basic:user", authentication.principal)
Assertions.assertEquals("basic", (authentication.details as AuthenticationDetails).identitySource)
Assertions.assertEquals("basic", authentication.identitySource())
}
}

Expand Down

0 comments on commit e347939

Please sign in to comment.