-
Notifications
You must be signed in to change notification settings - Fork 1
/
util.go
205 lines (185 loc) · 4.13 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
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
103
104
105
106
107
108
109
110
111
112
113
114
115
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
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
package gauth
import (
"context"
"crypto/sha1"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"math/rand"
"net"
"net/http"
"net/mail"
"net/url"
"strings"
"time"
"unicode"
"github.com/golang-jwt/jwt/v4"
"golang.org/x/crypto/bcrypt"
)
var (
recovChars = []rune("abcdefghijklmnopqrstuvwxyz0123456789")
)
func init() {
rand.Seed(time.Now().UnixNano())
}
func RequiredEmail(fID string, data map[string]interface{}) error {
s, _ := data[fID].(string)
_, err := mail.ParseAddress(s)
if err != nil {
return errors.New("enter a valid email")
}
return nil
}
func RequiredText(fID string, data map[string]interface{}) error {
s, _ := data[fID].(string)
if len(s) > 100 {
return errors.New("too long")
}
if len(s) == 0 {
return errors.New("required")
}
return nil
}
func RequiredPassword(fID string, data map[string]interface{}) error {
s, _ := data[fID].(string)
if s == "" {
return errors.New("required")
}
var (
hasMinLen = false
hasUpper = false
hasLower = false
hasNumber = false
hasSpecial = false
)
if len(s) >= 7 {
hasMinLen = true
}
for _, char := range s {
switch {
case unicode.IsUpper(char):
hasUpper = true
case unicode.IsLower(char):
hasLower = true
case unicode.IsNumber(char):
hasNumber = true
case unicode.IsPunct(char) || unicode.IsSymbol(char):
hasSpecial = true
}
}
if !hasMinLen {
return errors.New("must be 7 characters")
}
if !hasUpper {
return errors.New("must have upper case")
}
if !hasLower {
return errors.New("must have lower case")
}
if !hasNumber {
return errors.New("must have number")
}
if !hasSpecial {
return errors.New("must have special characters")
}
return nil
}
func AuthFromContext(ctx context.Context) *Auth {
if auth, ok := ctx.Value(AuthKey).(*Auth); ok {
return auth
}
return nil
}
func hashPassword(password string, cost int) (string, error) {
bytes, err := bcrypt.GenerateFromPassword([]byte(password), cost)
if err != nil {
return "", err
}
return string(bytes), nil
}
func validPassword(hashed, password string) bool {
return bcrypt.CompareHashAndPassword([]byte(hashed), []byte(password)) == nil
}
func randomJWTKey() ([]byte, error) {
key := make([]byte, 64)
_, err := rand.Read(key)
if err != nil {
return nil, err
}
return key, nil
}
func validRecaptcha(secret string, response string, ip string) error {
type verify struct {
Success bool `json:"success"`
}
hc := &http.Client{}
resp, err := hc.PostForm("https://www.google.com/recaptcha/api/siteverify", url.Values{
"secret": {secret},
"response": {response},
"remoteip": {ip},
})
if err != nil {
return fmt.Errorf("validRecaptcha: PostForm error %v", err)
}
defer resp.Body.Close()
body, _ := ioutil.ReadAll(resp.Body)
var v verify
if err := json.Unmarshal(body, &v); err != nil {
return err
}
if !v.Success {
return errors.New("failed recaptcha")
}
return nil
}
func realIP(r *http.Request) string {
if ip := r.Header.Get("X-Appengine-User-Ip"); ip != "" {
return ip
}
if ip := r.Header.Get("X-Forwarded-For"); ip != "" {
return strings.Split(ip, ", ")[0]
}
if ip := r.Header.Get("X-Real-IP"); ip != "" {
return ip
}
ra, _, _ := net.SplitHostPort(r.RemoteAddr)
return ra
}
func unverifiedClaims(t string) (jwt.MapClaims, error) {
token, _, err := new(jwt.Parser).ParseUnverified(t, jwt.MapClaims{})
if err != nil {
return nil, fmt.Errorf("unverifiedClaims: parse error %v", err)
}
if claims, ok := token.Claims.(jwt.MapClaims); ok {
return claims, nil
}
return nil, errors.New("invalid claims")
}
func randSeq(n int) string {
b := make([]rune, n)
for i := range b {
b[i] = recovChars[rand.Intn(len(recovChars))]
}
return string(b)
}
// sha1(ip+userAgent+key+$salt) + $salt
func clientFromRequest(r *http.Request, key, salt string) string {
if salt == "" {
salt = fmt.Sprintf("$%d", time.Now().Unix())
}
cid := realIP(r) + r.Header.Get("User-Agent") + key + salt
h := sha1.New()
h.Write([]byte(cid))
return hex.EncodeToString(h.Sum(nil)) + salt
}
func toString(s interface{}) string {
if val, ok := s.(string); ok {
return val
}
if val, ok := s.(*string); ok && val != nil {
return *val
}
return ""
}