-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauth.go
177 lines (141 loc) · 4.14 KB
/
auth.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
package main
import (
"fmt"
"net/http"
"database/sql"
_ "github.com/go-sql-driver/mysql"
"encoding/json"
"golang.org/x/crypto/bcrypt"
)
type AuthHandler struct {
db *sql.DB
}
type LoginHandler struct {
db *sql.DB
}
func (h *LoginHandler)ServeHTTP(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodPost {
username := r.PostFormValue("username")
password := r.PostFormValue("password")
if username != "" && password != "" {
pwd := h.findUserPassword(username)
if pwd == password {
w.WriteHeader(http.StatusAccepted)
token, err := generateJWT()
if err != nil {
fmt.Fprintln(w, "Error with token generation")
return
}
var out = struct { Token string `json:token` } { token}
jsn, err := json.Marshal(out)
if err != nil {
fmt.Fprintln(w, "Error with token because of the marshal")
return
}
w.Header().Set("Content-Type", "application/json")
w.Write(jsn)
} else {
w.WriteHeader(http.StatusForbidden)
w.Write([]byte("403 - Access Denied."))
}
} else {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte("400 - Bad Request: Missing Fields."))
}
} else {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte("400 - Bad Request: Incorrect Method."))
}
}
func registerHandler(db *sql.DB) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request){
if r.Method == http.MethodPost {
username := r.PostFormValue("username")
email := r.PostFormValue("email")
password := r.PostFormValue("password")
if username != "" && email != "" && password !="" {
hashed, err := bcrypt.GenerateFromPassword([]byte(password), 5)
if err != nil {
fmt.Println("Hashing Password Error")
}
stmtIns, err := db.Prepare("INSERT INTO t VALUES (?, ?, ?, ?)")
if err != nil { panic(err.Error())}
defer stmtIns.Close()
_, err = stmtIns.Exec( nil , username, email, hashed )
if err != nil { panic(err.Error()) }
fmt.Fprintln(w, "Finished inserting")
} else {
fmt.Fprintln(w, "Missing Parameter")
return
}
} else {
fmt.Fprintln(w, "Invalid Post")
return
}
})
}
func (h *LoginHandler)findUserPassword(name string) string {
var outUsername string
var outID int
var outEmail string
var outPassword string
stmtOut, err := h.db.Prepare("SELECT * FROM t WHERE username = ?")
if err != nil { panic(err.Error()) }
stmtOut.QueryRow(name).Scan(&outID, &outUsername, &outEmail, &outPassword)
return outPassword
}
func (a *AuthHandler)findUserByName(username string) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request){
var outUsername string
var outID int
var outEmail string
var outPassword string
fmt.Fprintln(w, r.URL.Path)
stmtOut, err := a.db.Prepare("SELECT * FROM t WHERE username = ?")
if err != nil { panic(err.Error()) }
conNum := a.db.Stats().OpenConnections
fmt.Fprintf(w, "Connection Number %d \n", conNum)
stmtOut.QueryRow(username).Scan(&outID, &outUsername, &outEmail, &outPassword)
fmt.Fprintf(w, "findUserByName: %s \n", outUsername )
})
}
func (a *AuthHandler)findUserByEmail(email string) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request){
var outID int
var outUsername string
var outEmail string
var outPassword string
stmtOut2, err := a.db.Prepare("SELECT * FROM t WHERE email = ?")
if err != nil { panic(err.Error()) }
stmtOut2.QueryRow(email).Scan(&outID, &outUsername, &outEmail, &outPassword)
fmt.Fprintf(w, "User Email: %s", outEmail)
})
}
func isAuthenticated() Adapter {
return func(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request){
bod := r.PostFormValue("bearer")
hed := r.Header.Get("bearer")
var tok string
if len(bod) < 5 && len(hed) < 5 {
panic(h)
}
if len(bod) < 5 {
tok = hed
} else {
tok = bod
}
if verifyJWT(tok) {
fmt.Println("authJWT has validate the result!")
h.ServeHTTP(w, r)
} else {
fmt.Println("authJWT return error!!!")
panic(h)
}
})
}
}
// using for testing purpose only
func sendProtected() http.Handler {
return http.HandlerFunc(setupUsers)
}