/
service.go
197 lines (162 loc) · 5.34 KB
/
service.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
package auth
import (
"context"
"fmt"
"github.com/ah8ad3/gateway/pkg/db"
"net/http"
"strings"
"time"
"github.com/ah8ad3/gateway/pkg/logger"
"github.com/dgrijalva/jwt-go"
"github.com/mongodb/mongo-go-driver/bson"
"github.com/mongodb/mongo-go-driver/mongo"
"golang.org/x/crypto/bcrypt"
)
var collection *mongo.Collection
func hashAndSalt(pwd []byte) string {
// Use GenerateFromPassword to hash & salt pwd.
// MinCost is just an integer constant provided by the bcrypt
// package along with DefaultCost & MaxCost.
// The cost can be any value you want provided it isn't lower
// than the MinCost (4)
hash, err := bcrypt.GenerateFromPassword(pwd, bcrypt.MinCost)
if err != nil {
logger.SetSysLog(logger.SystemLog{Log: logger.Log{Event: "critical", Description: err.Error()},
Pkg: "auth", Time: time.Now()})
//log.Println(err)
}
// GenerateFromPassword returns a byte slice so we need to
// convert the bytes to a string and return it
return string(hash)
}
func comparePasswords(hashedPwd string, plainPwd []byte) bool {
// Since we'll be getting the hashed password from the DB it
// will be a string so we'll need to convert it to a byte slice
byteHash := []byte(hashedPwd)
err := bcrypt.CompareHashAndPassword(byteHash, plainPwd)
if err != nil {
//log.Println(err)
return false
}
return true
}
// OpenAuthCollection open the collection of mongoDB called auth
func OpenAuthCollection() {
if logger.Connect {
collection = logger.DB.Collection("auth")
}
}
// CheckJwt if token is JWT and have time
func CheckJwt(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
if logger.Connect == false {
w.WriteHeader(500)
_, _ = w.Write([]byte(`{"error": "DataBase not connected, please check connection"}`))
return
}
_token := r.Header.Get("Authorization")
if _token == "" {
w.WriteHeader(400)
_, _ = w.Write([]byte(`{"error": "Authorization header missed with token value"}`))
return
}
token, _ := jwt.Parse(_token, func(token *jwt.Token) (interface{}, error) {
return []byte(db.SecretKey), nil
})
// When using `Parse`, the result `Claims` would be a map.
// In another way, you can decode token to your struct, which needs to satisfy `jwt.StandardClaims`
user := JWT{}
token, _ = jwt.ParseWithClaims(_token, &user, func(token *jwt.Token) (interface{}, error) {
return []byte(db.SecretKey), nil
})
if token.Valid {
w.WriteHeader(200)
_, _ = w.Write([]byte(`{"ok": "token right"}`))
return
}
w.WriteHeader(403)
_, _ = w.Write([]byte(`{"error": "token wrong"}`))
return
}
// SignJWT function to create jwt token
func SignJWT(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
if logger.Connect == false {
w.WriteHeader(500)
_, _ = w.Write([]byte(`{"error": "DataBase not connected, please check connection"}`))
return
}
_ = r.ParseForm()
username := strings.Join(r.Form["username"], "")
password := strings.Join(r.Form["password"], "")
if username == "" || password == "" {
w.WriteHeader(400)
_, _ = w.Write([]byte(`{"error": "input form is incomplete"}`))
return
}
pointer := collection.FindOne(context.Background(), bson.D{{"username", username}})
raw, err := pointer.DecodeBytes()
if err != nil {
w.WriteHeader(400)
_, _ = w.Write([]byte(`{"error": "username or password wrong"}`))
return
}
_username := raw.Lookup("username").StringValue()
_password := raw.Lookup("password").StringValue()
if username != _username || !ValidPassword(_password, password) {
w.WriteHeader(400)
_, _ = w.Write([]byte(`{"error": "username or password wrong"}`))
return
}
token := createTokenString(User{Username: username, Password: password})
w.WriteHeader(201)
_, _ = w.Write([]byte(fmt.Sprintf(`{"token": "%s"}`, token)))
return
}
func createTokenString(user User) string {
expireToken := time.Now().Add(time.Hour * 3).Unix() // token only valid 3 hours
// Embed User information to `token`
token := jwt.NewWithClaims(jwt.GetSigningMethod("HS256"), &JWT{
User: user,
Age: 30,
StandardClaims: jwt.StandardClaims{
ExpiresAt: expireToken,
},
})
// token -> string. Only server knows this secret
_token, err := token.SignedString([]byte(db.SecretKey))
if err != nil {
logger.SetSysLog(logger.SystemLog{Log: logger.Log{Event: "critical", Description: err.Error()},
Pkg: "auth", Time: time.Now()})
//log.Fatalln(err)
}
return _token
}
// RegisterUser function use in V1 router for sign up user
func RegisterUser(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
if logger.Connect == false {
w.WriteHeader(500)
_, _ = w.Write([]byte(`{"error": "DataBase not connected, please check connection"}`))
return
}
_ = r.ParseForm()
username := strings.Join(r.Form["username"], "")
password := strings.Join(r.Form["password"], "")
if username == "" || password == "" {
w.WriteHeader(400)
_, _ = w.Write([]byte(`{"error": "input form is incomplete"}`))
return
}
pointer := collection.FindOne(context.Background(), bson.D{{"username", username}})
_, err := pointer.DecodeBytes()
if err != nil {
_, _ = collection.InsertOne(context.Background(), User{Username: username, Password: SetPassword(password)})
w.WriteHeader(201)
_, _ = w.Write([]byte(`{"ok": "registered"}`))
return
}
w.WriteHeader(400)
_, _ = w.Write([]byte(`{"error": "username is taken"}`))
return
}