-
Notifications
You must be signed in to change notification settings - Fork 4
/
auth.go
110 lines (95 loc) · 1.92 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
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
110
/*
*
* Copyright 2022 The hvxahv Authors.
* * https://github.com/hvxahv/hvx **
* * https://disism.com **
* /
*/
// Microservice Authorization Certification Package.
package microsvc
import (
"context"
"github.com/hvxahv/hvx/auth"
"github.com/hvxahv/hvx/errors"
"github.com/spf13/viper"
"google.golang.org/grpc/metadata"
"strconv"
"strings"
)
type Userdata struct {
AccountId uint
ActorId uint
DeviceID uint
Username string
Mail string
}
func (x *Userdata) GetAccountId() uint {
if x != nil {
return x.AccountId
}
return 0
}
func (x *Userdata) GetActorId() uint {
if x != nil {
return x.ActorId
}
return 0
}
func (x *Userdata) GetDeviceId() uint {
if x != nil {
return x.DeviceID
}
return 0
}
func (x *Userdata) GetUsername() string {
if x != nil {
return x.Username
}
return ""
}
func (x *Userdata) GetMail() string {
if x != nil {
return x.Mail
}
return ""
}
func GetUserdataByAuthorizationToken(ctx context.Context) (*Userdata, error) {
md, _ := metadata.FromIncomingContext(ctx)
bearer := md.Get("authorization")
if len(bearer) != 1 {
return nil, errors.New(errors.ErrTokenUnauthorized)
}
var (
token = strings.Split(bearer[0], "Bearer ")[1]
secret = viper.GetString("authentication.token.secret")
)
parse, err := auth.NewParseJWTToken(token, secret).JWTTokenParse()
if err != nil {
return nil, err
}
accountId, err := strconv.Atoi(parse.AccountId)
if err != nil {
return nil, err
}
actor, err := strconv.Atoi(parse.ActorId)
if err != nil {
return nil, err
}
deviceId, err := strconv.Atoi(parse.DeviceID)
if err != nil {
return nil, err
}
d := &Userdata{
AccountId: uint(accountId),
ActorId: uint(actor),
DeviceID: uint(deviceId),
Username: parse.Username,
Mail: parse.Mail,
}
return d, nil
}
func GetUserAgent(ctx context.Context) string {
md, _ := metadata.FromIncomingContext(ctx)
ua := md.Get("grpcgateway-user-agent")
return ua[0]
}