-
Notifications
You must be signed in to change notification settings - Fork 0
/
social.go
107 lines (90 loc) · 2.22 KB
/
social.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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
package auth
import (
"context"
"net/http"
"github.com/caesar-rocks/core"
"github.com/gorilla/sessions"
"github.com/markbates/goth"
"github.com/markbates/goth/gothic"
"github.com/markbates/goth/providers/facebook"
"github.com/markbates/goth/providers/github"
"github.com/markbates/goth/providers/google"
)
type SocialAuthProvider struct {
name string
Key string
Secret string
CallbackURL string
Scopes []string
}
type SocialAuth struct {
Providers map[string]SocialAuthProvider
}
func NewSocialAuth(store *sessions.CookieStore, providers map[string]SocialAuthProvider) *SocialAuth {
gothic.Store = store
var gothProviders []goth.Provider
for name, provider := range providers {
switch name {
case "github":
gothProviders = append(
gothProviders,
github.New(provider.Key, provider.Secret, provider.CallbackURL, provider.Scopes...),
)
case "google":
gothProviders = append(
gothProviders,
google.New(provider.Key, provider.Secret, provider.CallbackURL, provider.Scopes...),
)
case "facebook":
gothProviders = append(
gothProviders,
facebook.New(provider.Key, provider.Secret, provider.CallbackURL, provider.Scopes...),
)
}
}
goth.UseProviders(
gothProviders...,
)
return &SocialAuth{
Providers: providers,
}
}
func (s *SocialAuth) Use(provider string) *SocialAuthProvider {
if p, ok := s.Providers[provider]; ok {
p.name = provider
return &p
}
return nil
}
func (p *SocialAuthProvider) Redirect(ctx *core.CaesarCtx) error {
r := ctx.Request.WithContext(
context.WithValue(
ctx.Request.Context(),
"provider", p.name,
),
)
// Handle HTMX requests
if ctx.GetHeader("HX-Request") == "true" {
url, err := gothic.GetAuthURL(ctx.ResponseWriter, r)
if err != nil {
return err
}
ctx.WithStatus(http.StatusSeeOther).SetHeader("HX-Redirect", url)
return nil
}
gothic.BeginAuthHandler(ctx.ResponseWriter, r)
return nil
}
func (p *SocialAuthProvider) Callback(ctx *core.CaesarCtx) (*goth.User, error) {
r := ctx.Request.WithContext(
context.WithValue(
ctx.Request.Context(),
"provider", p.name,
),
)
user, err := gothic.CompleteUserAuth(ctx.ResponseWriter, r)
if err != nil {
return nil, err
}
return &user, nil
}