Skip to content

Commit

Permalink
autenticacao implementada
Browse files Browse the repository at this point in the history
  • Loading branch information
meiryleneavelino committed Dec 18, 2024
1 parent 2bf96f2 commit d750a71
Show file tree
Hide file tree
Showing 6 changed files with 115 additions and 183 deletions.
62 changes: 29 additions & 33 deletions owasp-top10-2021-apps/a1/ecommerce-api/app/db/mongo.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,7 @@ import (

// Collections names used in MongoDB.
var (
UserCollection = "users"
TicketsCollection = "tickets" // Adicione a coleção de tickets
UserCollection = "users"
)

// DB is the struct that represents mongo session.
Expand All @@ -35,7 +34,6 @@ type Database interface {
UpdateAll(query, updateQuery bson.M, collection string) error
Upsert(query bson.M, obj interface{}, collection string) (*mgo.ChangeInfo, error)
SearchOne(query bson.M, selectors []string, collection string, obj interface{}) error
CheckUserPermission(userID, ticketID string) (bool, error) // Adicionado para refletir a sugestão
}

var config = &mongoConfig{
Expand All @@ -47,6 +45,8 @@ var config = &mongoConfig{

// Connect connects to mongo and returns the session.
func Connect() (*DB, error) {

// fmt.Printf("config:%#v", config)
dialInfo := &mgo.DialInfo{
Addrs: []string{config.Address},
Timeout: time.Second * 60,
Expand All @@ -64,62 +64,58 @@ func Connect() (*DB, error) {
return nil, err
}

//go autoReconnect(session)

return &DB{Session: session}, nil
}

// CheckUserPermission verifies if a user has access to a specific ticket.
func (db *DB) CheckUserPermission(userID, ticketID string) (bool, error) {
session := db.Session.Clone()
defer session.Close()
c := session.DB(config.DatabaseName).C(TicketsCollection)

query := bson.M{
"userID": userID,
"ticketID": ticketID,
}

var result bson.M
err := c.Find(query).One(&result)
if err != nil {
if err == mgo.ErrNotFound {
return false, nil
// autoReconnect checks mongo's connection each second and, if an error is found, reconnect to it.
func autoReconnect(session *mgo.Session) {
var err error
for {
err = session.Ping()
if err != nil {
session.Refresh()
err = session.Ping()
if err == nil {
} else {
}
}
return false, err
time.Sleep(time.Second * 1)
}

return true, nil
}

// Insert inserts a new document.
func (db *DB) Insert(obj interface{}, collection string) error {
session := db.Session.Clone()
c := session.DB(config.DatabaseName).C(collection)
c := session.DB("").C(collection)
defer session.Close()
return c.Insert(obj)
}

// Update updates a single document.
func (db *DB) Update(query, updateQuery interface{}, collection string) error {
session := db.Session.Clone()
c := session.DB(config.DatabaseName).C(collection)
c := session.DB("").C(collection)
defer session.Close()
return c.Update(query, updateQuery)
err := c.Update(query, updateQuery)
return err
}

// UpdateAll updates all documents that match the query.
func (db *DB) UpdateAll(query, updateQuery bson.M, collection string) error {
func (db *DB) UpdateAll(query, updateQuery interface{}, collection string) error {
session := db.Session.Clone()
c := session.DB(config.DatabaseName).C(collection)
c := session.DB("").C(collection)
defer session.Close()
_, err := c.UpdateAll(query, updateQuery)
return err
}

// Search searches all documents that match the query. If selectors are present, the return will be only the chosen fields.
// Search searchs all documents that match the query. If selectors are present, the return will be only the chosen fields.
func (db *DB) Search(query bson.M, selectors []string, collection string, obj interface{}) error {
session := db.Session.Clone()
defer session.Close()
c := session.DB(config.DatabaseName).C(collection)
c := session.DB("").C(collection)

var err error
if selectors != nil {
Expand All @@ -137,11 +133,11 @@ func (db *DB) Search(query bson.M, selectors []string, collection string, obj in
return err
}

// SearchOne searches for the first element that matches with the given query.
// SearchOne searchs for the first element that matchs with the given query.
func (db *DB) SearchOne(query bson.M, selectors []string, collection string, obj interface{}) error {
session := db.Session.Clone()
defer session.Close()
c := session.DB(config.DatabaseName).C(collection)
c := session.DB("").C(collection)

var err error
if selectors != nil {
Expand All @@ -159,10 +155,10 @@ func (db *DB) SearchOne(query bson.M, selectors []string, collection string, obj
return err
}

// Upsert inserts a document or updates it if it already exists.
// Upsert inserts a document or update it if it already exists.
func (db *DB) Upsert(query bson.M, obj interface{}, collection string) (*mgo.ChangeInfo, error) {
session := db.Session.Clone()
c := session.DB(config.DatabaseName).C(collection)
c := session.DB("").C(collection)
defer session.Close()
return c.Upsert(query, obj)
}
64 changes: 34 additions & 30 deletions owasp-top10-2021-apps/a1/ecommerce-api/app/handlers/handlers.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,65 +4,69 @@ import (
"fmt"
"net/http"



"github.com/globocom/secDevLabs/owasp-top10-2021-apps/a1/ecommerce-api/app/db"
"github.com/labstack/echo"
jwt "github.com/dgrijalva/jwt-go"
)

// HealthCheck is the health check function.
// HealthCheck is the heath check function.
func HealthCheck(c echo.Context) error {
return c.String(http.StatusOK, "WORKING\n")
}

// GetTicket returns the userID ticket.
func GetTicket(c echo.Context) error {
// Obter o userID do contexto
userIDFromContext, ok := c.Get("userID").(string)
if !ok {
return c.JSON(http.StatusUnauthorized, map[string]string{
"result": "error",
"details": "Invalid user authentication data.",
})
}

// Obter o userID da URL
authHeader := c.Request().Header.Get("Authorization")
id := c.Param("id")
if id == "" {
return c.JSON(http.StatusBadRequest, map[string]string{
"result": "error",
"details": "User ID is required.",
})
}

// Verificar se o userID autenticado corresponde ao userID fornecido
if userIDFromContext != id {
return c.JSON(http.StatusForbidden, map[string]string{
"result": "error",
"details": "Access denied. You are not authorized to view this ticket.",
if authHeader == "" {
return c.JSON(http.StatusUnauthorized, map[string]string{
"error": "Authorization header is missing",
})
}

// Consultar o banco de dados com base no userID
userDataQuery := map[string]interface{}{"userID": id}
userDataResult, err := db.GetUserData(userDataQuery)
if err != nil {
c.Logger().Errorf("Error querying user data: %v", err)
return c.JSON(http.StatusInternalServerError, map[string]string{
"result": "error",
"details": "An internal error occurred. Please try again later.",
})
// could not find this user in MongoDB (or MongoDB err connection)
return c.JSON(http.StatusBadRequest, map[string]string{"result": "error", "details": "Error finding this UserID."})
}

// Verificar o formato da resposta

format := c.QueryParam("format")
if format == "json" {
return c.JSON(http.StatusOK, map[string]interface{}{
return c.JSON(http.StatusOK, map[string]string{
"result": "success",
"username": userDataResult.Username,
"userId" : userDataResult.UserID,
"ticket": userDataResult.Ticket,
})
}

// Resposta em texto simples
msgTicket := fmt.Sprintf("Hey, %s! This is your ticket: %s\n", userDataResult.Username, userDataResult.Ticket)
return c.String(http.StatusOK, msgTicket)
}


func parseToken(tokenString string) (*Claims, error) {
claims := &Claims{}
// Exemplo de parsing do JWT
token, err := jwt.ParseWithClaims(tokenString, claims, func(token *jwt.Token) (interface{}, error) {
return []byte("secret"), nil // sua chave secreta
})

if err != nil || !token.Valid {
return nil, fmt.Errorf("invalid token")
}

return claims, nil
}

// Claims define os dados que estarão no JWT
type Claims struct {
UserID string `json:"userId"`
jwt.StandardClaims
}
Original file line number Diff line number Diff line change
Expand Up @@ -36,13 +36,15 @@ func ReadCookie(c echo.Context) error {
// Login checks MongoDB if this user exists and then returns a JWT session cookie.
func Login(c echo.Context) error {


loginAttempt := types.LoginAttempt{}
err := c.Bind(&loginAttempt)
if err != nil {
return c.JSON(http.StatusBadRequest, map[string]string{"result": "error", "details": "Error login1."})
}
// input validation missing!


userDataQuery := map[string]interface{}{"username": loginAttempt.Username}
userDataResult, err := db.GetUserData(userDataQuery)
if err != nil {
Expand All @@ -67,6 +69,8 @@ func Login(c echo.Context) error {
// Set claims
claims := token.Claims.(jwt.MapClaims)
claims["name"] = userDataResult.Username
claims["userId"]= userDataResult.UserID
claims["Ticket"]= userDataResult.Ticket
claims["exp"] = time.Now().Add(time.Hour * 72).Unix()

// Generate encoded token and send it as response.
Expand All @@ -86,6 +90,8 @@ func Login(c echo.Context) error {
"result": "success",
"username": userDataResult.Username,
"user_id": userDataResult.UserID,
"Ticket": userDataResult.Ticket,
"token": t,
})
}

Expand Down
Loading

0 comments on commit d750a71

Please sign in to comment.