git.iko.soy/typeable/oauth2-proxy
on master help sign in
Merge pull request #1028 from oauth2-proxy/templates
9cdcd2bJoel Speed
CHANGELOG.md+1
@@ -8,6 +8,7 @@
8
8
9## Changes since v7.0.1
9## Changes since v7.0.1
10
10
11+- [#1028](https://github.com/oauth2-proxy/oauth2-proxy/pull/1028) Refactor templates, update theme and provide styled error pages (@JoelSpeed)
11- [#1039](https://github.com/oauth2-proxy/oauth2-proxy/pull/1039) Ensure errors in tests are logged to the GinkgoWriter (@JoelSpeed)
12- [#1039](https://github.com/oauth2-proxy/oauth2-proxy/pull/1039) Ensure errors in tests are logged to the GinkgoWriter (@JoelSpeed)
12
13
13# V7.0.1
14# V7.0.1
oauthproxy.go+58−35
@@ -18,6 +18,7 @@ import (
18 middlewareapi "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/middleware"
18 middlewareapi "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/middleware"
19 "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/options"
19 "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/options"
20 sessionsapi "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/sessions"
20 sessionsapi "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/sessions"
21+ "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/app"
21 "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/authentication/basic"
22 "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/authentication/basic"
22 "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/cookies"
23 "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/cookies"
23 "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/encryption"
24 "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/encryption"
@@ -116,7 +117,10 @@ func NewOAuthProxy(opts *options.Options, validator func(string) bool) (*OAuthPr
116 return nil, fmt.Errorf("error initialising session store: %v", err)
117 return nil, fmt.Errorf("error initialising session store: %v", err)
117 }
118 }
118
119
119− templates := loadTemplates(opts.CustomTemplatesDir)
120+ templates, err := app.LoadTemplates(opts.Templates.Path)
121+ if err != nil {
122+ return nil, fmt.Errorf("error loading templates: %v", err)
123+ }
120 proxyErrorHandler := upstream.NewProxyErrorHandler(templates.Lookup("error.html"), opts.ProxyPrefix)
124 proxyErrorHandler := upstream.NewProxyErrorHandler(templates.Lookup("error.html"), opts.ProxyPrefix)
121 upstreamProxy, err := upstream.NewProxy(opts.UpstreamServers, opts.GetSignatureData(), proxyErrorHandler)
125 upstreamProxy, err := upstream.NewProxy(opts.UpstreamServers, opts.GetSignatureData(), proxyErrorHandler)
122 if err != nil {
126 if err != nil {
@@ -211,12 +215,12 @@ func NewOAuthProxy(opts *options.Options, validator func(string) bool) (*OAuthPr
211 SkipProviderButton: opts.SkipProviderButton,
215 SkipProviderButton: opts.SkipProviderButton,
212 templates: templates,
216 templates: templates,
213 trustedIPs: trustedIPs,
217 trustedIPs: trustedIPs,
214− Banner: opts.Banner,
218+ Banner: opts.Templates.Banner,
215− Footer: opts.Footer,
219+ Footer: opts.Templates.Footer,
216 SignInMessage: buildSignInMessage(opts),
220 SignInMessage: buildSignInMessage(opts),
217
221
218 basicAuthValidator: basicAuthValidator,
222 basicAuthValidator: basicAuthValidator,
219− displayHtpasswdForm: basicAuthValidator != nil && opts.DisplayHtpasswdForm,
223+ displayHtpasswdForm: basicAuthValidator != nil && opts.Templates.DisplayLoginForm,
220 sessionChain: sessionChain,
224 sessionChain: sessionChain,
221 headersChain: headersChain,
225 headersChain: headersChain,
222 preAuthChain: preAuthChain,
226 preAuthChain: preAuthChain,
@@ -301,11 +305,11 @@ func buildHeadersChain(opts *options.Options) (alice.Chain, error) {
301
305
302func buildSignInMessage(opts *options.Options) string {
306func buildSignInMessage(opts *options.Options) string {
303 var msg string
307 var msg string
304− if len(opts.Banner) >= 1 {
308+ if len(opts.Templates.Banner) >= 1 {
305− if opts.Banner == "-" {
309+ if opts.Templates.Banner == "-" {
306 msg = ""
310 msg = ""
307 } else {
311 } else {
308− msg = opts.Banner
312+ msg = opts.Templates.Banner
309 }
313 }
310 } else if len(opts.EmailDomains) != 0 && opts.AuthenticatedEmailsFile == "" {
314 } else if len(opts.EmailDomains) != 0 && opts.AuthenticatedEmailsFile == "" {
311 if len(opts.EmailDomains) > 1 {
315 if len(opts.EmailDomains) > 1 {
@@ -478,7 +482,7 @@ func (p *OAuthProxy) serveHTTP(rw http.ResponseWriter, req *http.Request) {
478
482
479 switch path := req.URL.Path; {
483 switch path := req.URL.Path; {
480 case path == p.RobotsPath:
484 case path == p.RobotsPath:
481− p.RobotsTxt(rw)
485+ p.RobotsTxt(rw, req)
482 case p.IsAllowedRequest(req):
486 case p.IsAllowedRequest(req):
483 p.SkipAuthProxy(rw, req)
487 p.SkipAuthProxy(rw, req)
484 case path == p.SignInPath:
488 case path == p.SignInPath:
@@ -499,30 +503,49 @@ func (p *OAuthProxy) serveHTTP(rw http.ResponseWriter, req *http.Request) {
499}
503}
500
504
501// RobotsTxt disallows scraping pages from the OAuthProxy
505// RobotsTxt disallows scraping pages from the OAuthProxy
502−func (p *OAuthProxy) RobotsTxt(rw http.ResponseWriter) {
506+func (p *OAuthProxy) RobotsTxt(rw http.ResponseWriter, req *http.Request) {
503 _, err := fmt.Fprintf(rw, "User-agent: *\nDisallow: /")
507 _, err := fmt.Fprintf(rw, "User-agent: *\nDisallow: /")
504 if err != nil {
508 if err != nil {
505 logger.Printf("Error writing robots.txt: %v", err)
509 logger.Printf("Error writing robots.txt: %v", err)
506− p.ErrorPage(rw, http.StatusInternalServerError, "Internal Server Error", err.Error())
510+ p.ErrorPage(rw, req, http.StatusInternalServerError, "Internal Server Error", err.Error())
507 return
511 return
508 }
512 }
509 rw.WriteHeader(http.StatusOK)
513 rw.WriteHeader(http.StatusOK)
510}
514}
511
515
512// ErrorPage writes an error response
516// ErrorPage writes an error response
513−func (p *OAuthProxy) ErrorPage(rw http.ResponseWriter, code int, title string, message string) {
517+func (p *OAuthProxy) ErrorPage(rw http.ResponseWriter, req *http.Request, code int, title string, message string) {
518+ redirectURL, err := p.getAppRedirect(req)
519+ if err != nil {
520+ logger.Errorf("Error obtaining redirect: %v", err)
521+ }
522+ if redirectURL == p.SignInPath || redirectURL == "" {
523+ redirectURL = "/"
524+ }
525+
514 rw.WriteHeader(code)
526 rw.WriteHeader(code)
527+
528+ // We allow unescaped template.HTML since it is user configured options
529+ /* #nosec G203 */
515 t := struct {
530 t := struct {
516 Title string
531 Title string
517 Message string
532 Message string
518 ProxyPrefix string
533 ProxyPrefix string
534+ StatusCode int
535+ Redirect string
536+ Footer template.HTML
537+ Version string
519 }{
538 }{
520− Title: fmt.Sprintf("%d %s", code, title),
539+ Title: title,
521 Message: message,
540 Message: message,
522 ProxyPrefix: p.ProxyPrefix,
541 ProxyPrefix: p.ProxyPrefix,
542+ StatusCode: code,
543+ Redirect: redirectURL,
544+ Footer: template.HTML(p.Footer),
545+ Version: VERSION,
523 }
546 }
547+
524− err := p.templates.ExecuteTemplate(rw, "error.html", t)
548+ if err := p.templates.ExecuteTemplate(rw, "error.html", t); err != nil {
525− if err != nil {
526 logger.Printf("Error rendering error.html template: %v", err)
549 logger.Printf("Error rendering error.html template: %v", err)
527 http.Error(rw, "Internal Server Error", http.StatusInternalServerError)
550 http.Error(rw, "Internal Server Error", http.StatusInternalServerError)
528 }
551 }
@@ -570,7 +593,7 @@ func (p *OAuthProxy) SignInPage(rw http.ResponseWriter, req *http.Request, code
570 err := p.ClearSessionCookie(rw, req)
593 err := p.ClearSessionCookie(rw, req)
571 if err != nil {
594 if err != nil {
572 logger.Printf("Error clearing session cookie: %v", err)
595 logger.Printf("Error clearing session cookie: %v", err)
573− p.ErrorPage(rw, http.StatusInternalServerError, "Internal Server Error", err.Error())
596+ p.ErrorPage(rw, req, http.StatusInternalServerError, "Internal Server Error", err.Error())
574 return
597 return
575 }
598 }
576 rw.WriteHeader(code)
599 rw.WriteHeader(code)
@@ -578,7 +601,7 @@ func (p *OAuthProxy) SignInPage(rw http.ResponseWriter, req *http.Request, code
578 redirectURL, err := p.getAppRedirect(req)
601 redirectURL, err := p.getAppRedirect(req)
579 if err != nil {
602 if err != nil {
580 logger.Errorf("Error obtaining redirect: %v", err)
603 logger.Errorf("Error obtaining redirect: %v", err)
581− p.ErrorPage(rw, http.StatusInternalServerError, "Internal Server Error", err.Error())
604+ p.ErrorPage(rw, req, http.StatusInternalServerError, "Internal Server Error", err.Error())
582 return
605 return
583 }
606 }
584
607
@@ -611,7 +634,7 @@ func (p *OAuthProxy) SignInPage(rw http.ResponseWriter, req *http.Request, code
611 err = p.templates.ExecuteTemplate(rw, "sign_in.html", t)
634 err = p.templates.ExecuteTemplate(rw, "sign_in.html", t)
612 if err != nil {
635 if err != nil {
613 logger.Printf("Error rendering sign_in.html template: %v", err)
636 logger.Printf("Error rendering sign_in.html template: %v", err)
614− p.ErrorPage(rw, http.StatusInternalServerError, "Internal Server Error", err.Error())
637+ p.ErrorPage(rw, req, http.StatusInternalServerError, "Internal Server Error", err.Error())
615 }
638 }
616}
639}
617
640
@@ -639,7 +662,7 @@ func (p *OAuthProxy) SignIn(rw http.ResponseWriter, req *http.Request) {
639 redirect, err := p.getAppRedirect(req)
662 redirect, err := p.getAppRedirect(req)
640 if err != nil {
663 if err != nil {
641 logger.Errorf("Error obtaining redirect: %v", err)
664 logger.Errorf("Error obtaining redirect: %v", err)
642− p.ErrorPage(rw, http.StatusInternalServerError, "Internal Server Error", err.Error())
665+ p.ErrorPage(rw, req, http.StatusInternalServerError, "Internal Server Error", err.Error())
643 return
666 return
644 }
667 }
645
668
@@ -649,7 +672,7 @@ func (p *OAuthProxy) SignIn(rw http.ResponseWriter, req *http.Request) {
649 err = p.SaveSession(rw, req, session)
672 err = p.SaveSession(rw, req, session)
650 if err != nil {
673 if err != nil {
651 logger.Printf("Error saving session: %v", err)
674 logger.Printf("Error saving session: %v", err)
652− p.ErrorPage(rw, http.StatusInternalServerError, "Internal Server Error", err.Error())
675+ p.ErrorPage(rw, req, http.StatusInternalServerError, "Internal Server Error", err.Error())
653 return
676 return
654 }
677 }
655 http.Redirect(rw, req, redirect, http.StatusFound)
678 http.Redirect(rw, req, redirect, http.StatusFound)
@@ -688,7 +711,7 @@ func (p *OAuthProxy) UserInfo(rw http.ResponseWriter, req *http.Request) {
688 err = json.NewEncoder(rw).Encode(userInfo)
711 err = json.NewEncoder(rw).Encode(userInfo)
689 if err != nil {
712 if err != nil {
690 logger.Printf("Error encoding user info: %v", err)
713 logger.Printf("Error encoding user info: %v", err)
691− p.ErrorPage(rw, http.StatusInternalServerError, "Internal Server Error", err.Error())
714+ p.ErrorPage(rw, req, http.StatusInternalServerError, "Internal Server Error", err.Error())
692 }
715 }
693}
716}
694
717
@@ -697,13 +720,13 @@ func (p *OAuthProxy) SignOut(rw http.ResponseWriter, req *http.Request) {
697 redirect, err := p.getAppRedirect(req)
720 redirect, err := p.getAppRedirect(req)
698 if err != nil {
721 if err != nil {
699 logger.Errorf("Error obtaining redirect: %v", err)
722 logger.Errorf("Error obtaining redirect: %v", err)
700− p.ErrorPage(rw, http.StatusInternalServerError, "Internal Server Error", err.Error())
723+ p.ErrorPage(rw, req, http.StatusInternalServerError, "Internal Server Error", err.Error())
701 return
724 return
702 }
725 }
703 err = p.ClearSessionCookie(rw, req)
726 err = p.ClearSessionCookie(rw, req)
704 if err != nil {
727 if err != nil {
705 logger.Errorf("Error clearing session cookie: %v", err)
728 logger.Errorf("Error clearing session cookie: %v", err)
706− p.ErrorPage(rw, http.StatusInternalServerError, "Internal Server Error", err.Error())
729+ p.ErrorPage(rw, req, http.StatusInternalServerError, "Internal Server Error", err.Error())
707 return
730 return
708 }
731 }
709 http.Redirect(rw, req, redirect, http.StatusFound)
732 http.Redirect(rw, req, redirect, http.StatusFound)
@@ -715,14 +738,14 @@ func (p *OAuthProxy) OAuthStart(rw http.ResponseWriter, req *http.Request) {
715 nonce, err := encryption.Nonce()
738 nonce, err := encryption.Nonce()
716 if err != nil {
739 if err != nil {
717 logger.Errorf("Error obtaining nonce: %v", err)
740 logger.Errorf("Error obtaining nonce: %v", err)
718− p.ErrorPage(rw, http.StatusInternalServerError, "Internal Server Error", err.Error())
741+ p.ErrorPage(rw, req, http.StatusInternalServerError, "Internal Server Error", err.Error())
719 return
742 return
720 }
743 }
721 p.SetCSRFCookie(rw, req, nonce)
744 p.SetCSRFCookie(rw, req, nonce)
722 redirect, err := p.getAppRedirect(req)
745 redirect, err := p.getAppRedirect(req)
723 if err != nil {
746 if err != nil {
724 logger.Errorf("Error obtaining redirect: %v", err)
747 logger.Errorf("Error obtaining redirect: %v", err)
725− p.ErrorPage(rw, http.StatusInternalServerError, "Internal Server Error", err.Error())
748+ p.ErrorPage(rw, req, http.StatusInternalServerError, "Internal Server Error", err.Error())
726 return
749 return
727 }
750 }
728 redirectURI := p.getOAuthRedirectURI(req)
751 redirectURI := p.getOAuthRedirectURI(req)
@@ -738,34 +761,34 @@ func (p *OAuthProxy) OAuthCallback(rw http.ResponseWriter, req *http.Request) {
738 err := req.ParseForm()
761 err := req.ParseForm()
739 if err != nil {
762 if err != nil {
740 logger.Errorf("Error while parsing OAuth2 callback: %v", err)
763 logger.Errorf("Error while parsing OAuth2 callback: %v", err)
741− p.ErrorPage(rw, http.StatusInternalServerError, "Internal Server Error", err.Error())
764+ p.ErrorPage(rw, req, http.StatusInternalServerError, "Internal Server Error", err.Error())
742 return
765 return
743 }
766 }
744 errorString := req.Form.Get("error")
767 errorString := req.Form.Get("error")
745 if errorString != "" {
768 if errorString != "" {
746 logger.Errorf("Error while parsing OAuth2 callback: %s", errorString)
769 logger.Errorf("Error while parsing OAuth2 callback: %s", errorString)
747− p.ErrorPage(rw, http.StatusForbidden, "Permission Denied", errorString)
770+ p.ErrorPage(rw, req, http.StatusForbidden, "Permission Denied", errorString)
748 return
771 return
749 }
772 }
750
773
751 session, err := p.redeemCode(req)
774 session, err := p.redeemCode(req)
752 if err != nil {
775 if err != nil {
753 logger.Errorf("Error redeeming code during OAuth2 callback: %v", err)
776 logger.Errorf("Error redeeming code during OAuth2 callback: %v", err)
754− p.ErrorPage(rw, http.StatusInternalServerError, "Internal Server Error", "Internal Error")
777+ p.ErrorPage(rw, req, http.StatusInternalServerError, "Internal Server Error", "Internal Error")
755 return
778 return
756 }
779 }
757
780
758 err = p.enrichSessionState(req.Context(), session)
781 err = p.enrichSessionState(req.Context(), session)
759 if err != nil {
782 if err != nil {
760 logger.Errorf("Error creating session during OAuth2 callback: %v", err)
783 logger.Errorf("Error creating session during OAuth2 callback: %v", err)
761− p.ErrorPage(rw, http.StatusInternalServerError, "Internal Server Error", "Internal Error")
784+ p.ErrorPage(rw, req, http.StatusInternalServerError, "Internal Server Error", "Internal Error")
762 return
785 return
763 }
786 }
764
787
765 state := strings.SplitN(req.Form.Get("state"), ":", 2)
788 state := strings.SplitN(req.Form.Get("state"), ":", 2)
766 if len(state) != 2 {
789 if len(state) != 2 {
767 logger.Error("Error while parsing OAuth2 state: invalid length")
790 logger.Error("Error while parsing OAuth2 state: invalid length")
768− p.ErrorPage(rw, http.StatusInternalServerError, "Internal Server Error", "Invalid State")
791+ p.ErrorPage(rw, req, http.StatusInternalServerError, "Internal Server Error", "Invalid State")
769 return
792 return
770 }
793 }
771 nonce := state[0]
794 nonce := state[0]
@@ -773,13 +796,13 @@ func (p *OAuthProxy) OAuthCallback(rw http.ResponseWriter, req *http.Request) {
773 c, err := req.Cookie(p.CSRFCookieName)
796 c, err := req.Cookie(p.CSRFCookieName)
774 if err != nil {
797 if err != nil {
775 logger.PrintAuthf(session.Email, req, logger.AuthFailure, "Invalid authentication via OAuth2: unable to obtain CSRF cookie")
798 logger.PrintAuthf(session.Email, req, logger.AuthFailure, "Invalid authentication via OAuth2: unable to obtain CSRF cookie")
776− p.ErrorPage(rw, http.StatusForbidden, "Permission Denied", err.Error())
799+ p.ErrorPage(rw, req, http.StatusForbidden, "Permission Denied", err.Error())
777 return
800 return
778 }
801 }
779 p.ClearCSRFCookie(rw, req)
802 p.ClearCSRFCookie(rw, req)
780 if c.Value != nonce {
803 if c.Value != nonce {
781 logger.PrintAuthf(session.Email, req, logger.AuthFailure, "Invalid authentication via OAuth2: CSRF token mismatch, potential attack")
804 logger.PrintAuthf(session.Email, req, logger.AuthFailure, "Invalid authentication via OAuth2: CSRF token mismatch, potential attack")
782− p.ErrorPage(rw, http.StatusForbidden, "Permission Denied", "CSRF Failed")
805+ p.ErrorPage(rw, req, http.StatusForbidden, "Permission Denied", "CSRF Failed")
783 return
806 return
784 }
807 }
785
808
@@ -797,13 +820,13 @@ func (p *OAuthProxy) OAuthCallback(rw http.ResponseWriter, req *http.Request) {
797 err := p.SaveSession(rw, req, session)
820 err := p.SaveSession(rw, req, session)
798 if err != nil {
821 if err != nil {
799 logger.Errorf("Error saving session state for %s: %v", remoteAddr, err)
822 logger.Errorf("Error saving session state for %s: %v", remoteAddr, err)
800− p.ErrorPage(rw, http.StatusInternalServerError, "Internal Server Error", err.Error())
823+ p.ErrorPage(rw, req, http.StatusInternalServerError, "Internal Server Error", err.Error())
801 return
824 return
802 }
825 }
803 http.Redirect(rw, req, redirect, http.StatusFound)
826 http.Redirect(rw, req, redirect, http.StatusFound)
804 } else {
827 } else {
805 logger.PrintAuthf(session.Email, req, logger.AuthFailure, "Invalid authentication via OAuth2: unauthorized")
828 logger.PrintAuthf(session.Email, req, logger.AuthFailure, "Invalid authentication via OAuth2: unauthorized")
806− p.ErrorPage(rw, http.StatusForbidden, "Permission Denied", "Invalid Account")
829+ p.ErrorPage(rw, req, http.StatusForbidden, "Permission Denied", "Invalid Account")
807 }
830 }
808}
831}
809
832
@@ -885,12 +908,12 @@ func (p *OAuthProxy) Proxy(rw http.ResponseWriter, req *http.Request) {
885 }
908 }
886
909
887 case ErrAccessDenied:
910 case ErrAccessDenied:
888− p.ErrorPage(rw, http.StatusUnauthorized, "Permission Denied", "Unauthorized")
911+ p.ErrorPage(rw, req, http.StatusUnauthorized, "Permission Denied", "Unauthorized")
889
912
890 default:
913 default:
891 // unknown error
914 // unknown error
892 logger.Errorf("Unexpected internal error: %v", err)
915 logger.Errorf("Unexpected internal error: %v", err)
893− p.ErrorPage(rw, http.StatusInternalServerError,
916+ p.ErrorPage(rw, req, http.StatusInternalServerError,
894 "Internal Error", "Internal Error")
917 "Internal Error", "Internal Error")
895 }
918 }
896}
919}
pkg/apis/options/app.gonew file+43
@@ -0,0 +1,43 @@
1+package options
2+
3+import "github.com/spf13/pflag"
4+
5+// Templates includes options for configuring the sign in and error pages
6+// appearance.
7+type Templates struct {
8+ // Path is the path to a folder containing a sign_in.html and an error.html
9+ // template.
10+ // These files will be used instead of the default templates if present.
11+ // If either file is missing, the default will be used instead.
12+ Path string `flag:"custom-templates-dir" cfg:"custom_templates_dir"`
13+
14+ // Banner overides the default sign_in page banner text. If unspecified,
15+ // the message will give users a list of allowed email domains.
16+ Banner string `flag:"banner" cfg:"banner"`
17+
18+ // Footer overrides the default sign_in page footer text.
19+ Footer string `flag:"footer" cfg:"footer"`
20+
21+ // DisplayLoginForm determines whether the sign_in page should render a
22+ // password form if a static passwords file (htpasswd file) has been
23+ // configured.
24+ DisplayLoginForm bool `flag:"display-htpasswd-form" cfg:"display_htpasswd_form"`
25+}
26+
27+func templatesFlagSet() *pflag.FlagSet {
28+ flagSet := pflag.NewFlagSet("templates", pflag.ExitOnError)
29+
30+ flagSet.String("custom-templates-dir", "", "path to custom html templates")
31+ flagSet.String("banner", "", "custom banner string. Use \"-\" to disable default banner.")
32+ flagSet.String("footer", "", "custom footer string. Use \"-\" to disable default footer.")
33+ flagSet.Bool("display-htpasswd-form", true, "display username / password login form if an htpasswd file is provided")
34+
35+ return flagSet
36+}
37+
38+// templatesDefaults creates a Templates and populates it with any default values
39+func templatesDefaults() Templates {
40+ return Templates{
41+ DisplayLoginForm: true,
42+ }
43+}
pkg/apis/options/options.go+14−19
@@ -53,14 +53,11 @@ type Options struct {
53 GoogleAdminEmail string `flag:"google-admin-email" cfg:"google_admin_email"`
53 GoogleAdminEmail string `flag:"google-admin-email" cfg:"google_admin_email"`
54 GoogleServiceAccountJSON string `flag:"google-service-account-json" cfg:"google_service_account_json"`
54 GoogleServiceAccountJSON string `flag:"google-service-account-json" cfg:"google_service_account_json"`
55 HtpasswdFile string `flag:"htpasswd-file" cfg:"htpasswd_file"`
55 HtpasswdFile string `flag:"htpasswd-file" cfg:"htpasswd_file"`
56− DisplayHtpasswdForm bool `flag:"display-htpasswd-form" cfg:"display_htpasswd_form"`
57− CustomTemplatesDir string `flag:"custom-templates-dir" cfg:"custom_templates_dir"`
58− Banner string `flag:"banner" cfg:"banner"`
59− Footer string `flag:"footer" cfg:"footer"`
60
56
61− Cookie Cookie `cfg:",squash"`
57+ Cookie Cookie `cfg:",squash"`
62− Session SessionOptions `cfg:",squash"`
58+ Session SessionOptions `cfg:",squash"`
63− Logging Logging `cfg:",squash"`
59+ Logging Logging `cfg:",squash"`
60+ Templates Templates `cfg:",squash"`
64
61
65 // Not used in the legacy config, name not allowed to match an external key (upstreams)
62 // Not used in the legacy config, name not allowed to match an external key (upstreams)
66 // TODO(JoelSpeed): Rename when legacy config is removed
63 // TODO(JoelSpeed): Rename when legacy config is removed
@@ -135,16 +132,17 @@ func (o *Options) SetRealClientIPParser(s ipapi.RealClientIPParser) { o.realClie
135// NewOptions constructs a new Options with defaulted values
132// NewOptions constructs a new Options with defaulted values
136func NewOptions() *Options {
133func NewOptions() *Options {
137 return &Options{
134 return &Options{
138− ProxyPrefix: "/oauth2",
135+ ProxyPrefix: "/oauth2",
139− ProviderType: "google",
136+ ProviderType: "google",
140− PingPath: "/ping",
137+ PingPath: "/ping",
141− HTTPAddress: "127.0.0.1:4180",
138+ HTTPAddress: "127.0.0.1:4180",
142− HTTPSAddress: ":443",
139+ HTTPSAddress: ":443",
143− RealClientIPHeader: "X-Real-IP",
140+ RealClientIPHeader: "X-Real-IP",
144− ForceHTTPS: false,
141+ ForceHTTPS: false,
145− DisplayHtpasswdForm: true,
142+
146 Cookie: cookieDefaults(),
143 Cookie: cookieDefaults(),
147 Session: sessionOptionsDefaults(),
144 Session: sessionOptionsDefaults(),
145+ Templates: templatesDefaults(),
148 AzureTenant: "common",
146 AzureTenant: "common",
149 SkipAuthPreflight: false,
147 SkipAuthPreflight: false,
150 Prompt: "", // Change to "login" when ApprovalPrompt officially deprecated
148 Prompt: "", // Change to "login" when ApprovalPrompt officially deprecated
@@ -200,10 +198,6 @@ func NewFlagSet() *pflag.FlagSet {
200 flagSet.String("client-secret-file", "", "the file with OAuth Client Secret")
198 flagSet.String("client-secret-file", "", "the file with OAuth Client Secret")
201 flagSet.String("authenticated-emails-file", "", "authenticate against emails via file (one per line)")
199 flagSet.String("authenticated-emails-file", "", "authenticate against emails via file (one per line)")
202 flagSet.String("htpasswd-file", "", "additionally authenticate against a htpasswd file. Entries must be created with \"htpasswd -B\" for bcrypt encryption")
200 flagSet.String("htpasswd-file", "", "additionally authenticate against a htpasswd file. Entries must be created with \"htpasswd -B\" for bcrypt encryption")
203− flagSet.Bool("display-htpasswd-form", true, "display username / password login form if an htpasswd file is provided")
204− flagSet.String("custom-templates-dir", "", "path to custom html templates")
205− flagSet.String("banner", "", "custom banner string. Use \"-\" to disable default banner.")
206− flagSet.String("footer", "", "custom footer string. Use \"-\" to disable default footer.")
207 flagSet.String("proxy-prefix", "/oauth2", "the url root path that this proxy should be nested under (e.g. /<oauth2>/sign_in)")
201 flagSet.String("proxy-prefix", "/oauth2", "the url root path that this proxy should be nested under (e.g. /<oauth2>/sign_in)")
208 flagSet.String("ping-path", "/ping", "the ping endpoint that can be used for basic health checks")
202 flagSet.String("ping-path", "/ping", "the ping endpoint that can be used for basic health checks")
209 flagSet.String("ping-user-agent", "", "special User-Agent that will be used for basic health checks")
203 flagSet.String("ping-user-agent", "", "special User-Agent that will be used for basic health checks")
@@ -251,6 +245,7 @@ func NewFlagSet() *pflag.FlagSet {
251
245
252 flagSet.AddFlagSet(cookieFlagSet())
246 flagSet.AddFlagSet(cookieFlagSet())
253 flagSet.AddFlagSet(loggingFlagSet())
247 flagSet.AddFlagSet(loggingFlagSet())
248+ flagSet.AddFlagSet(templatesFlagSet())
254
249
255 return flagSet
250 return flagSet
256}
251}
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+}
pkg/app/templates.gonew file+257
@@ -0,0 +1,257 @@
1+package app
2+
3+import (
4+ "fmt"
5+ "html/template"
6+ "os"
7+ "path/filepath"
8+ "strings"
9+
10+ "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/logger"
11+)
12+
13+const (
14+ errorTemplateName = "error.html"
15+ signInTemplateName = "sign_in.html"
16+
17+ defaultErrorTemplate = `{{define "error.html"}}
18+<!DOCTYPE html>
19+<html lang="en" charset="utf-8">
20+<head>
21+ <meta charset="utf-8">
22+ <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
23+ <title>{{.StatusCode}} {{.Title}}</title>
24+ <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bulma@0.9.1/css/bulma.min.css">
25+ <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.2/css/all.min.css">
26+
27+ <script type="text/javascript">
28+ document.addEventListener('DOMContentLoaded', function() {
29+ let cardToggles = document.getElementsByClassName('card-toggle');
30+ for (let i = 0; i < cardToggles.length; i++) {
31+ cardToggles[i].addEventListener('click', e => {
32+ e.currentTarget.parentElement.parentElement.childNodes[3].classList.toggle('is-hidden');
33+ });
34+ }
35+ });
36+ </script>
37+
38+ <style>
39+ body {
40+ height: 100vh;
41+ }
42+ .error-box {
43+ margin: 1.25rem auto;
44+ max-width: 600px;
45+ }
46+ .status-code {
47+ font-size: 12rem;
48+ font-weight: 600;
49+ }
50+ #more-info.card {
51+ border: 1px solid #f0f0f0;
52+ }
53+ footer a {
54+ text-decoration: underline;
55+ }
56+ </style>
57+</head>
58+<body class="has-background-light">
59+ <section class="section">
60+ <div class="box block error-box has-text-centered">
61+ <div class="status-code">{{.StatusCode}}</div>
62+ <div class="block">
63+ <h1 class="subtitle is-1">{{.Title}}</h1>
64+ </div>
65+
66+ {{ if .Message }}
67+ <div id="more-info" class="block card is-fullwidth is-shadowless">
68+ <header class="card-header is-shadowless">
69+ <p class="card-header-title">More Info</p>
70+ <a class="card-header-icon card-toggle">
71+ <i class="fa fa-angle-down"></i>
72+ </a>
73+ </header>
74+ <div class="card-content has-text-left is-hidden">
75+ <div class="content">
76+ {{.Message}}
77+ </div>
78+ </div>
79+ </div>
80+ {{ end }}
81+
82+ <hr>
83+
84+ <div class="columns">
85+ <div class="column">
86+ <form method="GET" action="{{.Redirect}}">
87+ <button type="submit" class="button is-danger is-fullwidth">Go back</button>
88+ </form>
89+ </div>
90+ <div class="column">
91+ <form method="GET" action="{{.ProxyPrefix}}/sign_in">
92+ <input type="hidden" name="rd" value="{{.Redirect}}">
93+ <button type="submit" class="button is-primary is-fullwidth">Sign in</button>
94+ </form>
95+ </div>
96+ </div>
97+
98+ </div>
99+ </section>
100+
101+ <footer class="footer has-text-grey has-background-light is-size-7">
102+ <div class="content has-text-centered">
103+ {{ if eq .Footer "-" }}
104+ {{ else if eq .Footer ""}}
105+ <p>Secured with <a href="https://github.com/oauth2-proxy/oauth2-proxy#oauth2_proxy" class="has-text-grey">OAuth2 Proxy</a> version {{.Version}}</p>
106+ {{ else }}
107+ <p>{{.Footer}}</p>
108+ {{ end }}
109+ </div>
110+ </footer>
111+
112+ </body>
113+</html>
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)
252+ if err != nil {
253+ logger.Errorf("Could not load file %s: %v, will use default template", fileName, err)
254+ return false
255+ }
256+ return info.Mode().IsRegular()
257+}
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.godeleted−187
@@ -1,187 +0,0 @@
1−package main
2−
3−import (
4− "html/template"
5− "path"
6− "strings"
7−
8− "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/logger"
9−)
10−
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−}
26−
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− <title>Sign In</title>
33− <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
34− <style>
35− body {
36− font-family: "Helvetica Neue",Helvetica,Arial,sans-serif;
37− font-size: 14px;
38− line-height: 1.42857143;
39− color: #333;
40− background: #f0f0f0;
41− }
42− .signin {
43− display:block;
44− margin:20px auto;
45− max-width:400px;
46− background: #fff;
47− border:1px solid #ccc;
48− border-radius: 10px;
49− padding: 20px;
50− }
51− .center {
52− text-align:center;
53− }
54− .btn {
55− color: #fff;
56− background-color: #428bca;
57− border: 1px solid #357ebd;
58− -webkit-border-radius: 4;
59− -moz-border-radius: 4;
60− border-radius: 4px;
61− font-size: 14px;
62− padding: 6px 12px;
63− text-decoration: none;
64− cursor: pointer;
65− }
66−
67− .btn:hover {
68− background-color: #3071a9;
69− border-color: #285e8e;
70− text-decoration: none;
71− }
72− label {
73− display: inline-block;
74− max-width: 100%;
75− margin-bottom: 5px;
76− font-weight: 700;
77− }
78− input {
79− display: block;
80− width: 100%;
81− height: 34px;
82− padding: 6px 12px;
83− font-size: 14px;
84− line-height: 1.42857143;
85− color: #555;
86− background-color: #fff;
87− background-image: none;
88− border: 1px solid #ccc;
89− border-radius: 4px;
90− -webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,.075);
91− box-shadow: inset 0 1px 1px rgba(0,0,0,.075);
92− -webkit-transition: border-color ease-in-out .15s,-webkit-box-shadow ease-in-out .15s;
93− -o-transition: border-color ease-in-out .15s,box-shadow ease-in-out .15s;
94− transition: border-color ease-in-out .15s,box-shadow ease-in-out .15s;
95− margin:0;
96− box-sizing: border-box;
97− }
98− footer {
99− display:block;
100− font-size:10px;
101− color:#aaa;
102− text-align:center;
103− margin-bottom:10px;
104− }
105− footer a {
106− display:inline-block;
107− height:25px;
108− line-height:25px;
109− color:#aaa;
110− text-decoration:underline;
111− }
112− footer a:hover {
113− color:#aaa;
114− }
115− </style>
116−</head>
117−<body>
118− <div class="signin center">
119− <form method="GET" action="{{.ProxyPrefix}}/start">
120− <input type="hidden" name="rd" value="{{.Redirect}}">
121− {{ if .SignInMessage }}
122− <p>{{.SignInMessage}}</p>
123− {{ end}}
124− <button type="submit" class="btn">Sign in with {{.ProviderName}}</button><br/>
125− </form>
126− </div>
127−
128− {{ if .CustomLogin }}
129− <div class="signin">
130− <form method="POST" action="{{.ProxyPrefix}}/sign_in">
131− <input type="hidden" name="rd" value="{{.Redirect}}">
132− <label for="username">Username:</label><input type="text" name="username" id="username" size="10"><br/>
133− <label for="password">Password:</label><input type="password" name="password" id="password" size="10"><br/>
134− <button type="submit" class="btn">Sign In</button>
135− </form>
136− </div>
137− {{ end }}
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− <footer>
155− {{ if eq .Footer "-" }}
156− {{ else if eq .Footer ""}}
157− Secured with <a href="https://github.com/oauth2-proxy/oauth2-proxy#oauth2_proxy">OAuth2 Proxy</a> version {{.Version}}
158− {{ else }}
159− {{.Footer}}
160− {{ end }}
161− </footer>
162−</body>
163−</html>
164−{{end}}`)
165− if err != nil {
166− logger.Fatalf("failed parsing template %s", err)
167− }
168−
169− t, err = t.Parse(`{{define "error.html"}}
170−<!DOCTYPE html>
171−<html lang="en" charset="utf-8">
172−<head>
173− <title>{{.Title}}</title>
174− <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
175−</head>
176−<body>
177− <h2>{{.Title}}</h2>
178− <p>{{.Message}}</p>
179− <hr>
180− <p><a href="{{.ProxyPrefix}}/sign_in">Sign In</a></p>
181−</body>
182−</html>{{end}}`)
183− if err != nil {
184− logger.Fatalf("failed parsing template %s", err)
185− }
186− return t
187−}
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−}