-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
103 lines (79 loc) · 2.22 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
93
94
95
96
97
98
99
100
101
102
103
package security
import (
"crypto/sha256"
"encoding/hex"
"net/http"
"strings"
"time"
"github.com/cjlapao/common-go/helper"
loggerModule "github.com/cjlapao/common-go/log"
"github.com/pascaldekloe/jwt"
)
var logger = loggerModule.Get()
// Security Constants
const (
Issuer = "Ittech24.co.uk"
LoginScope = "authorization"
PrivateKey = "somerandomshit"
)
// SHA256Encode Hash string with SHA256
func SHA256Encode(value string) string {
hasher := sha256.New()
bytes := []byte(value)
hasher.Write(bytes)
return hex.EncodeToString(hasher.Sum(nil))
}
// GenerateUserToken generates a jwt user token
func GenerateUserToken(email string) (string, string) {
var claims jwt.Claims
claims.Subject = email
claims.Issuer = Issuer
claims.Issued = jwt.NewNumericTime(time.Now().Round(time.Second))
claims.Expires = jwt.NewNumericTime(time.Now().Add(time.Hour * 1))
claims.Set = map[string]interface{}{"email_verified": false, "scope": "authentication"}
token, err := claims.HMACSign("HS256", []byte(PrivateKey))
helper.CheckError(err)
return string(token), claims.Expires.String()
}
func ValidateToken(token string) bool {
claims, err := jwt.HMACCheck([]byte(token), []byte(PrivateKey))
if err != nil {
logger.Error("Token is not valid ")
return false
}
email := claims.Subject
if !claims.Valid(time.Now()) {
logger.Error("Token is not valid for user " + email)
return false
}
if claims.Issuer != Issuer {
logger.Error("Token is not valid for user " + email)
return false
}
return true
}
func GetAuthorizationToken(request http.Header) (string, bool) {
authHeader := strings.Split(request.Get("Authorization"), "Bearer ")
if len(authHeader) != 2 {
return "", false
}
logger.Debug("Token: " + authHeader[1])
return authHeader[1], true
}
func AuthenticateMiddleware(target http.HandlerFunc) http.Handler {
next := http.Handler(target)
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
token, valid := GetAuthorizationToken(r.Header)
if !valid {
w.WriteHeader(http.StatusUnauthorized)
w.Write([]byte("Unauthorized"))
return
}
if !ValidateToken(token) {
w.WriteHeader(http.StatusUnauthorized)
w.Write([]byte("Unauthorized"))
return
}
next.ServeHTTP(w, r)
})
}