github.com/companieshouse/insolvency-api@v0.0.0-20231024103413-440c973d9e9b/interceptors/email_auth_interceptor.go (about)

     1  // Package interceptors contains the interceptor middleware that checks for authorisation.
     2  package interceptors
     3  
     4  import (
     5  	"fmt"
     6  	"net/http"
     7  
     8  	"github.com/companieshouse/chs.go/authentication"
     9  	"github.com/companieshouse/chs.go/log"
    10  	"github.com/companieshouse/insolvency-api/service"
    11  )
    12  
    13  // EmailAuthIntercept checks that the user has a registered Insolvency Practitioner email address in Mongo to perform the request action
    14  func EmailAuthIntercept(next http.Handler) http.Handler {
    15  	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    16  		// Get user details from context
    17  		userDetails, ok := r.Context().Value(authentication.ContextKeyUserDetails).(authentication.AuthUserDetails)
    18  		if !ok {
    19  			log.ErrorR(r, fmt.Errorf("email auth interceptor error: invalid AuthUserDetails from context"))
    20  			w.WriteHeader(http.StatusInternalServerError)
    21  			return
    22  		}
    23  
    24  		isUserOnEfsAllowList, err := service.IsUserOnEfsAllowList(userDetails.Email, r)
    25  
    26  		if err != nil {
    27  			log.ErrorR(r, fmt.Errorf("error checking EFS allow list: [%s]", err))
    28  			w.WriteHeader(http.StatusInternalServerError)
    29  			return
    30  		}
    31  		if !isUserOnEfsAllowList {
    32  			log.ErrorR(r, fmt.Errorf("user not on EFS allow list"))
    33  			w.WriteHeader(http.StatusUnauthorized)
    34  			return
    35  		}
    36  
    37  		next.ServeHTTP(w, r)
    38  	})
    39  }