This repository has been archived by the owner on Aug 1, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
168 lines (139 loc) · 4.41 KB
/
main.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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
package main
import (
"encoding/json"
"fmt"
"html/template"
"net"
"net/http"
"time"
"github.com/gorilla/mux"
"github.com/gorilla/sessions"
"github.com/markbates/goth"
"github.com/markbates/goth/gothic"
"github.com/markbates/goth/providers/gitea"
"github.com/sirupsen/logrus"
"github.com/spf13/viper"
)
var (
serviceName = "teabag"
msgTemplate = `<!DOCTYPE html><html><head></head><body>{{.}}</body></html>`
resTemplate = `
<!DOCTYPE html><html><head></head><body>
<script>
function recieveMsg(e) {
window.opener.postMessage("{{.OAuthResult}}", e.origin);
}
window.addEventListener("message", recieveMsg, false);
window.opener.postMessage("{{.Provider}}", "*");
</script>
</body></html>`
log *logrus.Entry
config *viper.Viper
)
func initConfig() {
config = viper.New()
config.SetConfigType("env")
config.SetConfigName("teabag")
config.AddConfigPath("./env/")
config.AddConfigPath("/etc/teabag/")
config.SetEnvPrefix("teabag")
config.AutomaticEnv()
if err := config.ReadInConfig(); err != nil {
if _, ok := err.(viper.ConfigFileNotFoundError); ok {
log.Infoln("config file not found, falling back to evironment variables")
} else {
log.Fatalf("error loading configuration: %v", err)
}
}
}
func initProvider() {
var (
providers []goth.Provider
)
type settings struct {
key, secret, BaseURL, CallbackURL, AuthURI, AccessTokenURI, UserURI string
}
log.Info("initialising provider")
getProviderSetings := func(name string) settings {
baseURL := config.GetString(name + "_base_url")
return settings{
key: config.GetString(name + "_key"),
secret: config.GetString(name + "_secret"),
BaseURL: baseURL,
AuthURI: fmt.Sprintf("%s/%s", baseURL, config.GetString(name+"_auth_uri")),
AccessTokenURI: fmt.Sprintf("%s/%s", baseURL, config.GetString(name+"_token_uri")),
UserURI: fmt.Sprintf("%s/%s", baseURL, config.GetString(name+"_user_uri")),
CallbackURL: config.GetString("callback_uri"),
}
}
log.Info("- adding gitea connector")
var p goth.Provider
s := getProviderSetings("gitea")
if s.AuthURI != "" {
out, _ := json.MarshalIndent(s, "", " ")
log.Infof("-- with custom settings %s", string(out))
p = gitea.NewCustomisedURL(s.key, s.secret, s.CallbackURL, s.AuthURI, s.AccessTokenURI, s.UserURI)
} else {
p = gitea.New(s.key, s.secret, s.CallbackURL)
}
providers = append(providers, p)
gothic.Store = sessions.NewCookieStore([]byte(config.GetString("session_secret")))
goth.UseProviders(providers...)
}
func main() {
log = logrus.New().WithFields(logrus.Fields{
"service": serviceName,
})
log.Info("starting up service")
initConfig()
initProvider()
r := mux.NewRouter()
r.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
t, _ := template.New("msg").Parse(msgTemplate)
t.Execute(w, fmt.Sprintf("Connected to %s", serviceName))
})
r.HandleFunc("/callback", func(w http.ResponseWriter, r *http.Request) {
user, err := gothic.CompleteUserAuth(w, r)
if err != nil {
log.Errorf("callback: CompleteUserAuth failed %v", err)
return
}
log.Infoln("logged in user to gitea")
t, _ := template.New("res").Parse(resTemplate)
data := struct {
Provider string
OAuthResult string
}{
Provider: fmt.Sprintf(`authorizing:gitea`),
OAuthResult: fmt.Sprintf(`authorization:gitea:%s:{"token":"%s", "provider":"%s"}`, "success", user.AccessToken, user.Provider),
}
t.Execute(w, data)
}).Methods("GET")
r.HandleFunc("/auth", func(w http.ResponseWriter, r *http.Request) {
log.Infoln("handling auth provider request for gitea")
if gothUser, err := gothic.CompleteUserAuth(w, r); err == nil {
t, _ := template.New("msg").Parse(msgTemplate)
t.Execute(w, fmt.Sprintf("Connected to existing session with UserID '%s'", gothUser.UserID))
} else {
gothic.BeginAuthHandler(w, r)
}
}).Methods("GET")
r.HandleFunc("/logout", func(w http.ResponseWriter, r *http.Request) {
log.Infoln("logout from gitea")
gothic.Logout(w, r)
w.Header().Set("Location", "/")
w.WriteHeader(http.StatusTemporaryRedirect)
}).Methods("GET")
http.Handle("/", r)
log.Infof("listening on %s:%d",
config.GetString("host"),
config.GetInt("port"),
)
srv := &http.Server{
Handler: r,
Addr: net.JoinHostPort(config.GetString("host"), config.GetString("port")),
WriteTimeout: 15 * time.Second,
ReadTimeout: 15 * time.Second,
}
log.Fatal(srv.ListenAndServe())
}