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

refactor: optimize get basic username and password from gin headers #67

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
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
15 changes: 4 additions & 11 deletions internal/pkg/middleware/auth/basic.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,6 @@
package auth

import (
"encoding/base64"
"strings"

"github.com/gin-gonic/gin"
"github.com/marmotedu/component-base/pkg/core"
"github.com/marmotedu/errors"
Expand All @@ -33,9 +30,8 @@ func NewBasicStrategy(compare func(username string, password string) bool) Basic
// AuthFunc defines basic strategy as the gin authentication middleware.
func (b BasicStrategy) AuthFunc() gin.HandlerFunc {
return func(c *gin.Context) {
auth := strings.SplitN(c.Request.Header.Get("Authorization"), " ", 2)

if len(auth) != 2 || auth[0] != "Basic" {
username, password, ok := c.Request.BasicAuth()
if !ok {
core.WriteResponse(
c,
errors.WithCode(code.ErrSignatureInvalid, "Authorization header format is wrong."),
Expand All @@ -46,10 +42,7 @@ func (b BasicStrategy) AuthFunc() gin.HandlerFunc {
return
}

payload, _ := base64.StdEncoding.DecodeString(auth[1])
pair := strings.SplitN(string(payload), ":", 2)

if len(pair) != 2 || !b.compare(pair[0], pair[1]) {
if !b.compare(username, password) {
core.WriteResponse(
c,
errors.WithCode(code.ErrSignatureInvalid, "Authorization header format is wrong."),
Expand All @@ -60,7 +53,7 @@ func (b BasicStrategy) AuthFunc() gin.HandlerFunc {
return
}

c.Set(middleware.UsernameKey, pair[0])
c.Set(middleware.UsernameKey, username)

c.Next()
}
Expand Down