forked from ribice/gorsk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
http.go
89 lines (79 loc) · 1.9 KB
/
http.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
package transport
import (
"net/http"
"github.com/ribice/gorsk/pkg/api/auth"
"github.com/labstack/echo"
)
// HTTP represents auth http service
type HTTP struct {
svc auth.Service
}
// NewHTTP creates new auth http service
func NewHTTP(svc auth.Service, e *echo.Echo, mw echo.MiddlewareFunc) {
h := HTTP{svc}
// swagger:route POST /login auth login
// Logs in user by username and password.
// responses:
// 200: loginResp
// 400: errMsg
// 401: errMsg
// 403: err
// 404: errMsg
// 500: err
e.POST("/login", h.login)
// swagger:operation GET /refresh/{token} auth refresh
// ---
// summary: Refreshes jwt token.
// description: Refreshes jwt token by checking at database whether refresh token exists.
// parameters:
// - name: token
// in: path
// description: refresh token
// type: string
// required: true
// responses:
// "200":
// "$ref": "#/responses/refreshResp"
// "400":
// "$ref": "#/responses/errMsg"
// "401":
// "$ref": "#/responses/err"
// "500":
// "$ref": "#/responses/err"
e.GET("/refresh/:token", h.refresh)
// swagger:route GET /me auth meReq
// Gets user's info from session.
// responses:
// 200: userResp
// 500: err
e.GET("/me", h.me, mw)
}
type credentials struct {
Username string `json:"username" validate:"required"`
Password string `json:"password" validate:"required"`
}
func (h *HTTP) login(c echo.Context) error {
cred := new(credentials)
if err := c.Bind(cred); err != nil {
return err
}
r, err := h.svc.Authenticate(c, cred.Username, cred.Password)
if err != nil {
return err
}
return c.JSON(http.StatusOK, r)
}
func (h *HTTP) refresh(c echo.Context) error {
r, err := h.svc.Refresh(c, c.Param("token"))
if err != nil {
return err
}
return c.JSON(http.StatusOK, r)
}
func (h *HTTP) me(c echo.Context) error {
user, err := h.svc.Me(c)
if err != nil {
return err
}
return c.JSON(http.StatusOK, user)
}