Blob


1 package lemmy
3 import (
4 "encoding/json"
5 "fmt"
6 "net/http"
7 )
9 func (c *Client) Login(name, password string) error {
10 if !c.ready {
11 if err := c.init(); err != nil {
12 return err
13 }
14 }
16 params := map[string]interface{}{
17 "username_or_email": name,
18 "password": password,
19 }
20 resp, err := c.post("/user/login", params)
21 if err != nil {
22 return err
23 }
24 defer resp.Body.Close()
25 if resp.StatusCode != http.StatusOK {
26 return fmt.Errorf("remote status %s: %w", resp.Status, decodeError(resp.Body))
27 }
29 var response struct {
30 JWT string
31 }
32 if err := json.NewDecoder(resp.Body).Decode(&response); err != nil {
33 return fmt.Errorf("decode login response: %w", err)
34 }
35 c.authToken = response.JWT
36 return nil
37 }
39 func (c *Client) Authenticated() bool {
40 return c.authToken != ""
41 }