Blame view

auth_utility.go 3.19 KB
90fd36e9b   Marko Tikvić   resolved some dep...
1
2
3
  package restutility
  
  import (
90fd36e9b   Marko Tikvić   resolved some dep...
4
  	"errors"
90fd36e9b   Marko Tikvić   resolved some dep...
5
6
7
8
9
10
  	"time"
  	"crypto/sha256"
  	"crypto/rand"
  	"encoding/hex"
  	"strings"
  	"github.com/dgrijalva/jwt-go"
90fd36e9b   Marko Tikvić   resolved some dep...
11
  )
7d3deb50d   Marko Tikvić   modified list_con...
12
13
  const OneDay   = time.Hour*24
  const OneWeek  = OneDay*7
90fd36e9b   Marko Tikvić   resolved some dep...
14
15
16
  const saltSize = 32
  const appName  = "korisnicki-centar"
  const secret   = "korisnicki-centar-api"
90fd36e9b   Marko Tikvić   resolved some dep...
17
18
  type TokenClaims struct {
  	Username string `json:"username"`
7d3deb50d   Marko Tikvić   modified list_con...
19
  	Role     string `json:"role"`
90fd36e9b   Marko Tikvić   resolved some dep...
20
21
22
23
24
25
26
  	jwt.StandardClaims
  }
  
  type CredentialsStruct struct {
  	Username string `json:"username"`
  	Password string `json:"password"`
  }
b291ac8c4   Marko Tikvić   clened up
27
  func GenerateSalt() (string, error) {
90fd36e9b   Marko Tikvić   resolved some dep...
28
  	salt := ""
90fd36e9b   Marko Tikvić   resolved some dep...
29
30
31
32
33
34
35
36
  	rawsalt := make([]byte, saltSize)
  	_, err := rand.Read(rawsalt)
  	if err != nil {
  		return "", err
  	}
  	salt = hex.EncodeToString(rawsalt)
  	return salt, nil
  }
b291ac8c4   Marko Tikvić   clened up
37
  func HashMessage(message string, presalt string) (string, string, error) {
90fd36e9b   Marko Tikvić   resolved some dep...
38
39
40
41
42
  	hash, salt := "", ""
  	var err error
  
  	// chech if message is presalted
  	if presalt == "" {
b291ac8c4   Marko Tikvić   clened up
43
  		salt, err = GenerateSalt()
90fd36e9b   Marko Tikvić   resolved some dep...
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
  		if err != nil {
  			return "", "", err
  		}
  	} else {
  		salt = presalt
  	}
  
  	// convert strings to raw byte slices
  	rawmessage := []byte(message)
  	rawsalt, err := hex.DecodeString(salt)
  	if err != nil {
  		return "", "", err
  	}
  	rawdata := make([]byte, len(rawmessage) + len(rawsalt))
  	rawdata = append(rawdata, rawmessage...)
  	rawdata = append(rawdata, rawsalt...)
  
  	// hash message + salt
  	hasher := sha256.New()
  	hasher.Write(rawdata)
  	rawhash := hasher.Sum(nil)
  	hash = hex.EncodeToString(rawhash)
  	return hash, salt, nil
  }
6f4b8a711   Marko Tikvić   token response ch...
68
  func IssueAPIToken(username, role string) (string, error) {
7d3deb50d   Marko Tikvić   modified list_con...
69
  	var apiToken string
90fd36e9b   Marko Tikvić   resolved some dep...
70
71
72
  	var err error
  
  	if err != nil {
6f4b8a711   Marko Tikvić   token response ch...
73
  		return "", err
90fd36e9b   Marko Tikvić   resolved some dep...
74
75
76
77
78
79
80
81
82
83
84
85
  	}
  
  	claims := TokenClaims{
  		username,
  		role,
  		jwt.StandardClaims{
  			ExpiresAt: (time.Now().Add(OneWeek)).Unix(),
  			Issuer:    appName,
  		},
  	}
  
  	jwtToken := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
6f4b8a711   Marko Tikvić   token response ch...
86
  	apiToken, err = jwtToken.SignedString([]byte(secret))
90fd36e9b   Marko Tikvić   resolved some dep...
87
  	if err != nil {
6f4b8a711   Marko Tikvić   token response ch...
88
  		return "", err
90fd36e9b   Marko Tikvić   resolved some dep...
89
90
91
  	}
  	return apiToken, nil
  }
6f4b8a711   Marko Tikvić   token response ch...
92
  func RefreshAPIToken(tokenString string) (string, error) {
7d3deb50d   Marko Tikvić   modified list_con...
93
  	var newToken string
90fd36e9b   Marko Tikvić   resolved some dep...
94
95
96
  	tokenString = strings.TrimPrefix(tokenString, "Bearer ")
  	token, err := parseTokenFunc(tokenString)
  	if err != nil {
6f4b8a711   Marko Tikvić   token response ch...
97
  		return "", err
90fd36e9b   Marko Tikvić   resolved some dep...
98
99
100
101
102
  	}
  
  	// type assertion
  	claims, ok := token.Claims.(*TokenClaims)
  	if !ok || !token.Valid {
6f4b8a711   Marko Tikvić   token response ch...
103
  		return "", errors.New("token is not valid")
90fd36e9b   Marko Tikvić   resolved some dep...
104
105
106
107
  	}
  
  	claims.ExpiresAt = (time.Now().Add(OneWeek)).Unix()
  	jwtToken := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
6f4b8a711   Marko Tikvić   token response ch...
108
  	newToken, err = jwtToken.SignedString([]byte(secret))
90fd36e9b   Marko Tikvić   resolved some dep...
109
  	if err != nil {
6f4b8a711   Marko Tikvić   token response ch...
110
  		return "", err
90fd36e9b   Marko Tikvić   resolved some dep...
111
112
113
114
  	}
  
  	return newToken, nil
  }
b291ac8c4   Marko Tikvić   clened up
115
  func ParseAPIToken(tokenString string) (*TokenClaims, error) {
90fd36e9b   Marko Tikvić   resolved some dep...
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
  	if ok := strings.HasPrefix(tokenString, "Bearer"); ok {
  		tokenString = strings.TrimPrefix(tokenString, "Bearer ")
  	} else {
  		return &TokenClaims{}, errors.New("Authorization header is incomplete")
  	}
  
  	token, err := parseTokenFunc(tokenString)
  	if err != nil {
  		return &TokenClaims{}, err
  	}
  
  	// type assertion
  	claims, ok := token.Claims.(*TokenClaims)
  	if !ok || !token.Valid {
  		return &TokenClaims{}, errors.New("token is not valid")
  	}
  	return claims, nil
  }
  
  func parseTokenFunc(tokenString string) (*jwt.Token, error) {
  	token, err := jwt.ParseWithClaims(tokenString,
  		&TokenClaims{},
  		func(token *jwt.Token) (interface{}, error) {
  			return []byte(secret), nil
  		},
  	)
  	return token, err
  }