88 lines
2.7 KiB
Java
Executable File
88 lines
2.7 KiB
Java
Executable File
package com.plannaplan.services;
|
|
|
|
import java.util.List;
|
|
import java.util.Optional;
|
|
import java.util.UUID;
|
|
|
|
import com.plannaplan.entities.User;
|
|
import com.plannaplan.exceptions.UserNotFoundException;
|
|
import com.plannaplan.repositories.UserRepository;
|
|
import com.plannaplan.types.UserRoles;
|
|
|
|
import org.springframework.beans.factory.annotation.Autowired;
|
|
import org.springframework.stereotype.Service;
|
|
|
|
/**
|
|
* Service of UserService which can get(By Email), login, save user.
|
|
*/
|
|
@Service
|
|
public class UserService {
|
|
@Autowired
|
|
private UserRepository repo;
|
|
|
|
public UserService() {
|
|
super();
|
|
}
|
|
|
|
public User checkForUser(String email, String usosId) {
|
|
if (usosId == null) {
|
|
Optional<User> user = this.repo.getByAuthority(email.replace("\n", "").trim());
|
|
if (user.isPresent()) {
|
|
return user.get();
|
|
} else {
|
|
final User newUser = new User(null, null, email.replace("\n", "").trim(), UserRoles.STUDENT);
|
|
return this.repo.save(newUser);
|
|
}
|
|
} else {
|
|
Optional<User> user = this.repo.getByUsosId(usosId.replace("\n", "").trim());
|
|
if (user.isPresent()) {
|
|
return user.get();
|
|
} else {
|
|
final User newUser = new User(null, null, email.replace("\n", "").trim(), usosId, UserRoles.STUDENT);
|
|
return this.repo.save(newUser);
|
|
}
|
|
}
|
|
}
|
|
|
|
public User login(User authority) throws UserNotFoundException {
|
|
final String token = UUID.randomUUID().toString();
|
|
try {
|
|
authority.setToken(token);
|
|
this.repo.save(authority);
|
|
} catch (Exception e) {
|
|
throw new UserNotFoundException(e.getMessage());
|
|
}
|
|
return authority;
|
|
}
|
|
|
|
public User save(User user) {
|
|
return this.repo.save(user);
|
|
}
|
|
|
|
public User getUserByEmail(String email) throws UserNotFoundException {
|
|
return this.repo.getByAuthority(email.replace("\n", "").trim())
|
|
.orElseThrow(() -> new UserNotFoundException("Cannot find user with given authority"));
|
|
|
|
}
|
|
|
|
public Optional<User> getByToken(String token) {
|
|
return this.repo.getByToken(token);
|
|
}
|
|
|
|
public List<User> searchForStudents(String query) {
|
|
return this.repo.searchForUsers(query, UserRoles.STUDENT);
|
|
}
|
|
|
|
public Optional<User> getById(Long userId) {
|
|
return this.repo.findById(userId);
|
|
}
|
|
|
|
public List<User> getAllStudents() {
|
|
return this.repo.getAllByRole(UserRoles.STUDENT);
|
|
}
|
|
|
|
public Optional<User> getUserByRefreshToken(String refreshToken) {
|
|
return this.repo.getByRefreshToken(refreshToken);
|
|
}
|
|
|
|
} |