add basic auth for webapi

This commit is contained in:
ginuerzh
2022-02-12 21:05:39 +08:00
parent fdd67a6086
commit f2d806886a
12 changed files with 197 additions and 86 deletions

View File

@ -2,51 +2,20 @@ package api
import (
"embed"
"net"
"net/http"
"time"
"github.com/gin-contrib/cors"
"github.com/gin-gonic/gin"
"github.com/go-gost/gost/pkg/config"
"github.com/go-gost/gost/pkg/logger"
)
var (
apiServer = &http.Server{}
//go:embed swagger.yaml
swaggerDoc embed.FS
)
func Init(cfg *config.APIConfig) {
gin.SetMode(gin.ReleaseMode)
func register(r *gin.RouterGroup) {
r.StaticFS("/docs", http.FS(swaggerDoc))
if cfg == nil {
cfg = &config.APIConfig{}
}
r := gin.New()
r.Use(
cors.New((cors.Config{
AllowAllOrigins: true,
AllowMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
AllowHeaders: []string{"*"},
})),
gin.Recovery(),
)
if cfg.AccessLog {
r.Use(loggerHandler)
}
router := r.Group("")
if cfg.PathPrefix != "" {
router = router.Group(cfg.PathPrefix)
}
router.StaticFS("/docs", http.FS(swaggerDoc))
config := router.Group("/config")
config := r.Group("/config")
{
config.GET("", getConfig)
@ -74,30 +43,6 @@ func Init(cfg *config.APIConfig) {
config.PUT("/hosts/:hosts", updateHosts)
config.DELETE("/hosts/:hosts", deleteHosts)
}
apiServer.Handler = r
}
func Run(ln net.Listener) error {
return apiServer.Serve(ln)
}
func loggerHandler(ctx *gin.Context) {
// start time
startTime := time.Now()
// Processing request
ctx.Next()
duration := time.Since(startTime)
logger.Default().WithFields(map[string]interface{}{
"kind": "api",
"method": ctx.Request.Method,
"uri": ctx.Request.RequestURI,
"code": ctx.Writer.Status(),
"client": ctx.ClientIP(),
"duration": duration,
}).Infof("| %3d | %13v | %15s | %-7s %s",
ctx.Writer.Status(), duration, ctx.ClientIP(), ctx.Request.Method, ctx.Request.RequestURI)
}
type Response struct {

View File

@ -54,7 +54,7 @@ func createService(ctx *gin.Context) {
return
}
go svc.Run()
go svc.Serve()
cfg := config.Global()
cfg.Services = append(cfg.Services, &req.Data)
@ -115,7 +115,7 @@ func updateService(ctx *gin.Context) {
return
}
go svc.Run()
go svc.Serve()
cfg := config.Global()
for i := range cfg.Services {

42
pkg/api/middleware.go Normal file
View File

@ -0,0 +1,42 @@
package api
import (
"net/http"
"time"
"github.com/gin-gonic/gin"
"github.com/go-gost/gost/pkg/auth"
"github.com/go-gost/gost/pkg/logger"
)
func mwLogger() gin.HandlerFunc {
return func(ctx *gin.Context) {
// start time
startTime := time.Now()
// Processing request
ctx.Next()
duration := time.Since(startTime)
logger.Default().WithFields(map[string]interface{}{
"kind": "api",
"method": ctx.Request.Method,
"uri": ctx.Request.RequestURI,
"code": ctx.Writer.Status(),
"client": ctx.ClientIP(),
"duration": duration,
}).Infof("| %3d | %13v | %15s | %-7s %s",
ctx.Writer.Status(), duration, ctx.ClientIP(), ctx.Request.Method, ctx.Request.RequestURI)
}
}
func mwBasicAuth(auther auth.Authenticator) gin.HandlerFunc {
return func(c *gin.Context) {
if auther == nil {
return
}
u, p, _ := c.Request.BasicAuth()
if !auther.Authenticate(u, p) {
c.AbortWithStatus(http.StatusUnauthorized)
}
}
}

96
pkg/api/server.go Normal file
View File

@ -0,0 +1,96 @@
package api
import (
"net"
"net/http"
"github.com/gin-contrib/cors"
"github.com/gin-gonic/gin"
"github.com/go-gost/gost/pkg/auth"
)
type options struct {
accessLog bool
pathPrefix string
auther auth.Authenticator
}
type Option func(*options)
func PathPrefixOption(pathPrefix string) Option {
return func(o *options) {
o.pathPrefix = pathPrefix
}
}
func AccessLogOption(enable bool) Option {
return func(o *options) {
o.accessLog = enable
}
}
func AutherOption(auther auth.Authenticator) Option {
return func(o *options) {
o.auther = auther
}
}
type Server struct {
s *http.Server
ln net.Listener
}
func NewServer(addr string, opts ...Option) (*Server, error) {
ln, err := net.Listen("tcp", addr)
if err != nil {
return nil, err
}
var options options
for _, opt := range opts {
opt(&options)
}
gin.SetMode(gin.ReleaseMode)
r := gin.New()
r.Use(
cors.New((cors.Config{
AllowAllOrigins: true,
AllowMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
AllowHeaders: []string{"*"},
})),
gin.Recovery(),
)
if options.accessLog {
r.Use(mwLogger())
}
if options.auther != nil {
r.Use(mwBasicAuth(options.auther))
}
router := r.Group("")
if options.pathPrefix != "" {
router = router.Group(options.pathPrefix)
}
register(router)
return &Server{
s: &http.Server{
Handler: r,
},
ln: ln,
}, nil
}
func (s *Server) Serve() error {
return s.s.Serve(s.ln)
}
func (s *Server) Addr() net.Addr {
return s.ln.Addr()
}
func (s *Server) Close() error {
return s.s.Close()
}