-
Notifications
You must be signed in to change notification settings - Fork 0
/
basic_auth.go
77 lines (65 loc) · 1.8 KB
/
basic_auth.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
package middleware
import (
"strings"
"time"
"github.com/dgrijalva/jwt-go"
"github.com/labstack/echo"
"github.com/labstack/echo/middleware"
)
//Credential - Struct to take hold username/password
type Credential struct {
Name string `json:"name"`
Password string `json:"password"`
}
//ClaimsInp - Input to generate payload
type ClaimsInp struct {
Name string
IsAdmin bool
}
var credentials = map[string]string{
"admin": "leviathan",
"jonsnow": "fluffy",
}
//SigningKey -
var SigningKey = []byte("awakes") // need to get this from an .env file
//FlixCultJwtConfig -
var FlixCultJwtConfig = middleware.JWTConfig{
SigningKey: SigningKey,
SigningMethod: middleware.AlgorithmHS256,
AuthScheme: "Bearer",
Skipper: SkipJWTAuthentication,
}
//BasicAuthenticate - returns (authenticationStatus, admin)
func BasicAuthenticate(username string, password string) (bool, bool) {
authenticationStatus := false
admin := false
if username != "" && credentials[username] == password {
authenticationStatus = true
if isUserAdmin(username) {
admin = true
}
}
return authenticationStatus, admin
}
func isUserAdmin(username string) bool {
if username == "admin" {
return true
}
return false
}
//GenerateJWT - Generates a JWT token using
func GenerateJWT(claimsInp ClaimsInp) string {
token := jwt.New(jwt.SigningMethodHS256)
claims := token.Claims.(jwt.MapClaims)
claims["admin"] = claimsInp.IsAdmin
claims["name"] = claimsInp.Name
claims["exp"] = time.Now().Add(time.Hour * 24).Unix()
tokenString, _ := token.SignedString(SigningKey)
return tokenString
}
//SkipJWTAuthentication - Skipper function to skip JWT Auth
func SkipJWTAuthentication(c echo.Context) bool {
skipAuth := strings.HasSuffix(c.Path(), "/login")
skipAuth = skipAuth && c.Request().Method == "GET"
return skipAuth
}