11package main
22
33import (
4+ "encoding/base64"
45 "errors"
56 "fmt"
67 "io/ioutil"
78 "os"
9+ "strconv"
810 "strings"
911
1012 log "github.com/Sirupsen/logrus"
@@ -15,12 +17,58 @@ import (
1517
1618const sessionHeader = "slide-session"
1719
20+ func Header (c * gin.Context , key string ) string {
21+ if values , _ := c .Request .Header [key ]; len (values ) > 0 {
22+ return values [0 ]
23+ }
24+ return ""
25+ }
26+
27+ func BasicAuth () gin.HandlerFunc {
28+ realm := "Authorization Required"
29+ realm = "Basic realm=" + strconv .Quote (realm )
30+ user := os .Getenv ("USER" )
31+ password := os .Getenv ("PASSWORD" )
32+ enabled := isEnabled (user , password )
33+ if enabled {
34+ log .Warn ("Auth mode enabled" )
35+ log .Warn (fmt .Sprintf ("Visit http://%s:%s@0.0.0.0:8080" , user , password ))
36+ }
37+ return func (c * gin.Context ) {
38+ header := Header (c , "Authorization" )
39+ if enabled && header != authorizationHeader (user , password ) {
40+ // Credentials doesn't match, we return 401 and abort handlers chain.
41+ c .Header ("WWW-Authenticate" , realm )
42+ c .AbortWithStatus (401 )
43+ return
44+ }
45+ c .Next ()
46+ }
47+ }
48+
49+ func isEnabled (user , password string ) bool {
50+ switch {
51+ case user == "" :
52+ return false
53+ case password == "" :
54+ return false
55+ default :
56+ return true
57+ }
58+ }
59+
60+ func authorizationHeader (user , password string ) string {
61+ base := user + ":" + password
62+ return "Basic " + base64 .StdEncoding .EncodeToString ([]byte (base ))
63+ }
64+
1865func NewApp () * gin.Engine {
1966
2067 r := gin .Default ()
2168
2269 store := sessions .NewCookieStore ([]byte ("secret" ))
2370 r .Use (sessions .Sessions (sessionHeader , store ))
71+ r .Use (BasicAuth ())
2472
2573 r .LoadHTMLGlob ("templates/*.tmpl" )
2674 r .Static ("/static" , "./static" )
0 commit comments