1 | package com.example.moviezone.service.Impl;
|
---|
2 |
|
---|
3 | import com.example.moviezone.model.Customer;
|
---|
4 | import com.example.moviezone.model.User;
|
---|
5 | import com.example.moviezone.model.Worker;
|
---|
6 | import com.example.moviezone.model.exceptions.PasswordsDoNotMatchException;
|
---|
7 | import com.example.moviezone.model.exceptions.UserNotFoundException;
|
---|
8 | import com.example.moviezone.repository.UserRepository;
|
---|
9 | import com.example.moviezone.service.UserService;
|
---|
10 | import org.springframework.security.crypto.password.PasswordEncoder;
|
---|
11 | import org.springframework.stereotype.Service;
|
---|
12 |
|
---|
13 | import java.util.List;
|
---|
14 |
|
---|
15 | @Service
|
---|
16 | public class UserServiceImpl implements UserService {
|
---|
17 |
|
---|
18 | private final UserRepository userRepository;
|
---|
19 | private final PasswordEncoder passwordEncoder;
|
---|
20 |
|
---|
21 | public UserServiceImpl(UserRepository userRepository, PasswordEncoder passwordEncoder) {
|
---|
22 | this.userRepository = userRepository;
|
---|
23 | this.passwordEncoder = passwordEncoder;
|
---|
24 | }
|
---|
25 |
|
---|
26 | @Override
|
---|
27 | public List<User> findAllUsers() {
|
---|
28 | return userRepository.findAll();
|
---|
29 | }
|
---|
30 |
|
---|
31 | @Override
|
---|
32 | public User findById(Integer id) {
|
---|
33 | return userRepository.findById(id).orElseThrow(UserNotFoundException::new);
|
---|
34 | }
|
---|
35 |
|
---|
36 | @Override
|
---|
37 | public User findByUsername(String username) {
|
---|
38 | return userRepository.findByUsername(username);
|
---|
39 | }
|
---|
40 |
|
---|
41 | @Override
|
---|
42 | public User register(String first_name, String last_name, String username, String email, String number, String password,String repeatedPassword, String role) {
|
---|
43 | if(!password.equals(repeatedPassword))
|
---|
44 | throw new PasswordsDoNotMatchException();
|
---|
45 | else
|
---|
46 | if(role.equals("worker"))
|
---|
47 | {
|
---|
48 | return userRepository.save(new Worker(passwordEncoder.encode(password),first_name,last_name,username,email,number));
|
---|
49 | }
|
---|
50 | else
|
---|
51 | return userRepository.save(new Customer(passwordEncoder.encode(password),first_name,last_name,username,email,number));
|
---|
52 | }
|
---|
53 |
|
---|
54 | @Override
|
---|
55 | public User login(String username, String password) {
|
---|
56 | return userRepository.findAllByUsernameAndPassword(username,password).stream().findFirst().orElseThrow(UserNotFoundException::new);
|
---|
57 | }
|
---|
58 |
|
---|
59 |
|
---|
60 | }
|
---|