-
Notifications
You must be signed in to change notification settings - Fork 96
/
login.go
66 lines (58 loc) · 1.56 KB
/
login.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
package middleware
import (
"errors"
"fmt"
"net/http"
"github.com/douyu/juno/internal/pkg/service/user"
"github.com/labstack/echo/v4"
)
type Auth struct {
Authenticator func(echo.Context) error
Unauthorized func(echo.Context) error
}
func (a Auth) Func() echo.MiddlewareFunc {
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(context echo.Context) error {
if err := a.Authenticator(context); err != nil {
return a.Unauthorized(context)
}
return next(context)
}
}
}
type RedirectType string
const (
RedirectTypeHttp RedirectType = "http_redirect"
RedirectTypeJson RedirectType = "json_redirect"
)
var RedirectParam string = "return_url"
func LoginAuth(loginURL string, redirectType RedirectType) *Auth {
return &Auth{
Authenticator: func(context echo.Context) error {
u := user.GetUser(context)
if !u.IsLogin() {
return errors.New("no session")
}
err := user.Session.Save(context, u)
if err != nil {
return errors.New(fmt.Sprintf("update session err: %s", err.Error()))
}
context.Set("user", u)
return nil
},
Unauthorized: func(context echo.Context) error {
auth := context.Request().Header.Get("juno_auth")
if auth != "" {
return nil
}
if redirectType == RedirectTypeHttp {
return context.Redirect(http.StatusFound, "/user/login?return_url="+context.Request().URL.EscapedPath())
}
return context.JSON(http.StatusOK, map[string]interface{}{
"code": 302,
"msg": fmt.Sprintf("%s?%s=%s", loginURL, RedirectParam, context.Request().RequestURI),
"data": "",
})
},
}
}