forked from goharbor/harbor
-
Notifications
You must be signed in to change notification settings - Fork 0
/
base.go
252 lines (215 loc) · 6.86 KB
/
base.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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
// Copyright (c) 2017 VMware, Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package controllers
import (
"bytes"
"html/template"
"net"
"net/http"
"os"
"regexp"
"strconv"
"github.com/astaxie/beego"
"github.com/beego/i18n"
"github.com/vmware/harbor/src/common"
"github.com/vmware/harbor/src/common/dao"
"github.com/vmware/harbor/src/common/models"
"github.com/vmware/harbor/src/common/utils"
email_util "github.com/vmware/harbor/src/common/utils/email"
"github.com/vmware/harbor/src/common/utils/log"
"github.com/vmware/harbor/src/ui/auth"
"github.com/vmware/harbor/src/ui/config"
)
// CommonController handles request from UI that doesn't expect a page, such as /SwitchLanguage /logout ...
type CommonController struct {
beego.Controller
i18n.Locale
}
// Render returns nil.
func (cc *CommonController) Render() error {
return nil
}
type messageDetail struct {
Hint string
URL string
UUID string
}
// Login handles login request from UI.
func (cc *CommonController) Login() {
principal := cc.GetString("principal")
password := cc.GetString("password")
user, err := auth.Login(models.AuthModel{
Principal: principal,
Password: password,
})
if err != nil {
log.Errorf("Error occurred in UserLogin: %v", err)
cc.CustomAbort(http.StatusUnauthorized, "")
}
if user == nil {
cc.CustomAbort(http.StatusUnauthorized, "")
}
cc.SetSession("user", *user)
}
// LogOut Habor UI
func (cc *CommonController) LogOut() {
cc.DestroySession()
}
// UserExists checks if user exists when user input value in sign in form.
func (cc *CommonController) UserExists() {
target := cc.GetString("target")
value := cc.GetString("value")
user := models.User{}
switch target {
case "username":
user.Username = value
case "email":
user.Email = value
}
exist, err := dao.UserExists(user, target)
if err != nil {
log.Errorf("Error occurred in UserExists: %v", err)
cc.CustomAbort(http.StatusInternalServerError, "Internal error.")
}
cc.Data["json"] = exist
cc.ServeJSON()
}
// SendResetEmail verifies the Email address and contact SMTP server to send reset password Email.
func (cc *CommonController) SendResetEmail() {
email := cc.GetString("email")
valid, err := regexp.MatchString(`^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$`, email)
if err != nil {
log.Errorf("failed to match regexp: %v", err)
cc.CustomAbort(http.StatusInternalServerError, "Internal error.")
}
if !valid {
cc.CustomAbort(http.StatusBadRequest, "invalid email")
}
queryUser := models.User{Email: email}
u, err := dao.GetUser(queryUser)
if err != nil {
log.Errorf("Error occurred in GetUser: %v", err)
cc.CustomAbort(http.StatusInternalServerError, "Internal error.")
}
if u == nil {
log.Debugf("email %s not found", email)
cc.CustomAbort(http.StatusNotFound, "email_does_not_exist")
}
if !isUserResetable(u) {
log.Errorf("Resetting password for user with ID: %d is not allowed", u.UserID)
cc.CustomAbort(http.StatusForbidden, http.StatusText(http.StatusForbidden))
}
uuid := utils.GenerateRandomString()
user := models.User{ResetUUID: uuid, Email: email}
if err = dao.UpdateUserResetUUID(user); err != nil {
log.Errorf("failed to update user reset UUID: %v", err)
cc.CustomAbort(http.StatusInternalServerError, http.StatusText(http.StatusInternalServerError))
}
messageTemplate, err := template.ParseFiles("views/reset-password-mail.tpl")
if err != nil {
log.Errorf("Parse email template file failed: %v", err)
cc.CustomAbort(http.StatusInternalServerError, err.Error())
}
message := new(bytes.Buffer)
harborURL, err := config.ExtEndpoint()
if err != nil {
log.Errorf("failed to get domain name: %v", err)
cc.CustomAbort(http.StatusInternalServerError, http.StatusText(http.StatusInternalServerError))
}
err = messageTemplate.Execute(message, messageDetail{
Hint: cc.Tr("reset_email_hint"),
URL: harborURL,
UUID: uuid,
})
if err != nil {
log.Errorf("Message template error: %v", err)
cc.CustomAbort(http.StatusInternalServerError, "internal_error")
}
settings, err := config.Email()
if err != nil {
log.Errorf("failed to get email configurations: %v", err)
cc.CustomAbort(http.StatusInternalServerError, "internal_error")
}
addr := net.JoinHostPort(settings.Host, strconv.Itoa(settings.Port))
err = email_util.Send(addr,
settings.Identity,
settings.Username,
settings.Password,
60, settings.SSL,
settings.Insecure,
settings.From,
[]string{email},
"Reset Harbor user password",
message.String())
if err != nil {
log.Errorf("Send email failed: %v", err)
cc.CustomAbort(http.StatusInternalServerError, "send_email_failed")
}
}
// ResetPassword handles request from the reset page and reset password
func (cc *CommonController) ResetPassword() {
resetUUID := cc.GetString("reset_uuid")
if resetUUID == "" {
cc.CustomAbort(http.StatusBadRequest, "Reset uuid is blank.")
}
queryUser := models.User{ResetUUID: resetUUID}
user, err := dao.GetUser(queryUser)
if err != nil {
log.Errorf("Error occurred in GetUser: %v", err)
cc.CustomAbort(http.StatusInternalServerError, "Internal error.")
}
if user == nil {
log.Error("User does not exist")
cc.CustomAbort(http.StatusBadRequest, "User does not exist")
}
if !isUserResetable(user) {
log.Errorf("Resetting password for user with ID: %d is not allowed", user.UserID)
cc.CustomAbort(http.StatusForbidden, http.StatusText(http.StatusForbidden))
}
password := cc.GetString("password")
if password != "" {
user.Password = password
err = dao.ResetUserPassword(*user)
if err != nil {
log.Errorf("Error occurred in ResetUserPassword: %v", err)
cc.CustomAbort(http.StatusInternalServerError, "Internal error.")
}
} else {
cc.CustomAbort(http.StatusBadRequest, "password_is_required")
}
}
func isUserResetable(u *models.User) bool {
if u == nil {
return false
}
mode, err := config.AuthMode()
if err != nil {
log.Errorf("Failed to get the auth mode, error: %v", err)
return false
}
if mode == common.DBAuth {
return true
}
return u.UserID == 1
}
func init() {
//conf/app.conf -> os.Getenv("config_path")
configPath := os.Getenv("CONFIG_PATH")
if len(configPath) != 0 {
log.Infof("Config path: %s", configPath)
if err := beego.LoadAppConfig("ini", configPath); err != nil {
log.Errorf("failed to load app config: %v", err)
}
}
}