/
UserAuth.go
246 lines (201 loc) · 5.45 KB
/
UserAuth.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
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
package main
import (
"encoding/json"
"net/http"
"time"
"github.com/gorilla/mux"
"github.com/gorilla/schema"
"utils"
)
type User struct {
ID int
Username string
PasswordHash string
PasswordSalt string
IsDisabled bool
}
type UserSession struct {
SessionKey string
LoginTime time.Time
}
const (
AuthSalt = "sydrtvgh"
)
type ErrorMsg struct {
Msg string
}
func UserAuth(username string, password string) (int, string, bool) {
row := MyDB.connection.QueryRow(`select id, passwordhash, passwordsalt, isdisabled
from users where username=$1`,
username)
var userID int
var passwordHash string
var passwordSalt string
var isDisabled bool
err := row.Scan(&userID, &passwordHash, &passwordSalt, &isDisabled)
if err != nil {
log.Info("Unknown login or password for %s", username)
return -1, "", false
}
if isDisabled {
log.Info("Username %s is disabled", username)
return -1, "", false
}
calculatedPasswordHash := utils.SHA1(passwordSalt + password)
log.Debug("calculated hash %s", calculatedPasswordHash)
if calculatedPasswordHash != passwordHash {
log.Info("Invalid password")
return -1, "", false
}
return userID, passwordSalt, true
}
// See if user is in the system, if yes assign a session ID to him
func UserAuthLoginHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
username, password, ok := r.BasicAuth()
if !ok {
w.WriteHeader(http.StatusUnauthorized)
return
}
userID, _, ok := UserAuth(username, password)
if !ok {
w.WriteHeader(http.StatusUnauthorized)
return
}
// creating session
sessionID := utils.RandomSHA1()
var err error
for tries := 0; tries < 3; tries++ {
_, err = MyDB.connection.Exec("insert into usersessions(sessionkey, user_id) values($1,$2)",
sessionID, userID)
if err == nil {
break
}
}
if err != nil {
panic(err)
}
// Set output
c := http.Cookie{Name: "sessionId", Value: sessionID}
http.SetCookie(w, &c)
log.Info("Login successful for user:%s user_id:%d", username, userID)
}
// log the user's session out of the system, do not check if the session is valid
func UserAuthLogoutHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
vars := mux.Vars(r)
sessionID := vars["session_id"]
log.Info("Logging out session %s", sessionID)
_, err := MyDB.connection.Exec("delete from usersessions where sessionkey = $1", sessionID)
if err != nil {
panic(err)
}
}
type PasswordChangeForm struct {
New_password string
}
func UserAuthPasswordChangeHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
username, password, ok := r.BasicAuth()
if !ok {
w.WriteHeader(http.StatusUnauthorized)
return
}
userID, salt, ok := UserAuth(username, password)
if !ok {
w.WriteHeader(http.StatusUnauthorized)
return
}
err := r.ParseForm()
if err != nil {
w.WriteHeader(http.StatusBadRequest)
panic(err)
}
decoder := schema.NewDecoder()
passwordchange_form := new(PasswordChangeForm)
err = decoder.Decode(passwordchange_form, r.PostForm)
if err != nil || passwordchange_form.New_password == "" {
w.WriteHeader(http.StatusBadRequest)
return
}
newpassword := passwordchange_form.New_password
if newpassword == password {
errmsg := ErrorMsg{Msg: "The new password cannot be the same as the current one"}
str, _ := json.Marshal(errmsg)
w.Write(str)
return
}
newpasswordhash := utils.SHA1(salt + newpassword)
// update password
_, err = MyDB.connection.Exec("UPDATE users SET passwordhash=$1 where id=$2",
newpasswordhash, userID)
if err != nil {
panic(err)
}
// expire all sessions
_, err = MyDB.connection.Exec("DELETE FROM usersessions WHERE user_id=$1",
userID)
if err != nil {
panic(err)
}
}
type SignupForm struct {
Username string
Password string
// Telephone
}
func (form *SignupForm) validate() bool {
if form.Username == "" || form.Password == "" {
return false
}
return true
}
func UserAuthSignupHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
err := r.ParseForm()
if err != nil {
w.WriteHeader(http.StatusBadRequest)
panic(err)
}
decoder := schema.NewDecoder()
signupForm := new(SignupForm)
err = decoder.Decode(signupForm, r.PostForm)
if err != nil || !signupForm.validate() {
w.WriteHeader(http.StatusBadRequest)
return
}
// check if user exists
var id int
err = MyDB.connection.QueryRow("SELECT 1 FROM users WHERE username = $1",
signupForm.Username).Scan(&id)
if err == nil {
log.Info("User %s already exists", signupForm.Username)
w.WriteHeader(http.StatusBadRequest)
return
}
passwordhash := utils.SHA1(AuthSalt + signupForm.Password)
_, err = MyDB.connection.Exec(`INSERT INTO
users(username, passwordhash, passwordsalt)
VALUES($1,$2,$3)`,
signupForm.Username, passwordhash, AuthSalt)
if err != nil {
panic(err)
}
log.Info("Created user %s", signupForm.Username)
}
func SessionRequired(f http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
f(w, r)
}
}
func SessionValid(user_id int, session_key string) bool {
var id int
// Need a cache
err := MyDB.connection.QueryRow(`SELECT 1 FROM usersessions
WHERE sessionkey = $1 and user_id = $2`,
session_key, user_id).Scan(&id)
if err != nil {
return false
}
return true
}