Skip to content

Commit

Permalink
feature: adding readme.me
Browse files Browse the repository at this point in the history
  • Loading branch information
jeffersonrodrigues92 committed Mar 3, 2025
1 parent 6a0cc67 commit ff3379f
Show file tree
Hide file tree
Showing 2 changed files with 100 additions and 2 deletions.
91 changes: 89 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,91 @@
# Authorization Middleware for Fiber

# Auth SDK
Este repositório contém um middleware de autorização para o framework Fiber em Go, que permite verificar se um usuário está autorizado a realizar uma ação específica em um recurso. O middleware envia uma solicitação POST para um serviço de autorização, passando os detalhes do usuário, recurso e ação desejada.

## 📦 Instalação

```bash
go get -u github.com/gofiber/fiber/v2
```

## 🚀 Como Usar

### 1. Crie uma instância do `AuthClient`:

```go
import "github.com/suapasta/middleware"

authClient := &middleware.AuthClient{
AuthAddress: "http://localhost:3000",
}
```

### 2. Use o middleware na sua aplicação Fiber:

```go
app := fiber.New()

app.Use(authClient.Authorize("user123", "resource_name", "read"))

app.Get("/resource", func(c *fiber.Ctx) error {
return c.SendString("Você tem permissão para acessar este recurso!")
})

app.Listen(":8080")
```

## 🛠️ Funcionamento

A função `Authorize`:

- Recebe o `sub` (usuário), `resource` (recurso) e `action` (ação desejada).
- Envia uma solicitação POST ao serviço de autorização.
- Verifica se a resposta indica que o usuário está autorizado.
- Permite o fluxo normal da aplicação ou retorna um erro 403 (Forbidden).

## 📥 Exemplo de Requisição

```http
POST /v1/authorize
Content-Type: application/json
Authorization: Bearer seu_token_aqui
{
"sub": "lerian/user123_role",
"resource": "resource_name",
"action": "read"
}
```

## 📡 Serviço de Autorização Esperado

O serviço de autorização deve retornar uma resposta JSON no seguinte formato:

```json
{
"authorized": true,
"timestamp": "2025-03-03T12:00:00Z"
}
```

## 🚧 Tratamento de Erros

O middleware captura e exibe logs para os seguintes tipos de erro:

- Falha ao criar a requisição
- Falha ao enviar a requisição
- Falha ao ler o corpo da resposta
- Falha ao desserializar o JSON de resposta

## 📄 Licença

Este projeto está licenciado sob a licença MIT. Sinta-se à vontade para usá-lo e modificá-lo conforme necessário.

## 🧑‍💻 Contribuindo

Contribuições são bem-vindas! Abra uma issue ou um pull request para sugestões e melhorias.

## 📧 Contato

Para dúvidas ou suporte, entre em contato pelo e-mail: contato\@lerian.studio.

This is the Auth SDK for Go, providing authentication functionalities for your applications.
11 changes: 11 additions & 0 deletions auth/middleware/middleware.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,17 @@ type AuthResponse struct {
Timestamp time.Time `json:"timestamp"`
}

// Authorize is a middleware function for the Fiber framework that checks if a user is authorized to perform a specific action on a resource.
// It sends a POST request to the authorization service with the subject, resource, and action details.
// If the user is authorized, the request is passed to the next handler; otherwise, a 403 Forbidden status is returned.
//
// Parameters:
// - sub: The subject (user) identifier.
// - resource: The resource the user wants to access.
// - action: The action the user wants to perform on the resource.
//
// Returns:
// - fiber.Handler: A Fiber handler function that performs the authorization check.
func (auth *AuthClient) Authorize(sub string, resource string, action string) fiber.Handler {
return func(c *fiber.Ctx) error {
client := http.Client{}
Expand Down

0 comments on commit ff3379f

Please sign in to comment.