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

Feat/prsd 358 create controller and service #7

Merged
merged 12 commits into from
Oct 15, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
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
30 changes: 29 additions & 1 deletion ReadMe.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,8 @@ postgres database. This takes extra time to spin up, and spins up a clean contai
for integration tests that need to interact with a real database - for other tests the relevant repository beans should
be mocked instead.

You can run the unit tests by running the `verification\test` task from the Gradle tab in Intellij.

### Code structure

#### Backend
Expand Down Expand Up @@ -80,4 +82,30 @@ Database migrations <will be/ are> run at deployment time for all non-local depl
the `flywayMigrate` Gradle task. When developing locally using the `local` profile the migrations will run at
application start up. If you are using the `local` launch profile in IntelliJ, this will also run the `flywayClean` task
before running the migrations. After the migrations have run Spring Boot will then run the SQL in `data-local.sql` to
populate the database with seed data.
populate the database with seed data.

### One Login accounts
When you run the app and try to view pages, you will be prompted to sign in or create a One Login account.

To view most pages, your account will need to have been added to the relevant database (e.g. LandlordUser,
LocalAuthorityUser) for you to be able to see the page. It checks the database on login (you can step through
`getRolesforSubjectId` in `UserRolesService` to test it), so you will need to log in again to see the change in
permissions (if logging out is not yet implemented, try running in an incognito tab so you are prompted to log in
again).

For local dev, you can add your account by modifying the `data-local.sql` file. Insert an entry into the
`one_login_user` database with a subject_identifier matching your real one login id (see below).
Then you can add entries to any other user database that you need access to (e.g. landlord_user, local_authority_user
with is_manager set to true to see local authority admin pages).

#### Finding your One Login id
One way to find your id is to check the `subjectId` in `getRolesForSubjectId` in the `UserRolesService` while you are
logging in.

* Run the app in debug mode, add a break point in `getRolesForSubjectId`
* If you are already logged in it won't hit the breakpoint. Load the app in an incognito tab so that you are prompted
to log in again.
* When you hit the debug point, your one login id should be available in `subjectId`
(it should look like `urn:fdc:gov.uk:2022:string-of-characters`)

