Skip to content

Commit

Permalink
Serialized roles and per activity roles
Browse files Browse the repository at this point in the history
  • Loading branch information
coutinho21 committed Apr 28, 2023
1 parent fdf8f9b commit 073d8e8
Show file tree
Hide file tree
Showing 7 changed files with 52 additions and 33 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package pt.up.fe.ni.website.backend.annotations.validation

import org.springframework.core.annotation.AliasFor
import org.springframework.security.access.prepost.PreAuthorize

@PreAuthorize("")
annotation class HasActivityRole(
@get:AliasFor(annotation = PreAuthorize::class, attribute = "value")
val perActivityRole: String
)

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ class Account(
@OneToMany(cascade = [CascadeType.ALL], fetch = FetchType.EAGER)
val websites: List<@Valid CustomWebsite> = emptyList(),

@ManyToMany
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable
@OrderColumn
@JsonIgnore // TODO: Decide if we want to return roles (or IDs) by default
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,4 +26,10 @@ class PerActivityRole(
@ManyToOne
@JsonBackReference
lateinit var role: Role

override fun toString(): String {
val activityTitle = activity.title.filter { it.isLetterOrDigit() }
val permissionNames = permissions.joinToString(separator = "-") { it.name }
return "$activityTitle:$permissionNames"
}
}
6 changes: 6 additions & 0 deletions src/main/kotlin/pt/up/fe/ni/website/backend/model/Role.kt
Original file line number Diff line number Diff line change
Expand Up @@ -50,4 +50,10 @@ class Role(
@ManyToOne(fetch = FetchType.LAZY)
@JsonBackReference
lateinit var generation: Generation

override fun toString(): String {
val finalPermissions = permissions.joinToString(separator = " ") { it.name } +
" " + associatedActivities.joinToString(separator = " ")
return finalPermissions.trimEnd()
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -57,4 +57,10 @@ class AccountService(private val repository: AccountRepository, private val enco
}
repository.deleteById(id)
}

fun getRoles(account: Account): List<String> {
return account.roles.map { role ->
"${role.name}(${role.permissions.joinToString { it.name }})"
}
}
}
30 changes: 23 additions & 7 deletions src/main/kotlin/pt/up/fe/ni/website/backend/service/AuthService.kt
Original file line number Diff line number Diff line change
Expand Up @@ -16,21 +16,28 @@ import org.springframework.security.oauth2.server.resource.InvalidBearerTokenExc
import org.springframework.stereotype.Service
import pt.up.fe.ni.website.backend.config.auth.AuthConfigProperties
import pt.up.fe.ni.website.backend.model.Account
import pt.up.fe.ni.website.backend.model.Role
import pt.up.fe.ni.website.backend.model.PerActivityRole
import pt.up.fe.ni.website.backend.model.Project
import pt.up.fe.ni.website.backend.model.permissions.Permission
import pt.up.fe.ni.website.backend.model.permissions.Permissions
import pt.up.fe.ni.website.backend.repository.ActivityRepository

@Service
class AuthService(
val accountService: AccountService,
val authConfigProperties: AuthConfigProperties,
val jwtEncoder: JwtEncoder,
val jwtDecoder: JwtDecoder,
private val passwordEncoder: PasswordEncoder
private val passwordEncoder: PasswordEncoder,
val repository: ActivityRepository<Project>
) {
fun authenticate(email: String, password: String): Account {
val account = accountService.getAccountByEmail(email)
if (!passwordEncoder.matches(password, account.password)) {
throw InvalidBearerTokenException(ErrorMessages.invalidCredentials)
}
val authentication = UsernamePasswordAuthenticationToken(email, password, getAuthorities())
val authentication = UsernamePasswordAuthenticationToken(email, password, getAuthorities(account))
SecurityContextHolder.getContext().authentication = authentication
return account
}
Expand Down Expand Up @@ -63,7 +70,7 @@ class AuthService(
}

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

private fun getAuthorities(): List<GrantedAuthority> {
return listOf("BOARD", "MEMBER").stream() // TODO: get roles from account
.map { role -> SimpleGrantedAuthority(role) }
.collect(Collectors.toList())
private fun getAuthorities(account: Account): List<GrantedAuthority> {
/* val testRole = Role("MEMBER", Permissions(listOf(Permission.CREATE_ACCOUNT, Permission.CREATE_ACTIVITY)), false)
val testPerActivityRole = PerActivityRole(Permissions(listOf(Permission.CREATE_ACCOUNT, Permission.CREATE_ACTIVITY)))
val activity = Project("Test Activity", "Test Description", mutableListOf(), mutableListOf())
testPerActivityRole.activity = activity
repository.save(activity)
testRole.associatedActivities.add(testPerActivityRole)
account.roles.add(testRole)
*/
return account.roles.flatMap { role ->
val roleString = "${role.name} ${role.permissions.joinToString(separator = " ") { it.name }}"
roleString.split(" ")
}.map { SimpleGrantedAuthority(it) }
}
}

0 comments on commit 073d8e8

Please sign in to comment.