Different model validation on User Name in Scala Play! 2 form mapping in create and update

后端 未结 1 590
悲&欢浪女
悲&欢浪女 2021-02-11 07:46

I have user mapping as follows (there are few others too)

val userMapping: Mapping[User] = mapping(
    \"id\" -> ignored(NotAssigned: Pk[Long]),
    \"title\         


        
1条回答
  •  悲哀的现实
    2021-02-11 08:44

    For validating the uniqueness of the userName and company, I believe the problem is that on editing the User, the validator function finds the userName / company in the Database because it is the record you inserted beforehand. So you will need to check if the userName / company exists and if it does exist, check if the id of the row is the id of the user. If they are the same, return true because it has only found the record you're currently updating.

    With the id of the User, it's best to handle this in the Action and not the form binding due to security implications. E.g if the id is set and submitted in the form, it would be easy for someone to change the value of the id input to the id of another User to change their details. This is similar to how GitHub got compromised last year http://www.infoq.com/news/2012/03/GitHub-Compromised

    In terms of a rough code snippet, something along the lines of:

    def update(userId: Long) = Action { implicit request =>
      val user = User.find(userId)
      // Some type of authorization
      if(!authorize(getCurrentUser(), user) {
        BadRequest("access denied")
      } else {
        UserFormWithMappings.bindFromRequest().fold(
           formWithErrors => Ok("form errors"),
           updatedUser  => {
             updatedUser.id = userId
             User.update(updatedUser) // insert into db
             Ok("User changes saved")
           }
        )
      }
    }
    

    0 讨论(0)
提交回复
热议问题