Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: gen staff token #32

Merged
merged 3 commits into from
Jan 11, 2024
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
@@ -14,3 +14,5 @@ OAUTH2_REDIRECT_URL=http://localhost:3000/auth/callback
OAUTH2_SCOPES=openid,email

CORS_ORIGINS=https://openhouse.chula.ac.th,https://isd-sgcu.in.th,https://openhouse.isd-sgcu.in.th

JWT_SECRET_KEY=secret
14 changes: 14 additions & 0 deletions cfgldr/cfgldr.go
Original file line number Diff line number Diff line change
@@ -9,6 +9,7 @@ type Config struct {
AppConfig AppConfig
RedisConfig RedisConfig
OAuth2Config OAuth2Config
JWTConfig JWTConfig
CorsConfig CorsConfig
}

@@ -34,6 +35,9 @@ type OAuth2Config struct {
ClientSecret string `mapstructure:"CLIENT_SECRET"`
Scopes []string `mapstructure:"SCOPES"`
}
type JWTConfig struct {
SecretKey string `mapstructure:"SECRET_KEY"`
}

type CorsConfig struct {
AllowOrigins string `mapstructure:"ORIGINS"`
@@ -76,6 +80,15 @@ func LoadConfig() (*Config, error) {
return nil, err
}

jwtCfgLdr := viper.New()
jwtCfgLdr.SetEnvPrefix("JWT")
jwtCfgLdr.AutomaticEnv()
jwtCfgLdr.AllowEmptyEnv(false)
jwtConfig := JWTConfig{}
if err := jwtCfgLdr.Unmarshal(&jwtConfig); err != nil {
return nil, err
}

corsConfigLdr := viper.New()
corsConfigLdr.SetEnvPrefix("CORS")
corsConfigLdr.AutomaticEnv()
@@ -90,6 +103,7 @@ func LoadConfig() (*Config, error) {
AppConfig: appConfig,
RedisConfig: redisConfig,
OAuth2Config: oauth2Config,
JWTConfig: jwtConfig,
CorsConfig: corsConfig,
}, nil
}
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
@@ -31,6 +31,7 @@ require (
github.com/cespare/xxhash/v2 v2.2.0 // indirect
github.com/chenzhuoyu/base64x v0.0.0-20230717121745-296ad89f973d // indirect
github.com/chenzhuoyu/iasm v0.9.1 // indirect
github.com/dgrijalva/jwt-go v3.2.0+incompatible
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
github.com/felixge/httpsnoop v1.0.4 // indirect
github.com/fsnotify/fsnotify v1.7.0 // indirect
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
@@ -30,6 +30,8 @@ github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSs
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM=
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/dgrijalva/jwt-go v3.2.0+incompatible h1:7qlOGliEKZXTDg6OTjfoBKDXWrumCAMpl/TFQ4/5kLM=
github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ=
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78=
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc=
github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4=
22 changes: 19 additions & 3 deletions internal/middleware/auth.middleware.go
Original file line number Diff line number Diff line change
@@ -3,6 +3,7 @@ package middleware
import (
"strings"

"github.com/dgrijalva/jwt-go"
"github.com/gin-gonic/gin"
"github.com/isd-sgcu/oph66-backend/apperror"
"github.com/isd-sgcu/oph66-backend/cfgldr"
@@ -31,9 +32,24 @@ func NewAuthMiddleware(userRepo auth.Repository, cfg *cfgldr.Config) AuthMiddlew
token, err := idtoken.Validate(c, tokenString, cfg.OAuth2Config.ClientId)

if err != nil {
utils.ReturnError(c, apperror.InvalidToken)
c.Abort()
return
SecretKey := cfg.JWTConfig.SecretKey
tokenStaff, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
AKKatung159 marked this conversation as resolved.
Show resolved Hide resolved
return []byte(SecretKey), nil
})
if err != nil {
utils.ReturnError(c, apperror.InvalidToken)
c.Abort()
return
}
if tokenStaff.Valid && tokenStaff.Claims.(jwt.MapClaims)["role"] == "staff" {
c.Set("department", tokenStaff.Claims.(jwt.MapClaims)["department"])
c.Next()
return
} else {
utils.ReturnError(c, apperror.InvalidToken)
c.Abort()
return
}
}

if email, ok := token.Claims["email"].(string); ok {
44 changes: 44 additions & 0 deletions tools/gen_token_staff.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
package main

import (
"fmt"

"github.com/dgrijalva/jwt-go"
"github.com/isd-sgcu/oph66-backend/apperror"
"github.com/isd-sgcu/oph66-backend/cfgldr"
)

func GenTokenStaff(department string, cfg *cfgldr.Config) (string, *apperror.AppError) {
secretKey := cfg.JWTConfig.SecretKey

claims := jwt.MapClaims{
"role": "staff",
"department": department,
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we need to store to match database format
so it would be
department and faculty. identify using code.

e.g.
department: 0
faculty: 34

}

token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)

tokenString, err := token.SignedString([]byte(secretKey))
if err != nil {
return "", apperror.InternalError
}

return tokenString, nil
}

func main() {
config, err := cfgldr.LoadConfig()
if err != nil {
fmt.Println("Failed to load configuration:", err)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

also here

return
}

department := "IT"
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

accept input from other source i.e. stdin, argv.

token, appErr := GenTokenStaff(department, config)
if appErr != nil {
fmt.Println("Failed to generate JWT token:", appErr)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
fmt.Println("Failed to generate JWT token:", appErr)
fmt.FatalF("Failed to generate JWT token:", appErr) // something I don't remember

return
}

fmt.Println("Generated JWT token for staff in department", department, ":", token)
}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is it possible to make is bash script or something else. Making new main package will likely interrupt with ./... syntax which is used across the project.