Reputation: 13
currently I'm working on a Spring Boot based web application in Java. I'm trying to create worker registration for my application. To be honest this is my first application like this and I don't really know how to grant user roles while registration. I've watched a couple of tutorials, but no one shows how to grant roles, while adding new user to database.
In my database I have tables Worker and Role like below.
In registration form I have two checkboxes: worker and admin and I would like to grant permissions depending on which ones have been selected .
This is what I have:
Worker.java
@Id
@Column(name = "workerId")
@GeneratedValue(
strategy= GenerationType.AUTO,
generator="native"
)
@GenericGenerator(
name = "native",
strategy = "native"
)
private int workerId;
@Column(name = "login")
@NotEmpty
private String username;
@Column(name = "password")
@NotEmpty
private String password;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "workerId", fetch = FetchType.EAGER, orphanRemoval = true)
private Set<Role> roles;
WorkerRole.java
public enum WorkerRole {
WORKER,ADMIN;}
Role.java
@NotNull
@ManyToOne
@JoinColumn(name = "workerId")
private Worker workerId;
@Id
@Column(name = "role")
private String role;
//getters and setters
WorkerService.java
@PersistenceContext
EntityManager entityManager;
@Autowired
private WorkerRepository workerRepository;
@Autowired
public WorkerService(WorkerRepository workerRepository){
this.workerRepository = workerRepository;
}
public Worker findByEmail(String email){
return workerRepository.findByEmail(email);
}
public Optional<Worker> findByUsername(String username)
{
return workerRepository.findByUsername(username);
}
public Worker findByConfirmationToken(String confirmationToken){
return workerRepository.findByConfirmationToken(confirmationToken);
}
public void saveUser(Worker worker){
workerRepository.save(worker);
}
public PasswordEncoder getPasswordEncoder() {
return new PasswordEncoder() {
@Override
public String encode(CharSequence charSequence) {
return charSequence.toString();
}
@Override
public boolean matches(CharSequence charSequence, String s) {
return true;
}
};
}
public Worker findByUname(String login){
Worker worker = null;
try{
worker = entityManager.createQuery("select w from Worker w " +
"where w.login = :login ", Worker.class)
.setParameter("login", login)
.getSingleResult();
}catch (Exception e){
System.out.println("No results found for that uname");
}
return worker;
}
CustomUserDetails.java
public CustomUserDetails(final Worker worker) {
super(worker);
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return getRoles()
.stream()
.map(role -> new SimpleGrantedAuthority("ROLE_" + role.getRole()))
.collect(Collectors.toList());
}
@Override
public String getPassword() {
return super.getPassword();
}
@Override
public String getUsername() {
return super.getUsername();
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return true;
}
CustomUserDetailsService.java
@Autowired
private WorkerRepository workerRepository;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
Optional<Worker> optionalUsers = workerRepository.findByUsername(username);
optionalUsers
.orElseThrow(() -> new UsernameNotFoundException("Worker not found"));
return optionalUsers
.map(CustomUserDetails::new)
.get();
}
I think that's all, I hope somebody can help me :)
Upvotes: 0
Views: 5316
Reputation: 64
In case of yours, you don't need that Role
class. Just use List<WorkerRole> roles
in Worker.java
.
Also you can implement UserDetails
in Worker.java
, instead of using that CustomUserDetails
.
Assuming that you are using Thymeleaf, a multiple selection dropdown can be populated with enum values.
After populating dropdown with enum values, you can just select role(s) and create the new user.
Upvotes: 1