1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859 |
- package com.ademicon.service.auth;
- import java.time.LocalDateTime;
- import com.ademicon.model.auth.AuthenticationModel;
- import com.ademicon.model.auth.TokenModel;
- import com.ademicon.repository.auth.TokenRepository;
- public class TokenService {
- private static TokenRepository tokenRepository = new TokenRepository();
- private static AuthenticationService authenticationService = new AuthenticationService();
- private static String refreshToken() throws Exception {
- try {
- AuthenticationModel authenticationModel = authenticationService.getToken();
- TokenModel tokenModel = new TokenModel();
- tokenModel.setAccess_token(authenticationModel.getAccess_token());
- tokenModel.setExpires_in(calculateDeadline(authenticationModel.getExpires_in()));
- tokenRepository.save(tokenModel);
- var rs = tokenModel.getAccess_token();
- return rs;
- } catch (Exception e) {
- System.out.println(e);
- e.printStackTrace();
- throw new Exception(e.getMessage());
- }
- }
- public String getToken() throws Exception {
- try {
- TokenModel tokenModel = tokenRepository.find();
- boolean isValid = tokenIsValid(tokenModel.getExpires_in());
- if (!isValid) {
- return refreshToken();
- }
- var rs = tokenModel.getAccess_token();
- return rs;
-
- } catch (Exception e) {
- System.err.println(e);
- throw e;
- }
- }
- private static LocalDateTime calculateDeadline(Integer deadline) {
- LocalDateTime newDate = LocalDateTime.now();
- return newDate.plusSeconds(deadline);
- }
- private static boolean tokenIsValid(LocalDateTime localDateTime) {
- LocalDateTime newLocalDateTime = LocalDateTime.now();
- boolean isValid = newLocalDateTime.isBefore(localDateTime);
- return isValid;
- }
- }
|