/
sso.go
200 lines (168 loc) · 4.79 KB
/
sso.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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
package sso
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"github.com/dptsi/its-go/models"
"github.com/dptsi/its-go/oidc"
"github.com/dptsi/its-go/web"
"golang.org/x/oauth2"
)
type stringAsBool bool
func (sb *stringAsBool) UnmarshalJSON(b []byte) error {
switch string(b) {
case "1", `"1"`:
*sb = true
case "0", `"0"`:
*sb = false
default:
return errors.New("invalid value for boolean")
}
return nil
}
type Role struct {
RoleId string `json:"role_id"`
RoleName string `json:"role_name"`
IsDefault stringAsBool `json:"is_default"`
}
type Group struct {
GroupId string `json:"group_id"`
GroupName string `json:"group_name"`
}
type resource struct {
Path string `json:"path"`
}
type userInfoRaw struct {
Sub string `json:"sub"`
Name string `json:"name"`
Email string `json:"email"`
EmailVerified stringAsBool `json:"email_verified"`
Phone string `json:"phone"`
PhoneVerified stringAsBool `json:"phone_verified"`
Picture string `json:"picture"`
PreferredUsername string `json:"preferred_username"`
Group []Group `json:"group"`
Roles []Role `json:"role"`
Resource interface{} `json:"resource"`
OriginalUserId *string `json:"original_user_id"`
}
type Roles map[string]Role
type RolePermissions map[string][]string
type GroupRoleMapping map[string]string
type Config struct {
// Jika true, maka role dan permission user akan diambil dari SSO
IsRoleFromSso bool
// Jika true, maka group akan dimapping langsung ke role
IsGroupMappedDirectlyToRole bool
// Mekanisme mapping group ke role
// Hanya digunakan ketika isGroupMappedDirectlyToRole = false
// Referensi role yang tersedia
Roles
RolePermissions // Mapping role ke permission
// Mapping group ke role ID
GroupRoleMapping
}
type Sso struct {
client *oidc.Client
cfg Config
}
func NewSso(appCfg map[string]interface{}, client *oidc.Client) *Sso {
cfg, ok := appCfg["sso"].(Config)
if !ok {
return &Sso{
client: client,
cfg: Config{
IsRoleFromSso: true,
IsGroupMappedDirectlyToRole: true,
Roles: nil,
RolePermissions: nil,
GroupRoleMapping: nil,
},
}
}
return &Sso{
client: client,
cfg: cfg,
}
}
func (s *Sso) GetUserFromAuthorizationCode(ctx *web.Context, code string, state string) (*models.User, error) {
token, _, err := s.client.ExchangeCodeForToken(ctx, code, state)
if err != nil {
return nil, fmt.Errorf("get user from myits sso failed: %w", err)
}
userInfo, err := s.userInfo(ctx, s.client, oauth2.StaticTokenSource(token))
if err != nil {
return nil, fmt.Errorf("get user from myits sso failed: %w", err)
}
user := models.NewUser(userInfo.Sub)
user.SetName(userInfo.Name)
user.SetPreferredUsername(userInfo.PreferredUsername)
user.SetEmail(userInfo.Email)
user.SetPhone(userInfo.Phone)
user.SetPicture(userInfo.Picture)
user.SetImpersonatorId(userInfo.OriginalUserId)
if s.cfg.IsRoleFromSso {
for _, r := range userInfo.Roles {
permissions, ok := s.cfg.RolePermissions[r.RoleId]
if !ok {
permissions = make([]string, 0)
}
user.AddRole(r.RoleId, r.RoleName, permissions, bool(r.IsDefault))
}
}
for _, g := range userInfo.Group {
if s.cfg.IsGroupMappedDirectlyToRole {
user.AddRole(g.GroupId, g.GroupName, nil, false)
continue
}
roleId, ok := s.cfg.GroupRoleMapping[g.GroupId]
if !ok {
continue
}
role, ok := s.cfg.Roles[roleId]
if !ok {
continue
}
permissions, ok := s.cfg.RolePermissions[roleId]
if !ok {
permissions = make([]string, 0)
}
user.AddRole(role.RoleId, role.RoleName, permissions, bool(role.IsDefault))
}
return user, nil
}
func (s *Sso) userInfo(ctx context.Context, oidcClient *oidc.Client, tokenSource oauth2.TokenSource) (*userInfoRaw, error) {
userInfoURL := oidcClient.UserInfoEndpoint()
if userInfoURL == "" {
return nil, errors.New("oidc: user info endpoint is not supported by this provider")
}
req, err := http.NewRequest("GET", userInfoURL, nil)
if err != nil {
return nil, fmt.Errorf("oidc: create GET request: %w", err)
}
token, err := tokenSource.Token()
if err != nil {
return nil, fmt.Errorf("oidc: get access token: %w", err)
}
token.SetAuthHeader(req)
resp, err := http.DefaultClient.Do(req.WithContext(ctx))
if err != nil {
return nil, fmt.Errorf("oidc: user info request: %w", err)
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("%s: %s", resp.Status, body)
}
var userInfo userInfoRaw
if err := json.Unmarshal(body, &userInfo); err != nil {
return nil, fmt.Errorf("oidc: failed to decode userinfo: %v", err)
}
return &userInfo, nil
}