Skip to content

Commit

Permalink
Merge pull request #38 from appKom/26-create-logic-to-check-if-user-h…
Browse files Browse the repository at this point in the history
…as-admin-privileges

26 create logic to check if user has admin privileges
  • Loading branch information
akselsf authored Sep 20, 2024
2 parents a140c7b + 4626b43 commit cf9ca17
Show file tree
Hide file tree
Showing 6 changed files with 112 additions and 33 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -37,3 +37,4 @@ out/
.vscode/

application.properties
**/.DS_Store
19 changes: 18 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,24 @@
- auth0.domain=
- azure.storage.container-name=
- azure.storage.connection-string=
- environment = dev | prod
- superadmin.emails =

## Current endpoints
**Header required for all requests**

```"Authorization" "Bearer <access token>"```

### /api/auth/check
```GET```
```
{
"success": Boolean,
"isadmin": Boolean,
"issuperadmin": Boolean,
}
```

### /api/receipt/create
```POST```
```
Expand All @@ -30,7 +42,12 @@
},
"attachments": [
base64 string, base64 string, ...
]
],
"receiptPaymentInformation": {
cardnumber: String?,
accountnumber: String?,
usedOnlineCard: Boolean,
}
}
```

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,14 +22,9 @@ class AuthenticationController {

@GetMapping("/check")
fun checkUser(): ResponseEntity<AuthenticatedUserResponse> {
val sub: String
try {
sub = authenticationService.getUserSub();
} catch (e: Exception) {
return ResponseEntity.badRequest().build();
}

return try {
ResponseEntity.ok(onlineUserService.checkStoredUserBySub(sub))
ResponseEntity.ok(onlineUserService.checkUser())
} catch (e: Exception) {
ResponseEntity.badRequest().build();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,5 @@ package com.example.autobank.data.authentication;
class AuthenticatedUserResponse(
val success: Boolean,
val isadmin: Boolean,
val issuperadmin: Boolean
)
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package com.example.autobank.service

import com.example.autobank.data.authentication.Auth0User
import org.springframework.beans.factory.annotation.Value
import org.springframework.core.ParameterizedTypeReference
import org.springframework.http.HttpEntity
import org.springframework.http.HttpHeaders
import org.springframework.http.HttpMethod
Expand All @@ -18,9 +19,22 @@ class AuthenticationService {

private val restTemplate = RestTemplate()

private val fetchProfileUrl = "https://old.online.ntnu.no/api/v1/profile/"

private val fetchUserCommitteesUrl = "https://old.online.ntnu.no/api/v1/group/online-groups/?members__user="

private val adminCommitteeNameLong = "Applikasjonskomiteen" // Temporarily appkom

@Value("\${auth0.domain}")
private val domain: String = ""


@Value("\${environment}")
private val environment: String = ""

@Value("\${superadmin.emails}")
private val superadminEmails: String = ""

fun getAuth0User(token: String): Auth0User {
return Auth0User("sub", "email", "name")
}
Expand Down Expand Up @@ -63,4 +77,65 @@ class AuthenticationService {
)
}

}
private fun fetchOnlineuserId(): Int {
val headers = HttpHeaders().apply {
set("Authorization", "Bearer ${getAccessToken()}")
}
val entity = HttpEntity<Void>(headers)
val response: ResponseEntity<Map<String, Any>> = restTemplate.exchange(
fetchProfileUrl,
HttpMethod.GET,
entity,
)

if (response.statusCode.isError || response.body == null) {

throw Exception("Error fetching user id")
}

return response.body?.get("id").toString().toInt()
}

private fun fetchUserCommittees(userid: Int): List<String> {

val headers = HttpHeaders()
val entity = HttpEntity<Void>(headers)
val response: ResponseEntity<UserCommitteeResponse> = restTemplate.exchange(
fetchUserCommitteesUrl + userid,
HttpMethod.GET,
entity,
object : ParameterizedTypeReference<UserCommitteeResponse>() {}
)

if (response.statusCode.isError || response.body == null) {
throw Exception("Error fetching user committees")
}

return response.body?.results?.map { it.name_long } ?: listOf()
}

fun checkBankomMembership(): Boolean {
if (environment != "prod") {
return true
}

val userId = fetchOnlineuserId()
val userCommittees = fetchUserCommittees(userId)
return userCommittees.contains(adminCommitteeNameLong)
}

fun checkSuperAdmin(): Boolean {
return superadminEmails.split(",").contains(getUserDetails().email)
}

data class Result(
val name_long: String = ""
)

data class UserCommitteeResponse(
val results: List<Result> = listOf()
)

}


38 changes: 14 additions & 24 deletions src/main/kotlin/com/example/autobank/service/OnlineUserService.kt
Original file line number Diff line number Diff line change
Expand Up @@ -10,32 +10,31 @@ import org.springframework.stereotype.Service

@Service
class OnlineUserService(
val repository: OnlineUserRepository,
@Autowired val onlineUserRepository: OnlineUserRepository
) {

@Autowired
lateinit var authenticationService: AuthenticationService

@Autowired
lateinit var onlineUserRepository: OnlineUserRepository




fun getOnlineUser(): OnlineUser? {
val sub: String = authenticationService.getUserSub()
return onlineUserRepository.findByOnlineId(sub)
}

fun checkStoredUserBySub(sub: String): AuthenticatedUserResponse {
if (sub.isEmpty()) {
return AuthenticatedUserResponse(success = false, false)
}
val storedUser = onlineUserRepository.findByOnlineId(sub)
return if (storedUser != null) {
AuthenticatedUserResponse(success = true, false)
} else {
return createOnlineUser()
fun checkUser(): AuthenticatedUserResponse {
var storedUser = onlineUserRepository.findByOnlineId(authenticationService.getUserSub())
if (storedUser == null) {
storedUser = createOnlineUser()
}
return AuthenticatedUserResponse(success = true, authenticationService.checkBankomMembership(), authenticationService.checkSuperAdmin())
}

fun createOnlineUser(): AuthenticatedUserResponse {
try {
fun createOnlineUser(): OnlineUser {
val userinfo: Auth0User = authenticationService.getUserDetails()
val onlineUser = OnlineUser(
id = 0,
Expand All @@ -44,16 +43,7 @@ class OnlineUserService(
fullname = userinfo.name,
)

if (onlineUser.onlineId.isEmpty() || onlineUser.email.isEmpty() || onlineUser.fullname.isEmpty()) {
return AuthenticatedUserResponse(success = false, false)
}

onlineUserRepository.save(onlineUser)

return AuthenticatedUserResponse(success = true, false)
} catch (e: Exception) {
println(e)
return AuthenticatedUserResponse(success = false, false)
}
return onlineUserRepository.save(onlineUser)
}

}

0 comments on commit cf9ca17

Please sign in to comment.