TokenService.java 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. package com.ademicon.service.auth;
  2. import java.time.LocalDateTime;
  3. import com.ademicon.model.auth.AuthenticationModel;
  4. import com.ademicon.model.auth.TokenModel;
  5. import com.ademicon.repository.auth.TokenRepository;
  6. public class TokenService {
  7. private static TokenRepository tokenRepository = new TokenRepository();
  8. private static AuthenticationService authenticationService = new AuthenticationService();
  9. private static String refreshToken() throws Exception {
  10. try {
  11. AuthenticationModel authenticationModel = authenticationService.getToken();
  12. TokenModel tokenModel = new TokenModel();
  13. tokenModel.setAccess_token(authenticationModel.getAccess_token());
  14. tokenModel.setExpires_in(calculateDeadline(authenticationModel.getExpires_in()));
  15. tokenRepository.save(tokenModel);
  16. var rs = tokenModel.getAccess_token();
  17. return rs;
  18. } catch (Exception e) {
  19. System.out.println(e);
  20. e.printStackTrace();
  21. throw new Exception(e.getMessage());
  22. }
  23. }
  24. public String getToken() throws Exception {
  25. try {
  26. TokenModel tokenModel = tokenRepository.find();
  27. boolean isValid = tokenIsValid(tokenModel.getExpires_in());
  28. if (!isValid) {
  29. return refreshToken();
  30. }
  31. var rs = tokenModel.getAccess_token();
  32. return rs;
  33. } catch (Exception e) {
  34. System.err.println(e);
  35. throw e;
  36. }
  37. }
  38. private static LocalDateTime calculateDeadline(Integer deadline) {
  39. LocalDateTime newDate = LocalDateTime.now();
  40. return newDate.plusSeconds(deadline);
  41. }
  42. private static boolean tokenIsValid(LocalDateTime localDateTime) {
  43. LocalDateTime newLocalDateTime = LocalDateTime.now();
  44. boolean isValid = newLocalDateTime.isBefore(localDateTime);
  45. return isValid;
  46. }
  47. }