msgraph

package module
v0.0.0-...-a7bf31e Latest Latest
Warning

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

Go to latest
Published: Feb 17, 2020 License: MIT Imports: 12 Imported by: 0

README

Golang Microsoft Graph API implementation

godoc Build Status Go Report Card Codacy Badge codebeat badge codecov

go-msgraph is a go lang implementation of the Microsoft Graph API. See https://developer.microsoft.com/en-us/graph/docs/concepts/overview

General

This implementation has been written to get various user, group and calendar details out of a Microsoft Azure Active Directory. Currently only READ-access is implemented, but you are welcome to add WRITE-support to it & backmerge it

Features

working & tested:

  • list users, groups, calendars, calendarevents
  • automatically grab & refresh token for API-access
  • json-load the GraphClient struct & initialize it
  • set timezone for full-day CalendarEvent

in progress:

  • implement paging to load huge data-sets, currently limitted to one page, 999 entries

planned:

Example

To get your credentials visit: https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-group-create-service-principal-portal

// initialize GraphClient manually
graphClient, err := msgraph.NewGraphClient("<TenantID>", "<ApplicationID>", "<ClientSecret>")
if err != nil {
    fmt.Println("Credentials are probably wrong or system time is not synced: ", err)
}

// initialize the GraphClient via JSON-Load. Please do proper error-handling (!)
// Specify JSON-Fields TenantID, ApplicationID and ClientSecret 
fileContents, err := ioutil.ReadFile("./msgraph-credentials.json")
var graphClient msgraph.GraphClient
err = json.Unmarshal(fileContents, &graphClient)

// List all users
users, err := graphClient.ListUsers()
// Gets all the detailled information about a user identified by it's ID or userPrincipalName
user, err := graphClient.GetUser("humpty@contoso.com") 
// List all groups
groups, err := graphClient.ListGroups()
// List all members of a group.
groupMembers, err := groups[0].ListMembers()
// Lists all Calendars of a user
calendars, err := user.ListCalendars()

// Let all full-day calendar events that are loaded from ms graph be set to timezone Europe/Vienna:
// Standard is time.Local
msgraph.FullDayEventTimeZone, _ = time.LoadLocation("Europe/Vienna")

// Lists all CalendarEvents of the given userPrincipalName/ID that starts/ends within the the next 7 days
startTime := time.Now()
endTime := time.Now().Add(time.Hour * 24 * 7)
events, err := graphClient.ListCalendarView("alice@contoso.com", startTime, endTime)

Installation

Using go get
$ go get github.com/open-networks/go-msgraph

You can use go get -u to update the package.

Documentation

For docs, see http://godoc.org/github.com/open-networks/go-msgraph or run:

$ godoc github.com/open-networks/go-msgraph

Documentation

Overview

Package msgraph is a go lang implementation of the Microsoft Graph API

See: https://developer.microsoft.com/en-us/graph/docs/concepts/overview

Index

Constants

View Source
const APIVersion string = "v1.0"

APIVersion represents the APIVersion of msgraph used by this implementation

View Source
const BaseURL string = "https://graph.microsoft.com"

BaseURL represents the URL used to perform all ms graph API-calls

View Source
const LoginBaseURL string = "https://login.microsoftonline.com"

LoginBaseURL represents the basic url used to acquire a token for the msgraph api

View Source
const MaxPageSize int = 999

MaxPageSize is the maximum Page size for an API-call. This will be rewritten to use paging some day. Currently limits environments to 999 entries (e.g. Users, CalendarEvents etc.)

Variables

View Source
var (
	// ErrFindUser is returned on any func that tries to find a user with the given parameters that can not be found
	ErrFindUser = errors.New("unable to find user")
	// ErrFindGroup is returned on any func that tries to find a group with the given parameters that can not be found
	ErrFindGroup = errors.New("unable to find group")
	// ErrFindCalendar is returned on any func that tries to find a calendar with the given parameters that can not be found
	ErrFindCalendar = errors.New("unable to find calendar")
	// ErrNotGraphClientSourced is returned if e.g. a ListMembers() is called but the Group has not been created by a graphClient query
	ErrNotGraphClientSourced = errors.New("Instance is not created from a GraphClient API-Call, can not directly get further information")
)
View Source
var FullDayEventTimeZone = time.Local

FullDayEventTimeZone is used by CalendarEvent.UnmarshalJSON to set the timezone for full day events.

That method json-unmarshal automatically sets the Begin/End Date to 00:00 with the correnct days then. This has to be done because Microsoft always sets the timezone to UTC for full day events. To work with that within your program is probably a bad idea, hence configure this as you need or probably even back to time.UTC

