summaryrefslogtreecommitdiff
path: root/pkg/bitmask/auth.go
blob: a87a2eaa7e09d51d2dcd288ea65a5ea882108680 (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
package bitmask

import (
	"io/ioutil"
	"log"
	"math/rand"
	"os"
	"path/filepath"
	"runtime"
	"strings"
	"time"
)

/* functions for local authentication of control endpoints */

const bitmaskToken = "bitmask-token"

func GenerateAuthToken() {
	if runtime.GOOS != "linux" {
		log.Println("Authentication token only implemented in linux at the moment.")
		return
	}
	t := getRandomString()
	tokenPath := filepath.Join(os.TempDir(), bitmaskToken)
	err := ioutil.WriteFile(tokenPath, []byte(t), os.FileMode(int(0600)))
	if err != nil {
		log.Println("Could not write authentication token.")
	}
}

func ReadAuthToken() string {
	if runtime.GOOS != "linux" {
		log.Println("Authentication token only implemented in linux at the moment.")
		return ""
	}
	tokenPath := filepath.Join(os.TempDir(), bitmaskToken)
	token, err := ioutil.ReadFile(tokenPath)
	if err != nil {
		log.Println("Error reading token:", err)
	}
	return string(token)
}

func getRandomString() string {
	rand.Seed(time.Now().UnixNano())
	chars := []rune("ABCDEFGHIJKLMNOPQRSTUVWXYZ" +
		"abcdefghijklmnopqrstuvwxyz" +
		"0123456789")
	length := 40
	var b strings.Builder
	for i := 0; i < length; i++ {
		b.WriteRune(chars[rand.Intn(len(chars))])
	}
	return b.String()
}