Skip to content

Commit

Permalink
Package Router:
Browse files Browse the repository at this point in the history
- rework to apply standard hierarchy
- move auth to dedicated sub package
- move header to dedicated sub package

Package Static:
- fix bugs
  • Loading branch information
nabbar committed Dec 2, 2023
1 parent 4a47f39 commit 824f9cc
Show file tree
Hide file tree
Showing 21 changed files with 668 additions and 383 deletions.
2 changes: 1 addition & 1 deletion config/components/head/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@
package head

import (
librtr "github.com/nabbar/golib/router"
librtr "github.com/nabbar/golib/router/header"
spfcbr "github.com/spf13/cobra"
spfvpr "github.com/spf13/viper"
)
Expand Down
3 changes: 2 additions & 1 deletion config/components/head/interface.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,10 @@ package head
import (
"sync"

librtr "github.com/nabbar/golib/router/header"

libcfg "github.com/nabbar/golib/config"
cfgtps "github.com/nabbar/golib/config/types"
librtr "github.com/nabbar/golib/router"
)

type ComponentHead interface {
Expand Down
3 changes: 2 additions & 1 deletion config/components/head/model.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,9 @@ package head
import (
"sync"

librtr "github.com/nabbar/golib/router/header"

libctx "github.com/nabbar/golib/context"
librtr "github.com/nabbar/golib/router"
)

type componentHead struct {
Expand Down
1 change: 0 additions & 1 deletion prometheus/interface.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,6 @@ import (
"sync"

ginsdk "github.com/gin-gonic/gin"

libctx "github.com/nabbar/golib/context"
libmet "github.com/nabbar/golib/prometheus/metrics"
prmpol "github.com/nabbar/golib/prometheus/pool"
Expand Down
48 changes: 48 additions & 0 deletions router/auth/interface.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
/*
* MIT License
*
* Copyright (c) 2019 Nicolas JUHEL
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/

package auth

import (
ginsdk "github.com/gin-gonic/gin"
liberr "github.com/nabbar/golib/errors"
liblog "github.com/nabbar/golib/logger"
rtrhdr "github.com/nabbar/golib/router/authheader"
)

type Authorization interface {
Handler(c *ginsdk.Context)
Register(router ...ginsdk.HandlerFunc) ginsdk.HandlerFunc
Append(router ...ginsdk.HandlerFunc)
}

func NewAuthorization(log liblog.FuncLog, HeadAuthType string, authCheckFunc func(AuthHeader string) (rtrhdr.AuthCode, liberr.Error)) Authorization {
return &authorization{
log: log,
check: authCheckFunc,
authType: HeadAuthType,
router: make([]ginsdk.HandlerFunc, 0),
}
}
78 changes: 14 additions & 64 deletions router/auth.go → router/auth/model.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,78 +23,28 @@
*
*/

package router
package auth

import (
"fmt"
"net/http"
"strings"

liblog "github.com/nabbar/golib/logger"

ginsdk "github.com/gin-gonic/gin"
liberr "github.com/nabbar/golib/errors"
liblog "github.com/nabbar/golib/logger"
loglvl "github.com/nabbar/golib/logger/level"
librtr "github.com/nabbar/golib/router"
rtrhdr "github.com/nabbar/golib/router/authheader"
)

type AuthCode uint8

const (
AUTH_CODE_SUCCESS = iota
AUTH_CODE_REQUIRE
AUTH_CODE_FORBIDDEN
)

const (
HEAD_AUTH_REQR = "WWW-Authenticate"
HEAD_AUTH_SEND = "Authorization"
HEAD_AUTH_REAL = "Basic realm=LDAP Authorization Required"
)

func AuthRequire(c *ginsdk.Context, err error) {
if err != nil {
c.Errors = append(c.Errors, &ginsdk.Error{
Err: err,
Type: ginsdk.ErrorTypePrivate,
})
}
// Credentials doesn't match, we return 401 and abort handlers chain.
c.Header(HEAD_AUTH_REQR, HEAD_AUTH_REAL)
c.AbortWithStatus(http.StatusUnauthorized)
}

func AuthForbidden(c *ginsdk.Context, err error) {
if err != nil {
c.Errors = append(c.Errors, &ginsdk.Error{
Err: err,
Type: ginsdk.ErrorTypePrivate,
})
}
c.AbortWithStatus(http.StatusForbidden)
}

type authorization struct {
log liblog.FuncLog
check func(AuthHeader string) (AuthCode, liberr.Error)
check func(AuthHeader string) (rtrhdr.AuthCode, liberr.Error)
router []ginsdk.HandlerFunc
authType string
}

type Authorization interface {
Handler(c *ginsdk.Context)
Register(router ...ginsdk.HandlerFunc) ginsdk.HandlerFunc
Append(router ...ginsdk.HandlerFunc)
}

func NewAuthorization(log liblog.FuncLog, HeadAuthType string, authCheckFunc func(AuthHeader string) (AuthCode, liberr.Error)) Authorization {
return &authorization{
log: log,
check: authCheckFunc,
authType: HeadAuthType,
router: make([]ginsdk.HandlerFunc, 0),
}
}

func (a *authorization) Register(router ...ginsdk.HandlerFunc) ginsdk.HandlerFunc {
a.router = router
return a.Handler
Expand All @@ -112,10 +62,10 @@ func (a *authorization) logDebug(msg string, args ...interface{}) {

func (a *authorization) Handler(c *ginsdk.Context) {
// Search user in the slice of allowed credentials
auth := c.Request.Header.Get(HEAD_AUTH_SEND)
auth := c.Request.Header.Get(rtrhdr.HeaderAuthSend)

if auth == "" {
AuthRequire(c, fmt.Errorf("%v", ErrorHeaderAuthMissing.Error(nil).GetErrorSlice()))
rtrhdr.AuthRequire(c, fmt.Errorf("%v", librtr.ErrorHeaderAuthMissing.Error(nil).GetErrorSlice()))
return
}

Expand All @@ -129,24 +79,24 @@ func (a *authorization) Handler(c *ginsdk.Context) {
}

if authValue == "" {
AuthRequire(c, fmt.Errorf("%v", ErrorHeaderAuthEmpty.Error(nil).GetErrorSlice()))
rtrhdr.AuthRequire(c, fmt.Errorf("%v", librtr.ErrorHeaderAuthEmpty.Error(nil).GetErrorSlice()))
return
} else {
code, err := a.check(authValue)

switch code {
case AUTH_CODE_SUCCESS:
case rtrhdr.AuthCodeSuccess:
for _, r := range a.router {
a.logDebug("Calling router '%s=%s'", c.Request.Method, c.Request.URL.RawPath)
r(c)
}
case AUTH_CODE_REQUIRE:
AuthRequire(c, fmt.Errorf("%v", ErrorHeaderAuthRequire.Error(err).GetErrorSlice()))
case AUTH_CODE_FORBIDDEN:
AuthForbidden(c, fmt.Errorf("%v", ErrorHeaderAuthForbidden.Error(err).GetErrorSlice()))
case rtrhdr.AuthCodeRequire:
rtrhdr.AuthRequire(c, fmt.Errorf("%v", librtr.ErrorHeaderAuthRequire.Error(err).GetErrorSlice()))
case rtrhdr.AuthCodeForbidden:
rtrhdr.AuthForbidden(c, fmt.Errorf("%v", librtr.ErrorHeaderAuthForbidden.Error(err).GetErrorSlice()))
default:
c.Errors = append(c.Errors, &ginsdk.Error{
Err: fmt.Errorf("%v", ErrorHeaderAuth.Error(err).GetErrorSlice()),
Err: fmt.Errorf("%v", librtr.ErrorHeaderAuth.Error(err).GetErrorSlice()),
Type: ginsdk.ErrorTypePrivate,
})
c.AbortWithStatus(http.StatusInternalServerError)
Expand Down
68 changes: 68 additions & 0 deletions router/authheader/interface.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
/*
* MIT License
*
* Copyright (c) 2019 Nicolas JUHEL
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/

package authheader

import (
"net/http"

ginsdk "github.com/gin-gonic/gin"
)

type AuthCode uint8

const (
AuthCodeSuccess = iota
AuthCodeRequire
AuthCodeForbidden
)

const (
HeaderAuthRequire = "WWW-Authenticate"
HeaderAuthSend = "Authorization"
HeaderAuthReal = "Basic realm=LDAP Authorization Required"
)

func AuthRequire(c *ginsdk.Context, err error) {
if err != nil {
c.Errors = append(c.Errors, &ginsdk.Error{
Err: err,
Type: ginsdk.ErrorTypePrivate,
})
}
// Credentials doesn't match, we return 401 and abort handlers chain.
c.Header(HeaderAuthRequire, HeaderAuthReal)
c.AbortWithStatus(http.StatusUnauthorized)
}

func AuthForbidden(c *ginsdk.Context, err error) {
if err != nil {
c.Errors = append(c.Errors, &ginsdk.Error{
Err: err,
Type: ginsdk.ErrorTypePrivate,
})
}
c.AbortWithStatus(http.StatusForbidden)
}
109 changes: 109 additions & 0 deletions router/default.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
/*
* MIT License
*
* Copyright (c) 2019 Nicolas JUHEL
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/

package router

import (
"net/http"

ginsdk "github.com/gin-gonic/gin"
)

func DefaultGinInit() *ginsdk.Engine {
engine := ginsdk.New()
engine.Use(ginsdk.Logger(), ginsdk.Recovery())

return engine
}

func DefaultGinWithTrustyProxy(trustyProxy []string) *ginsdk.Engine {
engine := ginsdk.New()
engine.Use(ginsdk.Logger(), ginsdk.Recovery())

if len(trustyProxy) > 0 {
_ = engine.SetTrustedProxies(trustyProxy)
}

return engine
}

func DefaultGinWithTrustedPlatform(trustedPlatform string) *ginsdk.Engine {
engine := ginsdk.New()
engine.Use(ginsdk.Logger(), ginsdk.Recovery())

if len(trustedPlatform) > 0 {
engine.TrustedPlatform = trustedPlatform
}

return engine
}

func RoutersRegister(method string, relativePath string, router ...ginsdk.HandlerFunc) {
defaultRouters.Register(method, relativePath, router...)
}

func RoutersRegisterInGroup(group, method string, relativePath string, router ...ginsdk.HandlerFunc) {
defaultRouters.RegisterInGroup(group, method, relativePath, router...)
}

func RoutersHandler(engine *ginsdk.Engine) {
defaultRouters.Handler(engine)
}

func GinEngine(trustedPlatform string, trustyProxy ...string) (*ginsdk.Engine, error) {
var err error

engine := ginsdk.New()
if len(trustyProxy) > 0 {
err = engine.SetTrustedProxies(trustyProxy)
}
if len(trustedPlatform) > 0 {
engine.TrustedPlatform = trustedPlatform
}

return engine, err
}

func GinAddGlobalMiddleware(eng *ginsdk.Engine, middleware ...ginsdk.HandlerFunc) *ginsdk.Engine {
eng.Use(middleware...)
return eng
}

// SetGinHandler func that return given func as ginTonic HandlerFunc interface type.
func SetGinHandler(fct func(c *ginsdk.Context)) ginsdk.HandlerFunc {
return fct
}

func Handler(routerList RouterList) http.Handler {
e := routerList.Engine()

if routerList == nil {
RoutersHandler(e)
} else {
routerList.Handler(e)
}

return e
}
Loading

0 comments on commit 824f9cc

Please sign in to comment.