Last active
March 26, 2021 23:11
-
-
Save rponte/6ff504a793028274395dd6657efa049d to your computer and use it in GitHub Desktop.
Decorator simples para cuidar da segurança de forma transparente
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class HowToUse { | |
public static void main(String[] args) { | |
MercadoLivreHttpClient client = new MercadoLivreHttpClient(); | |
MercadoLivreHttpClient securedClient = new MercadoLivreSecuredHttpClient(client); | |
HttpResponse<?> response = securedClient.post(null); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package br.com.zup.edu; | |
public class MercadoLivreHttpClient { | |
public HttpResponse<?> post(HttpRequest<?> request) { | |
// TODO: consome recurso aqui usando algum HTTP client da vida | |
// a idéia aqui é que seu código não se preocupe com autorização, com token etc | |
return null; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package br.com.zup.edu; | |
public class MercadoLivreSecuredHttpClient extends MercadoLivreHttpClient { // decorator | |
private final MercadoLivreHttpClient delegate; | |
public MercadoLivreSecuredHttpClient(MercadoLivreHttpClient delegate) { | |
this.delegate = delegate; | |
} | |
@Override | |
public HttpResponse<?> post(HttpRequest<?> request) { | |
int attemps = 3; // TODO: vc decide aqui | |
while (attemps != 0) { | |
try { | |
request.addHeader("authorization", token()); // adiciona token valido na requisição | |
return delegate.post(request); // invoca objeto original | |
} catch(ExpiredTokenException e) { | |
attemps--; | |
// TODO: revalida token aqui, substitui e tenta de novo | |
} | |
} | |
throw new ExpiredTokenException("Impossivel concluir a requisição pois token inválido"); | |
} | |
private String token() { | |
// TODO: faz tua magica aqui | |
return "<token-gerado-ou-extraido-do-banco>"; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment