/
authHandler.go
67 lines (52 loc) · 1.5 KB
/
authHandler.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
package handlers
import (
"encoding/json"
"fmt"
"net/http"
"time"
"github.com/RomaBiliak/lets-go-chat/pkg/response"
)
type authService interface {
Login(userName, password string) (string, error)
}
type authHTTP struct {
authService authService
}
func NewAuthHttp(authService authService) *authHTTP {
return &authHTTP{authService: authService}
}
type loginRequest struct {
UserName string `json:"userName"`
Password string `json:"password"`
}
func (r *loginRequest) validate() bool {
return len(r.UserName) > 0 && len(r.Password) > 0
}
type LoginResponse struct {
Url string `json:"url"`
}
//Login returns token to join chat, status code of 201
func (h *authHTTP) Login(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
response.WriteERROR(w, http.StatusMethodNotAllowed, nil)
return
}
loginRequest := &loginRequest{}
err := json.NewDecoder(r.Body).Decode(loginRequest)
if err != nil {
response.WriteERROR(w, http.StatusBadRequest, err)
return
}
if ok := loginRequest.validate(); !ok {
response.WriteERROR(w, http.StatusBadRequest, fmt.Errorf("%s", "Bad request, empty user name or password"))
return
}
token, err := h.authService.Login(loginRequest.UserName, loginRequest.Password)
if err != nil {
response.WriteERROR(w, http.StatusBadRequest, err)
return
}
w.Header().Set("X-Rate-Limit", "999999")
w.Header().Set("X-Expires-After", time.Now().Add(time.Hour*1).UTC().String())
response.WriteJSON(w, http.StatusCreated, LoginResponse{Url: token})
}