feat: add auth middleware
This commit is contained in:
parent
7d16707a28
commit
990d6d30b9
3 changed files with 64 additions and 8 deletions
49
internal/middleware/auth.go
Normal file
49
internal/middleware/auth.go
Normal file
|
@ -0,0 +1,49 @@
|
|||
package middleware
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"git.wh64.net/devproje/kuma-archive/internal/service"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func BasicAuth(ctx *gin.Context) {
|
||||
var matches = false
|
||||
var list = []string{"/settings"}
|
||||
|
||||
for _, i := range list {
|
||||
if !strings.Contains(ctx.Request.URL.Path, i) {
|
||||
continue
|
||||
}
|
||||
|
||||
matches = true
|
||||
}
|
||||
|
||||
if !matches {
|
||||
ctx.Next()
|
||||
return
|
||||
}
|
||||
|
||||
auth := service.NewAuthService()
|
||||
username, password, ok := ctx.Request.BasicAuth()
|
||||
if !ok {
|
||||
ctx.Status(403)
|
||||
return
|
||||
}
|
||||
|
||||
ok, err := auth.VerifyToken(username, password)
|
||||
if err != nil {
|
||||
ctx.Status(500)
|
||||
_, _ = fmt.Fprintln(os.Stderr, err)
|
||||
return
|
||||
}
|
||||
|
||||
if !ok {
|
||||
ctx.Status(403)
|
||||
return
|
||||
}
|
||||
|
||||
ctx.Next()
|
||||
}
|
|
@ -63,24 +63,30 @@ func authentication(group *gin.RouterGroup) {
|
|||
ctx.Status(200)
|
||||
})
|
||||
|
||||
// TODO: change to middleware soon
|
||||
group.GET("/check", func(ctx *gin.Context) {
|
||||
group.DELETE("/delete", func(ctx *gin.Context) {
|
||||
auth := service.NewAuthService()
|
||||
username, password, ok := ctx.Request.BasicAuth()
|
||||
pass := ctx.PostForm("password")
|
||||
username, _, ok := ctx.Request.BasicAuth()
|
||||
if !ok {
|
||||
ctx.Status(401)
|
||||
ctx.Status(403)
|
||||
return
|
||||
}
|
||||
|
||||
validate, err := auth.VerifyToken(username, password)
|
||||
ok, err := auth.Verify(username, pass)
|
||||
if err != nil {
|
||||
ctx.Status(500)
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
_, _ = fmt.Fprintln(os.Stderr, err)
|
||||
return
|
||||
}
|
||||
|
||||
if !validate {
|
||||
ctx.Status(401)
|
||||
if !ok {
|
||||
ctx.Status(403)
|
||||
return
|
||||
}
|
||||
|
||||
if err = auth.Delete(username); err != nil {
|
||||
ctx.Status(500)
|
||||
_, _ = fmt.Fprintln(os.Stderr, err)
|
||||
return
|
||||
}
|
||||
|
||||
|
|
|
@ -13,6 +13,7 @@ import (
|
|||
|
||||
func New(app *gin.Engine, version *service.Version, apiOnly bool) {
|
||||
app.Use(middleware.CORS)
|
||||
app.Use(middleware.BasicAuth)
|
||||
|
||||
api := app.Group("/api")
|
||||
{
|
||||
|
|
Loading…
Reference in a new issue