Skip to content

Commit

Permalink
update auth type
Browse files Browse the repository at this point in the history
  • Loading branch information
shijl0925 committed Jun 9, 2024
1 parent af5cfb9 commit 28c2aa9
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 7 deletions.
2 changes: 1 addition & 1 deletion examples/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import (
)

func main() {
client, _ := gerrit.NewClient("https://review.lineageos.org", "", "")
client, _ := gerrit.NewClient("https://review.lineageos.org")

ctx := context.Background()

Expand Down
24 changes: 21 additions & 3 deletions gerrit.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,12 @@ type Gerrit struct {
Config *ConfigService
}

func NewClient(gerritURL string, username string, password string) (*Gerrit, error) {
func NewClient(gerritURL string) (*Gerrit, error) {
client := &http.Client{
Timeout: 15 * time.Second, // 设置超时时间
}

r := &Requester{client: client, username: username, password: password}
r := &Requester{client: client}

if baseURL, err := SetBaseURL(gerritURL); err != nil {
return nil, err
Expand All @@ -41,4 +41,22 @@ func NewClient(gerritURL string, username string, password string) (*Gerrit, err
gerrit.Config = &ConfigService{gerrit: gerrit}

return gerrit, nil
}
}

func (g *Gerrit) SetBasicAuth(username, password string) {
g.Requester.authType = "basic"
g.Requester.username = username
g.Requester.password = password
}

func (g *Gerrit) SetDigestAuth(username, password string) {
g.Requester.authType = "digest"
g.Requester.username = username
g.Requester.password = password
}

func (g *Gerrit) SetCookieAuth(username, password string) {
g.Requester.authType = "cookie"
g.Requester.username = username
g.Requester.password = password
}
13 changes: 10 additions & 3 deletions request.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,13 +19,13 @@ type Requester struct {
baseURL *url.URL

// Gerrit service for authentication.
username, password string
username, password, authType string
}

func (r *Requester) NewRequest(ctx context.Context, method, endpoint string, opt interface{}) (*http.Request, error) {
hasAuth := false

if len(r.username) != 0 && len(r.password) != 0 {
if len(r.authType) != 0 {
hasAuth = true
}

Expand Down Expand Up @@ -74,7 +74,14 @@ func (r *Requester) NewRequest(ctx context.Context, method, endpoint string, opt

// Apply Authentication
if hasAuth {
req.SetBasicAuth(r.username, r.password)
switch r.authType {
case "cookie":
req.AddCookie(&http.Cookie{Name: r.username, Value: r.password})
case "digest":
// todo
default:
req.SetBasicAuth(r.username, r.password)
}
}

// Request compact JSON
Expand Down

0 comments on commit 28c2aa9

Please sign in to comment.