-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.go
46 lines (39 loc) · 1.23 KB
/
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
package http
import (
"context"
"time"
"github.com/AnkushJadhav/kamaji-root/pkg/utils"
"github.com/dgrijalva/jwt-go"
jwtware "github.com/gofiber/jwt"
)
// EnableJWTAuthentication enables JWT authentication on all routes added to the server
// after calling this function and persists the secret in the store
func (srv *Server) EnableJWTAuthentication() error {
jwtSecret := generateJWTSecret()
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
defer cancel()
if err := srv.config.StorageDriver.SetJWTToken(ctx, jwtSecret); err != nil {
return err
}
srv.config.JWTSecret = jwtSecret
srv.app.Use(jwtware.New(jwtware.Config{
SigningKey: []byte(jwtSecret),
// Signing method should always be explicitly mentioned
SigningMethod: jwt.SigningMethodHS256.Alg(),
}))
return nil
}
func generateJWTSecret() string {
return utils.GenerateUUID()
}
func (srv *Server) getJWTForUser(id string) (string, error) {
claims := jwt.StandardClaims{
Issuer: "kamaji-root",
Audience: "kamaji-root",
IssuedAt: time.Now().Unix(),
Subject: id,
ExpiresAt: time.Now().Add(24 * time.Hour).Unix(),
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
return token.SignedString([]byte(srv.config.JWTSecret))
}