github.com/volatiletech/authboss@v2.4.1+incompatible/defaults/renderer.go (about)

     1  package defaults
     2  
     3  import (
     4  	"context"
     5  	"encoding/json"
     6  
     7  	"github.com/volatiletech/authboss"
     8  )
     9  
    10  var (
    11  	jsonDefaultFailures = []string{authboss.DataErr, authboss.DataValidation}
    12  )
    13  
    14  // There is a separate package that does HTML Rendering authboss-renderer
    15  
    16  // JSONRenderer simply renders the data provided in JSON.
    17  // Known failure keys in the HTMLData can be passed in to force a
    18  // status: failure in the JSON when they appear.
    19  type JSONRenderer struct {
    20  	Failures []string
    21  }
    22  
    23  // Load is a no-op since json doesn't require any templates
    24  func (JSONRenderer) Load(names ...string) error {
    25  	return nil
    26  }
    27  
    28  // Render the data
    29  func (j JSONRenderer) Render(ctx context.Context, page string, data authboss.HTMLData) (output []byte, contentType string, err error) {
    30  	if data == nil {
    31  		return []byte(`{"status":"success"}`), "application/json", nil
    32  	}
    33  
    34  	if _, hasStatus := data["status"]; !hasStatus {
    35  		failures := j.Failures
    36  		if len(failures) == 0 {
    37  			failures = jsonDefaultFailures
    38  		}
    39  
    40  		status := "success"
    41  		for _, failure := range failures {
    42  			val, has := data[failure]
    43  			if has && val != nil {
    44  				status = "failure"
    45  				break
    46  			}
    47  		}
    48  
    49  		data["status"] = status
    50  	}
    51  
    52  	b, err := json.Marshal(data)
    53  	if err != nil {
    54  		return nil, "", err
    55  	}
    56  
    57  	return b, "application/json", nil
    58  }