-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauth.go
90 lines (80 loc) · 2.35 KB
/
auth.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
85
86
87
88
89
90
package deviantart
import (
"context"
"github.com/dghubble/sling"
"golang.org/x/oauth2"
"golang.org/x/oauth2/authhandler"
"golang.org/x/oauth2/clientcredentials"
"github.com/leonidboykov/go-deviantart/internal/authserver"
"github.com/leonidboykov/go-deviantart/internal/ratelimit"
)
// CallbackURL defines redirect URL for OAuth2.
var CallbackURL = "http://localhost:8080/callback"
// Authenticator describes authentication pipeline.
type Authenticator func(s *sling.Sling) error
// ClientCredentials allows gives access to "public" endpoints and do not
// require user authorization. Use this method to access read-only endpoints.
func ClientCredentials(clientID, clientSecret string) Authenticator {
conf := &clientcredentials.Config{
ClientID: clientID,
ClientSecret: clientSecret,
TokenURL: "https://www.deviantart.com/oauth2/token",
}
return func(s *sling.Sling) error {
s.Doer(ratelimit.NewHTTPClient(conf.Client(context.Background())))
return nil
}
}
const (
BasicScope = "basic"
BrowseMLTScope = "browse.mlt"
BrowseScope = "browse"
CollectionScope = "collection"
CommentPostScope = "comment.post"
GalleryScope = "gallery"
MessageScope = "message"
PublishScope = "publish"
StashScope = "stash"
UserManageScope = "user.manage"
UserScope = "user"
)
var AllScopes = []string{
BasicScope,
BrowseMLTScope,
BrowseScope,
CollectionScope,
CommentPostScope,
GalleryScope,
MessageScope,
PublishScope,
StashScope,
UserManageScope,
UserScope,
}
// AuthorizationCode grant is the most common OAuth2 grant type and gives access
// to aspects of a users account. Use this method if you need to upload images.
func AuthorizationCode(clientID, clientSecret string, scopes ...string) Authenticator {
conf := &oauth2.Config{
ClientID: clientID,
ClientSecret: clientSecret,
Endpoint: oauth2.Endpoint{
AuthURL: "https://www.deviantart.com/oauth2/authorize",
TokenURL: "https://www.deviantart.com/oauth2/token",
},
RedirectURL: CallbackURL,
Scopes: scopes,
}
return func(s *sling.Sling) error {
tok, err := authhandler.TokenSource(
context.Background(),
conf,
"state", // TODO: This is unsecure.
authserver.AuthHandler(CallbackURL),
).Token()
if err != nil {
return nil
}
s.Doer(ratelimit.NewHTTPClient(conf.Client(context.Background(), tok)))
return nil
}
}