基于角色在Spring Boot中创建用户

huangapple go评论77阅读模式
英文:

role based creation of users in Spring boot

问题

我有三个实体User用户)、Institution机构和Role角色)。
1) User与Institution之间是一对多关系
2) User与Role之间是多对多关系

-------User-------

@Entity
@Table(name = "user")
public class User {
    
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name="user_Id")
    private int userId;
    @Column(name="name")
    private String name;
    @Column(name="lastname")
    private String lastname;
    @Column(name="email")
    private String email;
    @Column(name="password")
    private String password;
    @Column(name="isActive")
    private boolean isActive;
    @Column(name="lastActive")
    private String lastActive;
    @Column(name="createdDate")
    private String createdDate;
    @Column(name="isBlocked")
    private boolean isBlocked;
    
    @ManyToOne(fetch = FetchType.LAZY, optional = false)
    @JoinColumn(name = "institution_id", nullable = false)
    @JsonIgnoreProperties(value = {"user"})
    private Institution institution;
    
    @ManyToMany(fetch = FetchType.LAZY)
    @JoinTable(name = "user_has_role",
            joinColumns = {
                    @JoinColumn(name = "user_id", referencedColumnName = "user_id",
                            nullable = false, updatable = true)},
            inverseJoinColumns = {
                    @JoinColumn(name = "role_id", referencedColumnName = "role_id",
                            nullable = false, updatable = true)})
    @JsonIgnoreProperties(value = {"users"})
    private Set<Role> roles = new HashSet<>();
}

-------Institution-------

@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@ToString

@Entity
@Table(name = "institution")
public class Institution {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name="institution_Id")
    private int institutionId;
    @Column(name="name")
    private String name;
    @Column(name="type")
    private String type;
    @Column(name="location")
    private String location;
    @OneToMany(mappedBy = "institution", fetch = FetchType.LAZY)
    @JsonIgnoreProperties(value = {"institution" , "user"})
    private Set<User> user;
}

-------Role-------

@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@ToString

@Entity
@Table(name = "role")
public class Role {
    
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name="role_Id")
    private int roleId;
    @Column(name="name")
    private String name;
    @Column(name="description")
    private String description;
    @ManyToMany(mappedBy = "roles", fetch = FetchType.LAZY)
    @JsonIgnoreProperties(value = {"roles"})
    private Set<User> users = new HashSet<>();
}

这些是我的三个实体和MySQL中的表格
我有7个角色:
 Super-User超级用户
 Bank-Admin银行管理员
 Bank-Support银行支持
 Bank-Service银行服务
 Merchant-Admin商家管理员
 Merchant-Support商家支持
 Merchant-service商家服务

超级用户可以创建任何角色的用户

@PostMapping("/addUser")
public String addUser(@RequestBody User user) {
    String rawpassword = user.getPassword();
    String encodedpasswrod = passwordencoder.encode(rawpassword);
    user.setPassword(encodedpasswrod);
    userrepository.save(user);
    return "user saved with name: " + user.getName();
}

此API可以正常工作并且我可以在API的JSON请求体中设置用户的角色

但是我希望如果用户是银行管理员Bank-Admin),则只能创建Bank-Support和Bank-Service角色的用户
我尝试创建一个新的API该API只能创建具有这两个特定角色的用户
并限制银行管理员访问另一个可以创建任何类型用户的API

有其他方法可以实现吗如果没有我应该如何做到这一点...
英文:

i have Three entities User, Institution and Role.
1)one to many between user and institution
2)and many to many between User and Role

-------user-------

@Entity
@Table(name = &quot;user&quot;)
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name=&quot;user_Id&quot;)
private int userId;
@Column(name=&quot;name&quot;)
private String name;
@Column(name=&quot;lastname&quot;)
private String lastname;
@Column(name=&quot;email&quot;)
private String email;
@Column(name=&quot;password&quot;)
private String password;
@Column(name=&quot;isActive&quot;)
private boolean isActive;
@Column(name=&quot;lastActive&quot;)
private String lastActive;
@Column(name=&quot;createdDate&quot;)
private String createdDate;
@Column(name=&quot;isBlocked&quot;)
private boolean isBlocked;
@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = &quot;institution_id&quot;, nullable = false)
@JsonIgnoreProperties(value = {&quot;user&quot;})
private Institution institution;
@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(name = &quot;user_has_role&quot;,
joinColumns = {
@JoinColumn(name = &quot;user_id&quot;, referencedColumnName = &quot;user_id&quot;,
nullable = false, updatable = true)},
inverseJoinColumns = {
@JoinColumn(name = &quot;role_id&quot;, referencedColumnName = &quot;role_id&quot;,
nullable = false, updatable = true)})
@JsonIgnoreProperties(value = {&quot;users&quot;})
private Set&lt;Role&gt; roles = new HashSet&lt;&gt;();
}

