forked from mxschmitt/golang-url-shortener
-
Notifications
You must be signed in to change notification settings - Fork 0
/
okta.go
84 lines (73 loc) · 2.86 KB
/
okta.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package auth
import (
"context"
"encoding/json"
"net/url"
"strings"
"github.com/russelltsherman/golang-url-shortener/internal/util"
"github.com/sirupsen/logrus"
"github.com/pkg/errors"
"golang.org/x/oauth2"
)
type oktaAdapter struct {
config *oauth2.Config
}
// NewOktaAdapter creates an oAuth adapter out of the credentials and the baseURL
func NewOktaAdapter(clientID, clientSecret, endpointURL string) Adapter {
if endpointURL == "" {
logrus.Error("Configure Okta Endpoint")
}
return &oktaAdapter{&oauth2.Config{
ClientID: clientID,
ClientSecret: clientSecret,
RedirectURL: util.GetConfig().BaseURL + "/api/v1/auth/okta/callback",
Scopes: []string{
"profile",
"openid",
"offline_access",
},
Endpoint: oauth2.Endpoint{
AuthURL: endpointURL + "/v1/authorize",
TokenURL: endpointURL + "/v1/token",
},
}}
}
func (a *oktaAdapter) GetRedirectURL(state string) string {
return a.config.AuthCodeURL(state)
}
func (a *oktaAdapter) GetUserData(state, code string) (*user, error) {
logrus.Debugf("Getting User Data with state: %s, and code: %s", state, code)
oAuthToken, err := a.config.Exchange(context.Background(), code)
if err != nil {
return nil, errors.Wrap(err, "could not exchange code")
}
if util.GetConfig().Okta.EndpointURL == "" {
logrus.Error("Okta EndpointURL is Empty")
}
oktaUrl, err := url.Parse(util.GetConfig().Okta.EndpointURL)
if err != nil {
return nil, errors.Wrap(err, "could not parse Okta EndpointURL")
}
oktaBaseURL := strings.Replace(oktaUrl.String(), oktaUrl.RequestURI(), "", 1)
oAuthUserInfoReq, err := a.config.Client(context.Background(), oAuthToken).Get(oktaBaseURL + "/api/v1/users/me")
if err != nil {
return nil, errors.Wrap(err, "could not get user data")
}
defer oAuthUserInfoReq.Body.Close()
var oUser struct {
ID int `json:"sub"`
// Custom URL property for user Avatar can go here
Name string `json:"name"`
}
if err = json.NewDecoder(oAuthUserInfoReq.Body).Decode(&oUser); err != nil {
return nil, errors.Wrap(err, "decoding user info failed")
}
return &user{
ID: string(oUser.ID),
Name: oUser.Name,
Picture: util.GetConfig().BaseURL + "/images/okta_logo.png", // Default Okta Avatar
}, nil
}
func (a *oktaAdapter) GetOAuthProviderName() string {
return "okta"
}