mirror of
https://gitea.com/webb/teal
synced 2024-08-15 03:18:56 +00:00
116 lines
2.4 KiB
Go
116 lines
2.4 KiB
Go
package teal
|
|
|
|
import (
|
|
"bytes"
|
|
"encoding/json"
|
|
"errors"
|
|
"io/ioutil"
|
|
"log"
|
|
"net/http"
|
|
)
|
|
|
|
// User holds all of the information about a user that is accessible from the profile page
|
|
type User struct {
|
|
ID int `json:"id"`
|
|
Username string `json:"username"`
|
|
Email string `json:"Email"`
|
|
RegistrationDate string `json:"registrationDate"`
|
|
LastLogin string `json:"lastLogin"`
|
|
UploadKey string `json:"uploadKey"`
|
|
RegistrationIP string `json:"registrationIp"`
|
|
Moderator bool `json:"moderator"`
|
|
Admin bool `json:"admin"`
|
|
Banned bool `json:"banned"`
|
|
BanReason string `json:"banReason"`
|
|
ImageCount int `json:"imageCount"`
|
|
}
|
|
|
|
// UpdateAccountInfo is a wrapper for GetAccountInfo() that replaces user info automatically
|
|
func (c *Client) UpdateAccountInfo() error {
|
|
u, err := GetAccountInfo(c.Session)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
c.User = u
|
|
return nil
|
|
}
|
|
|
|
// GetAccountInfo gets info of a user of a given authenticated session
|
|
func GetAccountInfo(session string) (User, error) {
|
|
httpClient := &http.Client{}
|
|
req, err := http.NewRequest("GET", "https://api.pxl.blue/users/@me", nil)
|
|
req.Header.Set("Authorization", session)
|
|
|
|
if err != nil {
|
|
log.Println(err)
|
|
return User{}, err
|
|
}
|
|
|
|
resp, err := httpClient.Do(req)
|
|
if err != nil {
|
|
log.Println(err)
|
|
return User{}, err
|
|
}
|
|
if resp != nil {
|
|
defer resp.Body.Close()
|
|
}
|
|
|
|
bodyReader, err := ioutil.ReadAll(resp.Body)
|
|
if err != nil {
|
|
return User{}, err
|
|
}
|
|
|
|
var uR userResponse
|
|
|
|
err = json.Unmarshal(bodyReader, &uR)
|
|
if err != nil {
|
|
{
|
|
return User{}, err
|
|
}
|
|
}
|
|
return uR.User, nil
|
|
|
|
}
|
|
|
|
// Gets session from given username and password
|
|
func getSession(u string, p string) (string, error) {
|
|
rb, err := json.Marshal(map[string]string{
|
|
"username": u,
|
|
"password": p,
|
|
})
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
|
|
rs, err := http.Post("https://api.pxl.blue/auth/login", "application/json", bytes.NewBuffer(rb))
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
|
|
body, err := ioutil.ReadAll(rs.Body)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
|
|
defer rs.Body.Close()
|
|
|
|
var lr loginResponse
|
|
err = json.Unmarshal(body, &lr)
|
|
if err != nil {
|
|
log.Println(err)
|
|
return "", err
|
|
}
|
|
|
|
if !lr.Success {
|
|
log.Println(err)
|
|
return "", errors.New(lr.Message)
|
|
}
|
|
|
|
if err != nil {
|
|
log.Println(err)
|
|
return "", err
|
|
}
|
|
|
|
defer rs.Body.Close()
|
|
return lr.Session, nil
|
|
}
|