-------institution-------

@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@ToString
@Entity
@Table(name = &quot;institution&quot;)
public class Institution {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name=&quot;institution_Id&quot;)
private int institutionId;
@Column(name=&quot;name&quot;)
private String name;
@Column(name=&quot;type&quot;)
private String type;
@Column(name=&quot;location&quot;)
private String location;
@OneToMany(mappedBy = &quot;institution&quot;, fetch = FetchType.LAZY)
@JsonIgnoreProperties(value = {&quot;institution&quot; , &quot;user&quot;})
private Set&lt;User&gt; user;
}

-------role-------

@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@ToString
@Entity
@Table(name = &quot;role&quot;)
public class Role {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name=&quot;role_Id&quot;)
private int roleId;
@Column(name=&quot;name&quot;)
private String name;
@Column(name=&quot;description&quot;)
private String description;
@ManyToMany(mappedBy = &quot;roles&quot;, fetch = FetchType.LAZY)
@JsonIgnoreProperties(value = {&quot;roles&quot;})
private Set&lt;User&gt; users = new HashSet&lt;&gt;();
}

Those are my 3 entities and tables in MySql
i have 7 roles
• Super-User
• Bank-Admin
• Bank-Support
• Bank-Service
• Merchant-Admin
• Merchant-Support
• Merchant-service

The super-User can create a user of any role

@PostMapping(&quot;/addUser&quot;)
public String addUser(@RequestBody User user) {
String rawpassword = user.getPassword();
String encodedpasswrod = passwordencoder.encode(rawpassword);
user.setPassword(encodedpasswrod);
userrepository.save(user);
return &quot;user saved with name: &quot; + user.getName();
}

this api works and i can set the role to anything in my api json body

But want that if the User is Bank-Admin he can only create Bank-Support and Bank-Service
im trying to create a new API which can only create a user with those 2 specific roles.
and then restrict the bank admin to access the other API that can create users of any kind.

is there any other way to do it and if no how can i do that...

答案1

得分: 1

你必须实现自定义的用户权限管理功能。

例如,根据登录人员,您将获得该登录人员的角色,然后根据您的标准进行验证,比如检查他正在尝试添加的实体是否有资格创建它。

Map<String, List<String>> roleUserAccessMap = new HashMap<>();
roleUserAccessMap.put("Bank-Admin", Arrays.asList("Bank-Support", "Bank-Service"));

只需像下面这样进行检查

String loginPersonRole = "Bank-Admin"; //此值应从已登录人员的上下文中获取
if (roleUserAccessMap.containsKey(loginPersonRole) && roleUserAccessMap.get(loginPersonRole).contains(newuserrole)) {
    //继续进行 Add API 操作
} else {
    System.out.println("您没有足够的权限来创建用户");
}

这将对您有所帮助
英文:

You have to implement your custom implementation of User Entitlement.

Like according to login person, you will get that login person role, and according to your criteria just put validation like check that entity he is trying to add is he eligible to create it.

Map&lt;String, List&lt;String&gt;&gt; roleUserAccessMap = new HashMap&lt;&gt;();
roleUserAccessMap.put(&quot;Bank-Admin&quot;, Arrays.asList(&quot;Bank-Support&quot;, &quot;Bank-Service&quot;));

Just check like below

        String loginPersonRole=&quot;Bank-Admin&quot;; //This value should get from logged-in person context
if(roleUserAccessMap.containsKey(loginPersonRole) &amp;&amp; roleUserAccessMap.get(loginPersonRole).contains(newuserrole) ){
//proceed ahead with Add api
}else{
System.out.println(&quot;You do not have enough privileage to create Use&quot;);
}

This will help you.

huangapple
  • 本文由 发表于 2020年8月21日 22:40:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/63524939.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定