Working on http client

This commit is contained in:
Andrea Fazzi 2020-01-02 13:01:21 +01:00
parent 7df11d017d
commit a590a57b65
8 changed files with 99 additions and 129 deletions

View file

@ -1,117 +0,0 @@
package client
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"strconv"
"git.andreafazzi.eu/andrea/oef/orm"
"git.andreafazzi.eu/andrea/oef/renderer"
)
// A client represents a client connection to the Headmaster test
// server.
type Client struct {
Url *url.URL
Username string
Password string
User string
token string
}
// Dial connects to a test server instance at the specified address
// using the given credentials.
func Dial(host, username, password string) (*Client, error) {
url, err := url.Parse(host)
if err != nil {
return nil, err
}
client := &Client{
Url: url,
Username: username,
Password: password,
}
response, err := client.SendRequest("GET", "get_token", nil)
if err != nil {
panic(err)
}
var data struct {
Token string
User string
}
if err := json.Unmarshal(response, &data); err != nil {
panic(err)
}
client.token = data.Token
client.User = data.User
return client, nil
}
func (c *Client) SendRequest(method string, path string, data []byte) ([]byte, error) {
// Create the https request
folderUrl, err := url.Parse(path)
if err != nil {
return nil, err
}
client := &http.Client{}
req, err := http.NewRequest(method, c.Url.ResolveReference(folderUrl).String(), bytes.NewReader(data))
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json")
req.SetBasicAuth(c.Username, c.Password)
if c.token != "" {
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", c.token))
}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
return body, nil
}
func (c *Client) GetContests() ([]*orm.Teacher, error) {
var (
response renderer.JsonResponse
teachers []*orm.Teacher
)
data, err := c.SendRequest("GET", "/api/teachers?format=json", nil)
if err != nil {
return nil, err
}
if err := json.Unmarshal(data, &response); err != nil {
return nil, err
}
if string(response.Error) != "" {
return nil, errors.New(string(response.Error))
}
if err := json.Unmarshal(response.Result, &teachers); err != nil {
return nil, err
}
return teachers, nil
}

View file

@ -1 +0,0 @@
andrea@aspire-E5-571.12528:1577436684

View file

@ -6,9 +6,9 @@ import (
"errors"
"fmt"
"io/ioutil"
"log"
"net/http"
"net/url"
"strconv"
"git.andreafazzi.eu/andrea/oef/orm"
"git.andreafazzi.eu/andrea/oef/renderer"
@ -91,13 +91,12 @@ func (c *Client) SendRequest(method string, path string, data []byte) ([]byte, e
return body, nil
}
func (c *Client) GetTeachers() ([]*orm.Teacher, error) {
func (c *Client) getModel(name string, model interface{}) (interface{}, error) {
var (
response renderer.JsonResponse
teachers []*orm.Teacher
)
data, err := c.SendRequest("GET", "/api/teachers?format=json", nil)
data, err := c.SendRequest("GET", fmt.Sprintf("/api/%s?format=json", name), nil)
if err != nil {
return nil, err
}
@ -110,8 +109,53 @@ func (c *Client) GetTeachers() ([]*orm.Teacher, error) {
return nil, errors.New(string(response.Error))
}
if err := json.Unmarshal(response.Result, &teachers); err != nil {
if err := json.Unmarshal(response.Result, &model); err != nil {
return nil, err
}
return teachers, nil
return model, nil
}
func (c *Client) Contests(contests *[]*orm.Contest) error {
var response renderer.JsonResponse
data, err := c.SendRequest("GET", "/api/contests?format=json", nil)
if err != nil {
return err
}
if err := json.Unmarshal(data, &response); err != nil {
return err
}
if string(response.Error) != "" {
return errors.New(string(response.Error))
}
if err := json.Unmarshal(response.Result, &contests); err != nil {
return err
}
return nil
}
func (c *Client) GetAll(model interface{}) error {
var response renderer.JsonResponse
log.Println(orm.ModelName(model))
data, err := c.SendRequest("GET", "/api/participants?format=json", nil)
if err != nil {
return err
}
if err := json.Unmarshal(data, &response); err != nil {
return err
}
if string(response.Error) != "" {
return errors.New(string(response.Error))
}
if err := json.Unmarshal(response.Result, &model); err != nil {
return err
}
return nil
}

View file

@ -246,7 +246,7 @@ func get(w http.ResponseWriter, r *http.Request, model string, pattern PathPatte
respondWithError(w, r, err)
} else {
claims := r.Context().Value("user").(*jwt.Token).Claims.(jwt.MapClaims)
log.Println(claims)
role := claims["role"].(string)
if !hasPermission(role, pattern.Path(model)) {
setFlashMessage(w, r, "notAuthorized")

View file

@ -127,6 +127,7 @@ func checkCredential(username string, password string) (*UserToken, error) {
return token, nil
}
// FIXME: Refactor the functions above please!!!
func getToken(username string, password string) ([]byte, error) {
user, err := checkCredential(username, password)
@ -154,6 +155,7 @@ func getToken(username string, password string) ([]byte, error) {
return []byte(tokenString), nil
}
// FIXME: Refactor the functions above please!!!
func tokenHandler() http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
username, password, _ := r.BasicAuth()
@ -165,8 +167,10 @@ func tokenHandler() http.Handler {
/* Set token claims */
claims := make(map[string]interface{})
claims["admin"] = true
claims["name"] = user.Username
claims["admin"] = user.Admin
claims["username"] = user.Username
claims["role"] = user.Role
claims["user_id"] = user.UserID
claims["exp"] = time.Now().Add(time.Hour * 24).Unix()
/* Create the token */

View file

@ -98,7 +98,7 @@ func DB() *gorm.DB {
func MapHandlers(models []interface{}) error {
for _, model := range models {
name := inflection.Plural(strings.ToLower(modelName(model)))
name := inflection.Plural(strings.ToLower(ModelName(model)))
for p, action := range map[string]string{
"": "ReadAll",
"create/": "Create",
@ -138,7 +138,7 @@ func PostNothing(args map[string]string, w http.ResponseWriter, r *http.Request)
return nil, nil
}
func modelName(s interface{}) string {
func ModelName(s interface{}) string {
if t := reflect.TypeOf(s); t.Kind() == reflect.Ptr {
return t.Elem().Name()
} else {

Binary file not shown.

View file

@ -0,0 +1,40 @@
package main
import (
"log"
"git.andreafazzi.eu/andrea/oef/client"
"git.andreafazzi.eu/andrea/oef/orm"
)
func main() {
url := "http://localhost:3000"
log.Printf("Connecting to %s", url)
client, err := client.Dial(url, "admin", "admin")
if err != nil {
panic(err)
}
var contests []*orm.Contest
err = client.Contests(&contests)
if err != nil {
panic(err)
}
var participants []*orm.Participant
err = client.GetAll(&participants)
if err != nil {
panic(err)
}
for _, c := range contests {
log.Println(c)
}
for _, c := range participants {
log.Println(c)
}
}