main.revisionMiddleware   A
last analyzed

Complexity

Conditions 4

Size

Total Lines 16
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 10
dl 0
loc 16
rs 9.9
c 0
b 0
f 0
nop 1
1
package main
2
3
import (
4
	"io/ioutil"
5
	"log"
6
	"net/http"
7
	"os"
8
	"strings"
9
10
	"github.com/gin-gonic/gin"
11
	uuid "github.com/satori/go.uuid"
12
13
	"github.com/rfinochi/golang-workshop-todo/pkg/common"
14
)
15
16
func logRequestMiddleware(infoLog *log.Logger) gin.HandlerFunc {
17
	return func(c *gin.Context) {
18
		infoLog.Printf("%s - %s %s %s", c.Request.RemoteAddr, c.Request.Proto, c.Request.Method, c.Request.URL.RequestURI())
19
		c.Next()
20
	}
21
}
22
23
func requestIDMiddleware() gin.HandlerFunc {
24
	return func(c *gin.Context) {
25
		c.Writer.Header().Set(common.APIRequestIDHeaderName, uuid.NewV4().String())
26
		c.Next()
27
	}
28
}
29
30
func revisionMiddleware(errorLog *log.Logger) gin.HandlerFunc {
31
	data, err := ioutil.ReadFile("REVISION")
32
33
	if err != nil {
34
		errorLog.Println("Revision Middleware error: ", err)
35
36
		return func(c *gin.Context) {
37
			c.Next()
38
		}
39
	}
40
41
	revision := strings.TrimSpace(string(data))
42
43
	return func(c *gin.Context) {
44
		c.Writer.Header().Set(common.APIRevisionHeaderName, revision)
45
		c.Next()
46
	}
47
}
48
49
func tokenAuthMiddleware(errorLog *log.Logger) gin.HandlerFunc {
50
	requiredToken := os.Getenv(common.APITokenEnvVarName)
51
52
	if requiredToken == "" {
53
		errorLog.Fatal("Please set environment variable ", common.APITokenEnvVarName)
54
	}
55
56
	return func(c *gin.Context) {
57
		if !strings.Contains(c.Request.RequestURI, "api-docs") {
58
			token := c.Request.Header.Get(common.APITokenHeaderName)
59
60
			if token == "" {
61
				common.RespondError(c, http.StatusUnauthorized, "API token required")
62
				return
63
			}
64
65
			if token != requiredToken {
66
				common.RespondError(c, http.StatusUnauthorized, "Invalid API token (request one via e-mail to [email protected]")
67
				return
68
			}
69
		}
70
		c.Next()
71
	}
72
}
73