API 1.1 WT Club changes

This commit is contained in:
Tibor Bossanyi
2023-02-04 18:41:55 +01:00
parent b17ea93836
commit 564e749bc2
100 changed files with 1085 additions and 230 deletions
@@ -1,18 +1,24 @@
package com.aitrainer.api.controller
import com.aitrainer.api.model.Customer
import com.aitrainer.api.model.User
import com.aitrainer.api.model.*
import com.aitrainer.api.service.ServiceBeans
import com.aitrainer.api.repository.CustomerRepository
import com.aitrainer.api.service.Email
import com.aitrainer.api.service.EmailTemplateService
import com.aitrainer.api.service.Firebase
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.http.HttpHeaders
import org.springframework.http.ResponseEntity
import org.springframework.security.access.annotation.Secured
import org.springframework.web.bind.annotation.*
import java.io.ByteArrayOutputStream
import java.nio.charset.StandardCharsets.UTF_8
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
import java.util.*
import java.util.zip.GZIPInputStream
import java.util.zip.GZIPOutputStream
import javax.validation.Valid
@@ -24,6 +30,9 @@ class CustomerController ( private val customerRepository: CustomerRepository) {
@Autowired
var serviceBeans: ServiceBeans? = null
@Autowired
private var emailTemplateService: EmailTemplateService? = null
@Secured
@GetMapping("/customers")
fun getAllCustomers(@RequestHeader headers: HttpHeaders): List<Customer> =
@@ -147,6 +156,98 @@ class CustomerController ( private val customerRepository: CustomerRepository) {
return ResponseEntity.ok().body(customerRepository.save(updatedCustomer))
}
@PostMapping("/club_registration")
fun clubRegistration(@Valid @RequestBody json: String): ResponseEntity<*> {
fun gzip(content: String): String {
val bos = ByteArrayOutputStream()
GZIPOutputStream(bos).bufferedWriter(UTF_8).use { it.write(content) }
return bos.toByteArray().toString()
}
fun unzip(content: ByteArray): String =
GZIPInputStream(content.inputStream()).bufferedReader(UTF_8).use { it.readText() }
val newUser: ClubUser = ClubUser().fromJson(json)
if ( newUser.email.isEmpty()) {
return ResponseEntity.badRequest().body("No Email")
}
val existingCustomer: Customer? = customerRepository.findByEmailAndActive(newUser.email, "Y")
if (existingCustomer != null ) {
return ResponseEntity.badRequest().body("Customer exists")
}
val current = LocalDateTime.now()
val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS")
val nowFormatted = current.format(formatter)
val stringCharacters = ('0'..'z').toList().toTypedArray()
val genPassword = (1..10).map { stringCharacters.random() }.joinToString("")
val firebase = Firebase()
val signupResponse = firebase.signUp(newUser.email, genPassword)
?: return ResponseEntity.badRequest().body("Firebase exception ${firebase.error}")
val saving_customer = Customer()
if ( serviceBeans == null ) {
serviceBeans = ServiceBeans()
}
with (saving_customer) {
email = newUser.email
password = serviceBeans!!.passwordEncoder().encode(genPassword)
idToken = signupResponse.idToken
firebaseUid = signupResponse.localId
dateAdd = nowFormatted
firstname = newUser.firstname
name = ""
goal = newUser.goal
fitnessLevel = newUser.fitnessLevel
}
val newCustomer = customerRepository.save(saving_customer)
if ( newUser.weight != 0.0 ) {
val property = CustomerPropertyProperty()
with (property) {
propertyId = 1
propertyValue = newUser.weight
dateAdd= nowFormatted
goal = false
customer = newCustomer
}
newCustomer.properties.add(property)
}
if ( newUser.height != 0.0 ) {
val property = CustomerPropertyProperty()
with (property) {
propertyId = 2
propertyValue = newUser.height
dateAdd= nowFormatted
goal = false
customer = newCustomer
}
newCustomer.properties.add(property)
}
customerRepository.save(newCustomer)
// create email link
val activationLink = "https://club.workouttest.com/welcome/id=${signupResponse.idToken}"
if ( emailTemplateService == null ) {
emailTemplateService = EmailTemplateService()
}
val html = emailTemplateService!!.getEmailBody(newUser.firstname, activationLink)
val subject = emailTemplateService!!.getSubject()
// send email
val email = Email()
email.send(newUser.email, html, subject)
return ResponseEntity.ok().body(newCustomer)
}
@PostMapping("/registration")
fun registration(@Valid @RequestBody json: String): ResponseEntity<*> {
@@ -180,9 +281,10 @@ class CustomerController ( private val customerRepository: CustomerRepository) {
} else {
ResponseEntity.badRequest().body("Customer exists")
}
}
@PostMapping("/login")
fun login(@Valid @RequestBody json: String): ResponseEntity<*> {
val customer = Customer()
@@ -0,0 +1,47 @@
package com.aitrainer.api.controller
import com.aitrainer.api.model.CustomerMembership
import com.aitrainer.api.repository.CustomerMembershipRepository
import org.slf4j.LoggerFactory
import org.springframework.http.ResponseEntity
import org.springframework.security.access.annotation.Secured
import org.springframework.web.bind.annotation.*
import javax.validation.Valid
@RestController
@RequestMapping("/api")
class CustomerMembershipController(private val customerMembershipRepository: CustomerMembershipRepository) {
private val logger = LoggerFactory.getLogger(javaClass)
@PostMapping("/customer_membership")
fun createNewCustomerMembership(@Valid @RequestBody customerMembership: CustomerMembership): ResponseEntity<CustomerMembership> {
logger.info("Create customer membership: $customerMembership")
return ResponseEntity.ok().body(customerMembershipRepository.save(customerMembership))
}
@Secured
@PostMapping("customer_membership/update/{id}")
fun updateCustomerMembership(@PathVariable(value = "id") membershipId: Long,
@Valid @RequestBody membershipToUpdate: CustomerMembership): ResponseEntity<CustomerMembership> {
val customerMembership = customerMembershipRepository.findById(membershipId).orElse(null)
?: return ResponseEntity.notFound().build()
val updatedCustomerMembership = customerMembership.copy(
trainingPlanId = membershipToUpdate.trainingPlanId,
days = membershipToUpdate.days,
)
return ResponseEntity.ok().body(customerMembershipRepository.save(updatedCustomerMembership))
}
@GetMapping("/customer_membership/{customer_id}")
fun getAllByCustomerId(@PathVariable(value = "customer_id") customerId: Long): ResponseEntity<List<CustomerMembership>> {
val membershipList: List<CustomerMembership> = customerMembershipRepository.findAllByCustomerId(customerId)
logger.info("Get all customer_membership by by customerId")
return if(membershipList.isNotEmpty())
ResponseEntity.ok().body(membershipList) else
ResponseEntity.notFound().build()
}
}
@@ -1,6 +1,7 @@
package com.aitrainer.api.controller
import com.aitrainer.api.model.*
import com.aitrainer.api.model.CustomerMembership
import com.aitrainer.api.repository.*
import com.google.gson.GsonBuilder
import org.springframework.http.ResponseEntity
@@ -19,8 +20,48 @@ class CustomerPackageController( private val customerRepository: CustomerReposit
private val exerciseResultRepository: ExerciseResultRepository,
private val customerActivityRepository: CustomerActivityRepository,
private val customerTrainingPlanRepository: CustomerTrainingPlanRepository,
private val customerMembership: CustomerMembershipRepository,
) {
@GetMapping("/club_customer_package/{id}")
fun getCustomerClubPackageData(@PathVariable(value = "id") customerId: Long): ResponseEntity<String> {
if (customerId <= 0) {
return ResponseEntity.notFound().build()
}
val gson = GsonBuilder()
.excludeFieldsWithoutExposeAnnotation()
.setPrettyPrinting()
.create()
val customer: Customer = customerRepository.findByCustomerIdAndActive(customerId, "Y")
?: return ResponseEntity.notFound().build()
val customerJson: String = gson.toJson(customer)
val listCustomerPropertyAll = customerPropertyRepository.findAllByCustomerId(customerId)
val listCustomerPropertyAllJson = gson.toJson(listCustomerPropertyAll)
val listCustomerProperty = customerPropertyRepository.findLastPropertiesByCustomerId(customerId)
val listCustomerPropertyJson = gson.toJson(listCustomerProperty)
val listTrainingPlan = customerTrainingPlanRepository.findAllByCustomerId(customerId)
val listTrainingPlanJson = gson.toJson(listTrainingPlan)
val listMembership = customerMembership.findAllByCustomerId(customerId)
val listMembershipJson = gson.toJson(listMembership)
val packageJson: String =
getClassRecord(Customer::class.simpleName, customerJson) +
"|||" + getClassRecord(CustomerProperty::class.simpleName+"All", listCustomerPropertyAllJson) +
"|||" + getClassRecord(CustomerProperty::class.simpleName, listCustomerPropertyJson) +
"|||" + getClassRecord(CustomerTrainingPlan::class.simpleName, listTrainingPlanJson +
"|||" + getClassRecord(CustomerMembership::class.simpleName, listMembershipJson)
)
return if (packageJson.isEmpty()) ResponseEntity.notFound().build() else
ResponseEntity.ok().body(packageJson)
}
@GetMapping("/app_customer_package/{id}")
fun getCustomerPackageData(@PathVariable(value = "id") customerId: Long): ResponseEntity<String> {
@@ -19,6 +19,12 @@ class CustomerPropertyController(private val customerPropertyRepository: Custome
return ResponseEntity.ok().body(customerPropertyRepository.save(customerProperty))
}
@PostMapping("/customer_goal")
fun createCustomerGoal(@Valid @RequestBody customerProperty: CustomerProperty): ResponseEntity<CustomerProperty> {
logger.info("Create customer goal: $customerProperty")
return ResponseEntity.ok().body(customerPropertyRepository.save(customerProperty))
}
@Secured
@PostMapping("customer_property/update/{id}")
fun updateCustomerProperty(@PathVariable(value = "id") propertyId: Long,
@@ -2,7 +2,6 @@ package com.aitrainer.api.controller
import com.aitrainer.api.model.*
import com.aitrainer.api.repository.*
import org.slf4j.LoggerFactory
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RequestMapping
@@ -29,9 +28,48 @@ class PackageController(private val exerciseAbilityRepository: ExerciseAbilityRe
private val splitTestsRepository: SplitTestsRepository,
private val trainingPlanDayRepository: TrainingPlanDayRepository,
private val appTextRepository: AppTextRepository,
private val trainingProgramRepository: TrainingProgramRepository
private val trainingProgramRepository: TrainingProgramRepository,
private val membershipRepository: MembershipRepository
) {
private val logger = LoggerFactory.getLogger(javaClass)
@GetMapping("/club_package")
fun getClubPackageData(): ResponseEntity<String> {
val gson = GsonBuilder()
.excludeFieldsWithoutExposeAnnotation()
.setPrettyPrinting()
.create()
val listProperty:List<Property> = propertyRepository.getProperties()
val listPropertyJson: String = gson.toJson(listProperty)
val listExerciseType = exerciseTypeRepository.findAll()
val listExerciseTypeJson = gson.toJson(listExerciseType)
val listTrainingPlan = trainingPlanRepository.findAll()
val listTrainingPlanJson = gson.toJson(listTrainingPlan)
val listTrainingPlanDay = trainingPlanDayRepository.findAll()
val listTrainingPlanDayJson = gson.toJson(listTrainingPlanDay)
val listTrainingProgram = trainingProgramRepository.findAll()
val listTrainingProgramJson = gson.toJson(listTrainingProgram)
val listMembership = membershipRepository.findAll()
val listMembershipJson = gson.toJson(listMembership)
val packageJson: String =
getClassRecord(Property::class.simpleName, listPropertyJson) +
"|||" + getClassRecord(ExerciseType::class.simpleName, listExerciseTypeJson) +
"|||" + getClassRecord(TrainingPlan::class.simpleName, listTrainingPlanJson) +
"|||" + getClassRecord(TrainingPlanDay::class.simpleName, listTrainingPlanDayJson) +
"|||" + getClassRecord(TrainingProgram::class.simpleName, listTrainingProgramJson) +
"|||" + getClassRecord(Membership::class.simpleName, listMembershipJson)
return if (packageJson.isEmpty()) ResponseEntity.notFound().build() else
ResponseEntity.ok().body(packageJson)
}
@GetMapping("/app_package")
fun getPackageData(): ResponseEntity<String> {
@@ -1,14 +1,14 @@
package com.aitrainer.api.model
import com.google.gson.annotations.Expose
import jakarta.persistence.*
import org.hibernate.annotations.Fetch
import org.hibernate.annotations.FetchMode
import org.springframework.lang.NonNull
import javax.persistence.*
@Entity
data class AppText (
@Expose @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @get: NonNull var textId: Long = 0,
@Expose @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @get: NonNull var textId: Long = 0,
@Expose @get: NonNull var textKey: String,
@Expose @get: NonNull var screenshotUrl: String,
@Expose @get: NonNull var checked: Boolean? = null,
@@ -3,7 +3,7 @@ package com.aitrainer.api.model
import com.fasterxml.jackson.annotation.JsonIgnore
import com.google.gson.annotations.Expose
import org.springframework.lang.NonNull
import javax.persistence.*
import jakarta.persistence.*
import javax.validation.constraints.NotBlank
@Entity
@@ -0,0 +1,18 @@
package com.aitrainer.api.model
import kotlinx.serialization.*
import kotlinx.serialization.json.*
@Serializable
data class ClubUser (
var email: String = "",
var firstname: String = "",
var weight: Double = 0.0,
var height: Double = 0.0,
var goal: String = "",
var fitnessLevel: String = "",
) {
fun fromJson(json: String): ClubUser {
return Json.decodeFromString(serializer(), json)
}
}
@@ -1,9 +1,6 @@
package com.aitrainer.api.model
import javax.persistence.Entity
import javax.persistence.GeneratedValue
import javax.persistence.GenerationType
import javax.persistence.Id
import jakarta.persistence.*
import javax.validation.constraints.NotBlank
@Entity
@@ -1,7 +1,9 @@
package com.aitrainer.api.model
import com.google.gson.annotations.Expose
import javax.persistence.*
import jakarta.persistence.*
import org.hibernate.annotations.Fetch
import org.hibernate.annotations.FetchMode
@Entity
data class Customer (
@@ -32,6 +34,11 @@ data class Customer (
@Expose var lang: String? = null,
@Expose var phone: String? = null,
@Expose var lifeLong: Int? = null,
@Expose var idToken: String? = null,
@Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Expose var customerId: Long = 0,
)
) {
@OneToMany(cascade = [(CascadeType.ALL)], fetch = FetchType.EAGER, mappedBy = "customer")
@Fetch(value = FetchMode.SUBSELECT)
@Expose val properties: MutableList<CustomerPropertyProperty> = mutableListOf()
}
@@ -1,8 +1,7 @@
package com.aitrainer.api.model
import com.fasterxml.jackson.annotation.JsonIgnore
import com.google.gson.annotations.Expose
import javax.persistence.*
import jakarta.persistence.*
import javax.validation.constraints.NotNull
@Entity
@@ -1,11 +1,8 @@
package com.aitrainer.api.model
import com.fasterxml.jackson.annotation.JsonIgnore
import com.google.gson.annotations.Expose
import org.hibernate.annotations.Fetch
import org.hibernate.annotations.FetchMode
import javax.persistence.*
import javax.validation.constraints.NotNull
import jakarta.persistence.*
@Entity
data class CustomerExerciseDevice (
@@ -0,0 +1,15 @@
package com.aitrainer.api.model
import com.google.gson.annotations.Expose
import org.springframework.lang.NonNull
import jakarta.persistence.*
@Entity
data class CustomerMembership (
@Expose @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @get: NonNull var id: Long = 0,
@Expose @get: NonNull var customerId: Long = 0,
@Expose @get: NonNull var membershipId: Long = 0,
@Expose @get: NonNull var startDate: String? = null,
@Expose @get: NonNull var trainingPlanId: Long = 0,
@Expose @get: NonNull var days: String? = null
)
@@ -2,10 +2,7 @@ package com.aitrainer.api.model
import com.google.gson.annotations.Expose
import org.springframework.lang.NonNull
import javax.persistence.Entity
import javax.persistence.GeneratedValue
import javax.persistence.GenerationType
import javax.persistence.Id
import jakarta.persistence.*
@Entity
data class CustomerProperty (
@@ -13,5 +10,7 @@ data class CustomerProperty (
@Expose @get: NonNull var customerId: Long = 0,
@Expose @get: NonNull var propertyId: Long = 0,
@Expose @get: NonNull var propertyValue: Double? = null,
@Expose @get: NonNull var dateAdd: String? = null
@Expose @get: NonNull var dateAdd: String? = null,
@Expose @get: NonNull var goal: Boolean? = null,
@Expose @get: NonNull var goalDate: String? = null,
)
@@ -0,0 +1,23 @@
package com.aitrainer.api.model
import com.fasterxml.jackson.annotation.JsonIgnore
import com.google.gson.annotations.Expose
import jakarta.persistence.*
import org.springframework.lang.NonNull
@Entity
@Table(name = "CustomerProperty")
data class CustomerPropertyProperty (
@Expose @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @get: NonNull var customerPropertyId: Long = 0,
@Expose @get: NonNull var propertyId: Long = 0,
@Expose @get: NonNull var propertyValue: Double? = null,
@Expose @get: NonNull var dateAdd: String? = null,
@Expose @get: NonNull var goal: Boolean? = null,
@Expose @get: NonNull var goalDate: String? = null,
) {
@ManyToOne(fetch = FetchType.EAGER, optional = false)
@JoinColumn(name = "customerId", nullable = false)
@JsonIgnore var customer: Customer? = null
}
@@ -4,7 +4,7 @@ import com.google.gson.annotations.Expose
import org.hibernate.annotations.Fetch
import org.hibernate.annotations.FetchMode
import org.springframework.lang.NonNull
import javax.persistence.*
import jakarta.persistence.*
@Entity
data class CustomerTrainingPlan (
@@ -2,10 +2,8 @@ package com.aitrainer.api.model
import com.fasterxml.jackson.annotation.JsonIgnore
import com.google.gson.annotations.Expose
import org.hibernate.annotations.Fetch
import org.hibernate.annotations.FetchMode
import org.springframework.lang.NonNull
import javax.persistence.*
import jakarta.persistence.*
@Entity
data class CustomerTrainingPlanDetails (
@@ -2,7 +2,7 @@ package com.aitrainer.api.model
import com.google.gson.annotations.Expose
import org.springframework.lang.NonNull
import javax.persistence.*
import jakarta.persistence.*
@Entity
data class CustomerTrainingPlanExercise (
@@ -4,7 +4,7 @@ import com.google.gson.annotations.Expose
import org.hibernate.annotations.Fetch
import org.hibernate.annotations.FetchMode
import org.springframework.lang.NonNull
import javax.persistence.*
import jakarta.persistence.*
@Entity
data class Description (
@@ -3,7 +3,7 @@ package com.aitrainer.api.model
import com.fasterxml.jackson.annotation.JsonIgnore
import com.google.gson.annotations.Expose
import org.springframework.lang.NonNull
import javax.persistence.*
import jakarta.persistence.*
import javax.validation.constraints.NotBlank
@Entity
@@ -4,7 +4,7 @@ import com.google.gson.annotations.Expose
import org.hibernate.annotations.Fetch
import org.hibernate.annotations.FetchMode
import org.springframework.lang.NonNull
import javax.persistence.*
import jakarta.persistence.*
import javax.validation.constraints.NotBlank
@Entity
@@ -3,7 +3,7 @@ package com.aitrainer.api.model
import com.fasterxml.jackson.annotation.JsonIgnore
import com.google.gson.annotations.Expose
import org.springframework.lang.NonNull
import javax.persistence.*
import jakarta.persistence.*
import javax.validation.constraints.NotBlank
@Entity
@@ -2,7 +2,7 @@ package com.aitrainer.api.model
import com.google.gson.annotations.Expose
import javax.persistence.*
import jakarta.persistence.*
import javax.validation.constraints.NotBlank
@Entity
@@ -3,7 +3,7 @@ package com.aitrainer.api.model
import com.google.gson.annotations.Expose
import org.hibernate.annotations.Fetch
import org.hibernate.annotations.FetchMode
import javax.persistence.*
import jakarta.persistence.*
import javax.validation.constraints.NotBlank
@Entity
@@ -19,8 +19,4 @@ data class ExerciseDevice (
@OneToMany(cascade = [(CascadeType.ALL)], fetch = FetchType.EAGER, mappedBy = "exerciseDevice")
@Fetch(value = FetchMode.SUBSELECT)
@Expose val translations: List<ExerciseDeviceTranslation> = mutableListOf<ExerciseDeviceTranslation>().toList()
@OneToMany(cascade = [(CascadeType.ALL)], fetch = FetchType.EAGER, mappedBy = "exerciseDevice")
@Fetch(value = FetchMode.SUBSELECT)
@Expose val alternatives: List<ExerciseDeviceAlternative> = mutableListOf<ExerciseDeviceAlternative>().toList()
}
@@ -1,22 +1,13 @@
package com.aitrainer.api.model
import com.fasterxml.jackson.annotation.JsonIgnore
import com.google.gson.annotations.Expose
import kotlinx.serialization.Contextual
import kotlinx.serialization.Serializable
import javax.persistence.*
import jakarta.persistence.*
import javax.validation.constraints.NotNull
@Entity
data class ExerciseDeviceAlternative (
@Expose @Id @GeneratedValue(strategy = GenerationType.IDENTITY) var exerciseDeviceAlternativeId: Long = 0,
@Expose @get: NotNull var exerciseDeviceChildId: Long?
) {
@ManyToOne(fetch = FetchType.EAGER, optional = false)
@JoinColumn(name = "exerciseDeviceParentId", nullable = false)
@JsonIgnore
val exerciseDevice: ExerciseDevice? = null
}
)
@@ -3,7 +3,7 @@ package com.aitrainer.api.model
import com.fasterxml.jackson.annotation.JsonIgnore
import com.google.gson.annotations.Expose
import kotlinx.serialization.Contextual
import javax.persistence.*
import jakarta.persistence.*
import javax.validation.constraints.NotBlank
@Entity
@@ -1,7 +1,7 @@
package com.aitrainer.api.model
import org.springframework.lang.NonNull
import javax.persistence.*
import jakarta.persistence.*
@Entity
data class ExercisePlan(
@@ -1,8 +1,8 @@
package com.aitrainer.api.model
import com.fasterxml.jackson.annotation.JsonIgnore
import org.springframework.lang.NonNull
import javax.persistence.*
import jakarta.persistence.*
@Entity
data class ExercisePlanDetail (
@@ -4,7 +4,7 @@ import com.google.gson.annotations.Expose
import org.hibernate.annotations.Fetch
import org.hibernate.annotations.FetchMode
import org.springframework.lang.NonNull
import javax.persistence.*
import jakarta.persistence.*
@Entity
data class ExercisePlanTemplate(
@@ -3,7 +3,7 @@ package com.aitrainer.api.model
import com.fasterxml.jackson.annotation.JsonIgnore
import com.google.gson.annotations.Expose
import org.springframework.lang.NonNull
import javax.persistence.*
import jakarta.persistence.*
import javax.validation.constraints.Null
@Entity
@@ -2,7 +2,7 @@ package com.aitrainer.api.model
import com.fasterxml.jackson.annotation.JsonIgnore
import com.google.gson.annotations.Expose
import javax.persistence.*
import jakarta.persistence.*
import javax.validation.constraints.NotBlank
@Entity
@@ -2,10 +2,7 @@ package com.aitrainer.api.model
import com.google.gson.annotations.Expose
import org.springframework.lang.NonNull
import javax.persistence.Entity
import javax.persistence.GeneratedValue
import javax.persistence.GenerationType
import javax.persistence.Id
import jakarta.persistence.*
@Entity
data class ExerciseResult(
@@ -4,7 +4,7 @@ import com.google.gson.annotations.Expose
import org.hibernate.annotations.Fetch
import org.hibernate.annotations.FetchMode
import org.springframework.lang.NonNull
import javax.persistence.*
import jakarta.persistence.*
import javax.validation.constraints.NotBlank
@Entity
@@ -21,9 +21,4 @@ data class ExerciseTree (
@OneToMany(cascade = [(CascadeType.ALL)], fetch = FetchType.EAGER, mappedBy = "exerciseTree")
@Fetch(value = FetchMode.SUBSELECT)
@Expose val translations: List<ExerciseTreeTranslation> = mutableListOf<ExerciseTreeTranslation>().toList()
@OneToMany(cascade = [(CascadeType.ALL)], fetch = FetchType.EAGER, mappedBy = "exerciseTree")
@Fetch(value = FetchMode.SUBSELECT)
@Expose val abilities: List<ExerciseTreeAbility> = mutableListOf()
}
@@ -2,7 +2,7 @@ package com.aitrainer.api.model
import com.fasterxml.jackson.annotation.JsonIgnore
import com.google.gson.annotations.Expose
import javax.persistence.*
import jakarta.persistence.*
import javax.validation.constraints.NotNull
@Entity
@@ -1,7 +1,7 @@
package com.aitrainer.api.model
import com.google.gson.annotations.Expose
import javax.persistence.*
import jakarta.persistence.*
import javax.validation.constraints.NotNull
@Entity
@@ -2,7 +2,7 @@ package com.aitrainer.api.model
import com.fasterxml.jackson.annotation.JsonIgnore
import com.google.gson.annotations.Expose
import javax.persistence.*
import jakarta.persistence.*
import javax.validation.constraints.NotBlank
@Entity
@@ -4,7 +4,7 @@ import com.google.gson.annotations.Expose
import org.hibernate.annotations.FetchMode
import org.hibernate.annotations.Fetch
import org.springframework.lang.NonNull
import javax.persistence.*
import jakarta.persistence.*
import javax.validation.constraints.NotBlank
import javax.validation.constraints.Null
@@ -2,7 +2,7 @@ package com.aitrainer.api.model
import com.fasterxml.jackson.annotation.JsonIgnore
import com.google.gson.annotations.Expose
import javax.persistence.*
import jakarta.persistence.*
import javax.validation.constraints.NotNull
@Entity
@@ -2,7 +2,7 @@ package com.aitrainer.api.model
import com.fasterxml.jackson.annotation.JsonIgnore
import com.google.gson.annotations.Expose
import javax.persistence.*
import jakarta.persistence.*
import javax.validation.constraints.NotNull
@Entity
@@ -2,8 +2,7 @@ package com.aitrainer.api.model
import com.fasterxml.jackson.annotation.JsonIgnore
import com.google.gson.annotations.Expose
import org.springframework.lang.NonNull
import javax.persistence.*
import jakarta.persistence.*
import javax.validation.constraints.NotBlank
@Entity
@@ -2,7 +2,7 @@ package com.aitrainer.api.model
import com.fasterxml.jackson.annotation.JsonIgnore
import com.google.gson.annotations.Expose
import javax.persistence.*
import jakarta.persistence.*
import javax.validation.constraints.NotNull
@Entity
@@ -2,7 +2,7 @@ package com.aitrainer.api.model
import com.fasterxml.jackson.annotation.JsonIgnore
import com.google.gson.annotations.Expose
import javax.persistence.*
import jakarta.persistence.*
import javax.validation.constraints.NotBlank
@Entity
@@ -2,10 +2,7 @@ package com.aitrainer.api.model
import com.google.gson.annotations.Expose
import org.springframework.lang.NonNull
import javax.persistence.Entity
import javax.persistence.GeneratedValue
import javax.persistence.GenerationType
import javax.persistence.Id
import jakarta.persistence.*
import javax.validation.constraints.Null
@Entity
@@ -4,7 +4,7 @@ import com.google.gson.annotations.Expose
import org.hibernate.annotations.Fetch
import org.hibernate.annotations.FetchMode
import org.springframework.lang.NonNull
import javax.persistence.*
import jakarta.persistence.*
@Entity
data class Faq (
@@ -3,7 +3,7 @@ package com.aitrainer.api.model
import com.fasterxml.jackson.annotation.JsonIgnore
import com.google.gson.annotations.Expose
import org.springframework.lang.NonNull
import javax.persistence.*
import jakarta.persistence.*
import javax.validation.constraints.NotBlank
@Entity
@@ -0,0 +1,15 @@
package com.aitrainer.api.model
import com.google.gson.annotations.Expose
import org.springframework.lang.NonNull
import jakarta.persistence.*
@Entity
data class Membership (
@Expose @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @get: NonNull var membershipId: Long = 0,
@Expose @get: NonNull var name: String,
@Expose @get: NonNull var description: String,
@Expose @get: NonNull var duration: Int? = null,
@Expose @get: NonNull var durationType: String? = null,
@Expose @get: NonNull var durationUnit: String? = null,
)
@@ -2,10 +2,7 @@ package com.aitrainer.api.model
import com.google.gson.annotations.Expose
import org.springframework.lang.NonNull
import javax.persistence.Entity
import javax.persistence.GeneratedValue
import javax.persistence.GenerationType
import javax.persistence.Id
import jakarta.persistence.*
import javax.validation.constraints.NotBlank
/*enum class ProductType(val type: String) {
@@ -1,11 +1,10 @@
package com.aitrainer.api.model
import com.google.gson.annotations.Expose
import kotlinx.serialization.Serializable
import org.hibernate.annotations.Fetch
import org.hibernate.annotations.FetchMode
import org.springframework.lang.NonNull
import javax.persistence.*
import jakarta.persistence.*
import javax.validation.constraints.NotBlank
@Entity
@@ -2,7 +2,7 @@ package com.aitrainer.api.model
import com.fasterxml.jackson.annotation.JsonIgnore
import com.google.gson.annotations.Expose
import javax.persistence.*
import jakarta.persistence.*
import javax.validation.constraints.NotBlank
@Entity
@@ -2,10 +2,7 @@ package com.aitrainer.api.model
import com.google.gson.annotations.Expose
import org.springframework.lang.NonNull
import javax.persistence.Entity
import javax.persistence.GeneratedValue
import javax.persistence.GenerationType
import javax.persistence.Id
import jakarta.persistence.*
import javax.validation.constraints.NotBlank
@Entity
@@ -1,11 +1,8 @@
package com.aitrainer.api.model
import com.google.gson.annotations.Expose
import kotlinx.serialization.Serializable
import org.hibernate.annotations.Fetch
import org.hibernate.annotations.FetchMode
import org.springframework.lang.NonNull
import javax.persistence.*
import jakarta.persistence.*
import javax.validation.constraints.NotBlank
@Entity
@@ -4,7 +4,7 @@ import com.google.gson.annotations.Expose
import org.hibernate.annotations.Fetch
import org.hibernate.annotations.FetchMode
import org.springframework.lang.NonNull
import javax.persistence.*
import jakarta.persistence.*
@Entity
data class Sport (
@@ -2,7 +2,7 @@ package com.aitrainer.api.model
import com.fasterxml.jackson.annotation.JsonIgnore
import com.google.gson.annotations.Expose
import javax.persistence.*
import jakarta.persistence.*
import javax.validation.constraints.NotBlank
@Entity
@@ -1,10 +1,7 @@
package com.aitrainer.api.model
import org.springframework.lang.NonNull
import javax.persistence.Entity
import javax.persistence.GeneratedValue
import javax.persistence.GenerationType
import javax.persistence.Id
import jakarta.persistence.*
@Entity
data class Tracking (
@@ -4,7 +4,7 @@ import com.google.gson.annotations.Expose
import org.hibernate.annotations.Fetch
import org.hibernate.annotations.FetchMode
import org.springframework.lang.NonNull
import javax.persistence.*
import jakarta.persistence.*
import javax.validation.constraints.NotBlank
@Entity
@@ -4,7 +4,7 @@ import com.google.gson.annotations.Expose
import org.hibernate.annotations.Fetch
import org.hibernate.annotations.FetchMode
import org.springframework.lang.NonNull
import javax.persistence.*
import jakarta.persistence.*
@Entity
data class TrainingPlanDay (
@@ -3,7 +3,7 @@ package com.aitrainer.api.model
import com.fasterxml.jackson.annotation.JsonIgnore
import com.google.gson.annotations.Expose
import org.springframework.lang.NonNull
import javax.persistence.*
import jakarta.persistence.*
import javax.validation.constraints.NotBlank
@Entity
@@ -3,7 +3,7 @@ package com.aitrainer.api.model
import com.fasterxml.jackson.annotation.JsonIgnore
import com.google.gson.annotations.Expose
import org.springframework.lang.NonNull
import javax.persistence.*
import jakarta.persistence.*
import javax.validation.constraints.NotBlank
@Entity
@@ -2,7 +2,7 @@ package com.aitrainer.api.model
import com.fasterxml.jackson.annotation.JsonIgnore
import com.google.gson.annotations.Expose
import javax.persistence.*
import jakarta.persistence.*
import javax.validation.constraints.NotBlank
@Entity
@@ -1,10 +1,8 @@
package com.aitrainer.api.model
import com.google.gson.annotations.Expose
import org.hibernate.annotations.Fetch
import org.hibernate.annotations.FetchMode
import org.springframework.lang.NonNull
import javax.persistence.*
import jakarta.persistence.*
@Entity
data class TrainingProgram (
@@ -1,11 +1,10 @@
package com.aitrainer.api.model
import com.google.gson.annotations.Expose
import kotlinx.serialization.Serializable
import org.hibernate.annotations.Fetch
import org.hibernate.annotations.FetchMode
import org.springframework.lang.NonNull
import javax.persistence.*
import jakarta.persistence.*
import javax.validation.constraints.NotBlank
@Entity
@@ -5,7 +5,7 @@ import com.google.gson.annotations.Expose
import org.hibernate.annotations.Fetch
import org.hibernate.annotations.FetchMode
import org.springframework.lang.NonNull
import javax.persistence.*
import jakarta.persistence.*
import javax.validation.constraints.NotBlank
@Entity
@@ -2,7 +2,7 @@ package com.aitrainer.api.model
import com.fasterxml.jackson.annotation.JsonIgnore
import com.google.gson.annotations.Expose
import javax.persistence.*
import jakarta.persistence.*
import javax.validation.constraints.NotBlank
@Entity
@@ -0,0 +1,12 @@
package com.aitrainer.api.model.firebase_response
import kotlinx.serialization.Serializable
@Serializable
data class SignupResponse(
var kind: String = "",
var idToken: String = "",
var email: String = "",
var refreshToken: String = "",
var expiresIn: String = "",
var localId: String = ""
)
@@ -0,0 +1,14 @@
package com.aitrainer.api.repository
import com.aitrainer.api.model.CustomerMembership
import org.springframework.data.jpa.repository.JpaRepository
import org.springframework.data.jpa.repository.Query
import org.springframework.stereotype.Repository
@Repository
interface CustomerMembershipRepository : JpaRepository<CustomerMembership, Long> {
@Query(" FROM CustomerMembership " +
" WHERE customerId = :customerId"
)
fun findAllByCustomerId(customerId: Long): List<CustomerMembership>
}
@@ -9,7 +9,6 @@ import org.springframework.stereotype.Repository
interface ExerciseDeviceRepository: JpaRepository<ExerciseDevice, Long> {
@Query("FROM ExerciseDevice as e " +
"LEFT JOIN ExerciseDeviceTranslation as t ON e.exerciseDeviceId = t.exerciseDevice AND t.languageCode = 'hu' " +
"LEFT JOIN ExerciseDeviceAlternative as t ON e.exerciseDeviceId = t.exerciseDevice " +
"ORDER BY e.exerciseDeviceId ")
fun getExerciseDevices(): List<ExerciseDevice>
}
@@ -1,6 +1,5 @@
package com.aitrainer.api.repository
import com.aitrainer.api.model.ExercisePlan
import com.aitrainer.api.model.ExercisePlanDetail
import org.springframework.data.jpa.repository.JpaRepository
import org.springframework.stereotype.Repository
@@ -8,14 +7,5 @@ import org.springframework.stereotype.Repository
@Repository
interface ExercisePlanDetailRepository: JpaRepository<ExercisePlanDetail, Long> {
/* @Query("FROM ExercisePlanDetail as d " +
"INNER JOIN ExercisePlan as p ON p.exercisePlanId = d.exercisePlan " +
"WHERE p.private = 1 " +
"AND p.customerId = :customerId " +
"ORDER BY p.dateAdd DESC ")
fun getLastExercisePlanDetail(customerId: Long): List<ExercisePlanDetail>
*/
fun findByExercisePlanId(exercisePlanId: Int): List<ExercisePlanDetail>
}
@@ -10,7 +10,6 @@ interface ExerciseTreeRepository : JpaRepository<ExerciseTree, Long> {
@Query("FROM ExerciseTree as e " +
"LEFT JOIN ExerciseTreeTranslation as t ON e.treeId = t.exerciseTree AND t.languageCode = 'hu' " +
"LEFT JOIN ExerciseTreeAbility as t ON e.treeId = t.exerciseTree " +
"WHERE e.active = 1 " +
"ORDER BY e.treeId ")
fun getActiveMenu(): List<ExerciseTree>
@@ -1,12 +1,10 @@
package com.aitrainer.api.repository
import com.aitrainer.api.model.ExerciseType
import com.aitrainer.api.model.Exercises
import org.springframework.data.jpa.repository.JpaRepository
import org.springframework.data.jpa.repository.Query
import org.springframework.data.repository.query.Param
import org.springframework.stereotype.Repository
import javax.persistence.NamedQuery
@Repository
interface ExerciseTypeRepository : JpaRepository<ExerciseType, Long>{
@@ -17,8 +15,8 @@ interface ExerciseTypeRepository : JpaRepository<ExerciseType, Long>{
"LEFT JOIN ExerciseTypeImage as i ON e.exerciseTypeId = i.exerciseType " +
"LEFT JOIN ExerciseTypeTranslation as t ON e.exerciseTypeId = t.exerciseType " +
"LEFT JOIN ExerciseTypeDevice as td ON e.exerciseTypeId = td.exerciseType " +
"LEFT JOIN ExerciseTypeAlternative as td ON e.exerciseTypeId = td.exerciseType " +
"LEFT JOIN ExerciseTypeParents as td ON e.exerciseTypeId = td.exerciseType " +
"LEFT JOIN ExerciseTypeAlternative as ta ON e.exerciseTypeId = ta.exerciseType " +
"LEFT JOIN ExerciseTypeParents as tp ON e.exerciseTypeId = tp.exerciseType " +
"WHERE e.active = 1 " +
"AND t.languageCode = 'hu' " +
"AND i.type = 'menu' " +
@@ -0,0 +1,9 @@
package com.aitrainer.api.repository
import com.aitrainer.api.model.Membership
import org.springframework.data.jpa.repository.JpaRepository
import org.springframework.stereotype.Repository
@Repository
interface MembershipRepository: JpaRepository<Membership, Long> {
}
@@ -9,12 +9,11 @@ import org.springframework.security.authentication.DisabledException
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken
import org.springframework.web.bind.annotation.*
import org.springframework.stereotype.Component
import javax.servlet.http.HttpServletRequest
import jakarta.servlet.http.HttpServletRequest
@Component
@RestController
//@CrossOrigin
@RequestMapping("/api")
class JwtAuthenticationController {
@Autowired
@@ -3,8 +3,8 @@ package com.aitrainer.api.security
import org.springframework.security.web.AuthenticationEntryPoint
import org.springframework.stereotype.Component
import java.io.IOException
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import jakarta.servlet.http.HttpServletRequest
import jakarta.servlet.http.HttpServletResponse
import java.io.Serializable
import org.springframework.security.core.AuthenticationException
@@ -10,10 +10,10 @@ import org.springframework.security.web.authentication.WebAuthenticationDetailsS
import org.springframework.stereotype.Component
import org.springframework.web.filter.OncePerRequestFilter
import java.io.IOException
import javax.servlet.FilterChain
import javax.servlet.ServletException
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import jakarta.servlet.FilterChain
import jakarta.servlet.ServletException
import jakarta.servlet.http.HttpServletRequest
import jakarta.servlet.http.HttpServletResponse
@Component
@@ -23,10 +23,6 @@ class JwtRequestFilter : OncePerRequestFilter() {
@Autowired
private val jwtTokenUtil: JwtTokenUtil? = null
//@Autowired
//private lateinit var authenticationController: JwtAuthenticationController
@Throws(ServletException::class, IOException::class)
override fun doFilterInternal(request: HttpServletRequest, response: HttpServletResponse, chain: FilterChain) {
val requestTokenHeader = request.getHeader("Authorization")
@@ -67,11 +63,4 @@ class JwtRequestFilter : OncePerRequestFilter() {
chain.doFilter(request, response)
}
/*private fun readUserCredentials(request: HttpServletRequest): UserCredentials? {
return try {
ObjectMapper().readValue(request.inputStream, UserCredentials::class.java)
} catch (ioe: IOException) {
throw BadCredentialsException("Invalid request", ioe)
}
}*/
}
@@ -9,57 +9,48 @@ import org.springframework.security.authentication.AuthenticationManager
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder
import org.springframework.security.config.annotation.web.builders.HttpSecurity
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.web.SecurityFilterChain
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter
@Configuration
@EnableWebSecurity
class JwtSecurityConfig : WebSecurityConfigurerAdapter() {
class JwtSecurityConfig {
@Autowired
private val jwtAuthenticationEntryPoint: JwtAuthenticationEntryPoint? = null
@Autowired
private val jwtUserDetailsService: UserDetailsServiceImpl? = null
@Autowired
private val jwtRequestFilter: JwtRequestFilter? = null
@Autowired
private val serviceBeans: ServiceBeans? = null
override fun configure(auth: AuthenticationManagerBuilder?) {
auth!!.userDetailsService(jwtUserDetailsService).passwordEncoder(serviceBeans!!.passwordEncoder())
@Autowired
private var jwtRequestFilter: JwtRequestFilter? = null
private fun authManager(http: HttpSecurity): AuthenticationManager {
val authenticationManagerBuilder = http.getSharedObject(
AuthenticationManagerBuilder::class.java
)
authenticationManagerBuilder.userDetailsService(jwtUserDetailsService).passwordEncoder(serviceBeans!!.passwordEncoder())
return authenticationManagerBuilder.build()
}
@Bean
@Throws(Exception::class)
override fun authenticationManagerBean(): AuthenticationManager {
return super.authenticationManagerBean()
fun filterChain(httpSecurity: HttpSecurity):SecurityFilterChain {
httpSecurity.
csrf().disable().
authorizeHttpRequests().requestMatchers("/api/authenticate").permitAll().
anyRequest().authenticated().and().
exceptionHandling().authenticationEntryPoint(jwtAuthenticationEntryPoint).and().
addFilterAfter(jwtRequestFilter, UsernamePasswordAuthenticationFilter::class.java).
// make sure we use stateless session; session won't be used to
// store user's state.
sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
return httpSecurity.build();
}
@Throws(Exception::class)
override fun configure(httpSecurity: HttpSecurity) {
// We don't need CSRF for this example
httpSecurity.
csrf().disable().
// dont authenticate this particular request
authorizeRequests().antMatchers("/api/authenticate").permitAll().
// all other requests need to be authenticated
anyRequest().authenticated().and().
// make sure we use stateless session; session won't be used to
// store user's state.
exceptionHandling().authenticationEntryPoint(jwtAuthenticationEntryPoint).and().
// Add a filter to validate the tokens with every request
//addFilterAt(JwtAuthenticationFilter(authenticationManagerBean()), UsernamePasswordAuthenticationFilter::class.java).
addFilterAfter(jwtRequestFilter, UsernamePasswordAuthenticationFilter::class.java).
sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
}
}
@@ -43,12 +43,12 @@ class JwtTokenUtil : Serializable {
fun generateToken(userDetails: UserDetails): String {
val claims: Map<String, Any> = HashMap()
return doGenerateToken(claims, userDetails.username)
return doGenerateToken(userDetails.username)
}
private fun doGenerateToken(claims: Map<String, Any>, subject: String): String {
return Jwts.builder().setClaims(claims).setSubject(subject).setIssuedAt(Date(System.currentTimeMillis()))
.setExpiration(Date(System.currentTimeMillis() + JWT_TOKEN_VALIDITY * 1000)).signWith(SignatureAlgorithm.HS512, secret).compact()
fun doGenerateToken(username: String): String {
return Jwts.builder().setSubject(username).setExpiration( Date(System.currentTimeMillis() + JWT_TOKEN_VALIDITY * 1000))
.signWith(SignatureAlgorithm.HS512, secret).compact()
}
fun canTokenBeRefreshed(token: String): Boolean {
@@ -0,0 +1,61 @@
package com.aitrainer.api.service
import java.util.Properties
import jakarta.mail.*
import jakarta.mail.internet.*
import org.jasypt.encryption.StringEncryptor
import org.jasypt.encryption.pbe.PooledPBEStringEncryptor
import org.jasypt.encryption.pbe.config.SimpleStringPBEConfig
class Email {
private val encodedPassword = "Jfn8xRIObqLXlx5AChKqNMqbHnZ2aois"
@Throws(MessagingException::class)
fun send(to: String, emailBody: String, subject: String) {
val properties = Properties().apply {
put("mail.smtp.auth", "true")
put("mail.smtp.starttls.enable", "true")
put("mail.smtp.host", "mail.aitrainer.info")
put("mail.smtp.port", "587")
}
fun getEncryptor(): StringEncryptor {
val encryptor = PooledPBEStringEncryptor()
val config = SimpleStringPBEConfig()
config.password = "workouttest"
config.algorithm = "PBEWithMD5AndDES"
config.setKeyObtentionIterations("1000")
config.setPoolSize("1")
config.providerName = "SunJCE"
config.setSaltGeneratorClassName("org.jasypt.salt.RandomSaltGenerator")
config.stringOutputType = "base64"
encryptor.setConfig(config)
return encryptor
}
val session: Session = Session.getInstance(properties, object : Authenticator() {
override fun getPasswordAuthentication(): PasswordAuthentication {
return PasswordAuthentication("service@workouttest.com", getEncryptor().decrypt(encodedPassword))
}
})
val message = MimeMessage(session).apply {
setFrom(InternetAddress("service@workouttest.com"))
setRecipients(Message.RecipientType.TO, InternetAddress.parse(to))
setRecipients(Message.RecipientType.BCC, InternetAddress.parse("service@workouttest.com"))
this.subject = subject
}
val bodyPart = MimeBodyPart().apply {
setContent(emailBody, "text/html")
}
val multipart = MimeMultipart().apply {
addBodyPart(bodyPart)
}
message.setContent(multipart)
Transport.send(message)
}
}
@@ -0,0 +1,31 @@
package com.aitrainer.api.service
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
import org.thymeleaf.TemplateEngine
import org.thymeleaf.context.Context
@Service
class EmailTemplateService {
@Autowired
private var templateEngine: TemplateEngine? = null
fun getEmailBody(firstname: String, activationLink: String): String {
val context = Context()
context.setVariable("firstname", firstname)
context.setVariable("activationLink", activationLink)
if ( templateEngine == null) {
templateEngine = TemplateEngine()
}
return templateEngine!!.process("registration_email", context)
}
fun getSubject(): String {
val context = Context()
if ( templateEngine == null) {
templateEngine = TemplateEngine()
}
return templateEngine!!.process("registration_subject", context)
}
}
@@ -0,0 +1,67 @@
package com.aitrainer.api.service
import com.aitrainer.api.model.firebase_response.SignupResponse
import com.google.gson.Gson
import java.net.URI
import java.net.http.HttpClient
import java.net.http.HttpRequest
import java.net.http.HttpResponse
import java.nio.charset.StandardCharsets
import org.json.JSONObject
class Firebase {
private val apiKey: String = "AIzaSyCUXBWV3_qzvV__ZWZA1siHftrrJpjDKh4"
private val firebaseBaseUrl: String = "https://identitytoolkit.googleapis.com/v1/accounts"
var statusCode: Int = 0
var error: String = ""
fun signUp(email: String, password: String): SignupResponse? {
val json = JSONObject()
.put("email", email)
.put("password", password)
.put("returnSecureToken", "true")
// Create the POST body with the email and password
val postData = json.toString()
println("Firebase post: $postData")
val response = this.call("signUp", postData)
if ( statusCode != 200) {
return null
}
val gson = Gson()
return gson.fromJson(response, SignupResponse::class.java)
}
fun deleteUser(idToken: String): Int {
val json = JSONObject().put("idToken", idToken)
val postData = json.toString()
this.call("delete", postData)
return statusCode
}
private fun call(command: String, postData: String): String {
val url = URI.create("$firebaseBaseUrl:$command?key=$apiKey")
// Create the HTTP request object
val request = HttpRequest.newBuilder()
.POST(HttpRequest.BodyPublishers.ofString(postData))
.uri(url)
.header("Content-Type", "application/json")
.build()
// Send the request and get the response
val response = HttpClient.newBuilder().build().send(request, HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8))
statusCode = response.statusCode()
if ( statusCode != 200) {
error = JSONObject(response.body()).getJSONObject("error").getString("message").toString()
return error
}
print("Firebase $command response $response")
error = ""
return response.body()
}
}
@@ -1,10 +1,13 @@
package com.aitrainer.api.service
import org.springframework.context.annotation.Bean
import org.springframework.security.authentication.AuthenticationManager
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder
import org.springframework.security.crypto.password.PasswordEncoder
import org.springframework.stereotype.Component
/*
Commonly used Beans
*/
@@ -16,4 +19,10 @@ class ServiceBeans {
fun passwordEncoder(): PasswordEncoder {
return BCryptPasswordEncoder()
}
@Bean
@Throws(java.lang.Exception::class)
fun authenticationManager(config: AuthenticationConfiguration): AuthenticationManager? {
return config.authenticationManager
}
}