View Javadoc
1   package usecase.user;
2   
3   import com.sun.istack.NotNull;
4   import media.MediaRepository;
5   import media.ReadLimitExceededException;
6   import model.entity.User;
7   import model.repository.GenericRepository;
8   import model.validation.*;
9   import usecase.auth.*;
10  import usecase.auth.Pbkdf2PasswordHash.HashedPassword;
11  
12  import javax.enterprise.context.ApplicationScoped;
13  import javax.inject.Inject;
14  import javax.transaction.Transactional;
15  import javax.validation.Valid;
16  import javax.validation.constraints.NotBlank;
17  import java.io.IOException;
18  import java.util.List;
19  import java.util.stream.Collectors;
20  
21  /**
22   * Classe che fornisce i servizi relativi agli utenti.
23   */
24  @ApplicationScoped
25  @Transactional
26  public class UserService {
27      private GenericRepository genericRepository;
28      private MediaRepository bcRepo;
29      private CurrentUser currentUser;
30      private Pbkdf2PasswordHash passwordHash;
31  
32      protected UserService(){}
33  
34      @Inject
35      protected UserService(GenericRepository genericRepository,
36                            MediaRepository mediaRepository, Pbkdf2PasswordHash passwordHash,
37                            CurrentUser currentUser){
38          this.genericRepository = genericRepository;
39          this.bcRepo = mediaRepository;
40          this.passwordHash = passwordHash;
41          this.currentUser = currentUser;
42      }
43  
44      /**
45       * Converte User in UserProfile.
46       * @param user utente da convertire
47       * @return UserProfile con i dati di user
48       */
49      private UserProfile map(User user){
50          return UserProfile.builder()
51                  .id(user.getId())
52                  .email(user.getEmail())
53                  .creationDate(user.getCreationDate())
54                  .description(user.getDescription())
55                  .picture(user.getPicture())
56                  .username(user.getUsername())
57                  .isAdmin(user.getAdmin()).build();
58      }
59  
60      /**
61       * Inverte lo stato di admin di un utente dato un id
62       * @param id id di un utente esistente
63       */
64      @AdminsOnly
65      public void toggleAdmin(@UserExists int id){
66          User u = genericRepository.findById(User.class,id);
67          u.setAdmin(!u.getAdmin());
68      }
69  
70      /**
71       * Ritorna un entita UserProfile dato un nome
72       * @param name di un utente esistente
73       * @return entita UserProfile
74       */
75      public UserProfile getUser(@NotBlank @UserExists String name){
76          User u = genericRepository.findByNaturalId(User.class,name);
77          return map(u);
78      }
79  
80      /**
81       * Ritorna un entita UserProfile dato un id
82       * @param id di un utente esistente
83       * @return entita UserProfile
84       */
85      public UserProfile getUser(@UserExists int id){
86          User u = genericRepository.findById(User.class,id);
87          return map(u);
88      }
89  
90      /**
91       * Ritorna un lo username di un utente dato un id
92       * @param id di un utente esistente
93       * @return nome dell'utente
94       */
95      public String getUsernameById(@UserExists int id){
96          return genericRepository.findById(User.class,id).getUsername();
97      }
98  
99      /**
100      * Ritorna un lista di UserProfile relativa agli utenti registrati
101      * @return lista di entita UserIdentityDTO
102      */
103     public List<UserProfile> showUsers(){
104         List<User> users = genericRepository.findAll(User.class);
105         return users.stream().map(this::map).collect(Collectors.toList());
106     }
107 
108     /**
109      * Elimina un utente dato un id
110      * @param id di un utente esistente
111      */
112     @AdminsOnly
113     public void delete(@UserExists int id){
114         genericRepository.remove(genericRepository.findById(User.class, id));
115     }
116 
117     /**
118      * Modifica i dati di un utente dato un id
119      * @param edit nuovi dati dell'utente
120      * @param id di un utente esistente
121      */
122     @AuthenticationRequired
123     public void edit(@Valid UserEditPage edit,
124                      @UserExists int id){
125         if(currentUser.getId() != id && !currentUser.isAdmin())
126             throw new AuthorizationException();
127 
128         User u = genericRepository.findById(User.class,id);
129 
130         if(edit.getDescription() != null){
131             u.setDescription(edit.getDescription());
132         }
133         if(edit.getEmail() != null){
134             u.setEmail(edit.getEmail());
135         }
136         if(edit.getPassword() != null){
137             HashedPassword hashedPassword = passwordHash.generate(edit.getPassword());
138             u.setPassword(hashedPassword.getPassword());
139             u.setSalt(hashedPassword.getSalt());
140         }
141         if(edit.getPicture() != null){
142             try {
143                 u.setPicture(bcRepo.insert(edit.getPicture()));
144             } catch(ReadLimitExceededException e){
145                 throw new IllegalArgumentException("Il file non deve superare i 5MB");
146             } catch (IOException e) {
147                 throw new RuntimeException(e); //todo: delet this
148             }
149         }
150     }
151 
152     /**
153      * Crea un nuovo utente e ne restituisce l'id
154      * @param email stringa non vuota, unica e in formato email
155      * @param username stringa non vuota e unica
156      * @param password Stringa non vuota con minimo: 3 e massimo: 255 caratteri
157      * @return identificativo dell'utente creato
158      */
159     public int newUser(@NotNull @EmailFormat @UniqueEmail String email,
160                        @NotNull @UsernameFormat @UniqueUsername String username,
161                        @NotNull @PasswordFormat String password){
162         User user = new User();
163         user.setUsername(username);
164         user.setEmail(email);
165         HashedPassword hashedPassword = passwordHash.generate(password);
166         user.setPassword(hashedPassword.getPassword());
167         user.setSalt(hashedPassword.getSalt());
168         user.setAdmin(false);
169 
170         user = genericRepository.insert(user);
171         return user.getId();
172     }
173 }