1 | package finki.it.phoneluxbackend.services;
|
---|
2 |
|
---|
3 | import com.auth0.jwt.JWT;
|
---|
4 | import com.auth0.jwt.JWTVerifier;
|
---|
5 | import com.auth0.jwt.algorithms.Algorithm;
|
---|
6 | import com.auth0.jwt.interfaces.DecodedJWT;
|
---|
7 | import finki.it.phoneluxbackend.data.UserRole;
|
---|
8 | import finki.it.phoneluxbackend.entities.PhoneOffer;
|
---|
9 | import finki.it.phoneluxbackend.entities.User;
|
---|
10 | import finki.it.phoneluxbackend.repositories.PhoneOfferRepository;
|
---|
11 | import finki.it.phoneluxbackend.repositories.UserRepository;
|
---|
12 | import finki.it.phoneluxbackend.entities.ConfirmationToken;
|
---|
13 | import lombok.AllArgsConstructor;
|
---|
14 | import org.springframework.http.ResponseEntity;
|
---|
15 | import org.springframework.security.core.userdetails.UserDetails;
|
---|
16 | import org.springframework.security.core.userdetails.UserDetailsService;
|
---|
17 | import org.springframework.security.core.userdetails.UsernameNotFoundException;
|
---|
18 | import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
|
---|
19 | import org.springframework.stereotype.Service;
|
---|
20 |
|
---|
21 | import java.time.LocalDateTime;
|
---|
22 |
|
---|
23 | import java.util.Comparator;
|
---|
24 | import java.util.List;
|
---|
25 | import java.util.UUID;
|
---|
26 | import java.util.stream.Collectors;
|
---|
27 |
|
---|
28 | @Service
|
---|
29 | @AllArgsConstructor
|
---|
30 | public class UserService implements UserDetailsService {
|
---|
31 | private final UserRepository userRepository;
|
---|
32 | private final PhoneOfferRepository phoneOfferRepository;
|
---|
33 | private final BCryptPasswordEncoder bCryptPasswordEncoder;
|
---|
34 | private final ConfirmationTokenService confirmationTokenService;
|
---|
35 |
|
---|
36 |
|
---|
37 | @Override
|
---|
38 | public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
|
---|
39 | return userRepository.findByEmail(email)
|
---|
40 | .orElseThrow(() -> new UsernameNotFoundException("User with email "+email+" not found!"));
|
---|
41 | }
|
---|
42 |
|
---|
43 |
|
---|
44 |
|
---|
45 | public ResponseEntity<Object> signUpUser(User user)
|
---|
46 | {
|
---|
47 | boolean userExists = userRepository.findByEmail(user.getEmail()).isPresent();
|
---|
48 |
|
---|
49 |
|
---|
50 | if (userExists){
|
---|
51 | User userToRegister = userRepository.findByEmail(user.getEmail()).get();
|
---|
52 | if(userToRegister.getEnabled()) {
|
---|
53 | return ResponseEntity.badRequest().body("Error:Е-маил адресата е веќе зафатена!");
|
---|
54 | }
|
---|
55 | else {
|
---|
56 | return ResponseEntity.badRequest().body("Error:Профилот не е активиран. Потврдете на вашата е-маил адреса!" );
|
---|
57 | }
|
---|
58 | }
|
---|
59 |
|
---|
60 | String encodedPassword = bCryptPasswordEncoder.encode(user.getPassword());
|
---|
61 |
|
---|
62 | user.setPassword(encodedPassword);
|
---|
63 |
|
---|
64 | String token = UUID.randomUUID().toString();
|
---|
65 | ConfirmationToken confirmationToken = new ConfirmationToken(token,
|
---|
66 | LocalDateTime.now(),
|
---|
67 | LocalDateTime.now().plusMinutes(15),
|
---|
68 | user
|
---|
69 | );
|
---|
70 |
|
---|
71 | confirmationTokenService.saveConfirmationToken(confirmationToken);
|
---|
72 |
|
---|
73 | return ResponseEntity.ok().body("token:"+token);
|
---|
74 | }
|
---|
75 |
|
---|
76 | public int enableUser(String email) {
|
---|
77 | return userRepository.enableUser(email);
|
---|
78 | }
|
---|
79 |
|
---|
80 |
|
---|
81 | public User getUserFromToken(String token) {
|
---|
82 | Algorithm algorithm = Algorithm.HMAC256("secret".getBytes());
|
---|
83 | JWTVerifier verifier = JWT.require(algorithm).build();
|
---|
84 | DecodedJWT decodedJWT = verifier.verify(token);
|
---|
85 | String email = decodedJWT.getSubject();
|
---|
86 | UserRole role = UserRole.valueOf(decodedJWT.getClaim("role").asArray(String.class)[0]);
|
---|
87 | String name = decodedJWT.getClaim("name").as(String.class);
|
---|
88 | Long id = decodedJWT.getClaim("id").as(Long.class);
|
---|
89 | // String pickedSpecifications = decodedJWT.getClaim("pickedSpecifications").as(String.class);
|
---|
90 | return new User(id,name,role);
|
---|
91 | }
|
---|
92 |
|
---|
93 | public List<PhoneOffer> getFavouriteOffersForUser(Long userId) {
|
---|
94 | boolean exists = userRepository.existsById(userId);
|
---|
95 | if(!exists)
|
---|
96 | throw new IllegalStateException("User with id "+userId+" does not exist");
|
---|
97 |
|
---|
98 | return userRepository.findById(userId).get().getFavouriteOffers();
|
---|
99 | }
|
---|
100 |
|
---|
101 | public ResponseEntity<Object> editOfferForUser(Long userId, Long offerId, String option) {
|
---|
102 | boolean userExists = userRepository.existsById(userId);
|
---|
103 | if (!userExists)
|
---|
104 | {
|
---|
105 | return ResponseEntity.badRequest().body("User with id "+userId+" doesn't exist");
|
---|
106 | }
|
---|
107 |
|
---|
108 | boolean offerExists = phoneOfferRepository.existsById(offerId);
|
---|
109 |
|
---|
110 | if (!offerExists)
|
---|
111 | {
|
---|
112 | return ResponseEntity.badRequest().body("Offer with id "+offerId+" doesn't exist");
|
---|
113 | }
|
---|
114 |
|
---|
115 | User user = userRepository.findById(userId).get();
|
---|
116 | PhoneOffer phoneOffer = phoneOfferRepository.findById(offerId).get();
|
---|
117 |
|
---|
118 | if(option.equals("add")) {
|
---|
119 | user.getFavouriteOffers().add(phoneOffer);
|
---|
120 | }
|
---|
121 | else{
|
---|
122 | user.getFavouriteOffers().remove(phoneOffer);
|
---|
123 | }
|
---|
124 |
|
---|
125 | userRepository.save(user);
|
---|
126 |
|
---|
127 | return ResponseEntity.ok().build();
|
---|
128 | }
|
---|
129 |
|
---|
130 | public List<User> getUsers(String searchValue) {
|
---|
131 | List<User> users = userRepository.findAll().stream()
|
---|
132 | .filter(user -> user.getUserRole() != UserRole.SUPERADMIN && user.getEnabled())
|
---|
133 | .map(user -> new User(user.getId(),user.getFirstName(),
|
---|
134 | user.getLastName(),user.getEmail(),user.getUserRole()))
|
---|
135 | .collect(Collectors.toList());
|
---|
136 |
|
---|
137 | if(searchValue != null)
|
---|
138 | {
|
---|
139 | users = users.stream()
|
---|
140 | .filter(user -> user.getEmail().toLowerCase().contains(searchValue.stripIndent().toLowerCase())
|
---|
141 | || user.getFirstName().toLowerCase().contains(searchValue.stripIndent().toLowerCase()))
|
---|
142 | .collect(Collectors.toList());
|
---|
143 | }
|
---|
144 |
|
---|
145 | return users.stream()
|
---|
146 | .sorted(Comparator.comparing(User::getId))
|
---|
147 | .collect(Collectors.toList());
|
---|
148 |
|
---|
149 | }
|
---|
150 |
|
---|
151 | public ResponseEntity<Object> giveAdminRoleToUser(Long userId) {
|
---|
152 | boolean userExists = userRepository.existsById(userId);
|
---|
153 | if (!userExists)
|
---|
154 | {
|
---|
155 | return ResponseEntity.badRequest().body("User with id "+userId+" doesn't exist");
|
---|
156 | }
|
---|
157 |
|
---|
158 | User user = userRepository.findById(userId).get();
|
---|
159 |
|
---|
160 | user.setUserRole(UserRole.ADMIN);
|
---|
161 | userRepository.save(user);
|
---|
162 |
|
---|
163 | return ResponseEntity.ok().build();
|
---|
164 | }
|
---|
165 |
|
---|
166 | public ResponseEntity<Object> removeAdminRoleFromUser(Long userId) {
|
---|
167 | boolean userExists = userRepository.existsById(userId);
|
---|
168 | if (!userExists)
|
---|
169 | {
|
---|
170 | return ResponseEntity.badRequest().body("User with id "+userId+" doesn't exist");
|
---|
171 | }
|
---|
172 |
|
---|
173 | User user = userRepository.findById(userId).get();
|
---|
174 |
|
---|
175 | user.setUserRole(UserRole.USER);
|
---|
176 | userRepository.save(user);
|
---|
177 | return ResponseEntity.ok().build();
|
---|
178 | }
|
---|
179 |
|
---|
180 | public ResponseEntity<Object> editSpecificationsForUser(Long userId, String specifications) {
|
---|
181 | boolean userExists = userRepository.existsById(userId);
|
---|
182 | if (!userExists)
|
---|
183 | {
|
---|
184 | return ResponseEntity.badRequest().body("User with id "+userId+" doesn't exist");
|
---|
185 | }
|
---|
186 | User user = userRepository.findById(userId).get();
|
---|
187 |
|
---|
188 | user.setSpecifications(specifications);
|
---|
189 | userRepository.save(user);
|
---|
190 |
|
---|
191 | return ResponseEntity.ok().build();
|
---|
192 | }
|
---|
193 |
|
---|
194 | public String getSpecificationsForUser(Long userId) {
|
---|
195 | boolean userExists = userRepository.existsById(userId);
|
---|
196 | if (!userExists)
|
---|
197 | {
|
---|
198 | throw new UsernameNotFoundException("User with id "+userId+" doesn't exist");
|
---|
199 | }
|
---|
200 |
|
---|
201 | User user = userRepository.findById(userId).get();
|
---|
202 |
|
---|
203 | return user.getSpecifications() != null ? user.getSpecifications() : "[]";
|
---|
204 | }
|
---|
205 | }
|
---|