View Source
var WinIANA = map[string]string{}/* 153 elements not displayed */

WinIANA contains a mapping for all Windows Time Zones to IANA time zones usable for time.LoadLocation. This list was initially copied from https://github.com/thinkovation/windowsiana/blob/master/windowsiana.go on 30th of August 2018, 14:00 and then extended on the same day.

The full list of time zones that have been added and are now supported come from an an API-Call described here: https://developer.microsoft.com/en-us/graph/docs/api-reference/v1.0/api/outlookuser_supportedtimezones

Functions

This section is empty.

Types

type Attendee

type Attendee struct {
	Type           string         // the type of the invitation, e.g. required, optional etc.
	Name           string         // the name of the person, comes from the E-Mail Address - hence not a reliable name to search for
	Email          string         // the e-mail address of the person - use this to identify the user
	ResponseStatus ResponseStatus // the ResponseStatus for that particular Attendee for the CalendarEvent
}

Attendee struct represents an attendee for a CalendarEvent

func (Attendee) Equal

func (a Attendee) Equal(other Attendee) bool

Equal compares the Attendee to the other Attendee and returns true if the two given Attendees are equal. Otherwise returns false

func (Attendee) String

func (a Attendee) String() string

func (*Attendee) UnmarshalJSON

func (a *Attendee) UnmarshalJSON(data []byte) error

UnmarshalJSON implements the json unmarshal to be used by the json-library

type Attendees

type Attendees []Attendee

Attendees struct represents multiple Attendees for a CalendarEvent

func (Attendees) Equal

func (a Attendees) Equal(other Attendees) bool

Equal compares the Attendee to the other Attendee and returns true if the two given Attendees are equal. Otherwise returns false

func (Attendees) String

func (a Attendees) String() string

type Calendar

type Calendar struct {
	ID                  string // The group's unique identifier. Read-only.
	Name                string // The calendar name.
	CanEdit             bool   // True if the user can write to the calendar, false otherwise. This property is true for the user who created the calendar. This property is also true for a user who has been shared a calendar and granted write access.
	CanShare            bool   // True if the user has the permission to share the calendar, false otherwise. Only the user who created the calendar can share it.
	CanViewPrivateItems bool   // True if the user can read calendar items that have been marked private, false otherwise.
	ChangeKey           string // Identifies the version of the calendar object. Every time the calendar is changed, changeKey changes as well. This allows Exchange to apply changes to the correct version of the object. Read-only.

	Owner EmailAddress // If set, this represents the user who created or added the calendar. For a calendar that the user created or added, the owner property is set to the user. For a calendar shared with the user, the owner property is set to the person who shared that calendar with the user.
	// contains filtered or unexported fields
}

Calendar represents a single calendar of a user

See https://developer.microsoft.com/en-us/graph/docs/api-reference/v1.0/resources/calendar

func (Calendar) String

func (c Calendar) String() string

func (*Calendar) UnmarshalJSON

func (c *Calendar) UnmarshalJSON(data []byte) error

UnmarshalJSON implements the json unmarshal to be used by the json-library

type CalendarEvent

type CalendarEvent struct {
	ID                    string
	CreatedDateTime       time.Time      // Creation time of the CalendarEvent, has the correct timezone set from OriginalStartTimeZone (json)
	LastModifiedDateTime  time.Time      // Last modified time of the CalendarEvent, has the correct timezone set from OriginalEndTimeZone (json)
	OriginalStartTimeZone *time.Location // The original start-timezone, is already integrated in the calendartimes. Caution: is UTC on full day events
	OriginalEndTimeZone   *time.Location // The original end-timezone, is already integrated in the calendartimes. Caution: is UTC on full day events
	ICalUID               string
	Subject               string
	Importance            string
	Sensitivity           string
	IsAllDay              bool   // true = full day event, otherwise false
	IsCancelled           bool   // calendar event has been cancelled but is still in the calendar
	IsOrganizer           bool   // true if the calendar owner is the organizer
	SeriesMasterID        string // the ID of the master-entry of this series-event if any
	ShowAs                string
	Type                  string
	ResponseStatus        ResponseStatus // how the calendar-owner responded to the event (normally "organizer" because support-calendar is the host)
	StartTime             time.Time      // starttime of the Event, correct timezone is set
	EndTime               time.Time      // endtime of the event, correct timezone is set

	Attendees      Attendees // represents all attendees to this CalendarEvent
	OrganizerName  string    // the name of the organizer from the e-mail, not reliable to identify anyone
	OrganizerEMail string    // the e-mail address of the organizer, use this to identify the user
}

