hostname-service/auth/handlers.go

83 lines
2.8 KiB
Go
Raw Normal View History

// Copyright 2024 Florian Beisel
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
2024-01-17 18:05:55 +01:00
package auth
import (
"database/sql"
"log"
2024-01-17 18:05:55 +01:00
"net/http"
"git.beisel.it/florian/hostname-service/db"
"git.beisel.it/florian/hostname-service/models"
"golang.org/x/crypto/bcrypt"
"github.com/gin-gonic/gin"
)
// LoginHandler godoc
//
// @Summary User login
// @Description Authenticate user and return JWT token
// @Tags Authentication
// @Accept json
// @Produce json
// @Param loginCredentials body models.LoginCredentials true "Login Credentials"
// @Success 200 {object} models.TokenResponse "Successfully authenticated, JWT token returned"
// @Failure 400 {object} models.ErrorResponse "Invalid request body"
// @Failure 401 {object} models.ErrorResponse "Invalid login credentials"
// @Failure 500 {object} models.ErrorResponse "Internal server error"
// @Router /login [post]
2024-01-17 18:05:55 +01:00
func LoginHandler(c *gin.Context) {
var creds models.LoginCredentials
// Bind JSON to creds
if err := c.BindJSON(&creds); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request body"})
return
}
// Fetch user from the database
var storedCreds models.User
err := db.DB.QueryRow("SELECT username, password FROM users WHERE username = ?", creds.Username).Scan(&storedCreds.Username, &storedCreds.Password)
if err != nil {
if err == sql.ErrNoRows {
// User not found
c.JSON(http.StatusUnauthorized, gin.H{"error": "Invalid login credentials"})
return
}
// Other errors
c.JSON(http.StatusInternalServerError, gin.H{"error": "Internal server error"})
return
}
// Compare provided password with stored hashed password
if err := bcrypt.CompareHashAndPassword([]byte(storedCreds.Password), []byte(creds.Password)); err != nil {
// Password does not match
c.JSON(http.StatusUnauthorized, gin.H{"error": "Invalid login credentials"})
return
}
// If password matches, generate a JWT token
token, err := GenerateToken(storedCreds.Username)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to generate token"})
log.Printf("Error generating token %v", err)
2024-01-17 18:05:55 +01:00
return
}
// Send the token in the response
c.JSON(http.StatusOK, gin.H{"token": token})
}