-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.go
71 lines (59 loc) · 1.36 KB
/
auth.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
package auth
import (
"github.com/bilibili/kratos/pkg/ecode"
bm "github.com/bilibili/kratos/pkg/net/http/blademaster"
"github.com/bilibili/kratos/pkg/net/metadata"
"github.com/bilibili/kratos/pkg/net/rpc/warden"
authrpc "github.com/itswcg/micro/auth/api"
)
type Config struct {
AuthClient *warden.ClientConfig
}
type Auth struct {
config *Config
ac authrpc.AuthClient
}
func New(conf *Config) *Auth {
auth := &Auth{config: conf}
ac, err := authrpc.NewClient(auth.config.AuthClient)
if err != nil {
panic(err)
}
auth.ac = ac
return auth
}
func (a *Auth) authToken(ctx *bm.Context, token string) (mid int64, err error) {
tokenReq := &authrpc.TokenReq{Token: token}
tokenReply, err := a.ac.Token(ctx, tokenReq)
if err != nil {
return 0, err
}
return tokenReply.Mid, nil
}
func (a *Auth) IsAdmin(ctx *bm.Context) {
}
func (a *Auth) IsAuthenticated(ctx *bm.Context) {
req := ctx.Request
token := req.Header.Get("Authorization")
if token == "" {
ctx.JSON(nil, ecode.Unauthorized)
ctx.Abort()
return
}
mid, err := a.authToken(ctx, token)
if err != nil {
ctx.JSON(nil, ecode.Unauthorized)
ctx.Abort()
return
}
a.setMid(ctx, mid)
}
func (a *Auth) AllowAny(ctx *bm.Context) {
}
func (a *Auth) setMid(ctx *bm.Context, mid int64) {
ctx.Set(metadata.Mid, mid)
if md, ok := metadata.FromContext(ctx); ok {
md[metadata.Mid] = mid
return
}
}