git.iko.soy/typeable/oauth2-proxy
on master help sign in
Move template loading to app package
commit0151ca11f6e4d2a97a384a7f77292a0aa5ddd6e6 authorJoel Speed <joel.speed@hotmail.co.uk> dateSat 6 Feb 2021, 18:56 (6 years ago) parent84f76c6
5 files changed+370−178
oauthproxy.go+5−1 pkg/app/app_suite_test.go+17 templates.go → pkg/app/templates.go+149−115 pkg/app/templates_test.go+199 templates_test.go−62
oauthproxy.go+5−1
@@ -18,6 +18,7 @@ import (
1818 middlewareapi "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/middleware"
1919 "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/options"
2020 sessionsapi "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/sessions"
21+ "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/app"
2122 "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/authentication/basic"
2223 "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/cookies"
2324 "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/encryption"
@@ -116,7 +117,10 @@ func NewOAuthProxy(opts *options.Options, validator func(string) bool) (*OAuthPr
116117 return nil, fmt.Errorf("error initialising session store: %v", err)
117118 }
118119
119− templates := loadTemplates(opts.Templates.Path)
120+ templates, err := app.LoadTemplates(opts.Templates.Path)
121+ if err != nil {
122+ return nil, fmt.Errorf("error loading templates: %v", err)
123+ }
120124 proxyErrorHandler := upstream.NewProxyErrorHandler(templates.Lookup("error.html"), opts.ProxyPrefix)
121125 upstreamProxy, err := upstream.NewProxy(opts.UpstreamServers, opts.GetSignatureData(), proxyErrorHandler)
122126 if err != nil {
pkg/app/app_suite_test.gonew file+17
@@ -0,0 +1,17 @@
1+package app
2+
3+import (
4+ "testing"
5+
6+ "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/logger"
7+ . "github.com/onsi/ginkgo"
8+ . "github.com/onsi/gomega"
9+)
10+
11+func TestOptionsSuite(t *testing.T) {
12+ logger.SetOutput(GinkgoWriter)
13+ logger.SetErrOutput(GinkgoWriter)
14+
15+ RegisterFailHandler(Fail)
16+ RunSpecs(t, "App Suite")
17+}
templates.go → pkg/app/templates.gorenamed+149−115
@@ -1,124 +1,20 @@
1−package main
1+package app
22
33import (
4+ "fmt"
45 "html/template"
5− "path"
6+ "os"
7+ "path/filepath"
68 "strings"
79
810 "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/logger"
911)
1012
11−func loadTemplates(dir string) *template.Template {
12− if dir == "" {
13− return getTemplates()
14− }
15− logger.Printf("using custom template directory %q", dir)
16− funcMap := template.FuncMap{
17− "ToUpper": strings.ToUpper,
18− "ToLower": strings.ToLower,
19− }
20− t, err := template.New("").Funcs(funcMap).ParseFiles(path.Join(dir, "sign_in.html"), path.Join(dir, "error.html"))
21− if err != nil {
22− logger.Fatalf("failed parsing template %s", err)
23− }
24− return t
25−}
13+const (
14+ errorTemplateName = "error.html"
15+ signInTemplateName = "sign_in.html"
2616
27−func getTemplates() *template.Template {
28− t, err := template.New("foo").Parse(`{{define "sign_in.html"}}
29−<!DOCTYPE html>
30−<html lang="en" charset="utf-8">
31− <head>
32− <meta charset="utf-8">
33− <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
34− <title>Sign In</title>
35− <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bulma@0.9.1/css/bulma.min.css">
36−
37− <style>
38− body {
39− height: 100vh;
40− }
41− .sign-in-box {
42− max-width: 400px;
43− margin: 1.25rem auto;
44− }
45− footer a {
46− text-decoration: underline;
47− }
48− </style>
49−
50− <script>
51− if (window.location.hash) {
52− (function() {
53− var inputs = document.getElementsByName('rd');
54− for (var i = 0; i < inputs.length; i++) {
55− // Add hash, but make sure it is only added once
56− var idx = inputs[i].value.indexOf('#');
57− if (idx >= 0) {
58− // Remove existing hash from URL
59− inputs[i].value = inputs[i].value.substr(0, idx);
60− }
61− inputs[i].value += window.location.hash;
62− }
63− })();
64− }
65− </script>
66− </head>
67− <body class="has-background-light">
68− <section class="section">
69− <div class="box block sign-in-box has-text-centered">
70− <form method="GET" action="{{.ProxyPrefix}}/start">
71− <input type="hidden" name="rd" value="{{.Redirect}}">
72− {{ if .SignInMessage }}
73− <p class="block">{{.SignInMessage}}</p>
74− {{ end}}
75− <button type="submit" class="button block is-primary">Sign in with {{.ProviderName}}</button>
76− </form>
77−
78− {{ if .CustomLogin }}
79− <hr>
80−
81− <form method="POST" action="{{.ProxyPrefix}}/sign_in" class="block">
82− <input type="hidden" name="rd" value="{{.Redirect}}">
83−
84− <div class="field">
85− <label class="label" for="username">Username</label>
86− <div class="control">
87− <input class="input" type="email" placeholder="e.g. userx@example.com" name="username" id="username">
88− </div>
89− </div>
90−
91− <div class="field">
92− <label class="label" for="password">Password</label>
93− <div class="control">
94− <input class="input" type="password" placeholder="********" name="password" id="password">
95− </div>
96− </div>
97− <button class="button is-primary">Sign in</button>
98− {{ end }}
99− </form>
100− </div>
101− </section>
102−
103− <footer class="footer has-text-grey has-background-light is-size-7">
104− <div class="content has-text-centered">
105− {{ if eq .Footer "-" }}
106− {{ else if eq .Footer ""}}
107− <p>Secured with <a href="https://github.com/oauth2-proxy/oauth2-proxy#oauth2_proxy" class="has-text-grey">OAuth2 Proxy</a> version {{.Version}}</p>
108− {{ else }}
109− <p>{{.Footer}}</p>
110− {{ end }}
111− </div>
112− </footer>
113−
114− </body>
115−</html>
116−{{end}}`)
117− if err != nil {
118− logger.Fatalf("failed parsing template %s", err)
119− }
120−
121− t, err = t.Parse(`{{define "error.html"}}
17+ defaultErrorTemplate = `{{define "error.html"}}
12218<!DOCTYPE html>
12319<html lang="en" charset="utf-8">
12420<head>
@@ -215,9 +111,147 @@ func getTemplates() *template.Template {
215111
216112 </body>
217113</html>
218−{{end}}`)
114+{{end}}`
115+
116+ defaultSignInTemplate = `{{define "sign_in.html"}}
117+<!DOCTYPE html>
118+<html lang="en" charset="utf-8">
119+ <head>
120+ <meta charset="utf-8">
121+ <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
122+ <title>Sign In</title>
123+ <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bulma@0.9.1/css/bulma.min.css">
124+
125+ <style>
126+ body {
127+ height: 100vh;
128+ }
129+ .sign-in-box {
130+ max-width: 400px;
131+ margin: 1.25rem auto;
132+ }
133+ footer a {
134+ text-decoration: underline;
135+ }
136+ </style>
137+
138+ <script>
139+ if (window.location.hash) {
140+ (function() {
141+ var inputs = document.getElementsByName('rd');
142+ for (var i = 0; i < inputs.length; i++) {
143+ // Add hash, but make sure it is only added once
144+ var idx = inputs[i].value.indexOf('#');
145+ if (idx >= 0) {
146+ // Remove existing hash from URL
147+ inputs[i].value = inputs[i].value.substr(0, idx);
148+ }
149+ inputs[i].value += window.location.hash;
150+ }
151+ })();
152+ }
153+ </script>
154+ </head>
155+ <body class="has-background-light">
156+ <section class="section">
157+ <div class="box block sign-in-box has-text-centered">
158+ <form method="GET" action="{{.ProxyPrefix}}/start">
159+ <input type="hidden" name="rd" value="{{.Redirect}}">
160+ {{ if .SignInMessage }}
161+ <p class="block">{{.SignInMessage}}</p>
162+ {{ end}}
163+ <button type="submit" class="button block is-primary">Sign in with {{.ProviderName}}</button>
164+ </form>
165+
166+ {{ if .CustomLogin }}
167+ <hr>
168+
169+ <form method="POST" action="{{.ProxyPrefix}}/sign_in" class="block">
170+ <input type="hidden" name="rd" value="{{.Redirect}}">
171+
172+ <div class="field">
173+ <label class="label" for="username">Username</label>
174+ <div class="control">
175+ <input class="input" type="email" placeholder="e.g. userx@example.com" name="username" id="username">
176+ </div>
177+ </div>
178+
179+ <div class="field">
180+ <label class="label" for="password">Password</label>
181+ <div class="control">
182+ <input class="input" type="password" placeholder="********" name="password" id="password">
183+ </div>
184+ </div>
185+ <button class="button is-primary">Sign in</button>
186+ {{ end }}
187+ </form>
188+ </div>
189+ </section>
190+
191+ <footer class="footer has-text-grey has-background-light is-size-7">
192+ <div class="content has-text-centered">
193+ {{ if eq .Footer "-" }}
194+ {{ else if eq .Footer ""}}
195+ <p>Secured with <a href="https://github.com/oauth2-proxy/oauth2-proxy#oauth2_proxy" class="has-text-grey">OAuth2 Proxy</a> version {{.Version}}</p>
196+ {{ else }}
197+ <p>{{.Footer}}</p>
198+ {{ end }}
199+ </div>
200+ </footer>
201+
202+ </body>
203+</html>
204+{{end}}`
205+)
206+
207+// LoadTemplates adds the Sign In and Error templates from the custom template
208+// directory, or uses the defaults if they do not exist or the custom directory
209+// is not provided.
210+func LoadTemplates(customDir string) (*template.Template, error) {
211+ t := template.New("").Funcs(template.FuncMap{
212+ "ToUpper": strings.ToUpper,
213+ "ToLower": strings.ToLower,
214+ })
215+ var err error
216+ t, err = addTemplate(t, customDir, signInTemplateName, defaultSignInTemplate)
217+ if err != nil {
218+ return nil, fmt.Errorf("could not add Sign In template: %v", err)
219+ }
220+ t, err = addTemplate(t, customDir, errorTemplateName, defaultErrorTemplate)
221+ if err != nil {
222+ return nil, fmt.Errorf("could not add Error template: %v", err)
223+ }
224+
225+ return t, nil
226+}
227+
228+// addTemplate will add the template from the custom directory if provided,
229+// else it will add the default template.
230+func addTemplate(t *template.Template, customDir, fileName, defaultTemplate string) (*template.Template, error) {
231+ filePath := filepath.Join(customDir, fileName)
232+ if customDir != "" && isFile(filePath) {
233+ t, err := t.ParseFiles(filePath)
234+ if err != nil {
235+ return nil, fmt.Errorf("failed to parse template %s: %v", filePath, err)
236+ }
237+ return t, nil
238+ }
239+ t, err := t.Parse(defaultTemplate)
240+ if err != nil {
241+ // This should not happen.
242+ // Default templates should be tested and so should never fail to parse.
243+ logger.Panic("Could not parse defaultTemplate: ", err)
244+ }
245+ return t, nil
246+}
247+
248+// isFile checks if the file exists and checks whether it is a regular file.
249+// If either of these fail then it cannot be used as a template file.
250+func isFile(fileName string) bool {
251+ info, err := os.Stat(fileName)
219252 if err != nil {
220− logger.Fatalf("failed parsing template %s", err)
253+ logger.Errorf("Could not load file %s: %v, will use default template", fileName, err)
254+ return false
221255 }
222− return t
256+ return info.Mode().IsRegular()
223257}
pkg/app/templates_test.gonew file+199
@@ -0,0 +1,199 @@
1+package app
2+
3+import (
4+ "bytes"
5+ "html/template"
6+ "io/ioutil"
7+ "os"
8+ "path/filepath"
9+
10+ . "github.com/onsi/ginkgo"
11+ . "github.com/onsi/gomega"
12+)
13+
14+var _ = Describe("Templates", func() {
15+ var customDir string
16+
17+ BeforeEach(func() {
18+ var err error
19+ customDir, err = ioutil.TempDir("", "oauth2-proxy-templates-test")
20+ Expect(err).ToNot(HaveOccurred())
21+
22+ templateHTML := `{{.TestString}} {{.TestString | ToLower}} {{.TestString | ToUpper}}`
23+ signInFile := filepath.Join(customDir, signInTemplateName)
24+ Expect(ioutil.WriteFile(signInFile, []byte(templateHTML), 0666)).To(Succeed())
25+ errorFile := filepath.Join(customDir, errorTemplateName)
26+ Expect(ioutil.WriteFile(errorFile, []byte(templateHTML), 0666)).To(Succeed())
27+ })
28+
29+ AfterEach(func() {
30+ Expect(os.RemoveAll(customDir)).To(Succeed())
31+ })
32+
33+ Context("LoadTemplates", func() {
34+ var data interface{}
35+ var t *template.Template
36+
37+ BeforeEach(func() {
38+ data = struct {
39+ // For default templates
40+ ProxyPrefix string
41+ Redirect string
42+ Footer string
43+
44+ // For default sign_in template
45+ SignInMessage string
46+ ProviderName string
47+ CustomLogin bool
48+
49+ // For default error template
50+ StatusCode int
51+ Title string
52+ Message string
53+
54+ // For custom templates
55+ TestString string
56+ }{
57+ ProxyPrefix: "<proxy-prefix>",
58+ Redirect: "<redirect>",
59+ Footer: "<footer>",
60+
61+ SignInMessage: "<sign-in-message>",
62+ ProviderName: "<provider-name>",
63+ CustomLogin: false,
64+
65+ StatusCode: 404,
66+ Title: "<title>",
67+ Message: "<message>",
68+
69+ TestString: "Testing",
70+ }
71+ })
72+
73+ Context("With no custom directory", func() {
74+ BeforeEach(func() {
75+ var err error
76+ t, err = LoadTemplates("")
77+ Expect(err).ToNot(HaveOccurred())
78+ })
79+
80+ It("Use the default sign_in page", func() {
81+ buf := bytes.NewBuffer([]byte{})
82+ Expect(t.ExecuteTemplate(buf, signInTemplateName, data)).To(Succeed())
83+ Expect(buf.String()).To(HavePrefix("\n<!DOCTYPE html>"))
84+ })
85+
86+ It("Use the default error page", func() {
87+ buf := bytes.NewBuffer([]byte{})
88+ Expect(t.ExecuteTemplate(buf, errorTemplateName, data)).To(Succeed())
89+ Expect(buf.String()).To(HavePrefix("\n<!DOCTYPE html>"))
90+ })
91+ })
92+
93+ Context("With a custom directory", func() {
94+ Context("With both templates", func() {
95+ BeforeEach(func() {
96+ var err error
97+ t, err = LoadTemplates(customDir)
98+ Expect(err).ToNot(HaveOccurred())
99+ })
100+
101+ It("Use the custom sign_in page", func() {
102+ buf := bytes.NewBuffer([]byte{})
103+ Expect(t.ExecuteTemplate(buf, signInTemplateName, data)).To(Succeed())
104+ Expect(buf.String()).To(Equal("Testing testing TESTING"))
105+ })
106+
107+ It("Use the custom error page", func() {
108+ buf := bytes.NewBuffer([]byte{})
109+ Expect(t.ExecuteTemplate(buf, errorTemplateName, data)).To(Succeed())
110+ Expect(buf.String()).To(Equal("Testing testing TESTING"))
111+ })
112+ })
113+
114+ Context("With no error template", func() {
115+ BeforeEach(func() {
116+ Expect(os.Remove(filepath.Join(customDir, errorTemplateName))).To(Succeed())
117+
118+ var err error
119+ t, err = LoadTemplates(customDir)
120+ Expect(err).ToNot(HaveOccurred())
121+ })
122+
123+ It("Use the custom sign_in page", func() {
124+ buf := bytes.NewBuffer([]byte{})
125+ Expect(t.ExecuteTemplate(buf, signInTemplateName, data)).To(Succeed())
126+ Expect(buf.String()).To(Equal("Testing testing TESTING"))
127+ })
128+
129+ It("Use the default error page", func() {
130+ buf := bytes.NewBuffer([]byte{})
131+ Expect(t.ExecuteTemplate(buf, errorTemplateName, data)).To(Succeed())
132+ Expect(buf.String()).To(HavePrefix("\n<!DOCTYPE html>"))
133+ })
134+ })
135+
136+ Context("With no sign_in template", func() {
137+ BeforeEach(func() {
138+ Expect(os.Remove(filepath.Join(customDir, signInTemplateName))).To(Succeed())
139+
140+ var err error
141+ t, err = LoadTemplates(customDir)
142+ Expect(err).ToNot(HaveOccurred())
143+ })
144+
145+ It("Use the default sign_in page", func() {
146+ buf := bytes.NewBuffer([]byte{})
147+ Expect(t.ExecuteTemplate(buf, signInTemplateName, data)).To(Succeed())
148+ Expect(buf.String()).To(HavePrefix("\n<!DOCTYPE html>"))
149+ })
150+
151+ It("Use the custom error page", func() {
152+ buf := bytes.NewBuffer([]byte{})
153+ Expect(t.ExecuteTemplate(buf, errorTemplateName, data)).To(Succeed())
154+ Expect(buf.String()).To(Equal("Testing testing TESTING"))
155+ })
156+ })
157+
158+ Context("With an invalid sign_in template", func() {
159+ BeforeEach(func() {
160+ signInFile := filepath.Join(customDir, signInTemplateName)
161+ Expect(ioutil.WriteFile(signInFile, []byte("{{"), 0666))
162+ })
163+
164+ It("Should return an error when loading templates", func() {
165+ t, err := LoadTemplates(customDir)
166+ Expect(err).To(MatchError(HavePrefix("could not add Sign In template:")))
167+ Expect(t).To(BeNil())
168+ })
169+ })
170+
171+ Context("With an invalid error template", func() {
172+ BeforeEach(func() {
173+ errorFile := filepath.Join(customDir, errorTemplateName)
174+ Expect(ioutil.WriteFile(errorFile, []byte("{{"), 0666))
175+ })
176+
177+ It("Should return an error when loading templates", func() {
178+ t, err := LoadTemplates(customDir)
179+ Expect(err).To(MatchError(HavePrefix("could not add Error template:")))
180+ Expect(t).To(BeNil())
181+ })
182+ })
183+ })
184+ })
185+
186+ Context("isFile", func() {
187+ It("with a valid file", func() {
188+ Expect(isFile(filepath.Join(customDir, signInTemplateName))).To(BeTrue())
189+ })
190+
191+ It("with a directory", func() {
192+ Expect(isFile(customDir)).To(BeFalse())
193+ })
194+
195+ It("with an invalid file", func() {
196+ Expect(isFile(filepath.Join(customDir, "does_not_exist.html"))).To(BeFalse())
197+ })
198+ })
199+})
templates_test.godeleted−62
@@ -1,62 +0,0 @@
1−package main
2−
3−import (
4− "bytes"
5− "io/ioutil"
6− "log"
7− "os"
8− "path/filepath"
9− "testing"
10−
11− "github.com/stretchr/testify/assert"
12−)
13−
14−func TestLoadTemplates(t *testing.T) {
15− data := struct {
16− TestString string
17− }{
18− TestString: "Testing",
19− }
20−
21− templates := loadTemplates("")
22− assert.NotEqual(t, templates, nil)
23−
24− var defaultSignin bytes.Buffer
25− templates.ExecuteTemplate(&defaultSignin, "sign_in.html", data)
26− assert.Equal(t, "\n<!DOCTYPE html>", defaultSignin.String()[0:16])
27−
28− var defaultError bytes.Buffer
29− templates.ExecuteTemplate(&defaultError, "error.html", data)
30− assert.Equal(t, "\n<!DOCTYPE html>", defaultError.String()[0:16])
31−
32− dir, err := ioutil.TempDir("", "templatetest")
33− if err != nil {
34− log.Fatal(err)
35− }
36− defer os.RemoveAll(dir)
37−
38− templateHTML := `{{.TestString}} {{.TestString | ToLower}} {{.TestString | ToUpper}}`
39− signInFile := filepath.Join(dir, "sign_in.html")
40− if err := ioutil.WriteFile(signInFile, []byte(templateHTML), 0666); err != nil {
41− log.Fatal(err)
42− }
43− errorFile := filepath.Join(dir, "error.html")
44− if err := ioutil.WriteFile(errorFile, []byte(templateHTML), 0666); err != nil {
45− log.Fatal(err)
46− }
47− templates = loadTemplates(dir)
48− assert.NotEqual(t, templates, nil)
49−
50− var sitpl bytes.Buffer
51− templates.ExecuteTemplate(&sitpl, "sign_in.html", data)
52− assert.Equal(t, "Testing testing TESTING", sitpl.String())
53−
54− var errtpl bytes.Buffer
55− templates.ExecuteTemplate(&errtpl, "error.html", data)
56− assert.Equal(t, "Testing testing TESTING", errtpl.String())
57−}
58−
59−func TestTemplatesCompile(t *testing.T) {
60− templates := getTemplates()
61− assert.NotEqual(t, templates, nil)
62−}