【问题标题】:allow the user to delete the entity which created by him in spring boot允许用户删除他在spring boot中创建的实体
【发布时间】:2021-03-02 20:10:10
【问题描述】:

我可以在 Spring Boot 控制器类中添加以下方法以允许用户删除他创建的餐厅的最佳方法是什么。

我不想将用户 ID 添加到路径中,我希望登录的用户不允许删除他没有创建的餐厅。

请注意,我扩展 Auditable 以将 createdBy 添加到数据库 mysql

    @DeleteMapping("/restaurant/{restaurantId}")
    public String deleteRestaurantById(@PathVariable("restaurantId") Long restaurantId) {
        if(restaurantService.existsById(id) == false){
            logger.info("Error occurred because this restaurant is not found!");
            throw new InternalServerErrorException("There is no restaurant with this id");
        }
        restaurantService.deleteById(id);
        return "deleted";
    }

餐厅.java

@Entity
@NoArgsConstructor
@RequiredArgsConstructor
@Getter
@Setter
@ToString
public class Restaurant extends Auditable{

    @Id
    @GeneratedValue
    private long id;

    @NonNull
    @NotEmpty(message = "The restaurant must have a name")
    private String name;
....

}

用户.java

@Entity
@RequiredArgsConstructor
@Getter
@Setter
@ToString
@NoArgsConstructor
@PasswordMatch
public class User implements UserDetails {
    @Id @GeneratedValue
    private Long id;

    @NonNull
    @Size(min = 8, max = 20)
    @Column(nullable = false, unique = true)
    private String email;

    @NonNull
    @Column(length = 100)
    private String password;

    @Transient
    @NotEmpty(message = "Please enter Password Confirmation.")
    private String confirmPassword;

    @NonNull
    @Column(nullable = false)
    private boolean enabled;

    @ManyToMany(fetch = FetchType.EAGER)
    @JoinTable(
            name = "users_roles",
            joinColumns = @JoinColumn(name = "user_id",referencedColumnName = "id"),
            inverseJoinColumns = @JoinColumn(name = "role_id",referencedColumnName = "id")
    )
    private Set<Role> roles = new HashSet<>();

    @NonNull
   @NotEmpty(message = "You must enter First Name.")
   private String firstName;

   @NonNull
   @NotEmpty(message = "You must enter Last Name.")
   private String lastName;

   @Transient
   @Setter(AccessLevel.NONE)
   private String fullName;

   @NonNull
   @NotEmpty(message = "Please enter alias.")
   @Column(nullable = false, unique = true)
   private String alias;

   private String activationCode;

   public String getFullName() {
       return firstName + " " + lastName;
   }
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return roles.stream().map(role -> new SimpleGrantedAuthority(role.getName())).collect(Collectors.toList());
    }

    public void addRole(Role role) {
        roles.add(role);
    }

    public void addRoles(Set<Role> roles) {
        roles.forEach(this::addRole);
    }

    @Override
    public String getUsername() {
        return email;
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return enabled;
    }
}

【问题讨论】:

    标签: java spring-boot spring-security


    【解决方案1】:

    如果用户能够创建唯一的餐厅,您可以通过连接表在用户和餐厅之间实现一对一的关系。

    【讨论】:

    • 不,我不想那样做。我想要一种具有弹簧安全性的方法,并且可以处理任何情况。但是感谢您努力回答我!
    【解决方案2】:

    Spring Security不可能神奇地知道用户创建了哪些餐厅。

    用户和餐厅之间必须存在某种形式的关系。

    如前所述,您可以在创建的餐厅和创建它们的用户之间建立关系。

    或者您可以在餐厅实体中有一个名为 created_by 的列,然后将用户 id 存储在该列中。因此,当您获取餐厅时,您可以使用Principal 中的id 来过滤由所述用户创建的餐厅。

    但期望 Spring Security 为您解决这个问题是不可能的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-03-19
      • 2015-10-03
      • 2017-10-22
      • 2019-07-09
      • 1970-01-01
      • 1970-01-01
      • 2018-01-28
      相关资源
      最近更新 更多