/
http.go
109 lines (95 loc) · 2.58 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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
package auth
import (
"net/http"
"strings"
"github.com/labstack/echo/v4"
"github.com/samber/lo"
"github.com/M15t/gram/internal/types"
"github.com/M15t/gram/pkg/server"
)
// HTTP represents auth http service
type HTTP struct {
svc Service
}
// Service represents auth service interface
type Service interface {
Login(echo.Context, Credentials) (*types.AuthToken, error)
RefreshToken(echo.Context, RefreshTokenData) (*types.AuthToken, error)
}
// NewHTTP attaches handlers to Echo routers under given group
func NewHTTP(svc Service, eg *echo.Group) {
h := HTTP{svc: svc}
// swagger:operation POST /auth/login auth authLogin
// ---
// summary: Logs in user by email, password and grant_type
// security: []
// parameters:
// - name: request
// in: body
// description: Request body. `grant_type` should be `app` or `portal`
// required: true
// schema:
// "$ref": "#/definitions/Credentials"
// responses:
// "200":
// description: Access token
// schema:
// "$ref": "#/definitions/AuthToken"
// default:
// description: 'Possible errors: 400, 401, 500'
// schema:
// "$ref": "#/definitions/ErrorResponse"
eg.POST("/login", h.login)
// swagger:operation POST /auth/refresh-token auth authRefreshToken
// ---
// summary: Refresh access token.
// security: []
// parameters:
// - name: token
// in: body
// description: The given `refresh_token` when login.
// required: true
// schema:
// "$ref": "#/definitions/RefreshTokenData"
// responses:
// "200":
// description: New access token. The new `refresh_token` will be returned only if the `access_token` is expired
// schema:
// "$ref": "#/definitions/AuthToken"
// default:
// description: 'Possible errors: 400, 401,500'
// schema:
// "$ref": "#/definitions/ErrorResponse"
eg.POST("/refresh-token", h.refreshToken)
}
func (h *HTTP) login(c echo.Context) error {
r := Credentials{}
if err := c.Bind(&r); err != nil {
return err
}
r.Email = strings.ToLower(strings.TrimSpace(r.Email))
if r.Email == "" {
r.Email = strings.ToLower(strings.TrimSpace(r.Username))
}
if !lo.Contains([]string{
"app", "portal",
}, r.GrantType) {
return server.NewHTTPValidationError("Invalid context")
}
resp, err := h.svc.Login(c, r)
if err != nil {
return err
}
return c.JSON(http.StatusOK, resp)
}
func (h *HTTP) refreshToken(c echo.Context) error {
r := RefreshTokenData{}
if err := c.Bind(&r); err != nil {
return err
}
resp, err := h.svc.RefreshToken(c, r)
if err != nil {
return err
}
return c.JSON(http.StatusOK, resp)
}