-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathUserService.java
92 lines (63 loc) · 2.55 KB
/
UserService.java
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
82
83
84
85
86
87
88
89
90
91
92
package com.example.fanaticbackend.service;
import com.example.fanaticbackend.exception.custom.FanaticDatabaseException;
import com.example.fanaticbackend.model.User;
import com.example.fanaticbackend.payload.PostResponse;
import com.example.fanaticbackend.repository.PostRepository;
import com.example.fanaticbackend.repository.UserRepository;
import lombok.AccessLevel;
import lombok.RequiredArgsConstructor;
import lombok.experimental.FieldDefaults;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.util.List;
@Service
@RequiredArgsConstructor
@FieldDefaults(level = AccessLevel.PRIVATE)
public class UserService {
//Dependency Injection
final UserRepository userRepository;
final PasswordEncoder passwordEncoder;
public User getUserByEmail(String email) {
User user = userRepository.findByEmail(email);
if (user == null) throw new FanaticDatabaseException("User not found with email: " + email);
return user;
}
public User getUserById(Long id) {
User user = userRepository.findUserById(id);
if (user == null) {
throw new FanaticDatabaseException("User not found with id: " + id);
}
return user;
}
public Boolean updateProfilePicture(User user, Long userId, MultipartFile profilePicture){
if (!user.getId().equals(userId)) {
throw new FanaticDatabaseException("You can only update your own profile picture");
}
try {
user.setProfilePicture(profilePicture.getBytes());
} catch (Exception e) {
throw new FanaticDatabaseException("Error while updating profile picture");
}
try {
userRepository.save(user);
} catch (Exception e) {
throw new FanaticDatabaseException("Error while saving new profile picture");
}
return true;
}
public Boolean updatePassword(User user, Long userId, String newPassword){
if (!user.getId().equals(userId)) {
throw new FanaticDatabaseException("You can only update your own password");
}
user.setPassword(passwordEncoder.encode(newPassword));
try {
userRepository.save(user);
} catch (Exception e) {
throw new FanaticDatabaseException("Error while saving new password");
}
return true;
}
}