Improve change password

This commit is contained in:
2020-01-30 14:18:40 +01:00
parent 3d2d3c2e14
commit 24bc1520f7
3 changed files with 37 additions and 10 deletions

View File

@@ -1,5 +1,6 @@
package fr.dcproject.routes
import com.fasterxml.jackson.module.kotlin.MissingKotlinParameterException
import fr.dcproject.citizen
import fr.dcproject.entity.Citizen
import fr.dcproject.routes.CitizenPaths.ChangePasswordCitizenRequest
@@ -11,6 +12,7 @@ import fr.dcproject.security.voter.CitizenVoter.Action.VIEW
import fr.dcproject.security.voter.assertCan
import fr.postgresjson.repository.RepositoryI.Direction
import io.ktor.application.call
import io.ktor.auth.UserPasswordCredential
import io.ktor.http.HttpStatusCode
import io.ktor.locations.KtorExperimentalLocationsAPI
import io.ktor.locations.Location
@@ -44,7 +46,7 @@ object CitizenPaths {
@Location("/citizens/{citizen}/password/change")
class ChangePasswordCitizenRequest(val citizen: Citizen) {
data class Content(val password: String)
data class Content(val oldPassword: String, val newPassword: String)
}
}
@@ -73,13 +75,20 @@ fun Route.citizen(
put<ChangePasswordCitizenRequest> {
assertCan(CHANGE_PASSWORD, it.citizen)
val content = call.receive<ChangePasswordCitizenRequest.Content>()
try {
val content = call.receive<ChangePasswordCitizenRequest.Content>()
val currentUser = userRepository.findByCredentials(UserPasswordCredential(citizen.user.username, content.oldPassword))
val user = it.citizen.user
if (currentUser == null || currentUser.id != user.id) {
call.respond(HttpStatusCode.BadRequest, "Bad password")
} else {
user.plainPassword = content.newPassword
userRepository.changePassword(user)
val user = it.citizen.user
user.plainPassword = content.password
userRepository.changePassword(user)
call.respond(HttpStatusCode.Created)
call.respond(HttpStatusCode.Created)
}
} catch (e: MissingKotlinParameterException) {
call.respond(HttpStatusCode.BadRequest, "Request format is not correct")
}
}
}

View File

@@ -154,7 +154,13 @@ paths:
application/json:
schema:
properties:
password:
old_password:
type: string
format: password
required: true
example:
azerty
new_password:
type: string
format: password
required: true

View File

@@ -39,7 +39,19 @@ Feature: citizens routes
When I send a PUT request to "/citizens/c211dca6-aa21-45c2-95ba-c7f2179ee37e/password/change" with body:
"""
{
"password": "qwerty"
"old_password": "azerty",
"new_password": "qwerty"
}
"""
Then the response status code should be 201
Scenario: If a send bad request when a change password, that return a 400 Bad request
Given I am authenticated as Joe Carotte with id "19110bb5-58a2-4ef1-9497-0207d4b4f48f"
When I send a PUT request to "/citizens/19110bb5-58a2-4ef1-9497-0207d4b4f48f/password/change" with body:
"""
{
"plup": "azerty",
"gloup": "qwerty"
}
"""
Then the response status code should be 400