From eb51bdbfef8c2aacf0fdfde279a40de7f74c8d86 Mon Sep 17 00:00:00 2001 From: Zach Berwaldt Date: Mon, 18 Mar 2024 21:27:24 -0400 Subject: clean up, add better error handling --- api/internal/controllers/auth.go | 21 +++++++++++++-------- 1 file changed, 13 insertions(+), 8 deletions(-) (limited to 'api/internal/controllers/auth.go') diff --git a/api/internal/controllers/auth.go b/api/internal/controllers/auth.go index ab2fbbb..b06c6ef 100644 --- a/api/internal/controllers/auth.go +++ b/api/internal/controllers/auth.go @@ -5,21 +5,21 @@ import ( "database/sql" "encoding/base64" "errors" - "github.com/gin-gonic/gin" "net/http" "water/api/internal/models" + "github.com/gin-gonic/gin" + + "water/api/internal/database" + _ "github.com/mattn/go-sqlite3" "golang.org/x/crypto/bcrypt" - "water/api/internal/database" ) - - // AuthHandler is a function that handles users' authentication. It checks if the request // has valid credentials, authenticates the user and sets the user's session. // If the authentication is successful, it will allow the user to access protected routes. -func AuthHandler (c *gin.Context) { +func AuthHandler(c *gin.Context) { username, password, ok := c.Request.BasicAuth() if !ok { c.Header("WWW-Authenticate", `Basic realm="Please enter your username and password."`) @@ -27,7 +27,11 @@ func AuthHandler (c *gin.Context) { return } - db := database.EstablishDBConnection() + db, err := database.EstablishDBConnection() + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + return + } defer func(db *sql.DB) { err := db.Close() if err != nil { @@ -44,6 +48,8 @@ func AuthHandler (c *gin.Context) { if errors.Is(err, sql.ErrNoRows) { c.JSON(http.StatusNotFound, gin.H{"error": err.Error()}) return + } else { + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) } } @@ -64,7 +70,6 @@ func AuthHandler (c *gin.Context) { c.JSON(http.StatusOK, gin.H{"token": apiToken, "user": user, "preferences": preference}) } - // generateToken is a helper function used in the AuthHandler. It generates a random token for API authentication. // This function creates an empty byte slice of length 32 and fills it with cryptographic random data using the rand.Read function. // If an error occurs during the generation, it will return an empty string. @@ -76,4 +81,4 @@ func generateToken() string { return "" } return base64.StdEncoding.EncodeToString(token) -} \ No newline at end of file +} -- cgit v1.1