If anyone knows a better way to do this please add it here!
4 changes: 4 additions & 0 deletions build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
plugins {
kotlin("jvm") version "1.9.25"
kotlin("plugin.spring") version "1.9.25"
kotlin("plugin.serialization") version "2.0.20"
id("org.springframework.boot") version "3.3.3"
id("io.spring.dependency-management") version "1.1.6"
kotlin("plugin.jpa") version "1.9.25"
Expand Down Expand Up @@ -70,6 +71,9 @@ dependencies {
testImplementation("org.springframework.security:spring-security-test")
testImplementation("com.microsoft.playwright:playwright:1.47.0")
testRuntimeOnly("org.junit.platform:junit-platform-launcher")

// Serialization
implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.7.1")
}

kotlin {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ class CustomSecurityConfig {
val subjectId = oidcUser.subject
val mappedAuthorities = HashSet<GrantedAuthority>()
if (subjectId != null) {
val userRoles = userRolesService.getRolesforSubjectId(subjectId)
val userRoles = userRolesService.getRolesForSubjectId(subjectId)
mappedAuthorities.addAll(
userRoles.map { role ->
SimpleGrantedAuthority(role)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
package uk.gov.communities.prsdb.webapp.controllers

import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
import org.springframework.security.access.prepost.PreAuthorize
import org.springframework.stereotype.Controller
import org.springframework.ui.Model
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RequestMapping
import uk.gov.communities.prsdb.webapp.constants.SERVICE_NAME
import uk.gov.communities.prsdb.webapp.services.LocalAuthorityDataService
import java.security.Principal

@PreAuthorize("hasRole('LA_ADMIN')")
@Controller
@RequestMapping("/manage-users")
class ManageLocalAuthorityUsersController(
val localAuthorityDataService: LocalAuthorityDataService,
) {
@GetMapping
fun index(
model: Model,
principal: Principal,
): String {
val currentUserLocalAuthority = localAuthorityDataService.getLocalAuthorityForUser(principal.name)!!

val users = localAuthorityDataService.getLocalAuthorityUsersForLocalAuthority(currentUserLocalAuthority)
val usersJson = Json.encodeToString(users)
model.addAttribute("usersJson", usersJson)

model.addAttribute("contentHeader", "Manage Local Authority Users")
model.addAttribute("title", "Manage Local Authority Users")
model.addAttribute("serviceName", SERVICE_NAME)

return "manageLAUsers"
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,5 @@ import uk.gov.communities.prsdb.webapp.database.entity.LandlordUser
interface LandlordUserRepository : JpaRepository<LandlordUser?, Long?> {
// The underscore tells JPA to access fields relating to the referenced table
@Suppress("ktlint:standard:function-naming")
fun findByBaseUser_Id(userName: String): List<LandlordUser>
fun findByBaseUser_Id(userName: String): LandlordUser?
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,14 @@
package uk.gov.communities.prsdb.webapp.database.repository

import org.springframework.data.jpa.repository.JpaRepository
import uk.gov.communities.prsdb.webapp.database.entity.LocalAuthority
import uk.gov.communities.prsdb.webapp.database.entity.LocalAuthorityUser

interface LocalAuthorityUserRepository : JpaRepository<LocalAuthorityUser?, Long?>
interface LocalAuthorityUserRepository : JpaRepository<LocalAuthorityUser?, Long?> {
// The underscore tells JPA to access fields relating to the referenced table
@Suppress("ktlint:standard:function-naming")
fun findByLocalAuthority(localAuthority: LocalAuthority): List<LocalAuthorityUser>

@Suppress("ktlint:standard:function-naming")
fun findByBaseUser_Id(userName: String): LocalAuthorityUser?
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package uk.gov.communities.prsdb.webapp.models.dataModels

import kotlinx.serialization.Serializable

@Serializable
data class LocalAuthorityUserDataModel(
val userName: String,
val isManager: Boolean,
)
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package uk.gov.communities.prsdb.webapp.services

import org.springframework.stereotype.Service
import uk.gov.communities.prsdb.webapp.database.entity.LocalAuthority
import uk.gov.communities.prsdb.webapp.database.repository.LocalAuthorityUserRepository
import uk.gov.communities.prsdb.webapp.models.dataModels.LocalAuthorityUserDataModel

@Service
class LocalAuthorityDataService(
val localAuthorityUserRepository: LocalAuthorityUserRepository,
) {
fun getLocalAuthorityUsersForLocalAuthority(localAuthority: LocalAuthority): List<LocalAuthorityUserDataModel> {
val usersInThisLocalAuthority = localAuthorityUserRepository.findByLocalAuthority(localAuthority)
return usersInThisLocalAuthority.map { LocalAuthorityUserDataModel(it.baseUser.name, it.isManager) }
}

fun getLocalAuthorityForUser(subjectId: String): LocalAuthority? {
val localAuthorityUser = localAuthorityUserRepository.findByBaseUser_Id(subjectId)
return localAuthorityUser?.localAuthority
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,29 @@ package uk.gov.communities.prsdb.webapp.services

import org.springframework.stereotype.Service
import uk.gov.communities.prsdb.webapp.database.repository.LandlordUserRepository
import uk.gov.communities.prsdb.webapp.database.repository.LocalAuthorityUserRepository

@Service
class UserRolesService(
val landlordRepository: LandlordUserRepository,
val localAuthorityUserRepository: LocalAuthorityUserRepository,
) {
fun getRolesforSubjectId(subjectId: String): List<String> {
fun getRolesForSubjectId(subjectId: String): List<String> {
val roles = mutableListOf<String>()

val matchingLandlordUser = landlordRepository.findByBaseUser_Id(subjectId)
if (matchingLandlordUser.isNotEmpty()) {
if (matchingLandlordUser != null) {
roles.add("ROLE_LANDLORD")
}

val matchingLocalAuthorityUser = localAuthorityUserRepository.findByBaseUser_Id(subjectId)
if (matchingLocalAuthorityUser != null) {
if (matchingLocalAuthorityUser.isManager) {
roles.add("ROLE_LA_ADMIN")
}
roles.add("ROLE_LA_USER")
}

return roles
}
}
17 changes: 14 additions & 3 deletions src/main/resources/data-local.sql
Original file line number Diff line number Diff line change
@@ -1,14 +1,25 @@
INSERT INTO one_login_user (id, name, email, created_date, last_modified_date)
VALUES ('urn:fdc:gov.uk:2022:ABCDE', 'Bob T Builder', '[email protected]', '09/13/24', '09/13/24'),
('urn:fdc:gov.uk:2022:FGHIJ', 'Anne Other', '[email protected]', '09/13/24', '09/13/24'),
('urn:fdc:gov.uk:2022:KLMNO', 'Ford Prefect', '[email protected]', '10/07/24', '10/07/24');
('urn:fdc:gov.uk:2022:KLMNO', 'Ford Prefect', '[email protected]', '10/07/24', '10/07/24'),
('urn:fdc:gov.uk:2022:PQRST', 'Arthur Dent', '[email protected]', '10/09/24', '10/09/24'),
('urn:fdc:gov.uk:2022:07lXHJeQwE0k5PZO7w_PQF425vT8T7e63MrvyPYNSoI', 'Jasmin Conterio', '[email protected]', '10/07/24', '10/07/24'),
('urn:fdc:gov.uk:2022:mGHDySEVfCsvfvc6lVWf6Qt9Dv0ZxPQWKoEzcjnBlUo','PRSDB Landlord', '[email protected]','10/15/24','10/15/24'),
('urn:fdc:gov.uk:2022:n93slCXHsxJ9rU6-AFM0jFIctYQjYf0KN9YVuJT-cao','PRSDB LA Admin', '[email protected]','10/15/24','10/15/24'),
('urn:fdc:gov.uk:2022:cgVX2oJWKHMwzm8Gzx25CSoVXixVS0rw32Sar4Om8vQ','PRSDB La User', '[email protected]', '10/15/24', '10/15/24');

INSERT INTO landlord_user (subject_identifier, phone_number, date_of_birth, created_date, last_modified_date)
VALUES ('urn:fdc:gov.uk:2022:ABCDE', '07712345678', '01/01/00', '09/13/24', '09/13/24'),
('urn:fdc:gov.uk:2022:FGHIJ', '07811111111', '11/23/98', '09/13/24', '09/13/24');
('urn:fdc:gov.uk:2022:FGHIJ', '07811111111', '11/23/98', '09/13/24', '09/13/24'),
('urn:fdc:gov.uk:2022:07lXHJeQwE0k5PZO7w_PQF425vT8T7e63MrvyPYNSoI', '01223456789','02/01/00','10/09/24', '10/09/24'),
('urn:fdc:gov.uk:2022:mGHDySEVfCsvfvc6lVWf6Qt9Dv0ZxPQWKoEzcjnBlUo','01223456789','03/05/00','10/15/24', '10/09/24');

INSERT INTO local_authority (name, created_date, last_modified_date)
VALUES ('Betelgeuse','09/13/24', '09/13/24');

INSERT INTO local_authority_user (subject_identifier, is_manager, local_authority_id, created_date, last_modified_date)
VALUES ('urn:fdc:gov.uk:2022:KLMNO',true, 1,'10/07/24', '10/07/24')
VALUES ('urn:fdc:gov.uk:2022:KLMNO',true, 1,'10/07/24', '10/07/24'),
('urn:fdc:gov.uk:2022:PQRST',false, 1,'10/09/24', '10/09/24'),
('urn:fdc:gov.uk:2022:07lXHJeQwE0k5PZO7w_PQF425vT8T7e63MrvyPYNSoI',true,1,'10/09/24', '10/09/24'),
('urn:fdc:gov.uk:2022:n93slCXHsxJ9rU6-AFM0jFIctYQjYf0KN9YVuJT-cao',true,1,'10/15/24','10/15/24'),
('urn:fdc:gov.uk:2022:cgVX2oJWKHMwzm8Gzx25CSoVXixVS0rw32Sar4Om8vQ',false,1,'10/15/24','10/15/24');
Original file line number Diff line number Diff line change
Expand Up @@ -23,16 +23,16 @@ CREATE TABLE local_authority_user
created_date TIMESTAMPTZ(6),
last_modified_date TIMESTAMPTZ(6),
subject_identifier VARCHAR(255) NOT NULL UNIQUE,
is_manager BOOLEAN,
local_authority_id INT,
is_manager BOOLEAN NOT NULL,
local_authority_id INT NOT NULL,
PRIMARY KEY (id)
);
CREATE TABLE local_authority
(
id INT GENERATED BY DEFAULT AS IDENTITY,
created_date TIMESTAMPTZ(6),
last_modified_date TIMESTAMPTZ(6),
name VARCHAR(255),
name VARCHAR(255) NOT NULL,
PRIMARY KEY (id)
);
ALTER TABLE IF EXISTS landlord_user
Expand Down
7 changes: 7 additions & 0 deletions src/main/resources/templates/manageLAUsers.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
<!DOCTYPE html>
<html th:replace="~{fragments/layout :: layout(${title}, ${serviceName}, ~{::main})}">
<main class="govuk-main-wrapper" id="main-content">
<h1 class="govuk-heading-xl" th:text="${contentHeader}">Default page template</h1>
<p th:text="${usersJson}"></p>
</main>
</html>
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import org.springframework.test.web.servlet.setup.MockMvcBuilders
import org.springframework.web.context.WebApplicationContext
import uk.gov.communities.prsdb.webapp.config.CustomSecurityConfig
import uk.gov.communities.prsdb.webapp.config.EnableMethodSecurityConfig
import uk.gov.communities.prsdb.webapp.services.LocalAuthorityDataService
import uk.gov.communities.prsdb.webapp.services.UserRolesService

@Import(CustomSecurityConfig::class, EnableMethodSecurityConfig::class)
Expand All @@ -33,4 +34,7 @@ abstract class ControllerTest(

@MockBean
lateinit var userRolesService: UserRolesService

@MockBean
lateinit var localAuthorityDataService: LocalAuthorityDataService
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
package uk.gov.communities.prsdb.webapp.controllers

import org.mockito.Mockito
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest
import org.springframework.security.test.context.support.WithMockUser
import org.springframework.test.util.ReflectionTestUtils
import org.springframework.test.web.servlet.get
import org.springframework.web.context.WebApplicationContext
import uk.gov.communities.prsdb.webapp.database.entity.LocalAuthority
import kotlin.test.Test

@WebMvcTest(ManageLocalAuthorityUsersController::class)
class ManageLocalAuthorityUsersControllerTests(
@Autowired val webContext: WebApplicationContext,
) : ControllerTest(webContext) {
@Test
fun `ManageLocalAuthorityUsersController returns a redirect for unauthenticated user`() {
mvc.get("/manage-users").andExpect {
status { is3xxRedirection() }
}
}

@Test
@WithMockUser
fun `ManageLocalAuthorityUsersController returns 403 for unauthorized user`() {
mvc
.get("/manage-users")
.andExpect {
status { isForbidden() }
}
}

@Test
@WithMockUser(roles = ["LA_ADMIN"])
fun `ManageLocalAuthorityUsersController returns 200 for authorized user`() {
val localAuthority = LocalAuthority()
ReflectionTestUtils.setField(localAuthority, "id", 123)
Mockito
.`when`(localAuthorityDataService.getLocalAuthorityForUser("user"))
.thenReturn(localAuthority)

mvc
.get("/manage-users")
.andExpect {
status { isOk() }
}
}
}
Loading