CalendarEvent represents a single event within a calendar

func (CalendarEvent) Equal

func (c CalendarEvent) Equal(other CalendarEvent) bool

Equal returns wether the CalendarEvent is identical to the given CalendarEvent

func (CalendarEvent) GetFirstAttendee

func (c CalendarEvent) GetFirstAttendee() Attendee

GetFirstAttendee returns the first Attendee that is not the organizer of the event from the Attendees array. If none is found then an Attendee with the Name of "None" will be returned.

func (CalendarEvent) PrettySimpleString

func (c CalendarEvent) PrettySimpleString() string

PrettySimpleString returns all Calendar Events in a readable format, mostly used for logging purposes

func (CalendarEvent) String

func (c CalendarEvent) String() string

func (*CalendarEvent) UnmarshalJSON

func (c *CalendarEvent) UnmarshalJSON(data []byte) error

UnmarshalJSON implements the json unmarshal to be used by the json-library

type CalendarEvents

type CalendarEvents []CalendarEvent

CalendarEvents represents multiple events of a Calendar. The amount of entries is determined by the timespan that is used to load the Calendar

func (CalendarEvents) Equal

func (c CalendarEvents) Equal(others CalendarEvents) bool

Equal returns true if the two CalendarEvent[] are equal. The order of the events doesn't matter

func (CalendarEvents) GetCalendarEventsAtCertainTime

func (c CalendarEvents) GetCalendarEventsAtCertainTime(givenTime time.Time) CalendarEvents

GetCalendarEventsAtCertainTime returns a subset of CalendarEvents that either start or end at the givenTime or whose StartTime is before and EndTime is After the givenTime

func (CalendarEvents) PrettySimpleString

func (c CalendarEvents) PrettySimpleString() string

PrettySimpleString returns all Calendar Events in a readable format, mostly used for logging purposes

func (CalendarEvents) SortByStartDateTime

func (c CalendarEvents) SortByStartDateTime()

SortByStartDateTime sorts the array in this CalendarEvents instance

func (CalendarEvents) String

func (c CalendarEvents) String() string

func (*CalendarEvents) UnmarshalJSON

func (c *CalendarEvents) UnmarshalJSON(data []byte) error

UnmarshalJSON implements the json unmarshal to be used by the json-library. The only purpose of this overwrite is to immediately sort the []CalendarEvent by StartDateTime

type Calendars

type Calendars []Calendar

Calendars represents an array of Calendar instances combined with some helper-functions

See: https://developer.microsoft.com/en-us/graph/docs/api-reference/v1.0/resources/calendar

func (Calendars) GetByName

func (c Calendars) GetByName(name string) (Calendar, error)

GetByName returns the calendar obj of that array whose DisplayName matches the given name. Returns an ErrFindCalendar if no calendar exists that matches the given name.

func (Calendars) String

func (c Calendars) String() string

type EmailAddress

type EmailAddress struct {
	Address string `json:"address"` // The email address of the person or entity.
	Name    string `json:"name"`    // The display name of the person or entity.
	// contains filtered or unexported fields
}

EmailAddress represents an emailAddress instance as microsoft.graph.EmailAddress. This is used at various positions, for example in CalendarEvents for attenees, owners, organizers or in Calendar for the owner.

Short: The name and email address of a contact or message recipient.

See https://developer.microsoft.com/en-us/graph/docs/api-reference/v1.0/resources/emailaddress

func (EmailAddress) GetUser

func (e EmailAddress) GetUser() (User, error)

GetUser tries to get the real User-Instance directly from msgraph identified by the e-mail address of the user. This should normally be the userPrincipalName anyways. Returns an error if any from GraphClient.

func (EmailAddress) String

func (e EmailAddress) String() string

type GraphClient

GraphClient represents a msgraph API connection instance.

An instance can also be json-unmarshalled an will immediately be initialized, hence a Token will be grabbed. If grabbing a token fails the JSON-Unmarshal returns an error.

func NewGraphClient

func NewGraphClient(tenantID, applicationID, clientSecret string) (*GraphClient, error)

NewGraphClient creates a new GraphClient instance with the given parameters and grab's a token.

Rerturns an error if the token can not be initialized. This method does not have to be used to create a new GraphClient

func (*GraphClient) GetGroup

func (g *GraphClient) GetGroup(groupID string) (Group, error)

