msgraph

package
v0.0.122 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 26, 2026 License: GPL-3.0 Imports: 15 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package msgraph is a minimal Microsoft Graph client. The app-only (client-credentials) Client covers exactly the slices of Graph the app uses as itself: directory profile reads (phone + manager, synced onto Ex profiles at SSO login) and creating Teams online meetings on behalf of a user (the /mstmeetings slash command). Because the workspace already authenticates through the same Azure AD app registration, no per-user account linking or token storage is needed — the app authenticates itself and acts via Graph application permissions (User.Read.All; OnlineMeetings.ReadWrite.All via an application access policy for meeting creation). Delegated (delegated.go) acts as a signed-in user instead, for what must never run with the app's rights: sharing SharePoint files.

Index

Constants

This section is empty.

Variables

View Source
var ErrForbidden = errors.New("msgraph: forbidden")

ErrForbidden marks a 403: the user may not do this, e.g. share an item they can only read.

View Source
var ErrNotFound = errors.New("msgraph: not found")

ErrNotFound marks a 404 from Graph — the directory object doesn't exist (user not in the tenant, or no manager assigned). Callers treat it as an empty result, not a failure.

View Source
var ErrSignInRequired = errors.New("msgraph: sign-in required")

ErrSignInRequired marks a delegated call the user's own token can no longer make: Graph refused it (401), or the token endpoint would not renew it (consent revoked, password changed, refresh token expired). Only signing in again fixes it.

Functions

func EncodeShareURL added in v0.0.116

func EncodeShareURL(link string) string

EncodeShareURL turns a link into the share id Graph's /shares endpoint takes: "u!" and the URL in unpadded base64url.

Types

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client is an app-only Microsoft Graph client with a cached bearer token.

func New

func New(cfg Config) (*Client, error)

New builds a Client, or (nil, nil) when the integration is not configured (any credential missing) — the same "absent config disables the feature" contract the OneSignal sender follows.

func (*Client) CreateOnlineMeeting

func (c *Client) CreateOnlineMeeting(ctx context.Context, organizerKey string, req OnlineMeetingRequest) (*OnlineMeeting, error)

CreateOnlineMeeting creates a Teams online meeting organized by the given user (AAD object ID or UPN). Attendees are pre-registered so tenant members bypass the lobby; unknown UPNs are ignored by Graph.

func (*Client) FindUserByEmail

func (c *Client) FindUserByEmail(ctx context.Context, email string) (*UserProfile, error)

FindUserByEmail resolves a user by their mail attribute via an OData filter. The plain /users/{key} path treats an email as a userPrincipalName, which 404s in tenants where mail != UPN — this is the fallback that keeps email-keyed resolution working there. ErrNotFound when no user carries the address.

func (*Client) GetUserManager

func (c *Client) GetUserManager(ctx context.Context, key string) (*UserProfile, error)

GetUserManager fetches a user's manager from the directory hierarchy. ErrNotFound when the user has no manager assigned (or doesn't exist).

func (*Client) GetUserProfile

func (c *Client) GetUserProfile(ctx context.Context, key string) (*UserProfile, error)

GetUserProfile fetches a user's directory profile. key is an AAD object ID or a userPrincipalName. ErrNotFound when the user isn't in the directory.

func (*Client) ListMemberGroups added in v0.0.121

func (c *Client) ListMemberGroups(ctx context.Context, parentID string) ([]Group, error)

ListMemberGroups returns the groups that are direct members of the group parentID (users and other members are left out). ErrNotFound when parentID doesn't exist.

func (*Client) ListMemberUserIDs added in v0.0.121

func (c *Client) ListMemberUserIDs(ctx context.Context, groupID string) ([]string, error)

ListMemberUserIDs returns the object IDs of the users who are direct members of the group groupID (nested groups and other members are left out).

func (*Client) ListUserAccounts added in v0.0.101

func (c *Client) ListUserAccounts(ctx context.Context) ([]UserAccount, error)

