This commit is contained in:
8
auth.go
8
auth.go
@@ -122,6 +122,7 @@ func AuthMiddleware() gin.HandlerFunc {
|
||||
func RegisterHandler(c *gin.Context) {
|
||||
var req RegisterRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
RecordAuthAttempt("register", "bad_request")
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
@@ -130,6 +131,7 @@ func RegisterHandler(c *gin.Context) {
|
||||
var existingUser User
|
||||
err := db.QueryRow("SELECT id FROM users WHERE username = $1 OR email = $2", req.Username, req.Email).Scan(&existingUser.ID)
|
||||
if err != sql.ErrNoRows {
|
||||
RecordAuthAttempt("register", "conflict")
|
||||
c.JSON(http.StatusConflict, gin.H{"error": "Username or email already exists"})
|
||||
return
|
||||
}
|
||||
@@ -160,6 +162,7 @@ func RegisterHandler(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
RecordAuthAttempt("register", "success")
|
||||
c.JSON(http.StatusCreated, AuthResponse{
|
||||
Token: token,
|
||||
User: user,
|
||||
@@ -170,6 +173,7 @@ func RegisterHandler(c *gin.Context) {
|
||||
func LoginHandler(c *gin.Context) {
|
||||
var req LoginRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
RecordAuthAttempt("login", "bad_request")
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
@@ -182,15 +186,18 @@ func LoginHandler(c *gin.Context) {
|
||||
).Scan(&user.ID, &user.Username, &user.Email, &user.Password, &user.CreatedAt, &user.UpdatedAt)
|
||||
|
||||
if err == sql.ErrNoRows {
|
||||
RecordAuthAttempt("login", "user_not_found")
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "Invalid credentials 1"})
|
||||
return
|
||||
} else if err != nil {
|
||||
RecordAuthAttempt("login", "database_error")
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "Database error"})
|
||||
return
|
||||
}
|
||||
|
||||
// Check password
|
||||
if !checkPasswordHash(req.Password, user.Password) {
|
||||
RecordAuthAttempt("login", "invalid_password")
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "Invalid credentials 2"})
|
||||
return
|
||||
}
|
||||
@@ -205,6 +212,7 @@ func LoginHandler(c *gin.Context) {
|
||||
// Clear password from response
|
||||
user.Password = ""
|
||||
|
||||
RecordAuthAttempt("login", "success")
|
||||
c.JSON(http.StatusOK, AuthResponse{
|
||||
Token: token,
|
||||
User: user,
|
||||
|
||||
Reference in New Issue
Block a user