Documentation
¶
Overview ¶
Package avatar is an Arandu module: the avatar of the people of a multi-tenant application, and the logo of its companies' spaces.
An avatar is drawn from the first of the sources the application's chain names that has something to show: the photo the person sent, the Gravatar they switched on, and a drawing made from their name -- initials, a block pattern, a face, marble, pixels, rings, a horizon, Bauhaus shapes, a polygon or a silhouette -- which needs no request and always works. A photo is checked by what its bytes are, cut to the square the person chose, scaled to a few sizes and encoded again, which strips every byte of metadata; it is kept on the application's Disk -- in production a private bucket -- under keys the server generates, and served by a route of this package with an entity tag and a long cache lifetime, at an address whose version changes when the photo does, so a CDN in front of the application keeps it.
The editor a person changes it in is a Kyse component, in the components package beside this one, and the page draws an avatar anywhere with another.
The files are laid out by role rather than by layer, so the whole package reads top to bottom:
module.go -> registration, routes and the contract with the framework config.go -> what the application passes in, and the route table contracts.go -> what the application implements: the directory of owners model.go -> the entity, its own rules, and the owner and source types picture.go -> how an owner is drawn, and the addresses of the photo policy.go -> who may do what, for a member of a space and for the team service.go -> the members' use cases, and Model access after authorization team.go -> the platform team's use cases editor.go -> what the editor is handed files.go -> keeping and removing the photos on the application's Disk gravatar.go -> the one look-up of a Gravatar, made when a person asks for it grants.go -> the two places a Grant is issued without a signed-in member activity.go -> what is recorded in arandu-activitylog handlers.go -> the controllers of both sides assets.go -> the script and the stylesheet the editor and the image use migrations.go -> the schema
An application registers it explicitly. There is no service provider, no container and no discovery: the wiring is the lines somebody wrote, and reading them is how they learn what the application is made of.
Index ¶
- Constants
- Variables
- func Actions() []security.Action
- func Assets() template.HTML
- func Lines(locale string) translation.Lines
- func Locales() []string
- func Script() template.HTML
- func Stylesheet() template.HTML
- func TeamActions() []security.Action
- type Avatar
- func (a *Avatar) ClearGravatar(now time.Time)
- func (a *Avatar) ClearUpload(now time.Time)
- func (row *Avatar) Fresh(ctx context.Context, g auth.Grant, with ...string) (*Avatar, error)
- func (a Avatar) HasGravatar() bool
- func (a Avatar) HasUpload() bool
- func (a Avatar) Ref() Ref
- func (row *Avatar) Replicate(except ...string) (*Avatar, error)
- func (a *Avatar) SetGravatar(hash, version, contentType string, sizes []int, now time.Time)
- func (a *Avatar) SetStyle(style Style, now time.Time)
- func (a *Avatar) SetUpload(version, contentType string, sizes []int, now time.Time)
- type AvatarCollection
- func (c AvatarCollection) Contains(key any) bool
- func (c AvatarCollection) Except(keys ...any) AvatarCollection
- func (c AvatarCollection) Find(key any) *Avatar
- func (c AvatarCollection) FindOrFail(key any) (*Avatar, error)
- func (c AvatarCollection) Fresh(ctx context.Context, g auth.Grant, with ...string) (AvatarCollection, error)
- func (c AvatarCollection) Load(ctx context.Context, g auth.Grant, relations ...string) error
- func (c AvatarCollection) LoadCount(ctx context.Context, g auth.Grant, relations ...string) error
- func (c AvatarCollection) LoadMissing(ctx context.Context, g auth.Grant, relations ...string) error
- func (c AvatarCollection) ModelKeys() []any
- func (c AvatarCollection) Only(keys ...any) AvatarCollection
- func (c AvatarCollection) Pluck(column string) []any
- func (c AvatarCollection) Rows() model.Rows
- func (c AvatarCollection) ToArray() []map[string]any
- func (c AvatarCollection) Unique() AvatarCollection
- type AvatarPolicy
- type AvatarQuery
- func (q *AvatarQuery) AddSelect(columns ...any) *AvatarQuery
- func (q *AvatarQuery) ApplyListing(state pagination.ListingState) *AvatarQuery
- func (q *AvatarQuery) Avg(ctx context.Context, g auth.Grant, column any) (any, error)
- func (q *AvatarQuery) Base() *model.Builder
- func (q *AvatarQuery) Chunk(ctx context.Context, g auth.Grant, count int, ...) error
- func (q *AvatarQuery) Clone() *AvatarQuery
- func (q *AvatarQuery) Count(ctx context.Context, g auth.Grant, columns ...any) (int64, error)
- func (q *AvatarQuery) Create(ctx context.Context, g auth.Grant, attributes map[string]any) (*Avatar, error)
- func (q *AvatarQuery) Cursor(ctx context.Context, g auth.Grant) iter.Seq2[*Avatar, error]
- func (q *AvatarQuery) CursorPaginate(ctx context.Context, g auth.Grant, perPage int, cursor *pagination.Cursor, ...) (AvatarCollection, *pagination.CursorPage, error)
- func (q *AvatarQuery) Decrement(ctx context.Context, g auth.Grant, column string, amount any, ...) (int64, error)
- func (q *AvatarQuery) Delete(ctx context.Context, g auth.Grant) (int64, error)
- func (q *AvatarQuery) DoesntExist(ctx context.Context, g auth.Grant) (bool, error)
- func (q *AvatarQuery) DoesntHave(relation, boolean string, callback func(*query.Builder)) *AvatarQuery
- func (q *AvatarQuery) Each(ctx context.Context, g auth.Grant, count int, ...) error
- func (q *AvatarQuery) Exists(ctx context.Context, g auth.Grant) (bool, error)
- func (q *AvatarQuery) Find(ctx context.Context, g auth.Grant, id any, columns ...any) (*Avatar, error)
- func (q *AvatarQuery) FindMany(ctx context.Context, g auth.Grant, ids []any, columns ...any) (AvatarCollection, error)
- func (q *AvatarQuery) FindOrFail(ctx context.Context, g auth.Grant, id any, columns ...any) (*Avatar, error)
- func (q *AvatarQuery) FindOrNew(ctx context.Context, g auth.Grant, id any, columns ...any) (*Avatar, error)
- func (q *AvatarQuery) First(ctx context.Context, g auth.Grant, columns ...any) (*Avatar, error)
- func (q *AvatarQuery) FirstOrCreate(ctx context.Context, g auth.Grant, attributes, values map[string]any) (*Avatar, error)
- func (q *AvatarQuery) FirstOrFail(ctx context.Context, g auth.Grant, columns ...any) (*Avatar, error)
- func (q *AvatarQuery) FirstOrNew(ctx context.Context, g auth.Grant, attributes, values map[string]any) (*Avatar, error)
- func (q *AvatarQuery) FirstWhere(ctx context.Context, g auth.Grant, column any, args ...any) (*Avatar, error)
- func (q *AvatarQuery) ForPage(page, perPage int) *AvatarQuery
- func (q *AvatarQuery) ForceCreate(ctx context.Context, g auth.Grant, attributes map[string]any) (*Avatar, error)
- func (q *AvatarQuery) Get(ctx context.Context, g auth.Grant, columns ...any) (AvatarCollection, error)
- func (q *AvatarQuery) GroupBy(groups ...any) *AvatarQuery
- func (q *AvatarQuery) Has(relation, operator string, count int, boolean string, ...) *AvatarQuery
- func (q *AvatarQuery) Increment(ctx context.Context, g auth.Grant, column string, amount any, ...) (int64, error)
- func (q *AvatarQuery) Insert(ctx context.Context, g auth.Grant, values ...map[string]any) (bool, error)
- func (q *AvatarQuery) InsertOrIgnore(ctx context.Context, g auth.Grant, values ...map[string]any) (bool, error)
- func (q *AvatarQuery) Join(table any, first any, args ...any) *AvatarQuery
- func (q *AvatarQuery) Latest(column ...string) *AvatarQuery
- func (q *AvatarQuery) Limit(value int) *AvatarQuery
- func (q *AvatarQuery) Listing(ctx context.Context, g auth.Grant, state pagination.ListingState, path string, ...) (AvatarCollection, *pagination.ListingResult, error)
- func (q *AvatarQuery) Max(ctx context.Context, g auth.Grant, column any) (any, error)
- func (q *AvatarQuery) Min(ctx context.Context, g auth.Grant, column any) (any, error)
- func (q *AvatarQuery) New() (*Avatar, error)
- func (q *AvatarQuery) Offset(value int) *AvatarQuery
- func (q *AvatarQuery) Oldest(column ...string) *AvatarQuery
- func (q *AvatarQuery) OrDoesntHave(relation string) *AvatarQuery
- func (q *AvatarQuery) OrHas(relation, operator string, count int) *AvatarQuery
- func (q *AvatarQuery) OrWhere(column any, args ...any) *AvatarQuery
- func (q *AvatarQuery) OrWhereDoesntHave(relation string, callback func(*query.Builder)) *AvatarQuery
- func (q *AvatarQuery) OrWhereHas(relation string, callback func(*query.Builder)) *AvatarQuery
- func (q *AvatarQuery) OrWhereNot(column any, args ...any) *AvatarQuery
- func (q *AvatarQuery) OrWhereRelation(relation string, column any, args ...any) *AvatarQuery
- func (q *AvatarQuery) OrderBy(column any, direction ...string) *AvatarQuery
- func (q *AvatarQuery) OrderByDesc(column any) *AvatarQuery
- func (q *AvatarQuery) Paginate(ctx context.Context, g auth.Grant, perPage, page int, opts pagination.Options, ...) (AvatarCollection, *pagination.LengthAwarePage, error)
- func (q *AvatarQuery) Pluck(ctx context.Context, g auth.Grant, column string) ([]any, error)
- func (q *AvatarQuery) Select(columns ...any) *AvatarQuery
- func (q *AvatarQuery) SelectRaw(expression string, bindings ...any) *AvatarQuery
- func (q *AvatarQuery) SimplePaginate(ctx context.Context, g auth.Grant, perPage, page int, opts pagination.Options, ...) (AvatarCollection, *pagination.Page, error)
- func (q *AvatarQuery) Sole(ctx context.Context, g auth.Grant, columns ...any) (*Avatar, error)
- func (q *AvatarQuery) SoleValue(ctx context.Context, g auth.Grant, column string) (any, error)
- func (q *AvatarQuery) Sum(ctx context.Context, g auth.Grant, column any) (any, error)
- func (q *AvatarQuery) Touch(ctx context.Context, g auth.Grant, column ...string) (int64, error)
- func (q *AvatarQuery) Update(ctx context.Context, g auth.Grant, values map[string]any) (int64, error)
- func (q *AvatarQuery) UpdateOrCreate(ctx context.Context, g auth.Grant, attributes, values map[string]any) (*Avatar, error)
- func (q *AvatarQuery) Upsert(ctx context.Context, g auth.Grant, values []map[string]any, ...) (int64, error)
- func (q *AvatarQuery) Value(ctx context.Context, g auth.Grant, column string) (any, error)
- func (q *AvatarQuery) ValueOrFail(ctx context.Context, g auth.Grant, column string) (any, error)
- func (q *AvatarQuery) Where(column any, args ...any) *AvatarQuery
- func (q *AvatarQuery) WhereBelongsTo(relationshipName string, related ...model.Entity) *AvatarQuery
- func (q *AvatarQuery) WhereBetween(column any, from, to any) *AvatarQuery
- func (q *AvatarQuery) WhereColumn(first any, args ...any) *AvatarQuery
- func (q *AvatarQuery) WhereDoesntHave(relation string, callback func(*query.Builder)) *AvatarQuery
- func (q *AvatarQuery) WhereExists(callback func(*query.Builder)) *AvatarQuery
- func (q *AvatarQuery) WhereHas(relation string, callback func(*query.Builder)) *AvatarQuery
- func (q *AvatarQuery) WhereHasCount(relation string, callback func(*query.Builder), operator string, count int) *AvatarQuery
- func (q *AvatarQuery) WhereIn(column any, values []any) *AvatarQuery
- func (q *AvatarQuery) WhereKey(id any) *AvatarQuery
- func (q *AvatarQuery) WhereNot(column any, args ...any) *AvatarQuery
- func (q *AvatarQuery) WhereNotExists(callback func(*query.Builder)) *AvatarQuery
- func (q *AvatarQuery) WhereNotIn(column any, values []any) *AvatarQuery
- func (q *AvatarQuery) WhereNotNull(columns ...any) *AvatarQuery
- func (q *AvatarQuery) WhereNull(columns ...any) *AvatarQuery
- func (q *AvatarQuery) WhereRelation(relation string, column any, args ...any) *AvatarQuery
- func (q *AvatarQuery) With(relations ...string) *AvatarQuery
- func (q *AvatarQuery) WithAvg(relation, column string) *AvatarQuery
- func (q *AvatarQuery) WithCount(relations ...string) *AvatarQuery
- func (q *AvatarQuery) WithExists(relation string) *AvatarQuery
- func (q *AvatarQuery) WithMax(relation, column string) *AvatarQuery
- func (q *AvatarQuery) WithMin(relation, column string) *AvatarQuery
- func (q *AvatarQuery) WithSum(relation, column string) *AvatarQuery
- func (q *AvatarQuery) Without(relations ...string) *AvatarQuery
- func (q *AvatarQuery) WithoutGlobalScope(identifier string) *AvatarQuery
- func (q *AvatarQuery) WithoutGlobalScopes(identifiers ...string) *AvatarQuery
- type AvatarService
- func (s *AvatarService) Editor(ctx context.Context, actor security.Subject, ref Ref) (Editor, error)
- func (s *AvatarService) Open(ctx context.Context, actor security.Subject, ref Ref, version string, size int, ...) (Opened, error)
- func (s *AvatarService) Picture(ctx context.Context, actor security.Subject, owner Owner) (Picture, error)
- func (s *AvatarService) Remove(ctx context.Context, actor security.Subject, ref Ref) error
- func (s *AvatarService) Resolve(ctx context.Context, actor security.Subject, owners ...Owner) (Pictures, error)
- func (s *AvatarService) SetGravatar(ctx context.Context, actor security.Subject, ref Ref, action GravatarAction) (*Avatar, error)
- func (s *AvatarService) SetStyle(ctx context.Context, actor security.Subject, ref Ref, style Style) (*Avatar, error)
- func (s *AvatarService) Upload(ctx context.Context, actor security.Subject, ref Ref, in UploadRequest) (*Avatar, error)
- type Config
- type Crop
- type Directory
- type Editor
- type EditorURLs
- type Flag
- type GravatarAction
- type GravatarState
- type Kind
- type Labels
- type Module
- func (m *Module) Avatars() *AvatarService
- func (m *Module) Editor(ctx context.Context, actor security.Subject, ref Ref) (Editor, error)
- func (m *Module) Labels() Labels
- func (m *Module) MemberRoutes(r *fhttp.Router)
- func (m *Module) Migrations() []foundation.Migration
- func (m *Module) Name() string
- func (m *Module) Picture(ctx context.Context, actor security.Subject, owner Owner) (Picture, error)
- func (m *Module) Resolve(ctx context.Context, actor security.Subject, owners ...Owner) (Pictures, error)
- func (m *Module) Routes(r *fhttp.Router)
- func (m *Module) Team() *TeamService
- func (m *Module) TeamRoutes(r *fhttp.Router)
- func (m *Module) URL(ctx context.Context, actor security.Subject, owner Owner, size int) (string, error)
- func (m *Module) URLs() URLs
- type Opened
- type Owner
- type Paths
- type Picture
- type Pictures
- type Ref
- type Renderer
- type Source
- type Style
- type StyleChoice
- type TeamOwner
- type TeamPolicy
- type TeamService
- func (s *TeamService) Open(ctx context.Context, actor security.Subject, ref Ref, space, version string, ...) (Opened, error)
- func (s *TeamService) Remove(ctx context.Context, actor security.Subject, ref Ref, space string) error
- func (s *TeamService) Resolve(ctx context.Context, actor security.Subject, owners ...TeamOwner) (Pictures, error)
- func (s *TeamService) SetStyle(ctx context.Context, actor security.Subject, ref Ref, space string, ...) (*Avatar, error)
- func (s *TeamService) Upload(ctx context.Context, actor security.Subject, ref Ref, space string, ...) (*Avatar, error)
- type URLs
- type UploadRequest
Constants ¶
const ( ActivityUploaded = "avatar.uploaded" ActivityRemoved = "avatar.removed" ActivityStyleChanged = "avatar.style_changed" ActivityGravatarEnabled = "avatar.gravatar_enabled" ActivityGravatarRefresh = "avatar.gravatar_refreshed" ActivityGravatarDisabled = "avatar.gravatar_disabled" )
The events this package records, one per act that changes something. The subject of each entry is the avatar row, and its properties say whose it is.
No entry carries a picture, an e-mail or the digest of one: that an act happened is what the log keeps.
const ( ScriptAsset = "arandu-avatar.js" StylesheetAsset = "arandu-avatar.css" )
The names the script and the stylesheet are served under, from this origin, by the application's asset handler. Hesape puts a digest of the bytes in the address, so a new release is a new address and the old one can be cached forever.
const ( // DefaultPrefix is where the routes are mounted when Config leaves Prefix // empty. DefaultPrefix = "/avatars" // DefaultTeamPrefix is where the platform team's routes are mounted when // Config leaves TeamPrefix empty. DefaultTeamPrefix = "/admin/avatars" // DefaultLocale is the language of the editor, the messages and the activity // descriptions when Config.Locale names none. DefaultLocale = "pt-BR" // FallbackLocale answers every line the locale in use does not have. FallbackLocale = "en" // DefaultStyle is the generated style of an owner who chose none. DefaultStyle = StyleInitials // DefaultMaxUploadBytes is the size of the largest photo a person sends when // Config leaves MaxUploadBytes at zero. DefaultMaxUploadBytes = 5 << 20 // MaxUploadBytesLimit is the ceiling MaxUploadBytes is refused above: the // file is read into memory to be looked at before it is kept. MaxUploadBytesLimit = 20 << 20 // DefaultMaxPixels is the most pixels a photo may declare when Config leaves // MaxPixels at zero: about thirty-six megapixels, which a phone camera does // not pass and which decodes in a bounded amount of memory. DefaultMaxPixels = 36_000_000 // MaxPixelsLimit is the ceiling MaxPixels is refused above. MaxPixelsLimit = 100_000_000 // DefaultJPEGQuality is the quality photos are encoded at. DefaultJPEGQuality = 85 // DefaultCacheMaxAge is how long a browser or a CDN may keep a picture, which // is as long as it may: the address changes when the picture does. DefaultCacheMaxAge = 365 * 24 * time.Hour // DefaultGravatarURL is where a Gravatar is fetched from. DefaultGravatarURL = "https://gravatar.com/avatar" // DefaultGravatarTimeout is how long the one request to Gravatar may take. DefaultGravatarTimeout = 5 * time.Second // MaxSizes is how many sizes a photo is kept at. MaxSizes = 4 // MaxSize is the largest side a photo is kept at. MaxSize = 1024 // MinSize is the smallest side a photo is kept at. MinSize = 16 )
The defaults for the optional settings. They are constants rather than literals inside Config.withDefaults, so the value a reader finds here is the value the package uses.
const ( // AvatarView is reading an avatar. Anybody signed in to the space reads the // avatars of the space: the tenant check is the membership. AvatarView security.Action = "avatar.view" // AvatarUpdate is a person changing, switching and removing their own // picture. AvatarUpdate security.Action = "avatar.update" // AvatarManageOrganization is changing the logo of an organization of the // space: for the people who run it. AvatarManageOrganization security.Action = "avatar.manage_organization" // AvatarViewAll is the platform team reading the avatar of any space. AvatarViewAll security.Action = "avatar.view_all" // AvatarManageAll is the platform team changing or removing the avatar of // any owner of any space. AvatarManageAll security.Action = "avatar.manage_all" )
The actions of this package. Constants rather than strings at the call site: a typo in an action name would silently authorize nothing, or worse, everything.
They are what an arandu-permission group carries where a group is needed: the application declares them in its catalogue (Actions and TeamActions), an organization or the platform grants them to whom it decides, and arandu-permission fills the subject's actions on every request. A person changing their own picture needs no group: it is theirs.
const ActivityLogName = "avatar"
ActivityLogName is the log every entry of this package is recorded in.
const ActivityRefType = "avatar"
ActivityRefType is the kind of subject an entry about an avatar names.
const TranslationGroup = "avatar"
TranslationGroup is the file every key of this package lives in, and the prefix of every key: "avatar.editor.title".
Variables ¶
var DefaultChain = []Source{SourceUpload, SourceGravatar, SourceGenerated}
DefaultChain is the order a picture is looked for: the photo the person sent, then their Gravatar when they switched it on, then a drawing.
var DefaultPaths = Paths{
Users: "/users", Organizations: "/organizations",
Editor: "/editor", Upload: "/photo", Gravatar: "/gravatar", Style: "/style", Removal: "/removal",
}
DefaultPaths are the English segments.
var DefaultSizes = []int{64, 128, 256}
DefaultSizes are the sides, in pixels, a photo is kept at: a list row, a profile menu and the editor. The browser picks one from the srcset for the size the avatar is drawn at and the density of the screen.
var ErrNotFound = fmt.Errorf("avatar: not found: %w", model.ErrModelNotFound)
ErrNotFound is returned when no row matches, including when the row exists in another tenant. The two cases are deliberately indistinguishable.
It wraps model.ErrModelNotFound, so the router answers it with 404 and a caller can still ask for it by name with errors.Is.
var ErrUnknownOwner = errors.New("avatar: the directory does not know this owner")
ErrUnknownOwner is what a Directory answers for an owner it does not know in the tenant of the Grant. The package turns it into ErrNotFound, so asking for the avatar of somebody who does not exist and of somebody in another space are the same answer.
var Kinds = []Kind{KindUser, KindOrganization}
Kinds are every kind, in the order the routes are registered.
var PortuguesePaths = Paths{
Users: "/pessoas", Organizations: "/espacos",
Editor: "/editor", Upload: "/foto", Gravatar: "/gravatar", Style: "/estilo", Removal: "/remocao",
}
PortuguesePaths are the segments in Brazilian Portuguese, for an application whose addresses are written in it. Mounted at "/avatares" they read /avatares/pessoas/{id}/foto and /avatares/espacos/{id}/remocao.
Functions ¶
func Actions ¶
Actions are the space's actions, for an application to declare in arandu-permission's catalogue beside its own, so an organization grants them to whom it decides. AvatarView and AvatarUpdate are decided by the space and by ownership, and are not offered.
func Assets ¶
Assets is the stylesheet and the script together: the one line a layout needs so every avatar and editor on every page is drawn and works.
{!! avatar.Assets() !!}
func Lines ¶
func Lines(locale string) translation.Lines
Lines are the sentences this package ships for one locale, keyed the way a translator asks for them ("avatar.validation.file_type"), and nil for a locale it does not ship. An application reads them to see what there is to override, or to check a catalogue of its own against them.
func Script ¶
Script is the <script> that loads the behaviours, for the end of a layout's <body> or its <head> with defer, after ui.js:
{!! avatar.Script() !!}
It is served from the origin.
func Stylesheet ¶
Stylesheet is the <link> to the stylesheet, for a layout's <head>:
{!! avatar.Stylesheet() !!}
It is served from the origin, so a strict Content-Security-Policy holds.
func TeamActions ¶
TeamActions are the platform team's actions. They are declared apart from Actions so a catalogue an organization grants from never holds them: an application gives them to the groups of its own team only, and TeamPolicy refuses them to any subject outside Config.TeamTenant besides.
Types ¶
type Avatar ¶
type Avatar struct {
model.Model
// ID is the identifier. It is generated by the application rather than by
// the database, because a DEFAULT that produces a uuid is spelled
// differently in every engine. It is also the folder the files are kept in.
ID string `db:"id"`
// TenantID is the space the row belongs to. It is written from the Grant and
// read back so the policy can compare it against the subject's tenant.
TenantID string `db:"tenant_id"`
// OwnerKind and OwnerID say whose avatar it is.
OwnerKind string `db:"owner_kind"`
OwnerID string `db:"owner_id"`
// Style is the generated style the owner chose. Empty means
// Config.DefaultStyle.
Style string `db:"style"`
// UploadVersion is the first sixteen hex characters of the digest of the
// largest photo that was sent, and the version in its address: a new photo
// is a new address, so a cache holds the old one without ever being wrong.
// Empty means no photo. UploadType is its content type and UploadSizes the
// sides, as "64,128,256".
UploadVersion string `db:"upload_version"`
UploadType string `db:"upload_type"`
UploadSizes string `db:"upload_sizes"`
// GravatarEnabled is the person's consent to look their Gravatar up. The
// rest is the copy kept of it: GravatarHash is the digest of the e-mail it
// was fetched for, so a changed e-mail does not show somebody else's face.
GravatarEnabled Flag `db:"gravatar_enabled"`
GravatarHash string `db:"gravatar_hash"`
GravatarVersion string `db:"gravatar_version"`
GravatarType string `db:"gravatar_type"`
GravatarSizes string `db:"gravatar_sizes"`
// CreatedAt is when the row was written, and UpdatedAt when it last changed,
// both in UTC.
CreatedAt time.Time `db:"created_at"`
UpdatedAt time.Time `db:"updated_at"`
}
Avatar is how one owner of a space is pictured: the photo they sent, the Gravatar they switched on and the generated style they chose. One row per owner and space.
It embeds the model, so a row returned by a query carries the connection and can be saved again. Build a new row with Avatars(db).New(): a struct literal has no connection and its write methods return model.ErrUnwired.
Avatars, AvatarQuery and AvatarCollection are generated beside this file, in AvatarQuery.go, by aru model:build.
func (*Avatar) ClearGravatar ¶
ClearGravatar withdraws the consent and forgets the copy.
func (*Avatar) ClearUpload ¶
ClearUpload forgets the photo.
func (*Avatar) Fresh ¶
Fresh reads the row again, as a new Avatar; it shadows the untyped one the embedded model promotes.
func (Avatar) HasGravatar ¶
HasGravatar reports whether a copy of the Gravatar is kept and the person still wants it.
func (*Avatar) Replicate ¶
Replicate returns an unsaved copy of the row without its key; it shadows the untyped one the embedded model promotes.
func (*Avatar) SetGravatar ¶
SetGravatar records the consent and the copy that is kept.
type AvatarCollection ¶
type AvatarCollection []*Avatar
AvatarCollection is rows of Avatar, as a query returns them.
func AvatarCollectionOf ¶
func AvatarCollectionOf(rows model.Rows) AvatarCollection
AvatarCollectionOf converts rows of the table of Avatar. A nil input is a nil collection.
func (AvatarCollection) Contains ¶
func (c AvatarCollection) Contains(key any) bool
func (AvatarCollection) Except ¶
func (c AvatarCollection) Except(keys ...any) AvatarCollection
func (AvatarCollection) Find ¶
func (c AvatarCollection) Find(key any) *Avatar
func (AvatarCollection) FindOrFail ¶
func (c AvatarCollection) FindOrFail(key any) (*Avatar, error)
func (AvatarCollection) Fresh ¶
func (c AvatarCollection) Fresh(ctx context.Context, g auth.Grant, with ...string) (AvatarCollection, error)
func (AvatarCollection) LoadMissing ¶
func (AvatarCollection) ModelKeys ¶
func (c AvatarCollection) ModelKeys() []any
func (AvatarCollection) Only ¶
func (c AvatarCollection) Only(keys ...any) AvatarCollection
func (AvatarCollection) Pluck ¶
func (c AvatarCollection) Pluck(column string) []any
func (AvatarCollection) Rows ¶
func (c AvatarCollection) Rows() model.Rows
Rows converts the collection back to the core's rows.
func (AvatarCollection) ToArray ¶
func (c AvatarCollection) ToArray() []map[string]any
func (AvatarCollection) Unique ¶
func (c AvatarCollection) Unique() AvatarCollection
type AvatarPolicy ¶
type AvatarPolicy struct{}
AvatarPolicy is the only authority over what a member of a space does with an Avatar.
It denies unless a rule below says otherwise. The tenant of the record is checked first, before any rule, so a rule that opens an action opens it inside one space only. A guest has no avatar. Everyone else of the space reads the space's avatars; a person changes their own; and the logo of an organization is changed by a subject who was granted AvatarManageOrganization.
func (AvatarPolicy) Can ¶
func (AvatarPolicy) Can(_ context.Context, s security.Subject, a security.Action, record Avatar) error
Can decides whether the subject may perform the action on the record.
The record is the candidate -- an empty ID, carrying only whose avatar it is -- where the question is "may this subject do this to this owner's avatar", and the loaded row where it is "may they do it to this one". Both say whose it is, which is what the rules about ownership read.
type AvatarQuery ¶
type AvatarQuery struct {
// contains filtered or unexported fields
}
AvatarQuery is a query on the table of Avatar.
The methods that build return the query, so they chain. The methods that run take a context and an auth.Grant, and return Avatar rows or a value; there is no way to run one without a Grant.
func Avatars ¶
func Avatars(db model.DB) *AvatarQuery
Avatars starts a query on the table of Avatar, through db.
Global scopes are on and, unless the table is Global, every statement is filtered by the tenant of the Grant its terminal takes.
func (*AvatarQuery) AddSelect ¶
func (q *AvatarQuery) AddSelect(columns ...any) *AvatarQuery
func (*AvatarQuery) ApplyListing ¶
func (q *AvatarQuery) ApplyListing(state pagination.ListingState) *AvatarQuery
ApplyListing narrows and orders the query as a listing state asks: the search, the facets and the sort with its tie-break. Every column comes from the spec the state was read with, never from the request.
func (*AvatarQuery) Base ¶
func (q *AvatarQuery) Base() *model.Builder
Base returns the core builder the query forwards to. It is for code in this package -- a local scope in the custom block of model.go -- and for the factory, which builds rows through it.
func (*AvatarQuery) Clone ¶
func (q *AvatarQuery) Clone() *AvatarQuery
Clone returns an independent copy of the query.
func (*AvatarQuery) CursorPaginate ¶
func (q *AvatarQuery) CursorPaginate(ctx context.Context, g auth.Grant, perPage int, cursor *pagination.Cursor, opts pagination.Options, columns ...any) (AvatarCollection, *pagination.CursorPage, error)
func (*AvatarQuery) DoesntExist ¶
func (*AvatarQuery) DoesntHave ¶
func (q *AvatarQuery) DoesntHave(relation, boolean string, callback func(*query.Builder)) *AvatarQuery
func (*AvatarQuery) FindMany ¶
func (q *AvatarQuery) FindMany(ctx context.Context, g auth.Grant, ids []any, columns ...any) (AvatarCollection, error)
func (*AvatarQuery) FindOrFail ¶
func (*AvatarQuery) FirstOrCreate ¶
func (*AvatarQuery) FirstOrFail ¶
func (*AvatarQuery) FirstOrNew ¶
func (*AvatarQuery) FirstWhere ¶
func (*AvatarQuery) ForPage ¶
func (q *AvatarQuery) ForPage(page, perPage int) *AvatarQuery
func (*AvatarQuery) ForceCreate ¶
func (*AvatarQuery) Get ¶
func (q *AvatarQuery) Get(ctx context.Context, g auth.Grant, columns ...any) (AvatarCollection, error)
Get runs the query and returns the rows.
func (*AvatarQuery) GroupBy ¶
func (q *AvatarQuery) GroupBy(groups ...any) *AvatarQuery
func (*AvatarQuery) Has ¶
func (q *AvatarQuery) Has(relation, operator string, count int, boolean string, callback func(*query.Builder)) *AvatarQuery
func (*AvatarQuery) InsertOrIgnore ¶
func (*AvatarQuery) Join ¶
func (q *AvatarQuery) Join(table any, first any, args ...any) *AvatarQuery
func (*AvatarQuery) Latest ¶
func (q *AvatarQuery) Latest(column ...string) *AvatarQuery
func (*AvatarQuery) Limit ¶
func (q *AvatarQuery) Limit(value int) *AvatarQuery
func (*AvatarQuery) Listing ¶
func (q *AvatarQuery) Listing(ctx context.Context, g auth.Grant, state pagination.ListingState, path string, columns ...any) (AvatarCollection, *pagination.ListingResult, error)
Listing runs the query as a listing state asks and returns the rows of the page beside the result a table is drawn from: the state, the page with its total and the count of every facet value. Every statement it issues carries the tenant of g.
func (*AvatarQuery) New ¶
func (q *AvatarQuery) New() (*Avatar, error)
New returns an empty Avatar on the query's connection, not yet saved, filled with what WithAttributes recorded on the query.
func (*AvatarQuery) Offset ¶
func (q *AvatarQuery) Offset(value int) *AvatarQuery
func (*AvatarQuery) Oldest ¶
func (q *AvatarQuery) Oldest(column ...string) *AvatarQuery
func (*AvatarQuery) OrDoesntHave ¶
func (q *AvatarQuery) OrDoesntHave(relation string) *AvatarQuery
func (*AvatarQuery) OrHas ¶
func (q *AvatarQuery) OrHas(relation, operator string, count int) *AvatarQuery
func (*AvatarQuery) OrWhere ¶
func (q *AvatarQuery) OrWhere(column any, args ...any) *AvatarQuery
OrWhere adds an or-where clause; a func(*AvatarQuery) in place of the column adds a group.
func (*AvatarQuery) OrWhereDoesntHave ¶
func (q *AvatarQuery) OrWhereDoesntHave(relation string, callback func(*query.Builder)) *AvatarQuery
func (*AvatarQuery) OrWhereHas ¶
func (q *AvatarQuery) OrWhereHas(relation string, callback func(*query.Builder)) *AvatarQuery
func (*AvatarQuery) OrWhereNot ¶
func (q *AvatarQuery) OrWhereNot(column any, args ...any) *AvatarQuery
OrWhereNot adds an or-joined negated where clause, or a negated group.
func (*AvatarQuery) OrWhereRelation ¶
func (q *AvatarQuery) OrWhereRelation(relation string, column any, args ...any) *AvatarQuery
func (*AvatarQuery) OrderBy ¶
func (q *AvatarQuery) OrderBy(column any, direction ...string) *AvatarQuery
func (*AvatarQuery) OrderByDesc ¶
func (q *AvatarQuery) OrderByDesc(column any) *AvatarQuery
func (*AvatarQuery) Paginate ¶
func (q *AvatarQuery) Paginate(ctx context.Context, g auth.Grant, perPage, page int, opts pagination.Options, columns ...any) (AvatarCollection, *pagination.LengthAwarePage, error)
func (*AvatarQuery) Select ¶
func (q *AvatarQuery) Select(columns ...any) *AvatarQuery
func (*AvatarQuery) SelectRaw ¶
func (q *AvatarQuery) SelectRaw(expression string, bindings ...any) *AvatarQuery
func (*AvatarQuery) SimplePaginate ¶
func (q *AvatarQuery) SimplePaginate(ctx context.Context, g auth.Grant, perPage, page int, opts pagination.Options, columns ...any) (AvatarCollection, *pagination.Page, error)
func (*AvatarQuery) UpdateOrCreate ¶
func (*AvatarQuery) ValueOrFail ¶
func (*AvatarQuery) Where ¶
func (q *AvatarQuery) Where(column any, args ...any) *AvatarQuery
Where adds a where clause; a func(*AvatarQuery) in place of the column adds a group.
func (*AvatarQuery) WhereBelongsTo ¶
func (q *AvatarQuery) WhereBelongsTo(relationshipName string, related ...model.Entity) *AvatarQuery
func (*AvatarQuery) WhereBetween ¶
func (q *AvatarQuery) WhereBetween(column any, from, to any) *AvatarQuery
func (*AvatarQuery) WhereColumn ¶
func (q *AvatarQuery) WhereColumn(first any, args ...any) *AvatarQuery
func (*AvatarQuery) WhereDoesntHave ¶
func (q *AvatarQuery) WhereDoesntHave(relation string, callback func(*query.Builder)) *AvatarQuery
func (*AvatarQuery) WhereExists ¶
func (q *AvatarQuery) WhereExists(callback func(*query.Builder)) *AvatarQuery
func (*AvatarQuery) WhereHas ¶
func (q *AvatarQuery) WhereHas(relation string, callback func(*query.Builder)) *AvatarQuery
func (*AvatarQuery) WhereHasCount ¶
func (q *AvatarQuery) WhereHasCount(relation string, callback func(*query.Builder), operator string, count int) *AvatarQuery
func (*AvatarQuery) WhereIn ¶
func (q *AvatarQuery) WhereIn(column any, values []any) *AvatarQuery
func (*AvatarQuery) WhereKey ¶
func (q *AvatarQuery) WhereKey(id any) *AvatarQuery
func (*AvatarQuery) WhereNot ¶
func (q *AvatarQuery) WhereNot(column any, args ...any) *AvatarQuery
WhereNot adds a negated where clause, or a negated group.
func (*AvatarQuery) WhereNotExists ¶
func (q *AvatarQuery) WhereNotExists(callback func(*query.Builder)) *AvatarQuery
func (*AvatarQuery) WhereNotIn ¶
func (q *AvatarQuery) WhereNotIn(column any, values []any) *AvatarQuery
func (*AvatarQuery) WhereNotNull ¶
func (q *AvatarQuery) WhereNotNull(columns ...any) *AvatarQuery
func (*AvatarQuery) WhereNull ¶
func (q *AvatarQuery) WhereNull(columns ...any) *AvatarQuery
func (*AvatarQuery) WhereRelation ¶
func (q *AvatarQuery) WhereRelation(relation string, column any, args ...any) *AvatarQuery
func (*AvatarQuery) With ¶
func (q *AvatarQuery) With(relations ...string) *AvatarQuery
func (*AvatarQuery) WithAvg ¶
func (q *AvatarQuery) WithAvg(relation, column string) *AvatarQuery
func (*AvatarQuery) WithCount ¶
func (q *AvatarQuery) WithCount(relations ...string) *AvatarQuery
func (*AvatarQuery) WithExists ¶
func (q *AvatarQuery) WithExists(relation string) *AvatarQuery
func (*AvatarQuery) WithMax ¶
func (q *AvatarQuery) WithMax(relation, column string) *AvatarQuery
func (*AvatarQuery) WithMin ¶
func (q *AvatarQuery) WithMin(relation, column string) *AvatarQuery
func (*AvatarQuery) WithSum ¶
func (q *AvatarQuery) WithSum(relation, column string) *AvatarQuery
func (*AvatarQuery) Without ¶
func (q *AvatarQuery) Without(relations ...string) *AvatarQuery
func (*AvatarQuery) WithoutGlobalScope ¶
func (q *AvatarQuery) WithoutGlobalScope(identifier string) *AvatarQuery
func (*AvatarQuery) WithoutGlobalScopes ¶
func (q *AvatarQuery) WithoutGlobalScopes(identifiers ...string) *AvatarQuery
type AvatarService ¶
type AvatarService struct {
// contains filtered or unexported fields
}
AvatarService orchestrates what the members of a space do with avatars: it validates the request, asks the policy for a Grant, applies the rules the entity holds for itself, and persists with that Grant.
It receives its collaborators through the constructor. There is no container and no resolution by reflection: what this service is made of is written at the one place that builds it, and reading that place is how somebody learns what the package touches.
func NewAvatarService ¶
func NewAvatarService(db *data.DB, cfg Config) *AvatarService
NewAvatarService wires the service over the application's database handle.
func (*AvatarService) Editor ¶
func (s *AvatarService) Editor(ctx context.Context, actor security.Subject, ref Ref) (Editor, error)
Editor is what the editor component is handed for one owner: the picture as it stands and what the signed-in subject may do about it. Reading it needs only the right to read; CanEdit says whether the forms are drawn.
func (*AvatarService) Open ¶
func (s *AvatarService) Open(ctx context.Context, actor security.Subject, ref Ref, version string, size int, ifNoneMatch string) (Opened, error)
Open reads the picture an address names: the owner, the version and the size.
The version is part of the address so that a cache may keep the answer for as long as it likes. An address whose version is not the owner's current one is not served: it is redirected to the current picture, which a page rendered before the change still links to. A size that is not one of the stored sizes is a 404.
func (*AvatarService) Picture ¶
func (s *AvatarService) Picture(ctx context.Context, actor security.Subject, owner Owner) (Picture, error)
Picture is how one owner is drawn. See Resolve.
func (*AvatarService) Remove ¶
Remove removes the owner's photo, and the files it was kept in. An owner with no photo is left as they are.
func (*AvatarService) Resolve ¶
func (s *AvatarService) Resolve(ctx context.Context, actor security.Subject, owners ...Owner) (Pictures, error)
Resolve is how the owners are drawn, in one query however many there are. An owner nobody has set up is drawn from their name, with the default style, so the answer holds an entry for every owner asked about. An owner of another space is drawn the same way: nothing here tells it exists.
func (*AvatarService) SetGravatar ¶
func (s *AvatarService) SetGravatar(ctx context.Context, actor security.Subject, ref Ref, action GravatarAction) (*Avatar, error)
SetGravatar switches the person's Gravatar on, refreshes it or switches it off. It is the person's act alone: only a person has one, and only they may switch it on, because the digest of their e-mail leaves for a third party.
func (*AvatarService) SetStyle ¶
func (s *AvatarService) SetStyle(ctx context.Context, actor security.Subject, ref Ref, style Style) (*Avatar, error)
SetStyle chooses the generated style an owner is drawn with when no photo stands in front of it.
func (*AvatarService) Upload ¶
func (s *AvatarService) Upload(ctx context.Context, actor security.Subject, ref Ref, in UploadRequest) (*Avatar, error)
Upload keeps a photo as the owner's picture: checked by what its bytes are, cut to the square, scaled to every size, encoded again without a byte of metadata, and written under keys the server generates. The photo it replaces is removed once the row names the new one.
type Config ¶
type Config struct {
// TeamTenant is the tenant the platform's own team signs in to. A team
// member is a subject of this tenant who holds the team's actions. Empty
// turns the team's side off: no team route is registered and the team
// service refuses everybody.
TeamTenant string
// Prefix is the path the routes are mounted under. Empty means
// DefaultPrefix.
Prefix string
// TeamPrefix is the path the team's routes are mounted under. Empty means
// DefaultTeamPrefix.
TeamPrefix string
// Paths are the segments every route is built from, under Prefix and
// TeamPrefix. A field left empty keeps its DefaultPaths value;
// PortuguesePaths is the whole set in Brazilian Portuguese.
Paths Paths
// Middleware runs on every route of this package after RequireAuth, in
// order, and TeamMiddleware after it on the team's routes only. An
// application whose permissions arandu-permission administers mounts its
// Roles() in Middleware: RequireAuth puts the subject as the session
// resolved it, without the actions arandu-permission resolves on each
// request. A guard answers "is this request on the right side" and stops;
// the policy still decides.
Middleware []func(http.Handler) http.Handler
TeamMiddleware []func(http.Handler) http.Handler
// Directory names who an avatar is for and says whether they exist. It
// belongs to the application, which owns its users and its organizations.
// Nil limits the editor to the signed-in person's own avatar, drawn with no
// name and with no e-mail, so no Gravatar can be looked up.
Directory Directory
// Files is the Disk the photos are kept on: the application's, which in
// production is a private bucket. Every key is generated by the server and
// every read goes through an authorized route; nothing is served by a public
// address. Nil turns uploads and Gravatar off, and the avatar is drawn from
// the name alone.
Files *filesystem.Disk
// Chain is the order the sources of a picture are tried in, ending in
// SourceGenerated, which cannot fail. Leaving SourceGravatar out turns
// Gravatar off for the application. Empty means DefaultChain.
Chain []Source
// DefaultStyle is the generated style of an owner who chose none. Empty
// means DefaultStyle.
DefaultStyle Style
// Styles are the generated styles the editor offers. Empty offers every
// style. DefaultStyle has to be one of them.
Styles []Style
// Palette is the colours a generated avatar is drawn with, as #rgb or
// #rrggbb: an application sets its brand's here. Empty means the palette of
// the package.
Palette []string
// Sizes are the sides, in pixels, a photo is kept at, ascending, up to
// MaxSizes of them between MinSize and MaxSize. Empty means DefaultSizes.
Sizes []int
// MaxUploadBytes is the size of the largest photo a person sends. Zero means
// DefaultMaxUploadBytes, and anything above MaxUploadBytesLimit is refused.
MaxUploadBytes int64
// MaxPixels is the most pixels a photo may declare, width times height,
// checked from the header before the picture is decoded. Zero means
// DefaultMaxPixels, and anything above MaxPixelsLimit is refused.
MaxPixels int
// JPEGQuality is the quality photos are encoded at, 1 to 100. Zero means
// DefaultJPEGQuality.
JPEGQuality int
// PublicCache says a CDN in front of the application may keep the pictures:
// they are answered with Cache-Control public. The default is private, which
// keeps them in the browser alone, because a shared cache serves a picture
// without asking the application who is looking. A picture's address holds
// the owner, a version and a size, so turning this on exposes only what
// somebody who already has the address could fetch.
PublicCache bool
// CacheMaxAge is how long a picture may be kept by whoever caches it. Zero
// means DefaultCacheMaxAge.
CacheMaxAge time.Duration
// GravatarURL is where Gravatar is fetched from. It has to be https, except
// for a loopback address, which a test serves. Empty means
// DefaultGravatarURL.
GravatarURL string
// HTTPClient makes the one request to Gravatar. Nil means a client with
// DefaultGravatarTimeout that follows a redirect only inside the host it was
// pointed at and Gravatar's own domain. An application passes its own to go
// through a proxy.
HTTPClient *http.Client
// Render draws the editor the module answers a request with. Pass
// components.Render from github.com/hyz-is/arandu-avatar/components. Nil
// makes every change answer with a redirect back to where it came from.
Render Renderer
// Activity is arandu-activitylog's logger, the application's one instance
// (activityModule.Logger()). Every change and removal of an avatar is
// recorded under the Grant it was authorized with, in the log named
// ActivityLogName. Nil records nothing.
Activity *activitylog.Logger
// Translator is the application's own catalogue, asked before the one this
// package ships, key by key: "avatar.editor.title". Optional.
Translator *translation.Translator
// Locale is the language the editor, the validation messages and the
// activity descriptions of this package are written in. Empty means
// DefaultLocale. The package ships the locales Locales() lists; any other
// reads the application's Translator first and English after it.
Locale string
// Now is the clock: every timestamp a row carries is read from it. Nil means
// time.Now. A test holds it still; an application leaves it nil.
Now func() time.Time
// Logger receives what the package cannot return to anybody: a file that
// could not be removed after the row that named it was changed. Nil means
// slog.Default().
Logger *slog.Logger
}
Config is what the application passes when it wires this package.
A typed struct rather than a map: a misspelled key in a map is a setting that silently keeps its default, and the failure shows up as behaviour nobody asked for rather than as an error. Here a field that does not exist does not compile.
It names no tenant for the members of a space, and that is deliberate. Every route sits behind RequireAuth, so the tenant of every statement is the one the Grant carries, from the session of whoever is asking; a tenant written here would be a second place for one to come from. The one tenant it does name is the team's own, TeamTenant, because the team is not a customer.
type Crop ¶
Crop is the square a person chose, in fractions of the photo as it is shown upright: X and Y are the top-left corner as a share of the width and of the height, and Size the side as a share of the shorter side. The zero Crop is the largest centred square, and whatever is written is clamped into the photo.
type Directory ¶
type Directory interface {
// Owner finds the owner in the tenant of g, or answers ErrUnknownOwner. The
// tenant is the Grant's: an implementation that looks the owner up in
// another one lets an avatar be attached to somebody else's account.
Owner(ctx context.Context, g security.Grant, ref Ref) (Owner, error)
}
Directory is what the application implements so the package can name the owners of its avatars without owning users or organizations.
type Editor ¶
type Editor struct {
// Owner is who the picture is for.
Owner Owner
// Picture is how the owner is drawn now.
Picture Picture
// CanEdit says the person may change this avatar. Without it the editor
// shows the picture and nothing to press.
CanEdit bool
// Upload says photos can be sent, and Accept and MaxMB describe what the
// picker offers and the limit.
Upload bool
Accept string
MaxMB string
MaxBytes int64
// HasPhoto says a photo the person sent is kept, so it can be removed.
HasPhoto bool
// Gravatar is the state of the Gravatar section.
Gravatar GravatarState
// Styles are the generated styles on offer.
Styles []StyleChoice
// URLs are where the forms post to.
URLs EditorURLs
// Labels are the sentences.
Labels Labels
// Notice is what the last change said, and Errors what the last was refused
// for. The handler sets them on the editor it answers with.
Notice string
Errors validation.Errors
}
Editor is what the editor component draws: the picture as it stands, what the person can do about it, and the sentences in their language.
func (Editor) ID ¶
ID is the identifier of the element the editor is drawn in, which the forms swap their answer into.
func (Editor) WithErrors ¶
func (e Editor) WithErrors(errs validation.Errors) Editor
WithErrors returns the editor with what the last change was refused for.
func (Editor) WithNotice ¶
WithNotice returns the editor with a sentence about what just changed.
type EditorURLs ¶
type EditorURLs struct {
Self, Upload, Gravatar, Style, Remove string
}
EditorURLs are the addresses the editor posts to and reads from.
type Flag ¶
type Flag bool
Flag is a yes-or-no a column holds as an integer, read back from whatever an engine answers with: the engines disagree about booleans and one place has to flatten them.
type GravatarAction ¶
type GravatarAction string
GravatarAction is what a person asks of their Gravatar.
const ( // GravatarEnable switches it on: the e-mail's digest goes to Gravatar once // and the picture that comes back is kept. GravatarEnable GravatarAction = "enable" // GravatarRefresh fetches the picture again. GravatarRefresh GravatarAction = "refresh" // GravatarDisable switches it off and forgets the copy. GravatarDisable GravatarAction = "disable" )
The things a person asks of their Gravatar.
func (GravatarAction) Valid ¶
func (a GravatarAction) Valid() bool
Valid reports whether the action is one of the three.
type GravatarState ¶
type GravatarState struct {
// Available says Gravatar is part of the chain and a Disk keeps the copy, and
// the owner is a person.
Available bool
// HasEmail says the application named an e-mail to look up. The e-mail itself
// is never in the editor.
HasEmail bool
// Enabled says the person switched it on and a copy is kept.
Enabled bool
// Covered says an uploaded photo is in front of it.
Covered bool
}
GravatarState is what the editor says about Gravatar.
type Kind ¶
type Kind string
Kind says what an avatar is for.
type Labels ¶
type Labels struct {
Locale string
// contains filtered or unexported fields
}
Labels are the sentences of this package in one locale.
func (Labels) Summary ¶
func (l Labels) Summary(errs validation.Errors) []string
Summary is one line per rejected message, the field named before it. Nil when nothing was rejected.
type Module ¶
type Module struct {
// contains filtered or unexported fields
}
Module is what the application registers.
It implements foundation.Module, which is Name and Routes and nothing else -- that pair is the whole public contract between a package and the framework. It also implements foundation.Migratable, because it owns a table. The other optional interfaces are declared beside Module in the framework and are opted into the same way, by implementing them.
func New ¶
New returns the module, or the reason it cannot be built.
The collaborators are parameters and not fields somebody fills in afterwards: a module that could be registered half-wired is a module whose first request is the thing that reports the missing half.
It returns an error rather than panicking or carrying on, because everything it refuses is a wiring mistake, and a wiring mistake found at boot costs one restart. The same mistake found later is a request that reached a nil handle.
func (*Module) Avatars ¶
func (m *Module) Avatars() *AvatarService
Avatars is the members' use cases, for an application that calls them from its own code. Every method asks the policy, so handing it out opens nothing.
func (*Module) Editor ¶
Editor is what the editor component is handed for one owner. See AvatarService.Editor.
func (*Module) MemberRoutes ¶
MemberRoutes registers the members' routes alone, under Prefix.
func (*Module) Migrations ¶
func (m *Module) Migrations() []foundation.Migration
Migrations declares the schema this module owns.
They are returned in the order their names sort in, which is the order they apply in: the name carries the order, and nothing else decides it.
func (*Module) Name ¶
Name is the module identifier: a lowercase slug, stable, no spaces.
It is what `aru route:list` groups by and what the route names are prefixed with, so changing it changes addresses that other code has already written down.
func (*Module) Resolve ¶
func (m *Module) Resolve(ctx context.Context, actor security.Subject, owners ...Owner) (Pictures, error)
Resolve is how the owners are drawn, in one query however many there are. It is the call a page makes before it draws a list of people. See AvatarService.Resolve.
func (*Module) Routes ¶
Routes registers every route of the module: the members' and the team's.
An application that keeps the two sides apart -- and the team's session is valid on its own side only -- registers them separately with MemberRoutes and TeamRoutes, each on the router group its own guards are on.
Every route needs somebody signed in, so the guard is mounted once per side, on the router the routes are registered on, rather than route by route: r is replaced by the guarded group before the first registration, and no unguarded router is left in scope for the next route to be added to. RequireAuth sends a request with no session to the sign-in screen, and puts the subject of one that has a session on its context, where a handler reads it with ctx.User; Config.Middleware runs after it, and Config.TeamMiddleware after that on the team's routes.
func (*Module) Team ¶
func (m *Module) Team() *TeamService
Team is the platform team's use cases, for an application that calls them from its own code. Every method asks TeamPolicy, so handing it out opens nothing.
func (*Module) TeamRoutes ¶
TeamRoutes registers the team's routes alone, under TeamPrefix, for an application that mounts them inside its operator console with that console's guards on r. It registers nothing when Config.TeamTenant is empty.
func (*Module) URL ¶
func (m *Module) URL(ctx context.Context, actor security.Subject, owner Owner, size int) (string, error)
URL is the address of one owner's picture at a size, for an <img src> or a stylesheet: the photo's address when they have a photo, and the drawing as a data: address when they do not, so the answer can always be used as an image. A page whose policy has no data: in img-src draws the drawing with Picture.SVG instead, which needs none.
type Opened ¶
type Opened struct {
// Body is the file. The caller closes it. Zero when NotModified or
// Redirect.
Body filesystem.File
// ContentType is what the file is, as the package detected and stored it.
ContentType string
// ETag is the entity tag of the picture, quoted.
ETag string
// NotModified says the caller's copy is the current one: answer 304.
NotModified bool
// Redirect is where the owner's current picture is, when the address asked
// for is one that was replaced: answer 302 there.
Redirect string
}
Opened is a picture ready to be written to a response.
type Owner ¶
type Owner struct {
Ref
// Name is the person's name or the organization's. It is the alternative
// text of the picture and the letters of the initials. Empty draws no
// letters.
Name string
// Email is the person's e-mail. It is used for one thing, and only when the
// person switched Gravatar on: the digest Gravatar is asked for. It is never
// stored, logged or sent anywhere else. Empty means Gravatar cannot be used.
Email string
}
Owner is who an avatar is for, as the application knows them: the identifier, the name an avatar is drawn and described with, and the e-mail a Gravatar is looked up by.
type Paths ¶
Paths are the segments the routes of this package are built from. Each one starts with "/" and holds no wildcard.
GET Prefix + Users + /{id}/{version}/{size} the picture
GET Prefix + Users + /{id} + Editor the editor, as a fragment
POST Prefix + Users + /{id} + Upload send a photo
POST Prefix + Users + /{id} + Gravatar switch Gravatar on, refresh it, switch it off
POST Prefix + Users + /{id} + Style choose the generated style
POST Prefix + Users + /{id} + Removal remove the photo
and the same under Organizations. Under TeamPrefix the picture and the removal.
type Picture ¶
type Picture struct {
// Owner is who it is for.
Owner Owner
// Source is where the picture comes from: the photo, the Gravatar copy or
// the drawing.
Source Source
// Style is the generated style, which is also what draws the picture while a
// photo loads and when it cannot.
Style Style
// Version is the version in the address of the photo, empty for a drawing.
Version string
// Type is the content type of the photo.
Type string
// Sizes are the sides the photo is kept at, ascending.
Sizes []int
// contains filtered or unexported fields
}
Picture is how one owner is drawn: where the picture comes from, the addresses of the photo when there is one, and the drawing that stands in when there is not.
It is a snapshot, holds no connection and carries nothing about the tenant. The zero Picture is valid and draws an unnamed initials tile.
func (Picture) DataURI ¶
DataURI is the drawing as an address an <img>, an e-mail or a stylesheet can hold. A page whose Content-Security-Policy has no data: in img-src cannot show it; SVG does not need one.
func (Picture) HasImage ¶
HasImage reports whether the picture is a photo. A drawing is not an image anybody fetches: SVG writes it into the page.
func (Picture) Initials ¶
Initials are the letters of the owner's name: the first and the last word of a person's, and the first two words of an organization's.
func (Picture) SVG ¶
SVG is the drawing, as an <svg> element for the page: it needs no request, shifts no layout and follows the size of its container.
type Ref ¶
Ref names whose avatar it is: a person or an organization, by the identifier the application knows them by.
type Renderer ¶
Renderer draws the editor the module answers a request with, as the markup that replaces it on the page. components.Render is the one this package ships.
type Source ¶
type Source string
Source is one place a picture can come from.
const ( // SourceUpload is a photo the person sent. SourceUpload Source = "upload" // SourceGravatar is the person's Gravatar, which they switched on. SourceGravatar Source = "gravatar" // SourceGenerated is a drawing made from the name, with nothing to send or // to fetch. It always works, so it ends every chain. SourceGenerated Source = "generated" )
The sources of a picture, which Config.Chain puts in order.
type Style ¶
Style names one way of drawing a generated avatar.
const ( StyleInitials Style = art.Initials StyleIdenticon Style = art.Identicon StylePattern Style = art.Pattern StyleBeam Style = art.Beam StyleMarble Style = art.Marble StylePixel Style = art.Pixel StyleRing Style = art.Ring StyleSunset Style = art.Sunset StyleBauhaus Style = art.Bauhaus StyleShapes Style = art.Shapes StyleSilhouette Style = art.Silhouette )
The generated styles, each a deterministic SVG drawn from the owner's identifier.
type StyleChoice ¶
type StyleChoice struct {
Style Style
Name string
Selected bool
// Picture draws the style: Picture.SVG is the preview.
Picture Picture
}
StyleChoice is one generated style the editor offers, drawn for this owner so the person sees their own picture in each of them.
type TeamOwner ¶
type TeamOwner struct {
Owner
// Space is the tenant of the owner. Empty takes the first space that has a
// row for them.
Space string
}
TeamOwner is an owner of a space the team looks at: the owner, and the space they are in when the application knows it.
type TeamPolicy ¶
type TeamPolicy struct {
// Realm is the tenant the team signs in to. Empty refuses everybody.
Realm string
}
TeamPolicy is the only authority over what the platform team does with an Avatar of any space.
It denies unless the subject is a member of the team -- a subject of Realm, the tenant the team signs in to -- who was granted the action. A subject of any other tenant is refused whatever actions it carries, and so is a subject somebody else is viewing as: an operator inside a customer's account acts as the customer and reads no other space.
It is the one policy that does not compare a record's tenant with the subject's, because crossing tenants is what the team does. The tenant of the work itself is not the subject's: the service reads the row to find it, and then acts in that tenant under a Grant scoped to it, issued only after this policy allowed the action.
type TeamService ¶
type TeamService struct {
// contains filtered or unexported fields
}
TeamService orchestrates what the platform team does with the avatars of every space.
A member of the team is a subject of Config.TeamTenant, and TeamPolicy decides what they may do. The avatars are in the customers' tenants, so a use case here goes in two steps: it asks the policy for a Grant in the team's own realm, finds the avatar's tenant with it, and then acts with a Grant scoped to that one tenant, which exists only because the first one was issued for the same action. Nothing a request names chooses the tenant: it is the one the row says. The one value a request may add is Space, to tell apart the rows of one owner that exist in two spaces, or to name the space of an owner who has no row yet; it narrows a look-up and is never a Grant.
func NewTeamService ¶
func NewTeamService(db *data.DB, cfg Config) *TeamService
NewTeamService wires the service over the application's database handle.
func (*TeamService) Open ¶
func (s *TeamService) Open(ctx context.Context, actor security.Subject, ref Ref, space, version string, size int, ifNoneMatch string) (Opened, error)
Open reads the picture an address names, for the team. See AvatarService.Open.
func (*TeamService) Remove ¶
func (s *TeamService) Remove(ctx context.Context, actor security.Subject, ref Ref, space string) error
Remove removes the owner's photo, for the team: what moderation does with a picture that should not be there.
func (*TeamService) Resolve ¶
func (s *TeamService) Resolve(ctx context.Context, actor security.Subject, owners ...TeamOwner) (Pictures, error)
Resolve is how the owners are drawn for the team, with addresses under the team's own prefix, which the team's session can read. An owner with no row is drawn from their name.
type URLs ¶
type URLs struct {
// contains filtered or unexported fields
}
URLs are the addresses of the module's routes, for an application that links to them: a menu, an e-mail, a form of its own.
func (URLs) Editor ¶
func (u URLs) Editor(ref Ref) EditorURLs
Editor is the addresses the editor of an owner uses.
type UploadRequest ¶
type UploadRequest struct {
// Body is the file as it was sent. It is read up to Config.MaxUploadBytes.
Body io.Reader
// Crop is the square the person chose. The zero Crop is the largest centred
// square.
Crop Crop
}
UploadRequest is the input contract of a photo.
The fields are explicit and there is no mass assignment. There is no tenant here and there must never be one: the tenant comes from the Grant, which comes from the session.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package components draws the avatar of a Kyse application: AvatarImage, the circle that shows a person's photo or a drawing made from their name, and AvatarEditor, where a person changes it.
|
Package components draws the avatar of a Kyse application: AvatarImage, the circle that shows a person's photo or a drawing made from their name, and AvatarEditor, where a person changes it. |
|
internal
|
|
|
art
Package art draws the avatars nobody uploaded: deterministic SVG pictures made from a seed and a name, with no network call and no stored state.
|
Package art draws the avatars nobody uploaded: deterministic SVG pictures made from a seed and a name, with no network call and no stored state. |
|
imaging
Package imaging turns the bytes somebody uploaded into the few square pictures an avatar is served as.
|
Package imaging turns the bytes somebody uploaded into the few square pictures an avatar is served as. |
|
platform
Package platform is the avatars table read without the tenant filter: the one read of arandu-avatar that crosses tenants, the lookup the platform team makes to find which space an avatar is in, after the team's policy allowed it.
|
Package platform is the avatars table read without the tenant filter: the one read of arandu-avatar that crosses tenants, the lookup the platform team makes to find which space an avatar is in, after the team's policy allowed it. |