/
util.go
63 lines (52 loc) · 1.56 KB
/
util.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
package platform
import (
"encoding/json"
"io"
"math"
"math/rand"
"github.com/2beens/ispend/internal/models"
log "github.com/sirupsen/logrus"
"golang.org/x/crypto/bcrypt"
)
func GenerateRandomString(length int) string {
text := ""
possible := "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
for i := 0; i < length; i++ {
possibleLen := float64(len(possible))
nextPossible := math.Floor(rand.Float64() * possibleLen)
text += string(possible[int(nextPossible)])
}
return text
}
func HashPassword(password string) (string, error) {
bytes, err := bcrypt.GenerateFromPassword([]byte(password), 14)
return string(bytes), err
}
func CheckPasswordHash(password, hash string) bool {
err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password))
return err == nil
}
func SendAPIResp(w io.Writer, data interface{}) {
dataBytes, err := json.Marshal(data)
if err != nil {
log.Warnf("#120412 failed to send API response: %s", err)
return
}
_, err = w.Write(dataBytes)
if err != nil {
log.Warnf("#120413 failed to send API response: %s", err)
return
}
}
func SendAPIOKResp(w io.Writer, message string) {
apiResp := models.APIResponse{Status: 200, Message: message}
SendAPIResp(w, apiResp)
}
func SendAPIOKRespWithData(w io.Writer, message string, data interface{}) {
apiResp := models.APIResponse{Status: 200, Message: message, Data: data}
SendAPIResp(w, apiResp)
}
func SendAPIErrorResp(w io.Writer, message string, status int) {
apiErr := models.APIResponse{Status: status, Message: message, IsError: true}
SendAPIResp(w, apiErr)
}