1 | package com.example.kvizko.service.impl;
|
---|
2 |
|
---|
3 | import com.example.kvizko.exceptions.InvalidCredentialsException;
|
---|
4 | import com.example.kvizko.exceptions.UsernameAlreadyTakenException;
|
---|
5 | import com.example.kvizko.models.Quiztaker;
|
---|
6 | import com.example.kvizko.models.User;
|
---|
7 | import com.example.kvizko.repository.QuizTakerRepository;
|
---|
8 | import com.example.kvizko.repository.UserRepository;
|
---|
9 | import com.example.kvizko.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 QuizTakerRepository quizTakerRepository;
|
---|
20 | private final PasswordEncoder passwordEncoder;
|
---|
21 |
|
---|
22 | public UserServiceImpl(UserRepository userRepository, QuizTakerRepository quizTakerRepository, PasswordEncoder passwordEncoder) {
|
---|
23 | this.userRepository = userRepository;
|
---|
24 | this.quizTakerRepository = quizTakerRepository;
|
---|
25 | this.passwordEncoder = passwordEncoder;
|
---|
26 | }
|
---|
27 |
|
---|
28 | @Override
|
---|
29 | public User findByUsernameAndPassword(String username, String password) throws InvalidCredentialsException {
|
---|
30 | User user=userRepository.findByUsername(username);
|
---|
31 | if(user==null || !passwordEncoder.matches(password, user.getPasswordAttr()))
|
---|
32 | throw new InvalidCredentialsException();
|
---|
33 |
|
---|
34 | return user;
|
---|
35 | }
|
---|
36 |
|
---|
37 | @Override
|
---|
38 | public void registerUser(String username, String full_name, String password) throws UsernameAlreadyTakenException {
|
---|
39 | if(this.userRepository.findByUsername(username)==null)
|
---|
40 | {
|
---|
41 | User user=this.userRepository.save(new User(full_name, username, passwordEncoder.encode(password)));
|
---|
42 | Quiztaker quiztakerID=new Quiztaker(user.getUserid());
|
---|
43 | this.quizTakerRepository.save(quiztakerID);
|
---|
44 | }
|
---|
45 | else
|
---|
46 | {
|
---|
47 | throw new UsernameAlreadyTakenException();
|
---|
48 | }
|
---|
49 | }
|
---|
50 |
|
---|
51 |
|
---|
52 | }
|
---|