Skip to content
Snippets Groups Projects
authentication.go 2.63 KiB
Newer Older
  • Learn to ignore specific revisions
  • Dean's avatar
    Dean committed
    package middleware
    
    import (
    	"context"
    	"database/sql"
    	"net/http"
    	"regexp"
    	"strings"
    
    	"owo.codes/whats-this/api/lib/apierrors"
    	"owo.codes/whats-this/api/lib/db"
    
    Dean's avatar
    Dean committed
    	"owo.codes/whats-this/api/lib/ratelimiter"
    
    Dean's avatar
    Dean committed
    
    	"github.com/rs/zerolog/log"
    
    Dean's avatar
    Dean committed
    	"github.com/spf13/viper"
    
    Dean's avatar
    Dean committed
    )
    
    // UUIDRegex is a UUID regex. See http://stackoverflow.com/a/13653180.
    var UUIDRegex = regexp.MustCompile("^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$")
    
    
    Dean's avatar
    Dean committed
    type authKey string
    
    Dean's avatar
    Dean committed
    
    // AuthorizedUserKey is the context value key for storing request authorization
    // information.
    
    Dean's avatar
    Dean committed
    var AuthorizedUserKey = authKey("AuthorizedUserKey")
    
    // BucketKey is the context value key for storing the request ratelimit bucket.
    var BucketKey = authKey("BucketKey")
    
    Dean's avatar
    Dean committed
    
    // Authenticator creates middleware that authenticates incoming requests using
    // a token and checking it against the database.
    func Authenticator(next http.Handler) http.Handler {
    	fn := func(w http.ResponseWriter, r *http.Request) {
    		ctx := r.Context()
    
    		// Get request token
    		token := r.Header.Get("Authorization")
    		if token == "" {
    			token = r.URL.Query().Get("key")
    		}
    		if token == "" {
    			token = r.URL.Query().Get("apikey")
    		}
    		if token == "" {
    			// No token present, move on
    			next.ServeHTTP(w, r)
    			return
    		}
    		token = strings.ToLower(token)
    		if !UUIDRegex.MatchString(token) {
    			panic(apierrors.BadToken)
    		}
    
    		// Select the user and add to request
    		user, err := db.SelectUserByToken(token)
    		switch {
    		case err == sql.ErrNoRows:
    			panic(apierrors.Unauthorized)
    		case err != nil:
    			log.Error().Err(err).Msg("failed to run SELECT query on database")
    			panic(apierrors.InternalServerError)
    		}
    		if user.IsBlocked {
    			panic(apierrors.Unauthorized)
    		}
    		ctx = context.WithValue(ctx, AuthorizedUserKey, user)
    
    Dean's avatar
    Dean committed
    
    		// Create a bucket and add to request
    		if viper.GetBool("ratelimiter.enable") {
    			bucketCapacity := user.BucketCapacity
    			if bucketCapacity < 0 {
    				bucketCapacity = 0
    			}
    			bucket := ratelimiter.NewBucket(user.ID, bucketCapacity, 0)
    			ctx = context.WithValue(ctx, BucketKey, bucket)
    		}
    
    Dean's avatar
    Dean committed
    		next.ServeHTTP(w, r.WithContext(ctx))
    	}
    	return http.HandlerFunc(fn)
    }
    
    // GetAuthorizedUser returns the current authorized user information.
    func GetAuthorizedUser(r *http.Request) db.User {
    	user, _ := r.Context().Value(AuthorizedUserKey).(db.User)
    	return user
    }
    
    Dean's avatar
    Dean committed
    
    // GetBucket returns the current authorized user's ratelimit bucket.
    func GetBucket(r *http.Request) ratelimiter.Bucket {
    	if !viper.GetBool("ratelimiter.enable") {
    		return ratelimiter.NoopBucket
    	}
    	bucket, ok := r.Context().Value(BucketKey).(ratelimiter.Bucket)
    	if !ok || bucket == nil {
    		return ratelimiter.EmptyBucket
    	}
    	return bucket
    }