-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Adicionado gerador de hash e jwt builder
- Loading branch information
Showing
9 changed files
with
278 additions
and
4 deletions.
There are no files selected for viewing
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
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
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
57 changes: 57 additions & 0 deletions
57
src/main/java/io/github/arrudalabs/mizudo/resources/membros/UsuarioDoMembroResource.java
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,57 @@ | ||
package io.github.arrudalabs.mizudo.resources.membros; | ||
|
||
import io.github.arrudalabs.mizudo.model.Membro; | ||
import io.github.arrudalabs.mizudo.model.Usuario; | ||
import io.github.arrudalabs.mizudo.validation.DeveSerIdValido; | ||
|
||
import javax.validation.Valid; | ||
import javax.validation.constraints.NotBlank; | ||
import javax.ws.rs.PUT; | ||
import javax.ws.rs.Path; | ||
import javax.ws.rs.PathParam; | ||
|
||
@Path("/membros/{membroId}/user") | ||
public class UsuarioDoMembroResource { | ||
|
||
@PUT | ||
public UsuarioRegistrado definirUsuario( | ||
@DeveSerIdValido( | ||
entityClass = Membro.class, | ||
message = "Membro inválido" | ||
) | ||
@PathParam("membroId") final Long membroId, | ||
@Valid final NovoUsuario novoUsuario) { | ||
|
||
return UsuarioRegistrado.of(novoUsuario.definirUsuario(membroId)); | ||
} | ||
|
||
public static class NovoUsuario { | ||
|
||
@NotBlank | ||
public String username; | ||
@NotBlank | ||
public String senha; | ||
@NotBlank | ||
public String confirmacaoSenha; | ||
|
||
public Usuario definirUsuario(Long membroId) { | ||
var usuario = new Usuario(); | ||
usuario.username = this.username; | ||
//TODO implementar | ||
return usuario; | ||
} | ||
} | ||
|
||
public static class UsuarioRegistrado { | ||
|
||
public static UsuarioRegistrado of(Usuario usuario) { | ||
var usuarioRegistrado = new UsuarioRegistrado(); | ||
usuarioRegistrado.username = usuario.username; | ||
return usuarioRegistrado; | ||
} | ||
|
||
public String username; | ||
public String senha = "*****"; | ||
} | ||
|
||
} |
38 changes: 38 additions & 0 deletions
38
src/main/java/io/github/arrudalabs/mizudo/services/GeradorDeHash.java
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,38 @@ | ||
package io.github.arrudalabs.mizudo.services; | ||
|
||
import org.eclipse.microprofile.config.inject.ConfigProperty; | ||
|
||
import javax.crypto.SecretKeyFactory; | ||
import javax.crypto.spec.PBEKeySpec; | ||
import javax.enterprise.context.ApplicationScoped; | ||
import java.nio.charset.StandardCharsets; | ||
import java.util.Base64; | ||
|
||
@ApplicationScoped | ||
public class GeradorDeHash { | ||
|
||
@ConfigProperty(name = "gerador.senha.algoritmo",defaultValue = "PBKDF2WithHmacSHA512") | ||
private String algoritmo; | ||
@ConfigProperty(name = "gerador.senha.iteracoes",defaultValue = "150000") | ||
private Integer iteracoes; | ||
@ConfigProperty(name = "gerador.senha.tamanho.chave",defaultValue = "32") | ||
private Integer tamanhoChave; | ||
|
||
public String gerarHash(String salt, String senha){ | ||
try { | ||
var hash = SecretKeyFactory.getInstance(this.algoritmo) | ||
.generateSecret( | ||
new PBEKeySpec( | ||
senha.toCharArray(), | ||
salt.getBytes(StandardCharsets.UTF_8), | ||
this.iteracoes, | ||
this.tamanhoChave | ||
) | ||
).getEncoded(); | ||
return Base64.getEncoder().encodeToString(hash); | ||
} catch (Exception e) { | ||
throw new RuntimeException(e); | ||
} | ||
} | ||
|
||
} |
63 changes: 63 additions & 0 deletions
63
src/main/java/io/github/arrudalabs/mizudo/services/JwtTokenBuilder.java
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,63 @@ | ||
package io.github.arrudalabs.mizudo.services; | ||
|
||
import io.smallrye.jwt.build.Jwt; | ||
import org.eclipse.microprofile.config.inject.ConfigProperty; | ||
|
||
import javax.enterprise.context.ApplicationScoped; | ||
import java.security.KeyFactory; | ||
import java.security.NoSuchAlgorithmException; | ||
import java.security.PrivateKey; | ||
import java.security.spec.InvalidKeySpecException; | ||
import java.security.spec.PKCS8EncodedKeySpec; | ||
import java.util.Base64; | ||
import java.util.Optional; | ||
import java.util.Set; | ||
import java.util.UUID; | ||
|
||
@ApplicationScoped | ||
public class JwtTokenBuilder { | ||
|
||
private final Long duracaoEmMinutos; | ||
private final String privateKey; | ||
private final String issuer; | ||
private final String keyId; | ||
|
||
public JwtTokenBuilder( | ||
@ConfigProperty(name = "jwt.token.duracao.minutos", defaultValue = "300") final Long duracaoEmMinutos, | ||
@ConfigProperty(name = "jwt.private.key") final String privateKey, | ||
@ConfigProperty(name = "jwt.issuer") final String issuer | ||
) { | ||
this.duracaoEmMinutos = duracaoEmMinutos; | ||
this.privateKey = privateKey; | ||
this.issuer = issuer; | ||
this.keyId = UUID.randomUUID().toString(); | ||
} | ||
|
||
public String gerarToken(String username, | ||
Set<String> papeis) throws NoSuchAlgorithmException, InvalidKeySpecException { | ||
|
||
long currentTimeInSecs = System.currentTimeMillis() / 1000; | ||
var claimsBuilder = Jwt.claims(); | ||
PrivateKey privateKey = decodePrivateKey(); | ||
|
||
claimsBuilder.issuer(this.issuer); | ||
claimsBuilder.subject(username); | ||
claimsBuilder.issuedAt(currentTimeInSecs); | ||
claimsBuilder.expiresAt(tempoDeExpiracao(currentTimeInSecs)); | ||
claimsBuilder.groups(papeis); | ||
|
||
return claimsBuilder.jws().keyId(this.keyId).sign(privateKey); | ||
} | ||
|
||
private PrivateKey decodePrivateKey() throws NoSuchAlgorithmException, InvalidKeySpecException { | ||
var decodedKey = Base64.getDecoder().decode(this.privateKey); | ||
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(decodedKey); | ||
KeyFactory keyFactory=KeyFactory.getInstance("RSA"); | ||
return keyFactory.generatePrivate(keySpec); | ||
} | ||
|
||
public long tempoDeExpiracao(long currentTimeInSecs) { | ||
return currentTimeInSecs + (this.duracaoEmMinutos * 60); | ||
} | ||
|
||
} |
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
61 changes: 61 additions & 0 deletions
61
src/test/java/io/github/arrudalabs/mizudo/resources/membros/UsuarioDoMembroTest.java
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,61 @@ | ||
package io.github.arrudalabs.mizudo.resources.membros; | ||
|
||
import io.github.arrudalabs.mizudo.model.Membro; | ||
import io.github.arrudalabs.mizudo.model.Usuario; | ||
import io.github.arrudalabs.mizudo.resources.ApiTestSupport; | ||
import io.quarkus.test.junit.QuarkusTest; | ||
import io.restassured.http.ContentType; | ||
import org.junit.jupiter.api.AfterEach; | ||
import org.junit.jupiter.api.BeforeEach; | ||
import org.junit.jupiter.api.Test; | ||
|
||
import javax.inject.Inject; | ||
import javax.json.Json; | ||
import javax.ws.rs.core.Response; | ||
|
||
import java.util.Map; | ||
import java.util.UUID; | ||
|
||
import static org.hamcrest.Matchers.*; | ||
import static org.hamcrest.MatcherAssert.*; | ||
|
||
@QuarkusTest | ||
public class UsuarioDoMembroTest { | ||
|
||
@Inject | ||
ApiTestSupport apiTestSupport; | ||
|
||
@BeforeEach | ||
@AfterEach | ||
void limparMembros(){ | ||
apiTestSupport.execute(Usuario::apagarTodosOsUsuarios); | ||
apiTestSupport.execute(Membro::removerTodosMembros); | ||
} | ||
|
||
@Test | ||
void deveDefinirUsuarioParaUmMembroValido(){ | ||
|
||
var membro = apiTestSupport.executeAndGet(()->Membro.novoMembro(UUID.randomUUID().toString())); | ||
|
||
String senha = UUID.randomUUID().toString(); | ||
String username = UUID.randomUUID().toString(); | ||
apiTestSupport | ||
.newAuthenticatedRequest() | ||
.log().everything() | ||
.contentType(ContentType.JSON) | ||
.body(Json.createObjectBuilder() | ||
.add("username", username) | ||
.add("senha", senha) | ||
.add("confirmacaoSenha",senha) | ||
.build().toString()) | ||
.put("/resources/membros/{id}/user", Map.of("id",membro.id)) | ||
.then() | ||
.log().everything() | ||
.statusCode(Response.Status.OK.getStatusCode()) | ||
.body("username", is(username)) | ||
.body("senha", is("*****")); | ||
|
||
} | ||
|
||
|
||
} |
25 changes: 25 additions & 0 deletions
25
src/test/java/io/github/arrudalabs/mizudo/services/JwtTokenBuilderTest.java
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,25 @@ | ||
package io.github.arrudalabs.mizudo.services; | ||
|
||
import io.quarkus.test.junit.QuarkusTest; | ||
import org.junit.jupiter.api.Test; | ||
|
||
import javax.inject.Inject; | ||
import java.security.NoSuchAlgorithmException; | ||
import java.security.spec.InvalidKeySpecException; | ||
import java.util.Set; | ||
|
||
@QuarkusTest | ||
class JwtTokenBuilderTest { | ||
|
||
@Inject | ||
JwtTokenBuilder jwtTokenBuilder; | ||
|
||
@Test | ||
void deveGerarUmTokenValido() throws NoSuchAlgorithmException, InvalidKeySpecException { | ||
|
||
System.out.println(jwtTokenBuilder.gerarToken("admin", Set.of("ADMIN", "USER"))); | ||
|
||
} | ||
|
||
|
||
} |