-
Notifications
You must be signed in to change notification settings - Fork 33
/
api.go
62 lines (46 loc) · 1.17 KB
/
api.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
package main
import (
"encoding/json"
"net/http"
"github.com/jeroendk/chatApplication/auth"
"github.com/jeroendk/chatApplication/repository"
)
type LoginUser struct {
Username string `json:"username"`
Password string `json:"password"`
}
type API struct {
UserRepository *repository.UserRepository
}
func (api *API) HandleLogin(w http.ResponseWriter, r *http.Request) {
var user LoginUser
// Try to decode the JSON request to a LoginUser
err := json.NewDecoder(r.Body).Decode(&user)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
// Find the user in the database by username
dbUser := api.UserRepository.FindUserByUsername(user.Username)
if dbUser == nil {
returnErrorResponse(w)
return
}
// Check if the passwords match
ok, err := auth.ComparePassword(user.Password, dbUser.Password)
if !ok || err != nil {
returnErrorResponse(w)
return
}
// Create a JWT
token, err := auth.CreateJWTToken(dbUser)
if err != nil {
returnErrorResponse(w)
return
}
w.Write([]byte(token))
}
func returnErrorResponse(w http.ResponseWriter) {
w.Header().Set("Content-Type", "application/json")
w.Write([]byte("{\"status\": \"error\"}"))
}