Skip to content

Commit

Permalink
https://github.com/DASISH/qddt-client/issues/770
Browse files Browse the repository at this point in the history
fixed  e
  • Loading branch information
StigNorland committed Feb 2, 2022
1 parent 08edd41 commit b5f2e5c
Show file tree
Hide file tree
Showing 102 changed files with 1,195 additions and 794 deletions.
15 changes: 14 additions & 1 deletion src/main/kotlin/no/nsd/qddt/config/AppConfig.kt
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,10 @@ import org.springframework.context.annotation.Configuration
import org.springframework.data.envers.repository.support.EnversRevisionRepositoryFactoryBean
import org.springframework.data.jpa.repository.config.EnableJpaAuditing
import org.springframework.data.jpa.repository.config.EnableJpaRepositories
import org.springframework.data.projection.SpelAwareProxyProjectionFactory
import org.springframework.hateoas.config.EnableHypermediaSupport
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity
import org.springframework.web.filter.ForwardedHeaderFilter
import org.springframework.web.filter.OncePerRequestFilter

Expand All @@ -18,17 +21,27 @@ import org.springframework.web.filter.OncePerRequestFilter
@Configuration
@EnableCaching
@EnableJpaAuditing(auditorAwareRef = "customAuditProvider")
@EnableHypermediaSupport(type=[EnableHypermediaSupport.HypermediaType.HAL])
@EnableHypermediaSupport(type=[EnableHypermediaSupport.HypermediaType.HAL,EnableHypermediaSupport.HypermediaType.HAL_FORMS, EnableHypermediaSupport.HypermediaType.COLLECTION_JSON])
@EnableJpaRepositories(
basePackages = ["no.nsd.qddt.repository", "no.nsd.qddt.service", "no.nsd.qddt.config", "no.nsd.qddt.security"],
repositoryFactoryBeanClass = EnversRevisionRepositoryFactoryBean::class)
@EnableWebSecurity
@EnableGlobalMethodSecurity(
securedEnabled = true,
jsr250Enabled = true,
prePostEnabled = true
)
class AppConfig {
@Bean
fun customAuditProvider(): AuditAwareImpl {
// val test = wildify
return AuditAwareImpl()
}

@Bean
fun projectionFactory(): SpelAwareProxyProjectionFactory? {
return SpelAwareProxyProjectionFactory()
}

@Bean
fun forwardedHeaderFilter(): FilterRegistrationBean<ForwardedHeaderFilter> {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ import org.springframework.stereotype.Component


@Component
class ModelProcessorAuditItem : RepresentationModelProcessor<EntityModel<AbstractEntityAudit>> {
class ModelProcessorEntityLinks : RepresentationModelProcessor<EntityModel<AbstractEntityAudit>> {

@Autowired
lateinit var entityLinks: RepositoryEntityLinks
Expand Down Expand Up @@ -69,13 +69,11 @@ class ModelProcessorAuditItem : RepresentationModelProcessor<EntityModel<Abstrac


return when (entity) {
is QuestionConstruct -> {
val uri = entity.questionId.toString()
return model.add(Link.of("$baseUri/questionitem/$uri", "questionItem"))
is QuestionConstruct -> with (entity.questionId.toString()){
return model.add(Link.of("$baseUri/questionitem/revison/$this", "questionItem"))
}
is QuestionItem -> {
val uri = entity.responseId.toString()
return model.add(Link.of("$baseUri/responsedomain/$uri", "responseDomain"))
is QuestionItem -> with(entity.responseId.toString()) {
return model.add(Link.of("$baseUri/responsedomain/revision/$this", "responseDomain"))
}
is ResponseDomain -> {
model
Expand Down
2 changes: 1 addition & 1 deletion src/main/kotlin/no/nsd/qddt/config/RepositoryRestConfig.kt
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package no.nsd.qddt.config

import no.nsd.qddt.model.*
import no.nsd.qddt.repository.StudyRepository
import org.springframework.beans.factory.annotation.Value
import org.springframework.data.rest.core.config.RepositoryRestConfiguration
import org.springframework.data.rest.core.mapping.RepositoryDetectionStrategy
Expand All @@ -23,6 +22,7 @@ class RepositoryRestConfig : RepositoryRestConfigurer {

cors.addMapping("/**").allowedOrigins(origin)


config.exposeIdsFor(Agency::class.java)
config.exposeIdsFor(Author::class.java)
config.exposeIdsFor(Category::class.java)
Expand Down
2 changes: 0 additions & 2 deletions src/main/kotlin/no/nsd/qddt/config/RevisionEntityImpl.kt
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,6 @@ package no.nsd.qddt.config
import no.nsd.qddt.model.User
import org.hibernate.envers.DefaultRevisionEntity
import org.hibernate.envers.RevisionEntity
import org.springframework.data.annotation.LastModifiedBy
import org.springframework.data.annotation.LastModifiedDate
import java.sql.Timestamp
import javax.persistence.Entity
import javax.persistence.ManyToOne
Expand Down
9 changes: 0 additions & 9 deletions src/main/kotlin/no/nsd/qddt/config/SecurityConfig.kt
Original file line number Diff line number Diff line change
Expand Up @@ -9,16 +9,13 @@ import org.springframework.beans.factory.annotation.Autowired
import org.springframework.beans.factory.annotation.Value
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.data.spel.spi.EvaluationContextExtension
import org.springframework.http.HttpMethod
import org.springframework.security.access.PermissionEvaluator
import org.springframework.security.authentication.AuthenticationManager
import org.springframework.security.config.BeanIds.AUTHENTICATION_MANAGER
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity
import org.springframework.security.config.annotation.web.builders.HttpSecurity
import org.springframework.security.config.annotation.web.builders.WebSecurity
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter
import org.springframework.security.config.http.SessionCreationPolicy
import org.springframework.security.core.AuthenticationException
Expand All @@ -37,12 +34,6 @@ import javax.servlet.http.HttpServletResponse
* @author Stig Norland
*/
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(
securedEnabled = true,
jsr250Enabled = true,
prePostEnabled = true
)
class SecurityConfig : WebSecurityConfigurerAdapter() {

protected val logger: Logger = LoggerFactory.getLogger(SecurityConfig::class.java)
Expand Down
117 changes: 75 additions & 42 deletions src/main/kotlin/no/nsd/qddt/controller/AbstractRestController.kt
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package no.nsd.qddt.controller
import no.nsd.qddt.model.builder.xml.XmlDDIFragmentAssembler
import no.nsd.qddt.model.classes.AbstractEntityAudit
import no.nsd.qddt.model.classes.UriId
import no.nsd.qddt.model.interfaces.RepLoaderService
import no.nsd.qddt.repository.BaseMixedRepository
import org.hibernate.Hibernate
import org.hibernate.envers.AuditReaderFactory
Expand All @@ -11,69 +12,78 @@ import org.hibernate.envers.query.AuditQuery
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.context.ApplicationContext
import org.springframework.data.domain.Page
import org.springframework.data.domain.PageRequest
import org.springframework.data.domain.Pageable
import org.springframework.data.domain.Sort
import org.springframework.data.history.Revision
import org.springframework.data.repository.history.RevisionRepository
import org.springframework.hateoas.*
import org.springframework.hateoas.mediatype.hal.HalModelBuilder
import org.springframework.hateoas.server.core.EmbeddedWrapper
import org.springframework.hateoas.server.mvc.BasicLinkBuilder
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.ResponseBody
import java.util.*
import javax.persistence.EntityManager


abstract class AbstractRestController<T : AbstractEntityAudit>( val repository: BaseMixedRepository<T>) {
abstract class AbstractRestController<T : AbstractEntityAudit>(val repository: BaseMixedRepository<T>) {

val baseUri get() = BasicLinkBuilder.linkToCurrentMapping()

@Autowired
private val entityManager: EntityManager? = null

@Autowired
private val applicationContext: ApplicationContext? = null

val repLoaderService get() = applicationContext?.getBean("repLoaderService") as RepLoaderService

@ResponseBody
open fun getRevision(@PathVariable uri: String): RepresentationModel<*>
{
open fun getRevision(@PathVariable uri: String): RepresentationModel<*> {
val uriId = UriId.fromAny(uri)

return if (uriId.rev != null) {
logger.debug("getRevisions entityRevisionModelBuilder")
val rev = repository.findRevision(uriId.id, uriId.rev!!).orElse( repository.findLastChangeRevision(uriId.id).orElseThrow())
val rev = repository.findRevision(uriId.id, uriId.rev!!)
.orElse(repository.findLastChangeRevision(uriId.id).orElseThrow())
entityRevisionModelBuilder(rev)
} else {
HalModelBuilder.emptyHalModel().build<EntityModel<T>>()
}
}

@ResponseBody
open fun getRevisions(@PathVariable uri: UUID, pageable: Pageable): RepresentationModel<*>
{
open fun getRevisions(@PathVariable uri: UUID, pageable: Pageable): RepresentationModel<*> {
val qPage: Pageable = if (pageable.sort.isUnsorted) {
PageRequest.of(pageable.pageNumber, pageable.pageSize,Sort.Direction.DESC,"modified")
PageRequest.of(pageable.pageNumber, pageable.pageSize, Sort.Direction.DESC, "modified")
} else {
pageable
}

logger.debug("getRevisions PagedModel: {}" , qPage)
logger.debug("getRevisions PagedModel: {}", qPage)
val revisions = repository.findRevisions(uri, qPage).map { rev -> entityRevisionModelBuilder(rev) }
return PagedModel.of(revisions.content, pageMetadataBuilder(revisions))
}

@ResponseBody
open fun getRevisionsByParent(@PathVariable uri: String, ofClass: Class<T>, pageable: Pageable?): RepresentationModel<*> {
open fun getRevisionsByParent(
@PathVariable uri: String,
ofClass: Class<T>,
pageable: Pageable?
): RepresentationModel<*> {
val uriId = UriId.fromAny(uri)

logger.debug("getRevisionByParent 1: {}" , uriId)
logger.debug("getRevisionByParent 1: {}", uriId)
val auditReader = AuditReaderFactory.get(entityManager)

val query: AuditQuery = auditReader.createQuery().forEntitiesAtRevision(ofClass,uriId.rev)
val query: AuditQuery = auditReader.createQuery().forEntitiesAtRevision(ofClass, uriId.rev)
.add(AuditEntity.property("parent_id").eq(uriId.id))

val result = query.resultList.map { rev -> entityModelBuilder(rev as T) }
// return PagedModel.of(revisions.content, pageMetadataBuilder(revisions))
return PagedModel.of(result, PagedModel.PageMetadata(result.size.toLong(),1L, result.size.toLong()))

return PagedModel.of(result, PagedModel.PageMetadata(result.size.toLong(), 1L, result.size.toLong()))

}

Expand All @@ -84,36 +94,15 @@ abstract class AbstractRestController<T : AbstractEntityAudit>( val repository:
}


open fun getXml(@PathVariable uri: String): ResponseEntity<String> {
logger.debug("compileToXml : {}" ,uri)
return ResponseEntity.ok(XmlDDIFragmentAssembler(getByUri(uri)).compileToXml())
open fun getXml(@PathVariable uri: String): String {
val xml = XmlDDIFragmentAssembler(getByUri(uri)).compileToXml()
logger.debug("compiledToXml : {}", xml)
return xml
}


protected fun getByUri(uri: String): T {
logger.debug("getByUri : {}" , uri)
return getByUri(UriId.fromAny(uri))
}


protected fun getByUri(uri: UriId): T {
logger.debug("_getByUri : {}" , uri)
return if (uri.rev != null)
repository.findRevision(uri.id, uri.rev!!).map {
logger.debug("_getByUri : {}" , it.entity.version.rev)
it.entity.version.rev = it.revisionNumber.get()
it.entity
}.orElseThrow()
else
repository.findById(uri.id).orElseThrow()
}

protected fun pageMetadataBuilder(revisions: Page<RepresentationModel<EntityModel<T>>>): PagedModel.PageMetadata {
return PagedModel.PageMetadata(revisions.size.toLong(),revisions.pageable.pageNumber.toLong(),revisions.totalElements,revisions.totalPages.toLong())
}

open fun entityModelBuilder(entity: T): RepresentationModel<EntityModel<T>> {
logger.debug("entityModelBuilder : {}" , entity.id)
logger.debug("entityModelBuilder : {}", entity.id)
val baseUri = BasicLinkBuilder.linkToCurrentMapping()

entity.comments.size
Expand All @@ -130,11 +119,55 @@ abstract class AbstractRestController<T : AbstractEntityAudit>( val repository:
}


fun entityRevisionModelBuilder(rev: Revision<Int, T>): RepresentationModel<EntityModel<T>> {
open fun getByUri(uri: String): T {
logger.debug("getByUri : {}", uri)
return getByUri(UriId.fromAny(uri))
}

protected fun <T : AbstractEntityAudit> loadRevisionEntity(
uri: UriId,
repository: RevisionRepository<T, UUID, Int>
): T {
return with(uri) {
if (rev != null)
repository.findRevision(id, rev!!).map {
it.entity.version.rev = it.revisionNumber.get()
it.entity
}.get()
else
repository.findLastChangeRevision(id).map {
it.entity.version.rev = it.revisionNumber.get()
it.entity
}.get()
}
}

protected fun pageMetadataBuilder(revisions: Page<RepresentationModel<EntityModel<T>>>): PagedModel.PageMetadata {
return PagedModel.PageMetadata(
revisions.size.toLong(),
revisions.pageable.pageNumber.toLong(),
revisions.totalElements,
revisions.totalPages.toLong()
)
}

private fun entityRevisionModelBuilder(rev: Revision<Int, T>): RepresentationModel<EntityModel<T>> {
rev.entity.version.rev = rev.revisionNumber.get()
return entityModelBuilder(rev.entity)
}

private fun getByUri(uri: UriId): T {
logger.debug("_getByUri : {}", uri)
return if (uri.rev != null)
repository.findRevision(uri.id, uri.rev!!).map {
logger.debug("_getByUri : {}", it.entity.version.rev)
it.entity.version.rev = it.revisionNumber.get()
it.entity
}.orElseThrow()
else
repository.findById(uri.id).orElseThrow()
}


companion object {
val logger: Logger = LoggerFactory.getLogger(this::class.java)
Expand Down
22 changes: 17 additions & 5 deletions src/main/kotlin/no/nsd/qddt/controller/AuthenticationController.kt
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,10 @@ import org.springframework.security.authentication.AuthenticationManager
import org.springframework.security.authentication.BadCredentialsException
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken
import org.springframework.security.core.context.SecurityContextHolder
import org.springframework.web.bind.annotation.*
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController

@RestController
@RequestMapping(path = ["/login"])
Expand All @@ -31,17 +34,26 @@ class AuthenticationController {
return try {
val authenticate =
if (userForm.email != null)
authenticationManager.authenticate(UsernamePasswordAuthenticationToken(userForm.email,userForm.password))
authenticationManager.authenticate(
UsernamePasswordAuthenticationToken(
userForm.email,
userForm.password
)
)
else
authenticationManager.authenticate(UsernamePasswordAuthenticationToken(userForm.username,userForm.password))
authenticationManager.authenticate(
UsernamePasswordAuthenticationToken(
userForm.username,
userForm.password
)
)
val user = authenticate.principal as User
logger.info("User logged in {}", user.toString())
SecurityContextHolder.getContext().authentication = authenticate
ResponseEntity.ok(jwtUtil.generateJwtToken(authenticate))
} catch (ex: BadCredentialsException) {
ResponseEntity.status(HttpStatus.UNAUTHORIZED).build<Any>()
}
catch (ex: Exception) {
} catch (ex: Exception) {
logger.error(ex.localizedMessage)
ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build<Any>()
}
Expand Down
Loading

0 comments on commit b5f2e5c

Please sign in to comment.