github.com/diadata-org/diadata@v1.4.593/pkg/http/restServer/diaApi/basicAuth.go (about)

     1  package diaApi
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"github.com/diadata-org/diadata/pkg/dia/helpers/db"
     7  	"github.com/gin-gonic/gin"
     8  	log "github.com/sirupsen/logrus"
     9  	"golang.org/x/crypto/bcrypt"
    10  	"time"
    11  )
    12  
    13  // Check if two passwords match using Bcrypt's CompareHashAndPassword
    14  // which return nil on success and an error on failure.
    15  func doPasswordsMatch(hashedPassword, currPassword string) bool {
    16  	err := bcrypt.CompareHashAndPassword(
    17  		[]byte(hashedPassword), []byte(currPassword))
    18  	return err == nil
    19  }
    20  
    21  type RestBasicAuth struct {
    22  	username string
    23  	password string
    24  }
    25  
    26  func BasicAuth(c *gin.Context) {
    27  	username, password, hasAuth := c.Request.BasicAuth()
    28  	if !hasAuth {
    29  		c.Abort()
    30  		c.Writer.Header().Set("WWW-Authenticate", "Basic realm=Restricted")
    31  		return
    32  	}
    33  
    34  	postgres := db.PostgresDatabase()
    35  	today := time.Now().Format("2006-01-02")
    36  
    37  	query := fmt.Sprintf("SELECT username, password from rest_basicauth where username = %s AND is_active = true AND (active_until IS NULL OR active_until <= %s", username, today)
    38  
    39  	rows, err := postgres.Query(context.Background(), query)
    40  	if err != nil {
    41  		log.Error("Run basicauth user search query:", err)
    42  		return
    43  	}
    44  	for rows.Next() {
    45  		var basicAuth RestBasicAuth
    46  		err := rows.Scan(
    47  			&basicAuth.username,
    48  			&basicAuth.password,
    49  		)
    50  		if err != nil {
    51  			log.Error(err)
    52  			return
    53  		}
    54  		// Get the Basic Authentication credentials
    55  		if doPasswordsMatch(basicAuth.password, password) {
    56  			log.WithFields(log.Fields{
    57  				"user":     username,
    58  				"endpoint": c.Request.URL.Path,
    59  			}).Info("User authenticated")
    60  		} else {
    61  			c.Abort()
    62  			c.Writer.Header().Set("WWW-Authenticate", "Basic realm=Restricted")
    63  			return
    64  		}
    65  	}
    66  	defer rows.Close()
    67  }