backend/buisnesslogic/src/main/java/com/plannaplan/services/UserService.java

84 lines
2.6 KiB
Java
Raw Normal View History

2020-07-25 10:38:19 +02:00
package com.plannaplan.services;
2020-10-19 12:13:02 +02:00
import java.util.List;
2020-09-25 17:01:38 +02:00
import java.util.Optional;
import java.util.UUID;
import com.plannaplan.entities.User;
import com.plannaplan.exceptions.UserNotFoundException;
2020-07-25 10:38:19 +02:00
import com.plannaplan.repositories.UserRepository;
2020-10-19 12:13:02 +02:00
import com.plannaplan.types.UserRoles;
2020-07-25 10:38:19 +02:00
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
2020-11-20 13:20:44 +01:00
/**
* Service of UserService which can get(By Email), login, save user.
*/
2020-07-25 10:38:19 +02:00
@Service
public class UserService {
2020-07-25 10:38:19 +02:00
@Autowired
2020-07-25 10:56:11 +02:00
private UserRepository repo;
2020-07-25 10:38:19 +02:00
2020-07-27 16:44:04 +02:00
public UserService() {
super();
2020-07-25 10:38:19 +02:00
}
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);
this.repo.save(newUser);
return 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);
this.repo.save(newUser);
return newUser;
}
}
}
public String login(String authority) throws UserNotFoundException {
User user = this.repo.getByAuthority(authority.replace("\n", "").trim())
.orElseThrow(() -> new UserNotFoundException("Can not find user with given authority"));
2020-10-19 12:13:02 +02:00
final String token = UUID.randomUUID().toString();
user.setToken(token);
2020-09-14 12:55:47 +02:00
this.repo.save(user);
return token;
}
2020-11-17 19:36:56 +01:00
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"));
}
2020-09-25 17:01:38 +02:00
public Optional<User> getByToken(String token) {
2020-09-14 14:02:05 +02:00
return this.repo.getByToken(token);
}
2020-10-19 12:13:02 +02:00
public List<User> searchForStudents(String query) {
return this.repo.searchForUsers(query, UserRoles.STUDENT);
}
2020-10-29 16:25:55 +01:00
public Optional<User> getById(Long userId) {
return this.repo.findById(userId);
}
2020-07-25 10:38:19 +02:00
}