fix: Fix issue where website auth_basic is not effective (#8045)

This commit is contained in:
zhengkunwang 2025-03-03 14:28:56 +08:00 committed by GitHub
parent c3bd196a23
commit 569aaf3c0a
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
15 changed files with 65 additions and 51 deletions

View file

@ -1853,7 +1853,6 @@ func (w WebsiteService) ClearProxyCache(req request.NginxCommonReq) error {
func (w WebsiteService) GetAuthBasics(req request.NginxAuthReq) (res response.NginxAuthRes, err error) { func (w WebsiteService) GetAuthBasics(req request.NginxAuthReq) (res response.NginxAuthRes, err error) {
var ( var (
website model.Website website model.Website
nginxInstall model.AppInstall
authContent []byte authContent []byte
nginxParams []response.NginxParam nginxParams []response.NginxParam
) )
@ -1861,12 +1860,7 @@ func (w WebsiteService) GetAuthBasics(req request.NginxAuthReq) (res response.Ng
if err != nil { if err != nil {
return return
} }
nginxInstall, err = getAppInstallByKey(constant.AppOpenresty) absoluteAuthPath := GetSitePath(website, SiteRootAuthBasicPath)
if err != nil {
return
}
authPath := fmt.Sprintf("/www/sites/%s/auth_basic/auth.pass", website.Alias)
absoluteAuthPath := path.Join(nginxInstall.GetPath(), authPath)
fileOp := files.NewFileOp() fileOp := files.NewFileOp()
if !fileOp.Stat(absoluteAuthPath) { if !fileOp.Stat(absoluteAuthPath) {
return return
@ -1897,7 +1891,6 @@ func (w WebsiteService) GetAuthBasics(req request.NginxAuthReq) (res response.Ng
func (w WebsiteService) UpdateAuthBasic(req request.NginxAuthUpdate) (err error) { func (w WebsiteService) UpdateAuthBasic(req request.NginxAuthUpdate) (err error) {
var ( var (
website model.Website website model.Website
nginxInstall model.AppInstall
params []dto.NginxParam params []dto.NginxParam
authContent []byte authContent []byte
authArray []string authArray []string
@ -1906,12 +1899,8 @@ func (w WebsiteService) UpdateAuthBasic(req request.NginxAuthUpdate) (err error)
if err != nil { if err != nil {
return err return err
} }
nginxInstall, err = getAppInstallByKey(constant.AppOpenresty)
if err != nil {
return
}
authPath := fmt.Sprintf("/www/sites/%s/auth_basic/auth.pass", website.Alias) authPath := fmt.Sprintf("/www/sites/%s/auth_basic/auth.pass", website.Alias)
absoluteAuthPath := path.Join(nginxInstall.GetPath(), authPath) absoluteAuthPath := GetSitePath(website, SiteRootAuthBasicPath)
fileOp := files.NewFileOp() fileOp := files.NewFileOp()
if !fileOp.Stat(path.Dir(absoluteAuthPath)) { if !fileOp.Stat(path.Dir(absoluteAuthPath)) {
_ = fileOp.CreateDir(path.Dir(absoluteAuthPath), constant.DirPerm) _ = fileOp.CreateDir(path.Dir(absoluteAuthPath), constant.DirPerm)
@ -2026,20 +2015,14 @@ func (w WebsiteService) UpdateAuthBasic(req request.NginxAuthUpdate) (err error)
func (w WebsiteService) GetPathAuthBasics(req request.NginxAuthReq) (res []response.NginxPathAuthRes, err error) { func (w WebsiteService) GetPathAuthBasics(req request.NginxAuthReq) (res []response.NginxPathAuthRes, err error) {
var ( var (
website model.Website website model.Website
nginxInstall model.AppInstall
authContent []byte authContent []byte
) )
website, err = websiteRepo.GetFirst(repo.WithByID(req.WebsiteID)) website, err = websiteRepo.GetFirst(repo.WithByID(req.WebsiteID))
if err != nil { if err != nil {
return return
} }
nginxInstall, err = getAppInstallByKey(constant.AppOpenresty)
if err != nil {
return
}
fileOp := files.NewFileOp() fileOp := files.NewFileOp()
authDir := fmt.Sprintf("/www/sites/%s/path_auth", website.Alias) absoluteAuthDir := GetSitePath(website, SitePathAuthBasicDir)
absoluteAuthDir := path.Join(nginxInstall.GetPath(), authDir)
passDir := path.Join(absoluteAuthDir, "pass") passDir := path.Join(absoluteAuthDir, "pass")
if !fileOp.Stat(absoluteAuthDir) || !fileOp.Stat(passDir) { if !fileOp.Stat(absoluteAuthDir) || !fileOp.Stat(passDir) {
return return
@ -2097,12 +2080,8 @@ func (w WebsiteService) UpdatePathAuthBasic(req request.NginxPathAuthUpdate) err
if err != nil { if err != nil {
return err return err
} }
nginxInstall, err := getAppInstallByKey(constant.AppOpenresty)
if err != nil {
return err
}
fileOp := files.NewFileOp() fileOp := files.NewFileOp()
authDir := path.Join(nginxInstall.GetPath(), "www", "sites", website.Alias, "path_auth") authDir := GetSitePath(website, SitePathAuthBasicDir)
if !fileOp.Stat(authDir) { if !fileOp.Stat(authDir) {
_ = fileOp.CreateDir(authDir, constant.DirPerm) _ = fileOp.CreateDir(authDir, constant.DirPerm)
} }

View file

@ -1171,6 +1171,8 @@ const (
SitesRootDir = "SitesRootDir" SitesRootDir = "SitesRootDir"
DefaultDir = "DefaultDir" DefaultDir = "DefaultDir"
DefaultRewriteDir = "DefaultRewriteDir" DefaultRewriteDir = "DefaultRewriteDir"
SiteRootAuthBasicPath = "SiteRootAuthBasicPath"
SitePathAuthBasicDir = "SitePathAuthBasicDir"
) )
func GetSitePath(website model.Website, confType string) string { func GetSitePath(website model.Website, confType string) string {
@ -1195,6 +1197,10 @@ func GetSitePath(website model.Website, confType string) string {
return path.Join(GteSiteDir(website.Alias), "rewrite", website.Alias+".conf") return path.Join(GteSiteDir(website.Alias), "rewrite", website.Alias+".conf")
case SiteRedirectDir: case SiteRedirectDir:
return path.Join(GteSiteDir(website.Alias), "redirect") return path.Join(GteSiteDir(website.Alias), "redirect")
case SiteRootAuthBasicPath:
return path.Join(GteSiteDir(website.Alias), "auth_basic", "auth.pass")
case SitePathAuthBasicDir:
return path.Join(GteSiteDir(website.Alias), "path_auth")
} }
return "" return ""
} }

View file

@ -6,6 +6,7 @@ ErrStructTransform: "Type conversion failure: {{ .detail }}"
ErrNotSupportType: "The system does not support the current type: {{ .detail }}" ErrNotSupportType: "The system does not support the current type: {{ .detail }}"
#common #common
ErrUsernameIsExist: "Username already exists"
ErrNameIsExist: "Name is already exist" ErrNameIsExist: "Name is already exist"
ErrDemoEnvironment: "Demo server, prohibit this operation!" ErrDemoEnvironment: "Demo server, prohibit this operation!"
ErrCmdTimeout: "Command execution timed out" ErrCmdTimeout: "Command execution timed out"

View file

@ -14,6 +14,7 @@ ErrApiConfigIPInvalid: "APIインターフェイスIPはホワイトリストに
ErrApiConfigDisable: "このインターフェイスは、APIインターフェイスコールの使用を禁止しています{{.Detail}}" ErrApiConfigDisable: "このインターフェイスは、APIインターフェイスコールの使用を禁止しています{{.Detail}}"
#common #common
ErrUsernameIsExist: "ユーザー名は既に存在します"
ErrNameIsExist: "名前はすでに存在しています" ErrNameIsExist: "名前はすでに存在しています"
ErrDemoEnvironment: "デモサーバー、この操作を禁止します!" ErrDemoEnvironment: "デモサーバー、この操作を禁止します!"
ErrCmdTimeout: "コマンド実行がタイムアウトしました!" ErrCmdTimeout: "コマンド実行がタイムアウトしました!"

View file

@ -15,6 +15,7 @@ ErrApiConfigDisable: "이 인터페이스는 API 호출을 금지합니다: {{ .
ErrApiConfigKeyTimeInvalid: "API 인터페이스 타임스탬프 오류: {{ .detail }}" ErrApiConfigKeyTimeInvalid: "API 인터페이스 타임스탬프 오류: {{ .detail }}"
# 공통 # 공통
ErrUsernameIsExist: "사용자 이름이 이미 존재합니다"
ErrNameIsExist: "이름이 이미 존재합니다" ErrNameIsExist: "이름이 이미 존재합니다"
ErrDemoEnvironment: "데모 서버에서는 이 작업이 금지되어 있습니다!" ErrDemoEnvironment: "데모 서버에서는 이 작업이 금지되어 있습니다!"
ErrCmdTimeout: "명령어 실행 시간이 초과되었습니다!" ErrCmdTimeout: "명령어 실행 시간이 초과되었습니다!"

View file

@ -15,6 +15,7 @@ ErrApiConfigDisable: "Antara muka ini melarang penggunaan panggilan API: {{ .det
ErrApiConfigKeyTimeInvalid: "Ralat cap waktu antara muka API: {{ .detail }}" ErrApiConfigKeyTimeInvalid: "Ralat cap waktu antara muka API: {{ .detail }}"
#common #common
ErrUsernameIsExist: "Nama pengguna sudah wujud"
ErrNameIsExist: "Nama sudah wujud" ErrNameIsExist: "Nama sudah wujud"
ErrDemoEnvironment: "Pelayan demo, operasi ini dilarang!" ErrDemoEnvironment: "Pelayan demo, operasi ini dilarang!"
ErrCmdTimeout: "Pelaksanaan arahan telah tamat masa!" ErrCmdTimeout: "Pelaksanaan arahan telah tamat masa!"

View file

@ -14,6 +14,7 @@ ErrApiConfigIPInvalid: "O IP da interface da API não está na lista de permiss
ErrApiConfigDisable: "Esta interface proíbe o uso de chamadas de API: {{ .detail }}" ErrApiConfigDisable: "Esta interface proíbe o uso de chamadas de API: {{ .detail }}"
#common #common
ErrUsernameIsExist: "Nome de usuário já existe"
ErrNameIsExist: "O nome já existe" ErrNameIsExist: "O nome já existe"
ErrDemoEnvironment: "Servidor de demonstração, operação proibida!" ErrDemoEnvironment: "Servidor de demonstração, operação proibida!"
ErrCmdTimeout: "Tempo limite de execução do comando excedido!" ErrCmdTimeout: "Tempo limite de execução do comando excedido!"

View file

@ -15,6 +15,7 @@ ErrApiConfigDisable: "Этот интерфейс запрещает испол
ErrApiConfigKeyTimeInvalid: "Ошибка временной метки интерфейса API: {{ .detail }}" ErrApiConfigKeyTimeInvalid: "Ошибка временной метки интерфейса API: {{ .detail }}"
#common #common
ErrUsernameIsExist: "Имя пользователя уже существует"
ErrNameIsExist: "Имя уже существует" ErrNameIsExist: "Имя уже существует"
ErrDemoEnvironment: "Демо-сервер, операция запрещена!" ErrDemoEnvironment: "Демо-сервер, операция запрещена!"
ErrCmdTimeout: "Время выполнения команды истекло!" ErrCmdTimeout: "Время выполнения команды истекло!"

View file

@ -10,6 +10,7 @@ ErrApiConfigIPInvalid: "调用 API 接口 IP 不在白名单: {{ .detail }}"
ErrApiConfigDisable: "此接口禁止使用 API 接口調用: {{ .detail }}" ErrApiConfigDisable: "此接口禁止使用 API 接口調用: {{ .detail }}"
#common #common
ErrUsernameIsExist: "使用者名稱已存在"
ErrNameIsExist: "名稱已存在" ErrNameIsExist: "名稱已存在"
ErrDemoEnvironment: "演示伺服器,禁止此操作!" ErrDemoEnvironment: "演示伺服器,禁止此操作!"
ErrCmdTimeout: "指令執行超時!" ErrCmdTimeout: "指令執行超時!"

View file

@ -16,6 +16,7 @@ ErrApiConfigDisable: "此接口禁止使用 API 接口调用: {{ .detail }}"
ErrApiConfigKeyTimeInvalid: "API 接口时间戳错误: {{ .detail }}" ErrApiConfigKeyTimeInvalid: "API 接口时间戳错误: {{ .detail }}"
#common #common
ErrUsernameIsExist: "用户名已存在"
ErrNameIsExist: "名称已存在" ErrNameIsExist: "名称已存在"
ErrDemoEnvironment: "演示服务器,禁止此操作!" ErrDemoEnvironment: "演示服务器,禁止此操作!"
ErrCmdTimeout: "命令执行超时!" ErrCmdTimeout: "命令执行超时!"

View file

@ -49,7 +49,7 @@ func loadDBConn() (*gorm.DB, error) {
baseDir = baseDir[:strings.LastIndex(baseDir, "/")] baseDir = baseDir[:strings.LastIndex(baseDir, "/")]
} }
db, err := gorm.Open(sqlite.Open(baseDir+"/1panel/db/1Panel.db"), &gorm.Config{}) db, err := gorm.Open(sqlite.Open(baseDir+"/1panel/db/core.db"), &gorm.Config{})
if err != nil { if err != nil {
return nil, fmt.Errorf("init my db conn failed, err: %v \n", err) return nil, fmt.Errorf("init my db conn failed, err: %v \n", err)
} }

View file

@ -211,6 +211,19 @@ const checkSimplePassword = (rule: any, value: any, callback: any) => {
} }
}; };
const checkAuthBasicPassword = (rule: any, value: any, callback: any) => {
if (value === '' || typeof value === 'undefined' || value == null) {
callback(new Error(i18n.global.t('commons.rule.authBasicPassword')));
} else {
const reg = /^[a-zA-Z0-9_\-\.@$!%*?&]{1,72}$/;
if (!reg.test(value)) {
callback(new Error(i18n.global.t('commons.rule.authBasicPassword')));
} else {
callback();
}
}
};
const checkDBName = (rule: any, value: any, callback: any) => { const checkDBName = (rule: any, value: any, callback: any) => {
if (value === '' || typeof value === 'undefined' || value == null) { if (value === '' || typeof value === 'undefined' || value == null) {
callback(new Error(i18n.global.t('commons.rule.dbName'))); callback(new Error(i18n.global.t('commons.rule.dbName')));
@ -622,6 +635,7 @@ interface CommonRule {
phpExtensions: FormItemRule; phpExtensions: FormItemRule;
supervisorName: FormItemRule; supervisorName: FormItemRule;
domainOrIP: FormItemRule; domainOrIP: FormItemRule;
authBasicPassword: FormItemRule;
paramCommon: FormItemRule; paramCommon: FormItemRule;
paramComplexity: FormItemRule; paramComplexity: FormItemRule;
@ -865,4 +879,8 @@ export const Rules: CommonRule = {
validator: checkPhone, validator: checkPhone,
trigger: 'blur', trigger: 'blur',
}, },
authBasicPassword: {
validator: checkAuthBasicPassword,
trigger: 'blur',
},
}; };

View file

@ -238,6 +238,7 @@ const message = {
phpExtension: '仅支持 , _ 小写英文和数字', phpExtension: '仅支持 , _ 小写英文和数字',
paramHttp: '必须以 http:// 或 https:// 开头', paramHttp: '必须以 http:// 或 https:// 开头',
phone: '手机号码格式不正确', phone: '手机号码格式不正确',
authBasicPassword: '支持字母数字以及常见特殊字符长度1-72',
}, },
res: { res: {
paramError: '请求失败,请稍后重试!', paramError: '请求失败,请稍后重试!',

View file

@ -56,7 +56,7 @@ import { getRandomStr } from '@/utils/util';
const proxyForm = ref<FormInstance>(); const proxyForm = ref<FormInstance>();
const rules = ref({ const rules = ref({
username: [Rules.requiredInput, Rules.name], username: [Rules.requiredInput, Rules.name],
password: [Rules.requiredInput], password: [Rules.requiredInput, Rules.authBasicPassword],
name: [Rules.requiredInput], name: [Rules.requiredInput],
path: [Rules.requiredInput], path: [Rules.requiredInput],
}); });

View file

@ -85,6 +85,7 @@ const buttons = [
{ {
label: i18n.global.t('commons.button.edit'), label: i18n.global.t('commons.button.edit'),
click: function (row: Website.NginxAuthConfig) { click: function (row: Website.NginxAuthConfig) {
row.scope = 'root';
openEdit(row); openEdit(row);
}, },
}, },
@ -100,6 +101,7 @@ const pathButtons = [
{ {
label: i18n.global.t('commons.button.edit'), label: i18n.global.t('commons.button.edit'),
click: function (row: Website.NginxAuthConfig) { click: function (row: Website.NginxAuthConfig) {
row.scope = 'path';
openEdit(row); openEdit(row);
}, },
}, },