GetGroup returns the group object identified by the given groupID.

Reference: https://developer.microsoft.com/en-us/graph/docs/api-reference/v1.0/api/group_get

func (*GraphClient) GetUser

func (g *GraphClient) GetUser(identifier string) (User, error)

GetUser returns the user object associated to the given user identified by either the given ID or userPrincipalName

Reference: https://developer.microsoft.com/en-us/graph/docs/api-reference/v1.0/api/user_get

func (*GraphClient) ListGroups

func (g *GraphClient) ListGroups() (Groups, error)

ListGroups returns a list of all groups

Reference: https://developer.microsoft.com/en-us/graph/docs/api-reference/v1.0/api/group_list

func (*GraphClient) ListUsers

func (g *GraphClient) ListUsers() (Users, error)

ListUsers returns a list of all users

Reference: https://developer.microsoft.com/en-us/graph/docs/api-reference/v1.0/api/user_list

func (*GraphClient) String

func (g *GraphClient) String() string

func (*GraphClient) UnmarshalJSON

func (g *GraphClient) UnmarshalJSON(data []byte) error

UnmarshalJSON implements the json unmarshal to be used by the json-library. This method additionally to loading the TenantID, ApplicationID and ClientSecret immediately gets a Token from msgraph (hence initialize this GraphAPI instance) and returns an error if any of the data provided is incorrect or the token can not be acquired

type Group

type Group struct {
	ID                           string
	Description                  string
	DisplayName                  string
	CreatedDateTime              time.Time
	GroupTypes                   []string
	Mail                         string
	MailEnabled                  bool
	MailNickname                 string
	OnPremisesLastSyncDateTime   time.Time // defaults to 0001-01-01 00:00:00 +0000 UTC if there's none
	OnPremisesSecurityIdentifier string
	OnPremisesSyncEnabled        bool
	ProxyAddresses               []string
	SecurityEnabled              bool
	Visibility                   string
	// contains filtered or unexported fields
}

Group represents one group of ms graph

See: https://developer.microsoft.com/en-us/graph/docs/api-reference/v1.0/api/group_get

func (Group) ListMembers

func (g Group) ListMembers() (Users, error)

ListMembers - Get a list of the group's direct members. A group can have users, contacts, and other groups as members. This operation is not transitive. This method will currently ONLY return User-instances of members

See https://developer.microsoft.com/en-us/graph/docs/api-reference/v1.0/api/group_list_members

func (Group) String

func (g Group) String() string

func (*Group) UnmarshalJSON

func (g *Group) UnmarshalJSON(data []byte) error

UnmarshalJSON implements the json unmarshal to be used by the json-library

type Groups

type Groups []Group

Groups represents multiple Group-instances.

func (Groups) GetByDisplayName

func (g Groups) GetByDisplayName(displayName string) (Group, error)

GetByDisplayName returns the Group obj of that array whose DisplayName matches the given name. Returns an ErrFindGroup if no group exists that matches the given DisplayName.

func (Groups) String

func (g Groups) String() string

type ResponseStatus

type ResponseStatus struct {
	Response string    // status of the response, may be organizer, accepted, declined etc.
	Time     time.Time // represents the time when the response was performed
}

ResponseStatus represents the response status for an Attendee to a CalendarEvent or just for a CalendarEvent

func (ResponseStatus) Equal

func (s ResponseStatus) Equal(other ResponseStatus) bool

Equal compares the ResponseStatus to the other Response status and returns true if the Response and time is equal

func (ResponseStatus) String

func (s ResponseStatus) String() string

func (*ResponseStatus) UnmarshalJSON

func (s *ResponseStatus) UnmarshalJSON(data []byte) error

UnmarshalJSON implements the json unmarshal to be used by the json-library

type Token

type Token struct {
	TokenType   string    // should always be "Bearer" for msgraph API-calls
	NotBefore   time.Time // time when the access token starts to be valid
	ExpiresOn   time.Time // time when the access token expires
	Resource    string    // will most likely always be https://graph.microsoft.com, hence the BaseURL
	AccessToken string    // the access-token itself
}

Token struct holds the Microsoft Graph API authentication token used by GraphClient to authenticate API-requests to the ms graph API

func (Token) GetAccessToken

func (t Token) GetAccessToken() string

GetAccessToken teturns the API access token in Bearer format representation ready to send to the API interface.

func (Token) HasExpired

func (t Token) HasExpired() bool

HasExpired returns true if the token has already expired.

Hint: this is a wrapper for >>!token.IsStillValid()<<

