[#746] added microsoft oauth2 provider

This commit is contained in:
Gani Georgiev
2022-10-31 21:17:10 +02:00
parent bcb9c22685
commit 5298543ce4
41 changed files with 279 additions and 141 deletions
+2
View File
@@ -95,6 +95,8 @@ func NewProviderByName(name string) (Provider, error) {
return NewDiscordProvider(), nil
case NameTwitter:
return NewTwitterProvider(), nil
case NameMicrosoft:
return NewMicrosoftProvider(), nil
default:
return nil, errors.New("Missing provider " + name)
}
+9
View File
@@ -63,4 +63,13 @@ func TestNewProviderByName(t *testing.T) {
if _, ok := p.(*auth.Discord); !ok {
t.Error("Expected to be instance of *auth.Discord")
}
// microsoft
p, err = auth.NewProviderByName(auth.NameMicrosoft)
if err != nil {
t.Errorf("Expected nil, got error %v", err)
}
if _, ok := p.(*auth.Microsoft); !ok {
t.Error("Expected to be instance of *auth.Microsoft")
}
}
+50
View File
@@ -0,0 +1,50 @@
package auth
import (
"golang.org/x/oauth2"
"golang.org/x/oauth2/microsoft"
)
var _ Provider = (*Microsoft)(nil)
// NameMicrosoft is the unique name of the Microsoft provider.
const NameMicrosoft string = "microsoft"
// Microsoft allows authentication via AzureADEndpoint OAuth2.
type Microsoft struct {
*baseProvider
}
// NewMicrosoftProvider creates new Microsoft AD provider instance with some defaults.
func NewMicrosoftProvider() *Microsoft {
endpoints := microsoft.AzureADEndpoint("")
return &Microsoft{&baseProvider{
scopes: []string{"User.Read"},
authUrl: endpoints.AuthURL,
tokenUrl: endpoints.TokenURL,
userApiUrl: "https://graph.microsoft.com/v1.0/me",
}}
}
// FetchAuthUser returns an AuthUser instance based on the Microsoft's user api.
func (p *Microsoft) FetchAuthUser(token *oauth2.Token) (*AuthUser, error) {
// https://learn.microsoft.com/en-us/azure/active-directory/develop/userinfo
// explore graph: https://developer.microsoft.com/en-us/graph/graph-explorer
rawData := struct {
Id string `json:"id"`
Name string `json:"displayName"`
Email string `json:"mail"`
}{}
if err := p.FetchRawUserData(token, &rawData); err != nil {
return nil, err
}
user := &AuthUser{
Id: rawData.Id,
Name: rawData.Name,
Email: rawData.Email,
}
return user, nil
}