11package main
22
33import (
4- "encoding/base64"
54 "errors"
65 "fmt"
76 "io/ioutil"
87 "os"
9- "strconv"
108 "strings"
119
1210 log "github.com/Sirupsen/logrus"
1311 haikunator "github.com/atrox/haikunatorgo"
1412 "github.com/gin-contrib/sessions"
1513 "github.com/gin-gonic/gin"
14+ "github.com/msoedov/hacker-slides/auth"
1615 "github.com/msoedov/hacker-slides/files"
1716)
1817
1918const sessionHeader = "slide-session"
2019
21- func Header (c * gin.Context , key string ) string {
22- if values , _ := c .Request .Header [key ]; len (values ) > 0 {
23- return values [0 ]
24- }
25- return ""
26- }
27-
28- func BasicAuth () gin.HandlerFunc {
29- realm := "Authorization Required"
30- realm = "Basic realm=" + strconv .Quote (realm )
31- user := os .Getenv ("USER" )
32- password := os .Getenv ("PASSWORD" )
33- enabled := isEnabled (user , password )
34- if enabled {
35- log .Warn ("Auth mode enabled" )
36- log .Warn (fmt .Sprintf ("Visit http://%s:%s@0.0.0.0:8080" , user , password ))
37- }
38- return func (c * gin.Context ) {
39- header := Header (c , "Authorization" )
40- if enabled && header != authorizationHeader (user , password ) {
41- // Credentials doesn't match, we return 401 and abort handlers chain.
42- c .Header ("WWW-Authenticate" , realm )
43- c .AbortWithStatus (401 )
44- return
45- }
46- c .Next ()
47- }
48- }
49-
50- func isEnabled (user , password string ) bool {
51- switch {
52- case user == "" :
53- return false
54- case password == "" :
55- return false
56- default :
57- return true
58- }
59- }
60-
61- func authorizationHeader (user , password string ) string {
62- base := user + ":" + password
63- return "Basic " + base64 .StdEncoding .EncodeToString ([]byte (base ))
64- }
65-
6620func SlidePath (name string ) string {
6721 return fmt .Sprintf ("slides/%s.md" , name )
6822}
@@ -73,7 +27,7 @@ func NewApp() *gin.Engine {
7327
7428 store := sessions .NewCookieStore ([]byte ("secret" ))
7529 r .Use (sessions .Sessions (sessionHeader , store ))
76- r .Use (BasicAuth ())
30+ r .Use (auth . BasicAuth ())
7731
7832 r .LoadHTMLGlob ("templates/*.tmpl" )
7933 r .Static ("/static" , "./static" )
0 commit comments