-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- login - token - middleware
- Loading branch information
Showing
8 changed files
with
195 additions
and
1 deletion.
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,73 @@ | ||
package autenticacao | ||
|
||
import ( | ||
"api/src/config" | ||
"errors" | ||
"fmt" | ||
jwt "github.com/dgrijalva/jwt-go" | ||
"net/http" | ||
"strconv" | ||
"strings" | ||
"time" | ||
) | ||
|
||
func CriarToken(usuarioID uint64) (string, error) { | ||
// Permissoes que terá | ||
permissoes := jwt.MapClaims{} | ||
permissoes["authorized"] = true | ||
permissoes["exp"] = time.Now().Add(time.Hour * 6).Unix() // 6 horas | ||
permissoes["usuarioId"] = usuarioID | ||
|
||
// Gera uma assinatura | ||
token := jwt.NewWithClaims(jwt.SigningMethodHS256, permissoes) | ||
return token.SignedString(config.SecretKey) | ||
} | ||
|
||
func ValidarToken(r *http.Request) error { | ||
tokenString := extrairToken(r) | ||
token, erro := jwt.Parse(tokenString, retornarChaveVerificacao) | ||
if erro != nil { | ||
return erro | ||
} | ||
if _, ok := token.Claims.(jwt.MapClaims); ok && token.Valid { | ||
return nil | ||
} | ||
|
||
return errors.New("token inválido") | ||
} | ||
|
||
func ExtrairUsuarioID(r *http.Request) (uint64, error) { | ||
tokenString := extrairToken(r) | ||
token, erro := jwt.Parse(tokenString, retornarChaveVerificacao) | ||
if erro != nil { | ||
return 0, erro | ||
} | ||
|
||
if permissoes, ok := token.Claims.(jwt.MapClaims); ok && token.Valid { | ||
usuarioID, erro := strconv.ParseUint(fmt.Sprintf("%.0f", permissoes["usuarioId"]), 10, 64) | ||
if erro != nil { | ||
return 0, erro | ||
} | ||
return usuarioID, nil | ||
} | ||
|
||
return 0, errors.New("token inválido") | ||
} | ||
|
||
func extrairToken(r *http.Request) string { | ||
token := r.Header.Get("Authorization") | ||
|
||
if len(strings.Split(token, " ")) == 2 { | ||
return strings.Split(token, " ")[1] | ||
} | ||
|
||
return "" | ||
} | ||
|
||
func retornarChaveVerificacao(token *jwt.Token) (interface{}, error) { | ||
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok { | ||
return nil, fmt.Errorf("Método de assinatura inesperado! %v", token.Header["alg"]) | ||
} | ||
|
||
return config.SecretKey, nil | ||
} |
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,50 @@ | ||
package controllers | ||
|
||
import ( | ||
"api/src/autenticacao" | ||
"api/src/banco" | ||
"api/src/modelos" | ||
"api/src/repositorios" | ||
"api/src/respostas" | ||
"api/src/seguranca" | ||
"encoding/json" | ||
"fmt" | ||
"io/ioutil" | ||
"net/http" | ||
) | ||
|
||
func Login(w http.ResponseWriter, r *http.Request) { | ||
corpoRequisicao, erro := ioutil.ReadAll(r.Body) | ||
if erro != nil { | ||
respostas.Erro(w, http.StatusUnprocessableEntity, erro) | ||
return | ||
} | ||
|
||
var usuario modelos.Usuario | ||
if erro = json.Unmarshal(corpoRequisicao, &usuario); erro != nil { | ||
respostas.Erro(w, http.StatusBadRequest, erro) | ||
return | ||
} | ||
|
||
db, erro := banco.Conectar() | ||
if erro != nil { | ||
respostas.Erro(w, http.StatusInternalServerError, erro) | ||
return | ||
} | ||
defer db.Close() | ||
|
||
repositorio := repositorios.NovoRepositorioDeUsuarios(db) | ||
usuarioSalvoNoBanco, erro := repositorio.BuscarPorEmail(usuario.Email) | ||
if erro != nil { | ||
respostas.Erro(w, http.StatusInternalServerError, erro) | ||
return | ||
} | ||
if erro = seguranca.VerificarSenha(usuarioSalvoNoBanco.Senha, usuario.Senha); erro != nil { | ||
respostas.Erro(w, http.StatusUnauthorized, erro) | ||
return | ||
} | ||
|
||
token, _ := autenticacao.CriarToken(usuarioSalvoNoBanco.ID) | ||
fmt.Println(token) | ||
w.Write([]byte(token)) | ||
} |
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 middlewares | ||
|
||
import ( | ||
"api/src/autenticacao" | ||
"api/src/respostas" | ||
"log" | ||
"net/http" | ||
) | ||
|
||
func Logger(next http.HandlerFunc) http.HandlerFunc { | ||
return func(w http.ResponseWriter, r *http.Request) { | ||
log.Printf("\n %s %s %s", r.Method, r.RequestURI, r.Host) | ||
next(w, r) | ||
} | ||
} | ||
|
||
func Autenticar(next http.HandlerFunc) http.HandlerFunc { | ||
return func(w http.ResponseWriter, r *http.Request) { | ||
if erro := autenticacao.ValidarToken(r); erro != nil { | ||
respostas.Erro(w, http.StatusUnauthorized, erro) | ||
return | ||
} | ||
next(w, r) | ||
} | ||
} |
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,13 @@ | ||
package rotas | ||
|
||
import ( | ||
"api/src/controllers" | ||
"net/http" | ||
) | ||
|
||
var rotaLogin = Rota{ | ||
URI: "/login", | ||
Metodo: http.MethodPost, | ||
Funcao: controllers.Login, | ||
RequerAutenticacao: false, | ||
} |
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,11 @@ | ||
package seguranca | ||
|
||
import "golang.org/x/crypto/bcrypt" | ||
|
||
func Hash(senha string) ([]byte, error) { | ||
return bcrypt.GenerateFromPassword([]byte(senha), bcrypt.DefaultCost) | ||
} | ||
|
||
func VerificarSenha(senhaHash, senhaString string) error { | ||
return bcrypt.CompareHashAndPassword([]byte(senhaHash), []byte(senhaString)) | ||
} |