Skip to content

Commit

Permalink
delete: doLogin を削除
Browse files Browse the repository at this point in the history
  • Loading branch information
K-shir0 committed Nov 12, 2023
1 parent 71068b6 commit 56d4b15
Showing 1 changed file with 3 additions and 84 deletions.
87 changes: 3 additions & 84 deletions client.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,26 +2,20 @@ package growi_client

import (
"encoding/json"
"errors"
"github.com/ictsc/growi_client/entity"
"golang.org/x/net/html"
"io/ioutil"
"net/http"
"net/http/cookiejar"
"net/url"
"strings"
)

type Client interface {
Init() error
GetSubordinatedPage(path string) ([]entity.SubordinatedPage, error)
GetPage(path string) (*entity.Page, error)
}

type GrowiClientOption struct {
URL *url.URL
Username string
Password string
AccessToken string
}

Expand All @@ -34,20 +28,12 @@ var client *http.Client

var _ Client = (*GrowiClient)(nil)

func (c *GrowiClient) Init() error {
func NewGrowiClient(option *GrowiClientOption) *GrowiClient {
client = &http.Client{}
client.Jar = c.Jar

csrfToken, err := getCsrfToken(*c.Option.URL, *client)
if err != nil {
return errors.New("failed to get csrf token")
}
err = doLogin(*c.Option.URL, *client, c.Option.Username, c.Option.Password, csrfToken)
if err != nil {
return errors.New("failed to login")
return &GrowiClient{
Option: option,
}

return nil
}

type SubordinatedPagesResponse struct {
Expand Down Expand Up @@ -127,70 +113,3 @@ func (c *GrowiClient) GetPage(path string) (*entity.Page, error) {

return &pageResponse.Page, nil
}

// getCsrfToken は CSRF Token を取得する
func getCsrfToken(u url.URL, client http.Client) (string, error) {
u.Path = "/login"

req, err := http.NewRequest("GET", u.String(), nil)
if err != nil {
return "", err
}

resp, err := client.Do(req)
if err != nil {
return "", err
}
defer resp.Body.Close()

body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", err
}

node, err := html.Parse(strings.NewReader(string(body)))
if err != nil {
return "", err
}

// html > body attr の中から csrfToken を取得
for c := node.FirstChild; c != nil; c = c.NextSibling {
if c.Type == html.ElementNode && c.Data == "html" {
for d := c.FirstChild; d != nil; d = d.NextSibling {
if d.Data == "body" {
for _, attr := range d.Attr {
if attr.Key == "data-csrftoken" {
return attr.Val, nil
}
}
}
}
}
}

return "", nil
}

func doLogin(u url.URL, client http.Client, username string, password string, csrfToken string) error {
u.Path = "/login"

form := url.Values{}
form.Add("loginForm[username]", username)
form.Add("loginForm[password]", password)
form.Add("_csrf", csrfToken)

req, err := http.NewRequest("POST", u.String(), strings.NewReader(form.Encode()))
if err != nil {
return err
}

req.Header.Set("Content-Type", "application/x-www-form-urlencoded")

resp, err := client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()

return nil
}

0 comments on commit 56d4b15

Please sign in to comment.