blob: f74308b346adf3a166d469964c63f3714977fbf8 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
|
package com.blog.web.models;
import jakarta.persistence.*;
import jakarta.validation.constraints.NotEmpty;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Collectors;
@Entity(name = "users")
// Named UserEntity to prevent conflicts with Java User object
public class UserEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private final long id = 0;
@NotEmpty
@Column(unique = true)
private String username;
@NotEmpty
@Column(unique = true)
private String email;
@NotEmpty
private String password;
@ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@JoinTable(name = "user_roles", joinColumns = {@JoinColumn(name = "user_id", referencedColumnName = "id")}, inverseJoinColumns = {@JoinColumn(name = "role_id", referencedColumnName = "id")})
private final Set<Role> roles = new HashSet<>();
public UserEntity(String username, String email, String password, HashSet<Role> roles) {
this.username = username;
this.email = email;
this.password = password;
setRoles(roles);
}
public UserEntity() {
}
public boolean equals(UserEntity user) {
return this.id == user.getId();
}
public User toSecurityUser() {
return new User(this.getEmail(), this.password, this.getRoles().stream().map((role) -> new SimpleGrantedAuthority(role.getName())).collect(Collectors.toList()));
}
public long getId() {
return id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public void setPassword(String password) {
this.password = password;
}
public Set<Role> getRoles() {
return roles;
}
public void setRoles(Set<Role> roles) {
this.roles.clear();
this.roles.addAll(roles);
}
}
|