-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.go
92 lines (76 loc) · 2.54 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
package main
import (
"context"
"encoding/gob"
"fmt"
"github.com/gin-contrib/gzip"
"github.com/gin-contrib/sessions"
"github.com/gin-contrib/sessions/cookie"
log "github.com/sirupsen/logrus"
"net/http"
"path/filepath"
"webfendr/authenticator"
"webfendr/config"
"webfendr/storage"
)
import "github.com/gin-gonic/gin"
func BuildUrl(ctx *gin.Context, cfg *config.Config) string {
return cfg.HttpProtocol() + "://" + ctx.Request.Host + ctx.Request.RequestURI
}
func IsAuthenticated(cfg *config.Config) gin.HandlerFunc {
return func(ctx *gin.Context) {
if sessions.Default(ctx).Get("profile") == nil {
session := sessions.Default(ctx)
session.Set("redirectUri", BuildUrl(ctx, cfg))
session.Save()
log.Debug("Redirecting to /webfendr/login")
ctx.Redirect(http.StatusSeeOther, "/webfendr/login")
} else {
ctx.Next()
}
}
}
func Router(auths *authenticator.Authenticators, cfg *config.Config) *gin.Engine {
router := gin.New()
//router.Use(ginLogrus.Logger(logger), gin.Recovery(), gzip.Gzip(gzip.DefaultCompression))
router.Use(gin.Recovery(), gzip.Gzip(gzip.DefaultCompression))
gob.Register(map[string]interface{}{})
store := cookie.NewStore([]byte("secret"))
router.Use(sessions.Sessions("auth-session", store))
router.Static("/webfendr/public", filepath.Join(cfg.WebFolder, "web/static"))
router.LoadHTMLGlob(filepath.Join(cfg.WebFolder, "web/template/**.html"))
router.GET("/webfendr", authenticator.IndexHandler(cfg))
router.GET("/webfendr/login", authenticator.LoginHandler(auths, cfg))
router.GET("/webfendr/callback", authenticator.CallbackHandler(auths, cfg))
router.GET("/webfendr/logout", authenticator.LogoutHandler(cfg))
router.NoRoute(IsAuthenticated(cfg), storage.FileHandler(cfg))
return router
}
func main() {
// Load config
cfg := config.PrepareConfig()
// Init logging
if cfg.WebFendrMode == gin.ReleaseMode {
log.SetFormatter(&log.JSONFormatter{})
} else {
log.SetFormatter(&log.TextFormatter{})
}
gin.SetMode(cfg.WebFendrMode)
// Init the oauth authenticator
auths := authenticator.Init()
// Create a default context
ctx, cancel := context.WithCancel(context.Background())
// Start the Google Storage synchronization runner
go storage.Syncer(ctx, cfg)
// Load Gin routes
rtr := Router(auths, cfg)
// Create server address
addr := fmt.Sprintf("0.0.0.0:%d", cfg.Port)
// Start http server
log.Info("Listening on host ", addr)
if err := http.ListenAndServe(addr, rtr); err != nil {
log.Fatalf("There was an error with the http server: %v", err)
}
// Run cancellation on default context
cancel()
}