github.com/cozy/cozy-stack@v0.0.0-20240603063001-31110fa4cae1/web/contacts/contacts.go (about)

     1  // Package contacts exposes a route for the myself document.
     2  package contacts
     3  
     4  import (
     5  	"encoding/json"
     6  	"errors"
     7  	"net/http"
     8  
     9  	"github.com/cozy/cozy-stack/model/contact"
    10  	"github.com/cozy/cozy-stack/model/permission"
    11  	"github.com/cozy/cozy-stack/pkg/couchdb"
    12  	"github.com/cozy/cozy-stack/pkg/jsonapi"
    13  	"github.com/cozy/cozy-stack/web/middlewares"
    14  	"github.com/labstack/echo/v4"
    15  )
    16  
    17  type apiMyself struct{ *contact.Contact }
    18  
    19  func (m *apiMyself) MarshalJSON() ([]byte, error)           { return json.Marshal(m.Contact) }
    20  func (m *apiMyself) Links() *jsonapi.LinksList              { return &jsonapi.LinksList{Self: "/contacts/myself"} }
    21  func (m *apiMyself) Relationships() jsonapi.RelationshipMap { return jsonapi.RelationshipMap{} }
    22  func (m *apiMyself) Included() []jsonapi.Object             { return []jsonapi.Object{} }
    23  
    24  // MyselfHandler is the handler for POST /contacts/myself. It returns the
    25  // information about the io.cozy.contacts document for the owner of this
    26  // instance, the "myself" contact. If the document does not exist, it is
    27  // recreated with some basic fields.
    28  func MyselfHandler(c echo.Context) error {
    29  	inst := middlewares.GetInstance(c)
    30  	myself, err := contact.GetMyself(inst)
    31  	if errors.Is(err, contact.ErrNotFound) {
    32  		var settings *couchdb.JSONDoc
    33  		settings, err = inst.SettingsDocument()
    34  		if err == nil {
    35  			myself, err = contact.CreateMyself(inst, settings)
    36  		}
    37  	}
    38  	if err != nil {
    39  		return err
    40  	}
    41  
    42  	if err := middlewares.Allow(c, permission.GET, myself); err != nil {
    43  		return err
    44  	}
    45  
    46  	return jsonapi.Data(c, http.StatusOK, &apiMyself{myself}, nil)
    47  }
    48  
    49  // Routes sets the routing for the contacts.
    50  func Routes(router *echo.Group) {
    51  	router.POST("/myself", MyselfHandler)
    52  }