ListUserAccounts returns every user account in the tenant with its enabled flag, following Graph's paging to the end: one call per 999 accounts, so a whole-tenant check stays cheap enough to run every few minutes.

func (*Client) ResolveUserByEmail

func (c *Client) ResolveUserByEmail(ctx context.Context, email string) (*UserProfile, error)

ResolveUserByEmail resolves an email to a directory profile. The app's source of truth is the OIDC email claim, which for Entra ID is the mail attribute — so the mail filter runs FIRST. Matching against UPNs first risks the wrong person in tenants where logins and mailboxes use different local parts (e.g. UPN firstname.lastname@ vs mail firstname@ — one user's mail can equal ANOTHER user's UPN). The UPN-keyed lookup remains as the fallback for accounts whose mail attribute is unset (their email claim was the UPN). Oid-keyed callers should use GetUserProfile directly.

type Config

type Config struct {
	TenantID     string
	ClientID     string
	ClientSecret string
	TokenURL     string
	BaseURL      string
	HTTPClient   *http.Client
}

Config carries the Azure AD app registration the client authenticates as. TokenURL/BaseURL/HTTPClient are injectable for tests (httptest servers).

type Delegated added in v0.0.116

type Delegated struct {
	// contains filtered or unexported fields
}

Delegated calls Microsoft Graph as a signed-in user, with that user's own token, so Graph allows exactly what the user may do. Sharing a file runs this way and never with the app's rights: with app-only access anyone could paste a link to a file they may not share, and the app would share it.

func NewDelegated added in v0.0.116

func NewDelegated(baseURL string, httpClient *http.Client) (*Delegated, error)

NewDelegated builds a Delegated client. BaseURL and HTTPClient are injectable for tests; empty and nil take the Graph defaults.

func (*Delegated) DeletePermission added in v0.0.116

func (d *Delegated) DeletePermission(ctx context.Context, ts oauth2.TokenSource, driveID, itemID, permissionID string) error

DeletePermission takes back one permission on the item. A permission that is already gone is not an error.

func (*Delegated) Grantees added in v0.0.116

func (d *Delegated) Grantees(ctx context.Context, ts oauth2.TokenSource, driveID, itemID string) ([]Grantee, error)

