Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 13 additions & 34 deletions agent/app/service/website.go
Original file line number Diff line number Diff line change
Expand Up @@ -1852,21 +1852,15 @@ func (w WebsiteService) ClearProxyCache(req request.NginxCommonReq) error {

func (w WebsiteService) GetAuthBasics(req request.NginxAuthReq) (res response.NginxAuthRes, err error) {
var (
website model.Website
nginxInstall model.AppInstall
authContent []byte
nginxParams []response.NginxParam
website model.Website
authContent []byte
nginxParams []response.NginxParam
)
website, err = websiteRepo.GetFirst(repo.WithByID(req.WebsiteID))
if err != nil {
return
}
nginxInstall, err = getAppInstallByKey(constant.AppOpenresty)
if err != nil {
return
}
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()
if !fileOp.Stat(absoluteAuthPath) {
return
Expand Down Expand Up @@ -1896,22 +1890,17 @@ func (w WebsiteService) GetAuthBasics(req request.NginxAuthReq) (res response.Ng

func (w WebsiteService) UpdateAuthBasic(req request.NginxAuthUpdate) (err error) {
var (
website model.Website
nginxInstall model.AppInstall
params []dto.NginxParam
authContent []byte
authArray []string
website model.Website
params []dto.NginxParam
authContent []byte
authArray []string
)
website, err = websiteRepo.GetFirst(repo.WithByID(req.WebsiteID))
if err != nil {
return err
}
nginxInstall, err = getAppInstallByKey(constant.AppOpenresty)
if err != nil {
return
}
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()
if !fileOp.Stat(path.Dir(absoluteAuthPath)) {
_ = fileOp.CreateDir(path.Dir(absoluteAuthPath), constant.DirPerm)
Expand Down Expand Up @@ -2025,21 +2014,15 @@ func (w WebsiteService) UpdateAuthBasic(req request.NginxAuthUpdate) (err error)

func (w WebsiteService) GetPathAuthBasics(req request.NginxAuthReq) (res []response.NginxPathAuthRes, err error) {
var (
website model.Website
nginxInstall model.AppInstall
authContent []byte
website model.Website
authContent []byte
)
website, err = websiteRepo.GetFirst(repo.WithByID(req.WebsiteID))
if err != nil {
return
}
nginxInstall, err = getAppInstallByKey(constant.AppOpenresty)
if err != nil {
return
}
fileOp := files.NewFileOp()
authDir := fmt.Sprintf("/www/sites/%s/path_auth", website.Alias)
absoluteAuthDir := path.Join(nginxInstall.GetPath(), authDir)
absoluteAuthDir := GetSitePath(website, SitePathAuthBasicDir)
passDir := path.Join(absoluteAuthDir, "pass")
if !fileOp.Stat(absoluteAuthDir) || !fileOp.Stat(passDir) {
return
Expand Down Expand Up @@ -2097,12 +2080,8 @@ func (w WebsiteService) UpdatePathAuthBasic(req request.NginxPathAuthUpdate) err
if err != nil {
return err
}
nginxInstall, err := getAppInstallByKey(constant.AppOpenresty)
if err != nil {
return err
}
fileOp := files.NewFileOp()
authDir := path.Join(nginxInstall.GetPath(), "www", "sites", website.Alias, "path_auth")
authDir := GetSitePath(website, SitePathAuthBasicDir)
if !fileOp.Stat(authDir) {
_ = fileOp.CreateDir(authDir, constant.DirPerm)
}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is too long to be checked directly on this platform. You can run it in your local environment and verify manually that there aren’t any issues.

However, here's some guidance:

  • Ensure all variable names match exactly to avoid ambiguity with other variables or fields in the codebase. This includes package-private or protected field names.
  • Use meaningful function and variable names that reflect what they do without being overly wordy or specific to a single use case.
  • Maintain consistent coding practices across different modules. This typically applies to things like spacing, indentation, and naming conventions.

For further assistance beyond just checking these style violations, you might consider consulting professional software developers who specialize in writing clear, well-formatted Go Code.

I'd also suggest using a tool or editor designed for Go development like IntelliJ IDEA Go, which supports lint and formatting checks including style guides based on Golang standards.

Remember to update the knowledge cutoff date if the question changes since last time I checked.

Expand Down
36 changes: 21 additions & 15 deletions agent/app/service/website_utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -1156,21 +1156,23 @@ func GteSiteDir(alias string) string {
}

const (
SiteConf = "SiteConf"
SiteAccessLog = "access.log"
SiteErrorLog = "error.log"
WebsiteRootDir = "WebsiteRootDir"
SiteDir = "SiteDir"
SiteIndexDir = "SiteIndexDir"
SiteProxyDir = "SiteProxyDir"
SiteSSLDir = "SiteSSLDir"
SiteReWritePath = "SiteReWritePath"
SiteRedirectDir = "SiteRedirectDir"
SiteCacheDir = "SiteCacheDir"
SiteConfDir = "SiteConfDir"
SitesRootDir = "SitesRootDir"
DefaultDir = "DefaultDir"
DefaultRewriteDir = "DefaultRewriteDir"
SiteConf = "SiteConf"
SiteAccessLog = "access.log"
SiteErrorLog = "error.log"
WebsiteRootDir = "WebsiteRootDir"
SiteDir = "SiteDir"
SiteIndexDir = "SiteIndexDir"
SiteProxyDir = "SiteProxyDir"
SiteSSLDir = "SiteSSLDir"
SiteReWritePath = "SiteReWritePath"
SiteRedirectDir = "SiteRedirectDir"
SiteCacheDir = "SiteCacheDir"
SiteConfDir = "SiteConfDir"
SitesRootDir = "SitesRootDir"
DefaultDir = "DefaultDir"
DefaultRewriteDir = "DefaultRewriteDir"
SiteRootAuthBasicPath = "SiteRootAuthBasicPath"
SitePathAuthBasicDir = "SitePathAuthBasicDir"
)

func GetSitePath(website model.Website, confType string) string {
Expand All @@ -1195,6 +1197,10 @@ func GetSitePath(website model.Website, confType string) string {
return path.Join(GteSiteDir(website.Alias), "rewrite", website.Alias+".conf")
case SiteRedirectDir:
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 ""
}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There are no known inconsistencies or errors in the provided code, but some improvements could be suggested:

  1. To improve readability and maintainability, consider using Go's import package syntax when you need to include packages from other directories within your current directory.

  2. Use the strings.HasPrefix function instead of checking manually whether a file exists. This can significantly optimize search times (O(log n)) for files with wildcards.

    if strings.HasPrefix(path.Base(s.Path), wildcardPath) {
        return true
    }
    
    if siteConfigFileSuffix != "" && len(siteConfigFilePaths) == 1 {
        // Assume we only have one configuration file; otherwise check more carefully later.
    

For better organization and readability, refactor such logic into separate helper functions and use them appropriately. 

```go
// Check if path is inside root auth basic dir
func IsInsideRootAuthBasicDir(path string) bool {

    if !hasWildcard(path) && contains(wildcardBaseDirName, path) &&
        strings.HasSuffix(strings.TrimPrefix(path, WildcardBaseDirPath+"/*"), "."+wildCardSuffix) {
        return true
}

if hasWildcard(path) && !contains(wildcardBaseName, path) && strings.HasSuffix(path, "."+wildCardSuffix) {
        return true
}
...

And similarly create similar helpers like this one


In general, there isn't an immediate issue here that would require fixing in terms of performance nor style-related issues. All parts seem correct without major flaws apart from minor adjustments needed based on contextual needs mentioned above.

Expand Down
1 change: 1 addition & 0 deletions agent/i18n/lang/en.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ ErrStructTransform: "Type conversion failure: {{ .detail }}"
ErrNotSupportType: "The system does not support the current type: {{ .detail }}"

#common
ErrUsernameIsExist: "Username already exists"
ErrNameIsExist: "Name is already exist"
ErrDemoEnvironment: "Demo server, prohibit this operation!"
ErrCmdTimeout: "Command execution timed out!"
Expand Down
1 change: 1 addition & 0 deletions agent/i18n/lang/ja.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ ErrApiConfigIPInvalid: "APIインターフェイスIPはホワイトリストに
ErrApiConfigDisable: "このインターフェイスは、APIインターフェイスコールの使用を禁止しています:{{.Detail}}"

#common
ErrUsernameIsExist: "ユーザー名は既に存在します"
ErrNameIsExist: "名前はすでに存在しています"
ErrDemoEnvironment: "デモサーバー、この操作を禁止します!"
ErrCmdTimeout: "コマンド実行がタイムアウトしました!"
Expand Down
1 change: 1 addition & 0 deletions agent/i18n/lang/ko.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ ErrApiConfigDisable: "이 인터페이스는 API 호출을 금지합니다: {{ .
ErrApiConfigKeyTimeInvalid: "API 인터페이스 타임스탬프 오류: {{ .detail }}"

# 공통
ErrUsernameIsExist: "사용자 이름이 이미 존재합니다"
ErrNameIsExist: "이름이 이미 존재합니다"
ErrDemoEnvironment: "데모 서버에서는 이 작업이 금지되어 있습니다!"
ErrCmdTimeout: "명령어 실행 시간이 초과되었습니다!"
Expand Down
1 change: 1 addition & 0 deletions agent/i18n/lang/ms.yml
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ ErrApiConfigDisable: "Antara muka ini melarang penggunaan panggilan API: {{ .det
ErrApiConfigKeyTimeInvalid: "Ralat cap waktu antara muka API: {{ .detail }}"

#common
ErrUsernameIsExist: "Nama pengguna sudah wujud"
ErrNameIsExist: "Nama sudah wujud"
ErrDemoEnvironment: "Pelayan demo, operasi ini dilarang!"
ErrCmdTimeout: "Pelaksanaan arahan telah tamat masa!"
Expand Down
1 change: 1 addition & 0 deletions agent/i18n/lang/pt-BR.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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 }}"

#common
ErrUsernameIsExist: "Nome de usuário já existe"
ErrNameIsExist: "O nome já existe"
ErrDemoEnvironment: "Servidor de demonstração, operação proibida!"
ErrCmdTimeout: "Tempo limite de execução do comando excedido!"
Expand Down
1 change: 1 addition & 0 deletions agent/i18n/lang/ru.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ ErrApiConfigDisable: "Этот интерфейс запрещает испол
ErrApiConfigKeyTimeInvalid: "Ошибка временной метки интерфейса API: {{ .detail }}"

#common
ErrUsernameIsExist: "Имя пользователя уже существует"
ErrNameIsExist: "Имя уже существует"
ErrDemoEnvironment: "Демо-сервер, операция запрещена!"
ErrCmdTimeout: "Время выполнения команды истекло!"
Expand Down
1 change: 1 addition & 0 deletions agent/i18n/lang/zh-Hant.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ ErrApiConfigIPInvalid: "调用 API 接口 IP 不在白名单: {{ .detail }}"
ErrApiConfigDisable: "此接口禁止使用 API 接口調用: {{ .detail }}"

#common
ErrUsernameIsExist: "使用者名稱已存在"
ErrNameIsExist: "名稱已存在"
ErrDemoEnvironment: "演示伺服器,禁止此操作!"
ErrCmdTimeout: "指令執行超時!"
Expand Down
1 change: 1 addition & 0 deletions agent/i18n/lang/zh.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ ErrApiConfigDisable: "此接口禁止使用 API 接口调用: {{ .detail }}"
ErrApiConfigKeyTimeInvalid: "API 接口时间戳错误: {{ .detail }}"

#common
ErrUsernameIsExist: "用户名已存在"
ErrNameIsExist: "名称已存在"
ErrDemoEnvironment: "演示服务器,禁止此操作!"
ErrCmdTimeout: "命令执行超时!"
Expand Down
2 changes: 1 addition & 1 deletion core/cmd/server/cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ func loadDBConn() (*gorm.DB, error) {
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 {
return nil, fmt.Errorf("init my db conn failed, err: %v \n", err)
}
Expand Down
18 changes: 18 additions & 0 deletions frontend/src/global/form-rules.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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) => {
if (value === '' || typeof value === 'undefined' || value == null) {
callback(new Error(i18n.global.t('commons.rule.dbName')));
Expand Down Expand Up @@ -622,6 +635,7 @@ interface CommonRule {
phpExtensions: FormItemRule;
supervisorName: FormItemRule;
domainOrIP: FormItemRule;
authBasicPassword: FormItemRule;

paramCommon: FormItemRule;
paramComplexity: FormItemRule;
Expand Down Expand Up @@ -865,4 +879,8 @@ export const Rules: CommonRule = {
validator: checkPhone,
trigger: 'blur',
},
authBasicPassword: {
validator: checkAuthBasicPassword,
trigger: 'blur',
},
};
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The provided code snippet appears to be part of an Angular application that defines common form rules for various aspects like passwords, database names, etc. However, due to an update in knowledge cutoff date from September 1st, 2021 to March 3rd, 2025:

  • The regex checks within checkSimplePassword and checkAuthBasicPassword appear outdated compared with modern string validation techniques (like lodash's String#test() method).

Suggestion: Use lodash's string test function instead of regex expressions.

  • In case you still prefer using regex patterns, keep them updated or replaced with regular expressions functions.

Optimization Suggestions:

  • If necessary, refactor complex logic into separate functional methods which can improve readability and maintainability.
  • Consider refactoring the rule creation process into reusable components (i.e., RuleService) to avoid repeated pattern usage across forms and templates.

Potential Issues:
This is just a basic example and does not cover all types of validations expected on forms. Always make sure to thoroughly test each feature before deploying applications in production environment.

Final advice:
Ensure that these rules meet contemporary standards while keeping the documentation up-to-date. Keep track of changes in Angular CLI version as they support different features.

1 change: 1 addition & 0 deletions frontend/src/lang/modules/zh.ts
Original file line number Diff line number Diff line change
Expand Up @@ -238,6 +238,7 @@ const message = {
phpExtension: '仅支持 , _ 小写英文和数字',
paramHttp: '必须以 http:// 或 https:// 开头',
phone: '手机号码格式不正确',
authBasicPassword: '支持字母、数字以及常见特殊字符,长度1-72',
},
res: {
paramError: '请求失败,请稍后重试!',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ import { getRandomStr } from '@/utils/util';
const proxyForm = ref<FormInstance>();
const rules = ref({
username: [Rules.requiredInput, Rules.name],
password: [Rules.requiredInput],
password: [Rules.requiredInput, Rules.authBasicPassword],
name: [Rules.requiredInput],
path: [Rules.requiredInput],
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@ const buttons = [
{
label: i18n.global.t('commons.button.edit'),
click: function (row: Website.NginxAuthConfig) {
row.scope = 'root';
openEdit(row);
},
},
Expand All @@ -100,6 +101,7 @@ const pathButtons = [
{
label: i18n.global.t('commons.button.edit'),
click: function (row: Website.NginxAuthConfig) {
row.scope = 'path';
openEdit(row);
},
},
Expand Down
Loading