1 | package mk.ukim.finki.busngo.service.impl;
|
---|
2 |
|
---|
3 | import mk.ukim.finki.busngo.model.entities.Korisnik;
|
---|
4 | import mk.ukim.finki.busngo.model.exceptions.InvalidCredentialsException;
|
---|
5 | import mk.ukim.finki.busngo.model.exceptions.UserAlreadyExistsException;
|
---|
6 | import mk.ukim.finki.busngo.repository.KorisnikRepository;
|
---|
7 | import mk.ukim.finki.busngo.service.AuthService;
|
---|
8 | import org.springframework.security.crypto.password.PasswordEncoder;
|
---|
9 | import org.springframework.stereotype.Service;
|
---|
10 |
|
---|
11 | import java.util.List;
|
---|
12 |
|
---|
13 | @Service
|
---|
14 | public class AuthServiceImpl implements AuthService {
|
---|
15 | private final KorisnikRepository korisnikRepository;
|
---|
16 | private final PasswordEncoder passwordEncoder;
|
---|
17 |
|
---|
18 | public AuthServiceImpl(KorisnikRepository korisnikRepository, PasswordEncoder passwordEncoder) {
|
---|
19 | this.korisnikRepository = korisnikRepository;
|
---|
20 | this.passwordEncoder = passwordEncoder;
|
---|
21 | }
|
---|
22 |
|
---|
23 | @Override
|
---|
24 | public Korisnik login(String email, String password) {
|
---|
25 | if(email == null || password == null || email.isEmpty() || password.isEmpty())
|
---|
26 | throw new InvalidCredentialsException();
|
---|
27 | return korisnikRepository.findByKEmailAndKLozinka(email, password).orElseThrow(InvalidCredentialsException::new);
|
---|
28 | }
|
---|
29 |
|
---|
30 | @Override
|
---|
31 | public Korisnik register(String ime, String email, String password, String confirmPassword, String address, String telefon) {
|
---|
32 | if (email == null || password == null || email.isEmpty() || password.isEmpty()) {
|
---|
33 | throw new InvalidCredentialsException();
|
---|
34 | }
|
---|
35 |
|
---|
36 | if (!password.equals(confirmPassword)) {
|
---|
37 | throw new InvalidCredentialsException();
|
---|
38 | }
|
---|
39 |
|
---|
40 | if(this.korisnikRepository.findByKEmail(email).isPresent()) {
|
---|
41 | throw new UserAlreadyExistsException(email);
|
---|
42 | }
|
---|
43 |
|
---|
44 | Korisnik korisnik = new Korisnik();
|
---|
45 | korisnik.setKIme(ime);
|
---|
46 | korisnik.setKAdresa(address);
|
---|
47 | korisnik.setKLozinka(passwordEncoder.encode(password));
|
---|
48 | korisnik.setKEmail(email);
|
---|
49 | korisnik.setKTelefon(telefon);
|
---|
50 | korisnik.setKIsAdmin(false);
|
---|
51 |
|
---|
52 | return korisnikRepository.save(korisnik);
|
---|
53 | }
|
---|
54 |
|
---|
55 |
|
---|
56 | }
|
---|