Skip to content

Commit

Permalink
Brain-up#2406 code refactoring
Browse files Browse the repository at this point in the history
  • Loading branch information
naXa777 committed Oct 24, 2023
1 parent 64b21d0 commit 62cabf2
Show file tree
Hide file tree
Showing 5 changed files with 103 additions and 16 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -37,16 +37,9 @@ class FirebaseTokenAuthenticationFilter(
filterChain: FilterChain
) {
verifyToken(request)
markVisit()
filterChain.doFilter(request, response)
}

private fun markVisit() {
if (SecurityContextHolder.getContext().authentication != null) {
userAccountService.markVisitForCurrentUser()
}
}

private fun verifyToken(request: HttpServletRequest) {
val token: String? = tokenHelperUtils.getBearerToken(request)
try {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package com.epam.brn.auth.filter

import com.epam.brn.service.UserAccountService
import org.apache.logging.log4j.kotlin.logger
import org.springframework.security.core.context.SecurityContextHolder
import org.springframework.stereotype.Component
import org.springframework.web.filter.OncePerRequestFilter
import javax.servlet.FilterChain
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

@Component
class RememberLastVisitFilter(
private val userAccountService: UserAccountService,
) : OncePerRequestFilter() {

private val log = logger()

override fun doFilterInternal(
request: HttpServletRequest,
response: HttpServletResponse,
filterChain: FilterChain
) {
markVisit()
filterChain.doFilter(request, response)
}

private fun markVisit() {
try {
if (SecurityContextHolder.getContext().authentication != null) userAccountService.markVisitForCurrentUser()
} catch (e: Exception) {
log.error("Error: ${e.message}", e)
}
}
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.epam.brn.config

import com.epam.brn.auth.filter.FirebaseTokenAuthenticationFilter
import com.epam.brn.auth.filter.RememberLastVisitFilter
import com.epam.brn.enums.BrnRole
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
Expand All @@ -21,7 +22,8 @@ import javax.servlet.http.HttpServletResponse
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true, jsr250Enabled = true, prePostEnabled = true)
class WebSecurityBasicConfiguration(
private val firebaseTokenAuthenticationFilter: FirebaseTokenAuthenticationFilter
private val firebaseTokenAuthenticationFilter: FirebaseTokenAuthenticationFilter,
private val rememberLastVisitFilter: RememberLastVisitFilter,
) : WebSecurityConfigurerAdapter() {

@Throws(Exception::class)
Expand All @@ -32,6 +34,7 @@ class WebSecurityBasicConfiguration(
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.addFilterBefore(firebaseTokenAuthenticationFilter, UsernamePasswordAuthenticationFilter::class.java)
.addFilterAfter(rememberLastVisitFilter, UsernamePasswordAuthenticationFilter::class.java)
.authorizeRequests()
.antMatchers("/swagger-ui.html", "/swagger-resources/**", "/webjars/**").hasRole(BrnRole.ADMIN)
.and()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -86,10 +86,10 @@ internal class FirebaseTokenAuthenticationFilterTest {
every { firebaseAuth.verifyIdToken(token, true) } returns firebaseTokenMock
every { firebaseTokenMock.email } returns email
every { brainUpUserDetailsService.loadUserByUsername(email) } returns customUserDetailsMock
justRun { userAccountService.markVisitForCurrentUser() }

// WHEN
firebaseTokenAuthenticationFilter.doFilter(request, response, filterChain)

// THEN
val authentication = SecurityContextHolder.getContext().authentication
assertNotNull(authentication)
Expand All @@ -100,7 +100,6 @@ internal class FirebaseTokenAuthenticationFilterTest {
verify(exactly = 1) { tokenHelperUtils.getBearerToken(request) }
verify(exactly = 1) { firebaseAuth.verifyIdToken(token, true) }
verify(exactly = 1) { brainUpUserDetailsService.loadUserByUsername(email) }
verify(exactly = 1) { userAccountService.markVisitForCurrentUser() }
verify(exactly = 0) { firebaseUserService.getUserByUuid(any()) }
verify(exactly = 0) { userAccountService.createUser(any()) }
}
Expand Down Expand Up @@ -128,10 +127,10 @@ internal class FirebaseTokenAuthenticationFilterTest {
gender = null,
name = fullName
)
justRun { userAccountService.markVisitForCurrentUser() }

// WHEN
firebaseTokenAuthenticationFilter.doFilter(requestMock, responseMock, filterChain)

// THEN
val authentication = SecurityContextHolder.getContext().authentication
assertNotNull(authentication)
Expand All @@ -144,7 +143,6 @@ internal class FirebaseTokenAuthenticationFilterTest {
verify(exactly = 2) { brainUpUserDetailsService.loadUserByUsername(email) }
verify(exactly = 1) { firebaseUserService.getUserByUuid(uuid) }
verify(exactly = 1) { userAccountService.createUser(any()) }
verify(exactly = 1) { userAccountService.markVisitForCurrentUser() }
}

@Test
Expand All @@ -157,9 +155,16 @@ internal class FirebaseTokenAuthenticationFilterTest {
val filterChain = FilterChain { _, _ -> }

every { tokenHelperUtils.getBearerToken(requestMock) } returns tokenMock
every { firebaseAuth.verifyIdToken(tokenMock, true) } throws (FirebaseAuthException(FirebaseException(ErrorCode.INVALID_ARGUMENT, "Token invalid", null)))
every {
firebaseAuth.verifyIdToken(
tokenMock,
true
)
} throws (FirebaseAuthException(FirebaseException(ErrorCode.INVALID_ARGUMENT, "Token invalid", null)))

// WHEN
firebaseTokenAuthenticationFilter.doFilter(requestMock, responseMock, filterChain)

// THEN
val authentication = SecurityContextHolder.getContext().authentication
assertNull(authentication)
Expand All @@ -169,7 +174,6 @@ internal class FirebaseTokenAuthenticationFilterTest {
verify(exactly = 0) { brainUpUserDetailsService.loadUserByUsername(any()) }
verify(exactly = 0) { firebaseUserService.getUserByUuid(any()) }
verify(exactly = 0) { userAccountService.createUser(any()) }
verify(exactly = 0) { userAccountService.markVisitForCurrentUser() }
}

@Test
Expand All @@ -183,8 +187,10 @@ internal class FirebaseTokenAuthenticationFilterTest {

every { tokenHelperUtils.getBearerToken(requestMock) } returns tokenMock
every { firebaseAuth.verifyIdToken(tokenMock, true) } throws (IllegalArgumentException())

// WHEN
firebaseTokenAuthenticationFilter.doFilter(requestMock, responseMock, filterChain)

// THEN
val authentication = SecurityContextHolder.getContext().authentication
assertNull(authentication)
Expand All @@ -194,7 +200,6 @@ internal class FirebaseTokenAuthenticationFilterTest {
verify(exactly = 0) { brainUpUserDetailsService.loadUserByUsername(any()) }
verify(exactly = 0) { firebaseUserService.getUserByUuid(any()) }
verify(exactly = 0) { userAccountService.createUser(any()) }
verify(exactly = 0) { userAccountService.markVisitForCurrentUser() }
}

@Test
Expand All @@ -216,6 +221,7 @@ internal class FirebaseTokenAuthenticationFilterTest {

// WHEN
firebaseTokenAuthenticationFilter.doFilter(requestMock, responseMock, filterChain)

// THEN
val authentication = SecurityContextHolder.getContext().authentication
assertNull(authentication)
Expand All @@ -224,7 +230,6 @@ internal class FirebaseTokenAuthenticationFilterTest {
verify(exactly = 1) { firebaseAuth.verifyIdToken(tokenMock, true) }
verify(exactly = 1) { brainUpUserDetailsService.loadUserByUsername(email) }
verify(exactly = 1) { firebaseUserService.getUserByUuid(uuid) }
verify(exactly = 0) { userAccountService.markVisitForCurrentUser() }
verify(exactly = 0) { userAccountService.createUser(any()) }
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
package com.epam.brn.auth.filter

import com.epam.brn.service.UserAccountService
import io.mockk.impl.annotations.InjectMockKs
import io.mockk.impl.annotations.MockK
import io.mockk.junit5.MockKExtension
import io.mockk.justRun
import io.mockk.verify
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.DisplayName
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.ExtendWith
import org.springframework.http.HttpMethod
import org.springframework.mock.web.MockHttpServletRequest
import org.springframework.mock.web.MockHttpServletResponse
import org.springframework.security.core.context.SecurityContextHolder
import javax.servlet.FilterChain

@ExtendWith(MockKExtension::class)
@DisplayName("RememberLastVisitFilter test using MockK")
internal class RememberLastVisitFilterTest {

@InjectMockKs
lateinit var rememberLastVisitFilter: RememberLastVisitFilter

@MockK
lateinit var userAccountService: UserAccountService

@BeforeEach
fun init() {
SecurityContextHolder.clearContext()
}

@Test
fun `should mark visit for current user`() {
// GIVEN
val requestMock = MockHttpServletRequest(HttpMethod.GET.name, "/test")
val tokenMock = "firebaseTokenMock"
requestMock.addHeader("Authorization", "Bearer $tokenMock")
val responseMock = MockHttpServletResponse()
val filterChain = FilterChain { _, _ -> }

justRun { userAccountService.markVisitForCurrentUser() }

// WHEN
rememberLastVisitFilter.doFilter(requestMock, responseMock, filterChain)

// THEN
verify(exactly = 1) { userAccountService.markVisitForCurrentUser() }
}
}

0 comments on commit 62cabf2

Please sign in to comment.