summaryrefslogtreecommitdiff
path: root/pkg/ui/views/api.go
blob: 14f4cf209c20392984e4198db7b64ec7cfd60e23 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package views

import (
	"bufio"
	"bytes"
	"fmt"
	"net/http"
	"os"

	"github.com/boozec/rahanna/internal/api/auth"
)

// getAuthorizationToken reads the authentication token from the .rahannarc file
func getAuthorizationToken() (string, error) {
	f, err := os.Open(".rahannarc")
	if err != nil {
		return "", err
	}
	defer f.Close()

	scanner := bufio.NewScanner(f)
	var authorization string
	for scanner.Scan() {
		authorization = scanner.Text()
	}

	if err := scanner.Err(); err != nil {
		return "", fmt.Errorf("error reading auth token: %v", err)
	}

	return authorization, nil
}

// From a JWT token it returns the associated user ID
func getUserID() (int, error) {
	token, err := getAuthorizationToken()
	if err != nil {
		return -1, err
	}

	claims, err := auth.ValidateJWT(token)
	if err != nil {
		return -1, err
	}

	return claims.UserID, nil

}

// sendAPIRequest sends an HTTP request to the API with the given parameters
func sendAPIRequest(method, url string, payload []byte, authorization string) (*http.Response, error) {
	req, err := http.NewRequest(method, url, bytes.NewReader(payload))
	if err != nil {
		return nil, err
	}

	req.Header.Set("Content-Type", "application/json")
	req.Header.Add("Authorization", authorization)

	client := &http.Client{}
	return client.Do(req)
}