Grantees lists the people who already hold a permission of their own on the item, inherited or not (people with access through a group or a link aren't listed).

func (*Delegated) Invite added in v0.0.116

func (d *Delegated) Invite(ctx context.Context, ts oauth2.TokenSource, driveID, itemID, objectID string) (string, error)

Invite gives one person (by directory object id) edit access to the item, without emailing them, and returns the permission it created so that exactly this permission can be taken back later.

func (*Delegated) Preview added in v0.0.116

func (d *Delegated) Preview(ctx context.Context, ts oauth2.TokenSource, driveID, itemID string) (*url.URL, error)

Preview returns a short-lived address that shows the item as it is (Office for the web's viewer for Office files), embeddable in a frame. It carries the user's own access — whoever opens it acts as them — so it is for that user's eyes only. ErrNotFound when the item has no such preview.

func (d *Delegated) ResolveLink(ctx context.Context, ts oauth2.TokenSource, link string) (*DriveItem, error)

ResolveLink looks up the item a SharePoint or OneDrive link points to — a sharing link or the item's own address. ErrNotFound when the user can't see it.

func (*Delegated) Upload added in v0.0.116

func (d *Delegated) Upload(ctx context.Context, ts oauth2.TokenSource, folder []string, name string, body io.Reader, size int64) (*DriveItem, error)

Upload puts a file into the user's own OneDrive, at folder/name (folders are made as needed), and returns it. A file of that name already there is kept: the new one is renamed ("report 1.docx"). body must hold exactly size bytes.

type DriveItem added in v0.0.116

type DriveItem struct {
	ID     string `json:"id"`
	Name   string `json:"name"`
	Size   int64  `json:"size"`
	WebURL string `json:"webUrl"`
	File   *struct {
		MimeType string `json:"mimeType"`
	} `json:"file,omitempty"`
	Folder          *struct{} `json:"folder,omitempty"`
	ParentReference struct {
		DriveID string `json:"driveId"`
	} `json:"parentReference"`
	SharePointIDs *struct {
		ListItemUniqueID string `json:"listItemUniqueId"`
		SiteURL          string `json:"siteUrl"`
	} `json:"sharepointIds,omitempty"`
}

DriveItem is the slice of a SharePoint or OneDrive item the app shows.

func (*DriveItem) DownloadURL added in v0.0.116

func (i *DriveItem) DownloadURL() string

DownloadURL is where SharePoint downloads the file, or "" for a folder. (An Office file's webUrl opens its viewer instead.)

func (*DriveItem) EditURL added in v0.0.116

func (i *DriveItem) EditURL() string

EditURL is where the item opens for editing in Office for the web, or "" when Office doesn't edit this kind of file.

type Grantee added in v0.0.116

type Grantee struct {
	ID    string // directory object id
	Email string
}

Grantee is a person who holds a permission on an item.

type Group added in v0.0.121

type Group struct {
	ID          string `json:"id"`
	DisplayName string `json:"displayName"`
	Description string `json:"description"`
}

Group is a directory group as user groups read it.

type MeetingAttendee

type MeetingAttendee struct {
	UPN      string
	ObjectID string
}

MeetingAttendee identifies one invitee. ObjectID (the AAD object id) is what actually lands the person on the meeting roster for app-only created meetings — a bare UPN frequently fails to resolve there and leaves the participant list empty. UPN rides along as the display/resolution fallback.

type OnlineMeeting

type OnlineMeeting struct {
	ID      string `json:"id"`
	JoinURL string `json:"joinWebUrl"`
	Subject string `json:"subject"`
}

OnlineMeeting is the created meeting slice the app needs.

type OnlineMeetingRequest

type OnlineMeetingRequest struct {
	Subject   string
	StartAt   time.Time
	EndAt     time.Time
	Attendees []MeetingAttendee
}

OnlineMeetingRequest describes the Teams meeting to create.

type StatusError added in v0.0.116

type StatusError struct {
	Status int
	Code   string
}

StatusError is a non-2xx Graph response other than 404. It carries Graph's machine-readable error code but never its message: bodies are not echoed into errors, since they can carry directory PII.

func (*StatusError) Error added in v0.0.116

func (e *StatusError) Error() string

func (*StatusError) Is added in v0.0.116

func (e *StatusError) Is(target error) bool

Is lets callers test a refusal by kind: a 401 is ErrSignInRequired (the token was refused), a 403 ErrForbidden.

type UserAccount added in v0.0.101

type UserAccount struct {
	ID string `json:"id"`
	// AccountEnabled is false for an account disabled in Entra (it can no
	// longer sign in). Graph returns it only when selected; nil means it
	// wasn't reported, which never counts as disabled.
	AccountEnabled *bool `json:"accountEnabled"`
}

UserAccount is one directory account's sign-in standing.

func (UserAccount) Enabled added in v0.0.101

func (a UserAccount) Enabled() bool

Enabled reports whether the account can sign in. An unreported flag counts as enabled: missing data is never grounds to lock someone out.

type UserProfile

type UserProfile struct {
	ID                string   `json:"id"`
	DisplayName       string   `json:"displayName"`
	Mail              string   `json:"mail"`
	UserPrincipalName string   `json:"userPrincipalName"`
	MobilePhone       string   `json:"mobilePhone"`
	BusinessPhones    []string `json:"businessPhones"`
}

UserProfile is the directory slice the app reads for a user.

func (*UserProfile) EmailAddress

func (p *UserProfile) EmailAddress() string

EmailAddress returns the mailbox address, falling back to the UPN (which is mail-shaped and routable in the overwhelming majority of tenants).

func (*UserProfile) Phone

func (p *UserProfile) Phone() string

Phone returns the best single display number: mobile first, then the first business line.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL