Skip to content

Commit 3f14ec4

Browse files
Completed env loading and added it to main file
1 parent c8b7bc0 commit 3f14ec4

File tree

6 files changed

+87
-19
lines changed

6 files changed

+87
-19
lines changed

api/middleware/middleware.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
package middleware

cmd/laclm/main.go

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -26,18 +26,24 @@ func exec() error {
2626

2727
/* exec() wraps run() protecting it with user interrupts */
2828

29+
/* zap.L() can be used all over the code for global level logging */
30+
zap.L().Info("Logger Initiated ...")
31+
2932
/*
3033
load config file
3134
if there is an error in loading the config file, then it will exit with code 1
3235
*/
3336
config.LoadConfig("./config.yaml")
3437

38+
/*
39+
load environment variables
40+
if there is an error or environment variables are not set, then it will exit with code 1
41+
*/
42+
config.LoadEnv()
43+
3544
/* true for production, false for development mode */
3645
utils.InitLogger(false)
3746

38-
/* zap.L() can be used all over the code for global level logging */
39-
zap.L().Info("Logger Initiated ...")
40-
4147
ctx, cancel := context.WithCancel(context.Background())
4248
defer cancel()
4349

@@ -55,6 +61,8 @@ func exec() error {
5561
func run(ctx context.Context) error {
5662
var err error
5763

64+
/* complete backend system must initiate before http server starts */
65+
5866
/* setting up http mux and routes */
5967
mux := http.NewServeMux()
6068

@@ -105,5 +113,7 @@ func run(ctx context.Context) error {
105113

106114
zap.L().Info("HTTP server stopped")
107115

116+
/* after the http server is stopped, rest of the components can be shutdown */
117+
108118
return err
109119
}

config/loader.go

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -11,30 +11,30 @@ import (
1111
func LoadConfig(path string) {
1212

1313
/* read the yaml config file */
14-
data, err := os.ReadFile(path)
15-
if err != nil {
16-
zap.L().Fatal("Failed to read config file",
14+
data, err := os.ReadFile(path)
15+
if err != nil {
16+
zap.L().Fatal("Failed to read config file",
1717
zap.Error(err),
1818
)
19-
}
19+
}
2020

2121
/* unmarshal the yaml file to defined struct */
22-
err = yaml.Unmarshal(data, &BackendConfig)
23-
if err != nil {
24-
zap.L().Fatal("Failed to parse YAML config",
22+
err = yaml.Unmarshal(data, &BackendConfig)
23+
if err != nil {
24+
zap.L().Fatal("Failed to parse YAML config",
2525
zap.Error(err),
2626
)
27-
}
27+
}
2828
}
2929

3030
/* loads environment variables */
3131
func LoadEnv() {
3232

3333
/* get the JWT_SECRET_KEY from environment variable */
3434
secret := os.Getenv("JWT_SECRET_KEY")
35-
if secret == "" {
36-
zap.L().Fatal("JWT_SECRET_KEY environment variable not set")
37-
}
38-
35+
if secret == "" {
36+
zap.L().Fatal("JWT_SECRET_KEY environment variable not set")
37+
}
38+
3939
EnvConfig.JWTSecret = secret
4040
}

internal/authentication/authentication.go

Lines changed: 60 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,13 @@
11
package authentication
22

33
import (
4+
"fmt"
45
"time"
6+
"net/http"
7+
"strings"
58

6-
"github.com/PythonHacker24/linux-acl-management-backend/config"
79
"github.com/golang-jwt/jwt/v5"
10+
"github.com/PythonHacker24/linux-acl-management-backend/config"
811
)
912

1013
/* generating jwt token for user identification with specified configs */
@@ -21,3 +24,59 @@ func GenerateJWT(username string) (string, error) {
2124

2225
return token.SignedString([]byte(config.EnvConfig.JWTSecret))
2326
}
27+
28+
/* validate JWT token and return claims */
29+
func ValidateJWT(tokenString string) (jwt.MapClaims, error) {
30+
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
31+
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
32+
return nil, fmt.Errorf("unexpected signing method")
33+
}
34+
return config.EnvConfig.JWTSecret, nil
35+
})
36+
37+
if err != nil {
38+
return nil, err
39+
}
40+
41+
if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
42+
return claims, nil
43+
}
44+
45+
return nil, fmt.Errorf("invalid token")
46+
}
47+
48+
/* extracts username from JWT token */
49+
func GetUsernameFromJWT(tokenString string) (string, error) {
50+
51+
/* get claims from JWT Token */
52+
claims, err := ValidateJWT(tokenString)
53+
if err != nil {
54+
return "", fmt.Errorf("invalid token: %v", err)
55+
}
56+
57+
/* extract username from JWT Token */
58+
username, ok := claims["username"].(string)
59+
if !ok {
60+
return "", fmt.Errorf("username not found in token")
61+
}
62+
63+
return username, nil
64+
}
65+
66+
/* extract username from http request (wrapper around GetUsernameFromJWT for http requests) */
67+
func ExtractUsernameFromRequest(r *http.Request) (string, error) {
68+
69+
/* extract authentication hearder from http request */
70+
authHeader := r.Header.Get("Authorization")
71+
if authHeader == "" {
72+
return "", fmt.Errorf("missing Authorization header")
73+
}
74+
75+
/* parse the token from the header */
76+
tokenParts := strings.Split(authHeader, " ")
77+
if len(tokenParts) != 2 || tokenParts[0] != "Bearer" {
78+
return "", fmt.Errorf("invalid Authorization header format")
79+
}
80+
81+
return GetUsernameFromJWT(tokenParts[1])
82+
}

internal/models/models.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,9 +36,9 @@ type Logging struct {
3636

3737
/* file system server parameters */
3838
type FileSystemServers struct {
39+
Remote *Remote `yaml:"remote"`
3940
Path string `yaml:"path"`
4041
Method string `yaml:"method"`
41-
Remote *Remote `yaml:"remote"`
4242
}
4343

4444
/* remote parameters for file system server with laclm daemons installed */

internal/utils/utils.go

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,6 @@ import (
88
"go.uber.org/zap"
99
"go.uber.org/zap/zapcore"
1010
"gopkg.in/natefinch/lumberjack.v2"
11-
12-
"github.com/PythonHacker24/linux-acl-management-backend/internal/models"
1311
)
1412

1513
var (

0 commit comments

Comments
 (0)