TokenSingleton.java 1.96 KB
Newer Older
1 2 3
package web.multitask.trismegistoservices.singleton;

import lombok.Getter;
4
import lombok.NoArgsConstructor;
5 6
import org.json.JSONArray;
import org.json.JSONObject;
7
import org.springframework.beans.factory.annotation.Autowired;
8 9
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
10
import web.multitask.trismegistoservices.utils.JWTokenUtil;
11 12 13

@Getter
@Component
14
@NoArgsConstructor
15 16 17 18
public class TokenSingleton {

    private final JSONArray tokens = new JSONArray();

19 20 21
    @Autowired
    private JWTokenUtil jwtTokenUtil;

22 23 24 25 26 27 28 29 30 31 32 33 34 35
    public boolean consumeToken(String token) {
        boolean isAvailable = false;
        for (int i = 0; i < tokens.length(); i++) {
            if (tokens.getJSONObject(i).getString("token").equals(token)) {
                if (tokens.getJSONObject(i).getBoolean("available")) {
                    tokens.getJSONObject(i).put("available", false);
                    isAvailable = true;
                }
                break;
            }
        }
        return isAvailable;
    }

36
    public boolean isTokenAvailable(String token) {
37
        boolean isAvailable = true;
38 39 40 41 42 43 44 45 46
        for (int i = 0; i < tokens.length(); i++) {
            if (tokens.getJSONObject(i).getString("token").equals(token)) {
                isAvailable = tokens.getJSONObject(i).getBoolean("available");
                break;
            }
        }
        return isAvailable;
    }

47 48 49 50 51 52 53
    public void addToken(String token) {
        tokens.put(new JSONObject().put("token", token).put("available", true));
    }

    @Scheduled(fixedRate = 3600000)
    public void removeUnavailableTokens() {
        System.out.println("Removing unavailable tokens");
54 55 56
        for(int i = 0; i < tokens.length(); i++){
            if(!tokens.getJSONObject(i).getBoolean("available") || jwtTokenUtil.isTokenExpired(tokens.getJSONObject(i).getString("token"))){
                System.out.println("Token removed "+tokens.remove(i));
57
            }
58
        }
59 60
    }
}