-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathmain.go
223 lines (169 loc) · 4.63 KB
/
main.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
package main
import (
"database/sql"
"encoding/json"
"fmt"
"log"
"net/http"
"strings"
jwt "github.com/dgrijalva/jwt-go"
"github.com/gorilla/mux"
"github.com/lib/pq"
"golang.org/x/crypto/bcrypt"
)
type User struct {
ID int `json:"id"`
Email string `json:"email"`
Password string `json:"password"`
}
type JWT struct {
Token string `json:"token"`
}
type Error struct {
Message string `json:"message"`
}
var db *sql.DB
func main() {
pgUrl, err := pq.ParseURL("postgres://afdfadfdfadf:fdfdfdfdfd-2fdE-dffdfdfdfdfd@elmer.db.elephantsql.com:5432/afdfadfdfadf")
if err != nil {
log.Fatal(err)
}
db, err = sql.Open("postgres", pgUrl)
if err != nil {
log.Fatal(err)
}
err = db.Ping()
router := mux.NewRouter()
router.HandleFunc("/signup", signup).Methods("POST")
router.HandleFunc("/login", login).Methods("POST")
router.HandleFunc("/protected", TokenVerifyMiddleWare(protectedEndpoint)).Methods("GET")
log.Println("Listen on port 8000...")
log.Fatal(http.ListenAndServe(":8000", router))
}
func respondWithError(w http.ResponseWriter, status int, error Error) {
w.WriteHeader(status)
json.NewEncoder(w).Encode(error)
}
func responseJSON(w http.ResponseWriter, data interface{}) {
json.NewEncoder(w).Encode(data)
}
func signup(w http.ResponseWriter, r *http.Request) {
var user User
var error Error
json.NewDecoder(r.Body).Decode(&user)
if user.Email == "" {
error.Message = "Email is missing."
respondWithError(w, http.StatusBadRequest, error)
return
}
if user.Password == "" {
error.Message = "Password is missing."
respondWithError(w, http.StatusBadRequest, error)
return
}
hash, err := bcrypt.GenerateFromPassword([]byte(user.Password), 10)
if err != nil {
log.Fatal(err)
}
user.Password = string(hash)
stmt := "insert into users (email, password) values($1, $2) RETURNING id;"
err = db.QueryRow(stmt, user.Email, user.Password).Scan(&user.ID)
if err != nil {
error.Message = "Server error."
respondWithError(w, http.StatusInternalServerError, error)
return
}
user.Password = ""
w.Header().Set("Content-Type", "application/json")
responseJSON(w, user)
}
func GenerateToken(user User) (string, error) {
var err error
secret := "secret"
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"email": user.Email,
"iss": "course",
})
tokenString, err := token.SignedString([]byte(secret))
if err != nil {
log.Fatal(err)
}
return tokenString, nil
}
func login(w http.ResponseWriter, r *http.Request) {
var user User
var jwt JWT
var error Error
json.NewDecoder(r.Body).Decode(&user)
if user.Email == "" {
error.Message = "Email is missing."
respondWithError(w, http.StatusBadRequest, error)
return
}
if user.Password == "" {
error.Message = "Password is missing."
respondWithError(w, http.StatusBadRequest, error)
return
}
password := user.Password
row := db.QueryRow("select * from users where email=$1", user.Email)
err := row.Scan(&user.ID, &user.Email, &user.Password)
if err != nil {
if err == sql.ErrNoRows {
error.Message = "The user does not exist"
respondWithError(w, http.StatusBadRequest, error)
return
} else {
log.Fatal(err)
}
}
hashedPassword := user.Password
err = bcrypt.CompareHashAndPassword([]byte(hashedPassword), []byte(password))
if err != nil {
error.Message = "Invalid Password"
respondWithError(w, http.StatusUnauthorized, error)
return
}
token, err := GenerateToken(user)
if err != nil {
log.Fatal(err)
}
w.WriteHeader(http.StatusOK)
jwt.Token = token
responseJSON(w, jwt)
}
func protectedEndpoint(w http.ResponseWriter, r *http.Request) {
fmt.Println("protectedEndpoint invoked.")
}
func TokenVerifyMiddleWare(next http.HandlerFunc) http.HandlerFunc {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var errorObject Error
authHeader := r.Header.Get("Authorization")
bearerToken := strings.Split(authHeader, " ")
if len(bearerToken) == 2 {
authToken := bearerToken[1]
token, error := jwt.Parse(authToken, func(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("There was an error")
}
return []byte("secret"), nil
})
if error != nil {
errorObject.Message = error.Error()
respondWithError(w, http.StatusUnauthorized, errorObject)
return
}
if token.Valid {
next.ServeHTTP(w, r)
} else {
errorObject.Message = error.Error()
respondWithError(w, http.StatusUnauthorized, errorObject)
return
}
} else {
errorObject.Message = "Invalid token."
respondWithError(w, http.StatusUnauthorized, errorObject)
return
}
})
}