-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathutils.go
102 lines (85 loc) · 2.39 KB
/
utils.go
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
package main
import (
"bytes"
"crypto/rand"
"fmt"
"image"
"log"
"os"
"strings"
"golang.org/x/crypto/bcrypt"
"golang.org/x/exp/errors"
// clone of "code.google.com/p/rsc/qr" which no longer available
"github.com/vkuznet/rsc/qr"
// imaging library
"github.com/disintegration/imaging"
)
// helper function to generate QR image file
func generateQRImage(authLink, fname string) error {
// Encode authLink to QR codes
// qr.H = 65% redundant level
// see https://godoc.org/code.google.com/p/rsc/qr#Level
code, err := qr.Encode(authLink, qr.H)
if err != nil {
log.Println("unable to encode auth link", err)
return err
}
imgByte := code.PNG()
// convert byte to image for saving to file
img, _, _ := image.Decode(bytes.NewReader(imgByte))
// TODO: file should be unique for each client
err = imaging.Save(img, fname)
if err != nil {
log.Println("unable to generate QR image file", err)
}
return err
}
// getBearerToken returns token from
// HTTP Header "Authorization: Bearer <token>"
func getBearerToken(header string) (string, error) {
if header == "" {
return "", fmt.Errorf("An authorization header is required")
}
token := strings.Split(header, " ")
if Config.Verbose > 0 {
log.Println("getBearerToken", token)
}
if len(token) != 2 {
return "", fmt.Errorf("Malformed bearer token")
}
return token[1], nil
}
// helper function to check if file exists
func fileExists(path string) bool {
_, err := os.Stat(path)
return !errors.Is(err, os.ErrNotExist)
}
// helper function for random string generation
func randStr(strSize int, randType string) string {
var dictionary string
if randType == "alphanum" {
dictionary = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
}
if randType == "alpha" {
dictionary = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
}
if randType == "number" {
dictionary = "0123456789"
}
var bytes = make([]byte, strSize)
rand.Read(bytes)
for k, v := range bytes {
bytes[k] = dictionary[v%byte(len(dictionary))]
}
return string(bytes)
}
// helper function to generate password hash
func getPasswordHash(password string) (string, error) {
bytes, err := bcrypt.GenerateFromPassword([]byte(password), 14)
return string(bytes), err
}
// helper function to check password hash
func checkPasswordHash(password, hash string) bool {
err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password))
return err == nil
}