...

Source file src/jschan/app/auth.go

Documentation: jschan/app

     1  package jschan
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"net/http"
     7  	"net/url"
     8  	"strings"
     9  )
    10  
    11  type PostLoginOptions struct {
    12  	Username  string
    13  	Password  string
    14  	Twofactor string
    15  }
    16  
    17  func (c *Client) Login(ctx context.Context, options *PostLoginOptions) error {
    18  
    19  	formData := url.Values{}
    20  	formData.Set("username", options.Username)
    21  	formData.Set("password", options.Password)
    22  	formData.Set("twofactor", options.Twofactor)
    23  	encodedBody := strings.NewReader(formData.Encode())
    24  
    25  	url := fmt.Sprintf("%s/forms/login", c.BaseURL)
    26  
    27  	req, err := http.NewRequest(http.MethodPost, url, encodedBody)
    28  	if err != nil {
    29  		return err
    30  	}
    31  
    32  	req = req.WithContext(ctx)
    33  
    34  	if err := c.sendRequest(req, nil, nil); err != nil {
    35  		return err
    36  	}
    37  
    38  	return nil
    39  
    40  }
    41  
    42  type GetCSRFTokenResponse struct {
    43  	Token string `json:"token"`
    44  }
    45  
    46  func (c *Client) GetCSRFToken(ctx context.Context) (*GetCSRFTokenResponse, error) {
    47  
    48  	url := fmt.Sprintf("%s/csrf.json", c.BaseURL)
    49  
    50  	req, err := http.NewRequest(http.MethodGet, url, nil)
    51  	if err != nil {
    52  		return nil, err
    53  	}
    54  
    55  	req = req.WithContext(ctx)
    56  
    57  	res := &GetCSRFTokenResponse{}
    58  	if err := c.sendRequest(req, &res, nil); err != nil {
    59  		return nil, err
    60  	}
    61  
    62  	c.CsrfToken = res.Token
    63  
    64  	return res, nil
    65  
    66  }
    67  

View as plain text