-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
172 lines (144 loc) · 4.25 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
169
170
171
172
package main
import (
"flag"
"fmt"
"github.com/alexedwards/scs/v2"
"github.com/sirupsen/logrus"
"html/template"
"net/http"
"net/url"
"os"
"time"
)
var log = logrus.New()
var sessionManager *scs.SessionManager
var (
passwordFilePath = flag.String("password", "/secrets/password", "File path for the password")
password string
environment = os.Getenv("ENV")
authServiceUrl = os.Getenv("AUTH_SERVICE_URL")
cookieDomain = os.Getenv("COOKIE_DOMAIN")
)
type LoginPageData struct {
Message string
NextUrl string
}
func logWithFields(r *http.Request) *logrus.Entry {
return log.WithFields(logrus.Fields{
"client": r.Header.Get("X-Forwarded-For"),
"url": fullRequestUrl(r),
})
}
func fullRequestUrl(r *http.Request) string {
proto := r.Header.Get("X-Forwarded-Proto")
host := r.Header.Get("X-Forwarded-Host")
port := r.Header.Get("X-Forwarded-Port")
uri := r.Header.Get("X-Forwarded-Uri")
if port == "" {
return fmt.Sprintf("%s://%s%s", proto, host, uri)
} else {
return fmt.Sprintf("%s://%s:%s%s", proto, host, port, uri)
}
}
func main() {
if authServiceUrl == "" {
log.Fatalf("Environment variable AUTH_SERVICE_URL is not set")
os.Exit(1)
}
if cookieDomain == "" {
log.Fatalf("Environment variable COOKIE_DOMAIN is not set")
os.Exit(1)
}
if environment == "production" {
log.Formatter = &logrus.JSONFormatter{}
} else {
log.Formatter = &logrus.TextFormatter{ForceColors: true, FullTimestamp: true}
log.SetLevel(logrus.DebugLevel)
}
flag.Parse()
var err error
passwordBytes, err := os.ReadFile(*passwordFilePath)
if err != nil {
log.Fatalf("Failed to read password file: %v", err)
os.Exit(1)
}
log.Infof("Reading password from %s", *passwordFilePath)
password = string(passwordBytes)
sessionManager = scs.New()
sessionManager.Lifetime = 6000 * time.Hour
sessionManager.Cookie.Domain = cookieDomain
sessionManager.Cookie.Secure = true
sessionManager.Cookie.HttpOnly = true
mux := http.NewServeMux()
mux.HandleFunc("/auth", authHandler)
mux.HandleFunc("/login", loginHandler)
mux.HandleFunc("/logout", logoutHandler)
mux.HandleFunc("/healthz", healthzHandler)
err = http.ListenAndServe(":8080", sessionManager.LoadAndSave(mux))
if err != nil {
log.Fatalf("could not listen, %v", err)
}
}
func healthzHandler(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusOK)
_, err := fmt.Fprintln(w, "OK")
if err != nil {
log.Fatalf("could not write to healthz, %v", err)
}
}
func authHandler(w http.ResponseWriter, r *http.Request) {
isAuthenticated := sessionManager.GetBool(r.Context(), "authenticated")
if !isAuthenticated {
logWithFields(r).Info("Session is not authenticated. Redirecting to login.")
redirectToLogin(w, r)
return
}
logWithFields(r).Debug("Session is authenticated.")
w.WriteHeader(http.StatusOK)
}
func logoutHandler(w http.ResponseWriter, r *http.Request) {
sessionManager.Put(r.Context(), "authenticated", false)
http.Redirect(w, r, "/", http.StatusSeeOther)
}
func loginHandler(w http.ResponseWriter, r *http.Request) {
if r.Method == "POST" {
secretKey := r.FormValue("secretKey")
nextUrl := r.FormValue("nextUrl")
if authenticate(secretKey) {
logWithFields(r).WithField("nextUrl", nextUrl).Info("Login successful.")
sessionManager.Put(r.Context(), "authenticated", true)
if nextUrl == "" {
nextUrl = "/auth"
}
http.Redirect(w, r, nextUrl, http.StatusSeeOther)
return
}
logWithFields(r).Warn("Failed login attempt.")
}
nextUrl := r.URL.Query().Get("nextUrl")
logWithFields(r).Infof("Showing login page.")
tmpl, err := template.ParseFiles("web/login.html")
if err != nil {
log.Error(err)
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}
data := LoginPageData{
Message: "Please enter your secret key.",
NextUrl: nextUrl,
}
err = tmpl.Execute(w, data)
if err != nil {
log.Error(err)
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}
}
func redirectToLogin(w http.ResponseWriter, r *http.Request) {
escapedNextUrl := url.QueryEscape(fullRequestUrl(r))
loginUrl := fmt.Sprintf("%s/login?nextUrl=%s", authServiceUrl, escapedNextUrl)
http.Redirect(w, r, loginUrl, http.StatusSeeOther)
}
func authenticate(secretKey string) bool {
return secretKey == password
}