Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature/auth #54

Merged
merged 18 commits into from
Dec 7, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
import pt.up.fe.ni.website.backend.service.AuthService
import javax.servlet.http.HttpServletRequest

data class LoginDto(
val email: String,
Expand Down Expand Up @@ -37,7 +36,7 @@ class AuthController(val authService: AuthService) {

@GetMapping
@PreAuthorize("hasRole('MEMBER')")
fun checkAuthentication(request: HttpServletRequest): Map<String, String> {
fun checkAuthentication(): Map<String, String> {
val account = authService.getAuthenticatedAccount()
return mapOf("authenticated_user" to account.email)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,6 @@ import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.ResponseStatus
import org.springframework.web.bind.annotation.RestController
import org.springframework.web.bind.annotation.RestControllerAdvice
import org.springframework.web.server.ResponseStatusException
import javax.servlet.http.HttpServletResponse
import javax.validation.ConstraintViolationException

data class SimpleError(
Expand Down Expand Up @@ -110,12 +108,6 @@ class ErrorController : ErrorController {
return wrapSimpleError(e.message ?: "invalid authentication")
BrunoRosendo marked this conversation as resolved.
Show resolved Hide resolved
}

@ExceptionHandler(ResponseStatusException::class)
fun expectedError(e: ResponseStatusException, response: HttpServletResponse): CustomError {
response.status = e.status.value()
return wrapSimpleError(e.reason ?: (e.message))
}

fun wrapSimpleError(msg: String, param: String? = null, value: Any? = null) = CustomError(
mutableListOf(SimpleError(msg, param, value))
)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
package pt.up.fe.ni.website.backend.service

import org.springframework.http.HttpStatus
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken
import org.springframework.security.core.GrantedAuthority
import org.springframework.security.core.authority.SimpleGrantedAuthority
Expand All @@ -10,8 +9,8 @@ import org.springframework.security.oauth2.jwt.JwtClaimsSet
import org.springframework.security.oauth2.jwt.JwtDecoder
import org.springframework.security.oauth2.jwt.JwtEncoder
import org.springframework.security.oauth2.jwt.JwtEncoderParameters
import org.springframework.security.oauth2.server.resource.InvalidBearerTokenException
import org.springframework.stereotype.Service
import org.springframework.web.server.ResponseStatusException
import pt.up.fe.ni.website.backend.config.auth.AuthConfigProperties
import pt.up.fe.ni.website.backend.model.Account
import java.time.Duration
Expand All @@ -29,9 +28,9 @@ class AuthService(
fun authenticate(email: String, password: String): Account {
val account = accountService.getAccountByEmail(email)
if (!passwordEncoder.matches(password, account.password)) {
throw ResponseStatusException(HttpStatus.UNPROCESSABLE_ENTITY, "invalid credentials")
throw InvalidBearerTokenException("invalid credentials")
}
val authentication = UsernamePasswordAuthenticationToken(email, password, getAuthorities(account))
val authentication = UsernamePasswordAuthenticationToken(email, password, getAuthorities())
SecurityContextHolder.getContext().authentication = authentication
return account
}
Expand All @@ -49,10 +48,10 @@ class AuthService(
try {
jwtDecoder.decode(refreshToken)
} catch (e: Exception) {
throw ResponseStatusException(HttpStatus.UNAUTHORIZED, "invalid refresh token")
throw InvalidBearerTokenException("invalid refresh token")
}
if (jwt.expiresAt?.isBefore(Instant.now()) != false) {
throw ResponseStatusException(HttpStatus.UNAUTHORIZED, "refresh token has expired")
throw InvalidBearerTokenException("refresh token has expired")
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I didn't test this on my own so I'm going to ask. I like the change but is this exception being handled or does it just return an unexpected error?

Copy link
Collaborator Author

@bdmendes bdmendes Dec 6, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, it is an AuthenticationException. This is being tested, too

}
val account = accountService.getAccountByEmail(jwt.subject)
return generateAccessToken(account)
Expand All @@ -64,7 +63,7 @@ class AuthService(
}

private fun generateToken(account: Account, expiration: Duration, isRefresh: Boolean = false): String {
val roles = if (isRefresh) emptyList() else getAuthorities(account)
val roles = if (isRefresh) emptyList() else getAuthorities() // TODO: Pass account to getAuthorities()
val scope = roles
.stream()
.map(GrantedAuthority::getAuthority)
Expand All @@ -81,7 +80,7 @@ class AuthService(
return jwtEncoder.encode(JwtEncoderParameters.from(claims)).tokenValue
}

private fun getAuthorities(account: Account): List<GrantedAuthority> {
private fun getAuthorities(): List<GrantedAuthority> {
return listOf("BOARD", "MEMBER").stream() // TODO: get roles from account
BrunoRosendo marked this conversation as resolved.
Show resolved Hide resolved
.map { role -> SimpleGrantedAuthority(role) }
.collect(Collectors.toList())
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -401,16 +401,10 @@ class AccountControllerTest @Autowired constructor(
// password is ignored on serialization, so add it manually
// for account creation test cases
return objectMapper.writeValueAsString(
mapOf(
"name" to this?.name,
"email" to this?.email,
"password" to this?.password,
"bio" to this?.bio,
"birthDate" to this?.birthDate.toJson(),
"photoPath" to this?.photoPath,
"linkedin" to this?.linkedin,
"github" to this?.github,
"websites" to this?.websites
objectMapper.convertValue(this, Map::class.java).plus(
mapOf(
"password" to this?.password
)
)
)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ class AuthControllerTest @Autowired constructor(
}

@Test
fun `should fail when email is invalid`() {
fun `should fail when email is not registered`() {
mockMvc.post("/auth/new") {
contentType = MediaType.APPLICATION_JSON
content = objectMapper.writeValueAsString(
Expand All @@ -81,7 +81,7 @@ class AuthControllerTest @Autowired constructor(
contentType = MediaType.APPLICATION_JSON
content = objectMapper.writeValueAsString(LoginDto(testAccount.email, "wrong_password"))
}.andExpect {
status { isUnprocessableEntity() }
status { isUnauthorized() }
jsonPath("$.errors[0].message") { value("invalid credentials") }
}
}
Expand Down Expand Up @@ -179,7 +179,5 @@ class AuthControllerTest @Autowired constructor(
}
}
}

// TODO: Add tests for role access when implemented
}
}