-
Notifications
You must be signed in to change notification settings - Fork 0
/
helpers.go
74 lines (62 loc) · 1.52 KB
/
helpers.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
package main
import (
"os"
"net/http"
"log"
"encoding/json"
"fmt"
jwt "github.com/dgrijalva/jwt-go"
"golang.org/x/crypto/bcrypt"
// "github.com/joho/godotenv" //DEV
)
// func initLocalEnv() {
// err := godotenv.Load(".env")
// if err != nil {
// log.Fatalf("Error loading .env file")
// }
// }
//respond with 400 and an "error" value in json
func writeErrorToResponse(w http.ResponseWriter, err error) {
if err != nil {
w.WriteHeader(400)
log.Print(err)
e := Error{
Error: err.Error(),
}
json.NewEncoder(w).Encode(e)
}
}
//respond with 400 and an "error" value in json
func writeErrorMessageToResponse(w http.ResponseWriter, errorMessage string) {
w.WriteHeader(400)
log.Print(errorMessage)
e := Error{
Error: errorMessage,
}
json.NewEncoder(w).Encode(e)
}
func logError(msg string, err error) {
if err != nil {
log.Print(fmt.Errorf(msg+"; %w", err))
}
}
func hash(password string) string {
bytes, err := bcrypt.GenerateFromPassword([]byte(password), 14)
logError("hashPassword", err)
return string(bytes)
}
func checkPassword(password, hash string) error {
err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password))
logError("checkPasswordHash", err)
return err
}
func GetJWT(username string) string {
token := jwt.New(jwt.SigningMethodHS256)
claims := token.Claims.(jwt.MapClaims)
claims["authorized"] = true
claims["username"] = username
claims["iss"] = "dodue"
tokenString, err := token.SignedString([]byte(os.Getenv("JWT_SECRET")))
logError("JWT", err)
return tokenString
}