-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathuser_ctl.go
209 lines (182 loc) · 5.53 KB
/
user_ctl.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
201
202
203
204
205
206
207
208
209
package controller
import (
"context"
"encoding/hex"
"fmt"
"net/http"
"time"
"github.com/GitDataAI/jiaozifs/auth/rbac"
"github.com/GitDataAI/jiaozifs/controller/validator"
"github.com/GitDataAI/jiaozifs/models/rbacmodel"
"github.com/GitDataAI/jiaozifs/utils"
"github.com/GitDataAI/jiaozifs/api"
"github.com/GitDataAI/jiaozifs/auth"
"github.com/GitDataAI/jiaozifs/config"
"github.com/GitDataAI/jiaozifs/models"
"github.com/go-openapi/swag"
"github.com/gorilla/sessions"
logging "github.com/ipfs/go-log/v2"
openapitypes "github.com/oapi-codegen/runtime/types"
"go.uber.org/fx"
)
var userCtlLog = logging.Logger("user_ctl")
type UserController struct {
fx.In
BaseController
SessionStore sessions.Store
Repo models.IRepo
Config *config.AuthConfig
BasicAuthenticator *auth.BasicAuthenticator
}
func (userCtl UserController) Login(ctx context.Context, w *api.JiaozifsResponse, r *http.Request, body api.LoginJSONRequestBody) {
user, err := userCtl.BasicAuthenticator.AuthenticateUser(ctx, body.Name, body.Password)
if err != nil {
w.Code(http.StatusUnauthorized)
return
}
userCtl.generateAndRespToken(w, r, user.Name)
}
func (userCtl UserController) RefreshToken(ctx context.Context, w *api.JiaozifsResponse, r *http.Request) {
operator, err := auth.GetOperator(ctx)
if err != nil {
w.Error(err)
return
}
userCtl.generateAndRespToken(w, r, operator.Name)
}
func (userCtl UserController) generateAndRespToken(w *api.JiaozifsResponse, r *http.Request, name string) {
// Generate user token
loginTime := time.Now()
expires := loginTime.Add(auth.ExpirationDuration)
secretKey, err := hex.DecodeString(userCtl.Config.SecretKey)
if err != nil {
w.Error(err)
return
}
tokenString, err := auth.GenerateJWTLogin(secretKey, name, loginTime, expires)
if err != nil {
w.Error(err)
return
}
userCtlLog.Infof("user %s login successful", name)
internalAuthSession, _ := userCtl.SessionStore.Get(r, auth.InternalAuthSessionName)
internalAuthSession.Values[auth.TokenSessionKeyName] = tokenString
err = userCtl.SessionStore.Save(r, w, internalAuthSession)
if err != nil {
userCtlLog.Errorf("Failed to save internal auth session %v", err)
w.Code(http.StatusInternalServerError)
return
}
w.JSON(api.AuthenticationToken{
Token: tokenString,
TokenExpiration: swag.Int64(expires.Unix()),
})
}
func (userCtl UserController) Register(ctx context.Context, w *api.JiaozifsResponse, _ *http.Request, body api.RegisterJSONRequestBody) {
err := validator.ValidateUsername(body.Name)
if err != nil {
w.BadRequest(err.Error())
return
}
// check username, email
count1, err := userCtl.Repo.UserRepo().Count(ctx, models.NewCountUserParam().SetName(body.Name))
if err != nil {
w.Error(err)
return
}
count2, err := userCtl.Repo.UserRepo().Count(ctx, models.NewCountUserParam().SetEmail(string(body.Email)))
if err != nil {
w.Error(err)
return
}
if count1+count2 > 0 {
w.BadRequest(fmt.Sprintf("username %s or email %s not found ", body.Name, body.Email))
}
// reserve temporarily
password, err := auth.HashPassword(body.Password)
if err != nil {
w.Error(err)
return
}
// insert db
user := &models.User{
Name: body.Name,
Email: string(body.Email),
EncryptedPassword: string(password),
CurrentSignInAt: time.Time{},
LastSignInAt: time.Time{},
CurrentSignInIP: "",
LastSignInIP: "",
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
}
var insertUser *models.User
err = userCtl.Repo.Transaction(ctx, func(repo models.IRepo) error {
insertUser, err = repo.UserRepo().Insert(ctx, user)
if err != nil {
return fmt.Errorf("inser user %s user error %w", body.Name, err)
}
userOwnGroup, err := repo.GroupRepo().Get(ctx, rbacmodel.NewGetGroupParams().SetName(rbac.UserOwnAccess))
if err != nil {
return err
}
//bind own user group
_, err = repo.UserGroupRepo().Insert(ctx, &rbacmodel.UserGroup{
UserID: insertUser.ID,
GroupID: userOwnGroup.ID,
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
})
return err
})
if err != nil {
w.Error(err)
return
}
w.JSON(userInfoToDto(insertUser), http.StatusCreated)
}
func (userCtl UserController) GetUserInfo(ctx context.Context, w *api.JiaozifsResponse, _ *http.Request) {
// Get token from Header
user, err := auth.GetOperator(ctx)
if err != nil {
w.Code(http.StatusUnauthorized)
return
}
if !userCtl.authorize(ctx, w, rbac.Node{
Permission: rbac.Permission{
Action: rbacmodel.ListRepositoriesAction,
Resource: rbacmodel.RepoUArn(user.ID.String()),
},
}) {
return
}
w.JSON(userInfoToDto(user))
}
func (userCtl UserController) Logout(_ context.Context, w *api.JiaozifsResponse, r *http.Request) {
//todo only web credencial could logout
session, err := userCtl.SessionStore.Get(r, auth.InternalAuthSessionName)
if err != nil {
w.Error(err)
return
}
session.Options.MaxAge = -1
if session.Save(r, w) != nil {
userCtlLog.Errorf("Failed to save internal auth session %v", err)
w.Error(err)
return
}
http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
}
func userInfoToDto(user *models.User) *api.UserInfo {
return &api.UserInfo{
Id: user.ID,
Name: user.Name,
Email: openapitypes.Email(user.Email),
CurrentSignInAt: utils.Int64(user.CurrentSignInAt.UnixMilli()),
CurrentSignInIp: &user.CurrentSignInIP,
LastSignInAt: utils.Int64(user.LastSignInAt.UnixMilli()),
LastSignInIp: &user.LastSignInIP,
UpdatedAt: user.UpdatedAt.UnixMilli(),
CreatedAt: user.CreatedAt.UnixMilli(),
}
}