75 lines
2.3 KiB
Go
75 lines
2.3 KiB
Go
package webui
|
|
|
|
import (
|
|
"errors"
|
|
"net/http"
|
|
|
|
"github.com/samcharles93/archie-core/internal/domain/access"
|
|
"github.com/samcharles93/archie-core/internal/domain/org"
|
|
)
|
|
|
|
const orgCookieMaxAge = 365 * 24 * 60 * 60
|
|
|
|
// selectedOrg is the principal acting in the org the caller's cookie names. A
|
|
// selection the caller is not a member of is dropped, so a stale cookie falls
|
|
// back to the org the caller serves rather than locking it out.
|
|
func (s *Server) selectedOrg(w http.ResponseWriter, r *http.Request, principal access.Principal) (access.Principal, error) {
|
|
var chosen string
|
|
if cookie, err := r.Cookie(s.cookies().org); err == nil {
|
|
chosen = cookie.Value
|
|
}
|
|
if chosen == "" {
|
|
return principal, nil
|
|
}
|
|
// The lookup runs as the caller, so the State Store knows whose
|
|
// memberships entitle it to the chosen org's workspaces.
|
|
ctx := org.WithOrg(access.WithPrincipal(r.Context(), principal), principal.Org)
|
|
selected, err := principal.Select(ctx, org.OrgID(chosen), s.workspaces())
|
|
if errors.Is(err, access.ErrNotMember) {
|
|
s.setOrgCookie(w, r, "")
|
|
return principal, nil
|
|
}
|
|
return selected, err
|
|
}
|
|
|
|
// workspaces is nil, not a typed nil, when no org store is wired.
|
|
func (s *Server) workspaces() access.WorkspaceLister {
|
|
if s.Orgs == nil {
|
|
return nil
|
|
}
|
|
return s.Orgs
|
|
}
|
|
|
|
func (s *Server) setOrgCookie(w http.ResponseWriter, r *http.Request, id string) {
|
|
cookie := &http.Cookie{
|
|
Name: s.cookies().org, Value: id, Path: "/",
|
|
HttpOnly: true, SameSite: http.SameSiteStrictMode, Secure: r.TLS != nil, MaxAge: orgCookieMaxAge,
|
|
}
|
|
if id == "" {
|
|
cookie.MaxAge = -1
|
|
}
|
|
http.SetCookie(w, cookie)
|
|
}
|
|
|
|
// handleOrgSelect makes the caller's chosen org the one its tasks, workflows
|
|
// and settings act in. Only an org the caller is a member of may be chosen.
|
|
func (s *Server) handleOrgSelect(w http.ResponseWriter, r *http.Request) {
|
|
request, ok := decodeBody[struct {
|
|
ID string `json:"id"`
|
|
}](w, r)
|
|
if !ok {
|
|
return
|
|
}
|
|
principal, _ := access.PrincipalFromContext(r.Context())
|
|
if _, err := principal.Select(r.Context(), org.OrgID(request.ID), s.workspaces()); err != nil {
|
|
if errors.Is(err, access.ErrNotMember) {
|
|
http.Error(w, "not a member of that org", http.StatusForbidden)
|
|
return
|
|
}
|
|
writeOrgError(w, err)
|
|
return
|
|
}
|
|
s.setOrgCookie(w, r, request.ID)
|
|
w.WriteHeader(http.StatusNoContent)
|
|
}
|