Skip to content

Commit

Permalink
Merge pull request #17 from KordonDev/15/authentication
Browse files Browse the repository at this point in the history
Check and set token
  • Loading branch information
KordonDev authored Dec 4, 2022
2 parents 20a90d8 + bbb8736 commit 027bbea
Show file tree
Hide file tree
Showing 7 changed files with 48 additions and 48 deletions.
1 change: 1 addition & 0 deletions config.yml
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
debug: false
domain: localhost
origin: http://localhost:5173
jwtSecret: changeMe
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ require (
github.com/mattn/go-runewidth v0.0.12 // indirect
github.com/mattn/go-sqlite3 v1.14.15 // indirect
github.com/matttproud/golang_protobuf_extensions v1.0.1 // indirect
github.com/mitchellh/mapstructure v1.1.2 // indirect
github.com/mitchellh/mapstructure v1.5.0 // indirect
github.com/olekukonko/tablewriter v0.0.5 // indirect
github.com/prometheus/client_golang v1.10.0 // indirect
github.com/prometheus/client_model v0.2.0 // indirect
Expand Down
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -655,6 +655,8 @@ github.com/mitchellh/mapstructure v0.0.0-20160808181253-ca63d7c062ee/go.mod h1:F
github.com/mitchellh/mapstructure v0.0.0-20180220230111-00c29f56e238/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y=
github.com/mitchellh/mapstructure v1.1.2 h1:fmNYVwqnSfB9mZU6OS2O6GsXM+wcskZDuKQzvN1EDeE=
github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y=
github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY=
github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo=
github.com/mitchellh/reflectwalk v1.0.0/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw=
github.com/mitchellh/reflectwalk v1.0.1/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw=
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
Expand Down
28 changes: 15 additions & 13 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,17 @@ func main() {

db := createDB(config.Debug)

jwtService := security.JWTAuthService(config.Origin, config.JwtSecret)
userDB := security.NewUserDB(db)
webAuthNService := security.NewWebAuthNService(userDB, config.Origin, config.Domain, jwtService)
api.GET("/register/:username", webAuthNService.StartRegister)
api.POST("/register/:username", webAuthNService.FinishRegistration)
api.GET("/login/:username", webAuthNService.StartLogin)
api.POST("/login/:username", webAuthNService.FinishLogin)
api.POST("/logout", webAuthNService.Logout)

api.Use(security.AuthorizeJWTMiddleware(config.Domain, jwtService))

memberDB := members.NewMemberDB(db)
memberService := members.NewMemberService(memberDB)
membersRoute := api.Group("/members")
Expand All @@ -42,16 +53,6 @@ func main() {
membersRoute.PUT("/:id", memberService.UpdateMember)
membersRoute.DELETE("/:id", memberService.DeleteById)

userDB := security.NewUserDB(db)
webAuthNService := security.NewWebAuthNService(userDB, config.Origin, config.Domain)

api.GET("/register/:username", webAuthNService.StartRegister)
api.POST("/register/:username", webAuthNService.FinishRegistration)

api.GET("/login/:username", webAuthNService.StartLogin)
api.POST("/login/:username", webAuthNService.FinishLogin)
api.POST("/logout", webAuthNService.Logout)

router.Run(fmt.Sprintf("%s:8080", config.Domain))
}

Expand All @@ -77,9 +78,10 @@ func createDB(debug bool) *gorm.DB {
}

type Config struct {
Debug bool
Domain string
Origin string
Debug bool
Domain string
Origin string
JwtSecret string
}

func parseConfig() *Config {
Expand Down
11 changes: 6 additions & 5 deletions security/AuthorizationMiddleware.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,10 @@ import (
"net/http"
"strings"

"github.com/dgrijalva/jwt-go"
"github.com/gin-gonic/gin"
)

func AuthorizeJWTMiddleware() gin.HandlerFunc {
func AuthorizeJWTMiddleware(domain string, jwtService *JwtService) gin.HandlerFunc {
return func(c *gin.Context) {

var jwtCookie string
Expand All @@ -22,10 +21,12 @@ func AuthorizeJWTMiddleware() gin.HandlerFunc {
}

if len(jwtCookie) > 0 {
token, err := JWTAuthService().ValidateToken(jwtCookie)
token, err := jwtService.ValidateToken(jwtCookie)
if token.Valid {
claims := token.Claims.(jwt.MapClaims)
fmt.Println(claims)
jwtData := jwtService.GetClaims(token)

newToken := jwtService.GenerateToken(jwtData.Name, jwtData.IsUser)
c.SetCookie(AUTHORIZATION_COOKIE_KEY, newToken, 60*100, "/", domain, true, true)
} else {
fmt.Println(err)

Expand Down
46 changes: 21 additions & 25 deletions security/JWTAuthentication.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,46 +2,33 @@ package security

import (
"fmt"
"os"
"time"

"github.com/dgrijalva/jwt-go"
"github.com/mitchellh/mapstructure"
)

// jwt service
type JWTService interface {
GenerateToken(email string, isUser bool) string
ValidateToken(token string) (*jwt.Token, error)
}
type authCustomClaims struct {
Name string `json:"name"`
User bool `json:"user"`
type AuthCustomClaims struct {
Name string `json:"name"`
IsUser bool `json:"isUser"`
jwt.StandardClaims
}

type jwtServices struct {
type JwtService struct {
secretKey string
issure string
}

// auth-jwt
func JWTAuthService() JWTService {
return &jwtServices{
secretKey: getSecretKey(),
issure: "kordon",
}
}

func getSecretKey() string {
secret := os.Getenv("SECRET")
if secret == "" {
secret = "secret"
func JWTAuthService(origin string, jwtSecret string) *JwtService {
return &JwtService{
secretKey: jwtSecret,
issure: origin,
}
return secret
}

func (service *jwtServices) GenerateToken(email string, isUser bool) string {
claims := &authCustomClaims{
func (service *JwtService) GenerateToken(email string, isUser bool) string {
claims := &AuthCustomClaims{
email,
isUser,
jwt.StandardClaims{
Expand All @@ -60,7 +47,7 @@ func (service *jwtServices) GenerateToken(email string, isUser bool) string {
return t
}

func (service *jwtServices) ValidateToken(encodedToken string) (*jwt.Token, error) {
func (service *JwtService) ValidateToken(encodedToken string) (*jwt.Token, error) {
return jwt.Parse(encodedToken, func(token *jwt.Token) (interface{}, error) {
if _, isvalid := token.Method.(*jwt.SigningMethodHMAC); !isvalid {
return nil, fmt.Errorf("invalid token %s", token.Header["alg"])
Expand All @@ -69,3 +56,12 @@ func (service *jwtServices) ValidateToken(encodedToken string) (*jwt.Token, erro
return []byte(service.secretKey), nil
})
}

func (service *JwtService) GetClaims(token *jwt.Token) *AuthCustomClaims {
claims := token.Claims.(jwt.MapClaims)

var jwtData AuthCustomClaims
mapstructure.Decode(claims, &jwtData)

return &jwtData
}
6 changes: 2 additions & 4 deletions security/webauthn.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,14 @@ import (
type WebAuthNService struct {
webAuthn *webauthn.WebAuthn
sessionStore *session.Store
jwtService JWTService
jwtService *JwtService
userDB *userDB
domain string
}

var AUTHORIZATION_COOKIE_KEY = "Authorization"

func NewWebAuthNService(userDB *userDB, origin string, domain string) *WebAuthNService {
func NewWebAuthNService(userDB *userDB, origin string, domain string, jwtService *JwtService) *WebAuthNService {
var err error
webAuthn, err := webauthn.New(&webauthn.Config{
RPDisplayName: "equipment watchdog", // Display Name for your site
Expand All @@ -37,8 +37,6 @@ func NewWebAuthNService(userDB *userDB, origin string, domain string) *WebAuthNS
log.Fatal("Error creating sessionStore", err)
}

jwtService := JWTAuthService()

return &WebAuthNService{webAuthn: webAuthn, sessionStore: sessionStore, jwtService: jwtService, userDB: userDB, domain: domain}
}

Expand Down

0 comments on commit 027bbea

Please sign in to comment.