1
1
package main
2
2
3
3
import (
4
+ "encoding/base64"
4
5
"errors"
5
6
"fmt"
6
7
"io/ioutil"
7
8
"os"
9
+ "strconv"
8
10
"strings"
9
11
10
12
log "github.com/Sirupsen/logrus"
@@ -15,12 +17,58 @@ import (
15
17
16
18
const sessionHeader = "slide-session"
17
19
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
+
18
65
func NewApp () * gin.Engine {
19
66
20
67
r := gin .Default ()
21
68
22
69
store := sessions .NewCookieStore ([]byte ("secret" ))
23
70
r .Use (sessions .Sessions (sessionHeader , store ))
71
+ r .Use (BasicAuth ())
24
72
25
73
r .LoadHTMLGlob ("templates/*.tmpl" )
26
74
r .Static ("/static" , "./static" )
0 commit comments