func (Token) IsAlreadyValid

func (t Token) IsAlreadyValid() bool

IsAlreadyValid returns true if the token is already valid, hence the NotBefore is before the current time. Otherwise false.

Hint: The current time is determined by time.Now()

func (Token) IsStillValid

func (t Token) IsStillValid() bool

IsStillValid returns true if the token is still valid, hence the current time is before ExpiresOn. Does NOT check it the token is yet valid or in the future.

Hint: The current time is determined by time.Now()

func (Token) IsValid

func (t Token) IsValid() bool

IsValid returns true if the token is already valid and is still valid. Otherwise false.

Hint: this is a wrapper for >>token.IsAlreadyValid() && token.IsStillValid()<<

func (Token) String

func (t Token) String() string

func (*Token) UnmarshalJSON

func (t *Token) UnmarshalJSON(data []byte) error

UnmarshalJSON implements the json unmarshal to be used by the json-library.

Hint: the UnmarshalJSON also checks immediately if the token is valid, hence the current time.Now() is after NotBefore and before ExpiresOn

func (Token) WantsToBeRefreshed

func (t Token) WantsToBeRefreshed() bool

WantsToBeRefreshed returns true if the token is already invalid or close to expire (10 second before ExpiresOn), otherwise false. time.Now() is used to determine the current time.

type User

type User struct {
	ID                string   `json:"id"`
	BusinessPhones    []string `json:"businessPhones"`
	DisplayName       string   `json:"displayName"`
	GivenName         string   `json:"givenName"`
	Mail              string   `json:"mail"`
	MobilePhone       string   `json:"mobilePhone"`
	PreferredLanguage string   `json:"preferredLanguage"`
	Surname           string   `json:"surname"`
	UserPrincipalName string   `json:"userPrincipalName"`
	// contains filtered or unexported fields
}

User represents a user from the ms graph API

func (User) Equal

func (u User) Equal(other User) bool

Equal returns wether the user equals the other User by comparing every property of the user including the ID

func (*User) GetActivePhone

func (u *User) GetActivePhone() string

GetActivePhone returns the space-trimmed active phone-number of the user. The active phone number is either the MobilePhone number or the first business-Phone number

func (User) GetFullName

func (u User) GetFullName() string

GetFullName returns the full name in that format: <firstname> <lastname>

func (User) GetShortName

func (u User) GetShortName() string

GetShortName returns the first part of UserPrincipalName before the @. If there is no @, then just the UserPrincipalName will be returned

func (User) ListCalendarView

func (u User) ListCalendarView(startDateTime, endDateTime time.Time) (CalendarEvents, error)

ListCalendarView returns the CalendarEvents of the given user within the specified start- and endDateTime. The calendar used is the default calendar of the user. Returns an error if the user it not GraphClient sourced or if there is any error during the API-call.

See https://developer.microsoft.com/en-us/graph/docs/api-reference/v1.0/api/user_list_calendarview

func (User) ListCalendars

func (u User) ListCalendars() (Calendars, error)

ListCalendars returns all calendars associated to that user.

Reference: https://developer.microsoft.com/en-us/graph/docs/api-reference/v1.0/api/user_list_calendars

func (User) PrettySimpleString

func (u User) PrettySimpleString() string

PrettySimpleString returns the User-instance simply formatted for logging purposes: {FullName (email) (activePhone)}

func (*User) String

func (u *User) String() string

type Users

type Users []User

Users represents multiple Users, used in JSON unmarshal

func (Users) Equal

func (u Users) Equal(other Users) bool

Equal compares the Users to the other Users and returns true if the two given Users are equal. Otherwise returns false

func (Users) GetUserByActivePhone

func (u Users) GetUserByActivePhone(activePhone string) (User, error)

GetUserByActivePhone returns the User-instance whose activeNumber equals the given phone number. Will return an error ErrFindUser if the user can not be found

func (Users) GetUserByMail

func (u Users) GetUserByMail(email string) (User, error)

GetUserByMail returns the User-instance that e-mail address matches the given e-mail addr. Will return an error ErrFindUser if the user can not be found.

func (Users) GetUserByShortName

func (u Users) GetUserByShortName(shortName string) (User, error)

GetUserByShortName returns the first User object that has the given shortName. Will return an error ErrFindUser if the user can not be found

func (Users) PrettySimpleString

func (u Users) PrettySimpleString() string

PrettySimpleString returns the whole []Users pretty simply formatted for logging purposes

func (Users) String

func (u Users) String() string

Jump to

Keyboard shortcuts

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