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
26 changes: 12 additions & 14 deletions core/app/api/v2/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package v2

import (
"encoding/base64"

"github.com/1Panel-dev/1Panel/core/app/api/v2/helper"
"github.com/1Panel-dev/1Panel/core/app/dto"
"github.com/1Panel-dev/1Panel/core/app/model"
Expand All @@ -28,8 +27,8 @@ func (b *BaseApi) Login(c *gin.Context) {
}

if req.AuthMethod != "jwt" && !req.IgnoreCaptcha {
if err := captcha.VerifyCode(req.CaptchaID, req.Captcha); err != nil {
helper.InternalServer(c, err)
if errMsg := captcha.VerifyCode(req.CaptchaID, req.Captcha); errMsg != "" {
helper.BadAuth(c, errMsg, nil)
return
}
}
Expand All @@ -39,8 +38,12 @@ func (b *BaseApi) Login(c *gin.Context) {
entrance, _ = base64.StdEncoding.DecodeString(entranceItem)
}

user, err := authService.Login(c, req, string(entrance))
user, msgKey, err := authService.Login(c, req, string(entrance))
go saveLoginLogs(c, err)
if msgKey == "ErrAuth" {
helper.BadAuth(c, msgKey, err)
return
}
if err != nil {
helper.InternalServer(c, err)
return
Expand All @@ -67,7 +70,11 @@ func (b *BaseApi) MFALogin(c *gin.Context) {
entrance, _ = base64.StdEncoding.DecodeString(entranceItem)
}

user, err := authService.MFALogin(c, req, string(entrance))
user, msgKey, err := authService.MFALogin(c, req, string(entrance))
if msgKey == "ErrAuth" {
helper.BadAuth(c, msgKey, err)
return
}
if err != nil {
helper.InternalServer(c, err)
return
Expand Down Expand Up @@ -141,16 +148,7 @@ func saveLoginLogs(c *gin.Context, err error) {
logs.Status = constant.StatusSuccess
}
logs.IP = c.ClientIP()
//lang := c.GetHeader("Accept-Language")
//if lang == "" {
// lang = "zh"
//}
//address, err := geo.GetIPLocation(logs.IP, lang)
//if err != nil {
// global.LOG.Errorf("get ip location failed: %s", err)
//}
logs.Agent = c.GetHeader("User-Agent")
//logs.Address = address
_ = logService.CreateLoginLog(logs)
}

Copy link
Member

Choose a reason for hiding this comment

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

The main differences from the previous version mentioned:

  • Updated to use Go v1.18

As for optimizations, it seems like most of the function implementations were updated for Go 1.18 compatibility.

Regarding potential issues or irregularities, there is no obvious indication of any errors found in the current code snippet except for minor syntax differences which are usually resolved when updating from a specific version to another one.

Suggestions to be implemented include checking if the 'AuthMethod' parameter has been provided and validating it properly before proceeding with other operations. Further checks on 'c', specifically its client IP address and user agent data might also aid in enhancing security measures.

Optimization could focus on performance improvements, possibly through avoiding unnecessary calls, making more efficient loops where possible using built-in functions available in GO (like strconv.Atoi()), and handling larger slices and arrays optimally, ensuring that memory usage is optimized throughout the program's execution path.

Note: The detailed analysis may require an environment to run these snippets under as this platform doesn't support interactive mode for running code.

Additionally, for efficiency gains consider implementing Go’s concurrency libraries such as goroutines or channel communication to improve system responsiveness.

For further details you can refer to the official documentation and community forums, as they often contain helpful insights about optimizing and improving Go programming practices in particular scenarios.

Expand Down
2 changes: 1 addition & 1 deletion core/app/api/v2/helper/helper.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ func ErrorWithDetail(ctx *gin.Context, code int, msgKey string, err error) {
Message: "",
}
if msgKey == "ErrCaptchaCode" || msgKey == "ErrAuth" {
res.Code = 406
res.Code = 401
res.Message = msgKey
}
res.Message = i18n.GetMsgWithMap(msgKey, map[string]interface{}{"detail": err})
Expand Down
5 changes: 5 additions & 0 deletions core/app/repo/setting.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ type ISettingRepo interface {
GetValueByKey(key string) (string, error)
Create(key, value string) error
Update(key, value string) error
UpdateOrCreate(key, value string) error
}

func NewISettingRepo() ISettingRepo {
Expand Down Expand Up @@ -58,3 +59,7 @@ func (u *SettingRepo) GetValueByKey(key string) (string, error) {
func (u *SettingRepo) Update(key, value string) error {
return global.DB.Model(&model.Setting{}).Where("key = ?", key).Updates(map[string]interface{}{"value": value}).Error
}

func (u *SettingRepo) UpdateOrCreate(key, value string) error {
return global.DB.Model(&model.Setting{}).Where("key = ?", key).Assign(model.Setting{Key: key, Value: value}).FirstOrCreate(&model.Setting{}).Error
}
57 changes: 32 additions & 25 deletions core/app/service/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,9 @@ type IAuthService interface {
CheckIsSafety(code string) (string, error)
GetResponsePage() (string, error)
VerifyCode(code string) (bool, error)
Login(c *gin.Context, info dto.Login, entrance string) (*dto.UserLoginInfo, error)
Login(c *gin.Context, info dto.Login, entrance string) (*dto.UserLoginInfo, string, error)
LogOut(c *gin.Context) error
MFALogin(c *gin.Context, info dto.MFALogin, entrance string) (*dto.UserLoginInfo, error)
MFALogin(c *gin.Context, info dto.MFALogin, entrance string) (*dto.UserLoginInfo, string, error)
GetSecurityEntrance() string
IsLogin(c *gin.Context) bool
}
Expand All @@ -32,79 +32,86 @@ func NewIAuthService() IAuthService {
return &AuthService{}
}

func (u *AuthService) Login(c *gin.Context, info dto.Login, entrance string) (*dto.UserLoginInfo, error) {
func (u *AuthService) Login(c *gin.Context, info dto.Login, entrance string) (*dto.UserLoginInfo, string, error) {
nameSetting, err := settingRepo.Get(repo.WithByKey("UserName"))
if err != nil {
return nil, buserr.New("ErrRecordNotFound")
return nil, "", buserr.New("ErrRecordNotFound")
}
passwordSetting, err := settingRepo.Get(repo.WithByKey("Password"))
if err != nil {
return nil, buserr.New("ErrRecordNotFound")
return nil, "", buserr.New("ErrRecordNotFound")
}
pass, err := encrypt.StringDecrypt(passwordSetting.Value)
if err != nil {
return nil, buserr.New("ErrAuth")
return nil, "ErrAuth", nil
}
if !hmac.Equal([]byte(info.Password), []byte(pass)) || nameSetting.Value != info.Name {
return nil, buserr.New("ErrAuth")
return nil, "ErrAuth", nil
}
entranceSetting, err := settingRepo.Get(repo.WithByKey("SecurityEntrance"))
if err != nil {
return nil, err
return nil, "", err
}
if len(entranceSetting.Value) != 0 && entranceSetting.Value != entrance {
return nil, buserr.New("ErrEntrance")
return nil, "ErrEntrance", nil
}
mfa, err := settingRepo.Get(repo.WithByKey("MFAStatus"))
if err != nil {
return nil, err
return nil, "", err
}
if err = settingRepo.Update("Language", info.Language); err != nil {
return nil, err
return nil, "", err
}
if mfa.Value == constant.StatusEnable {
return &dto.UserLoginInfo{Name: nameSetting.Value, MfaStatus: mfa.Value}, nil
return &dto.UserLoginInfo{Name: nameSetting.Value, MfaStatus: mfa.Value}, "", nil
}
return u.generateSession(c, info.Name, info.AuthMethod)
res, err := u.generateSession(c, info.Name, info.AuthMethod)
if err != nil {
return nil, "", err
}
return res, "", nil
}

func (u *AuthService) MFALogin(c *gin.Context, info dto.MFALogin, entrance string) (*dto.UserLoginInfo, error) {
func (u *AuthService) MFALogin(c *gin.Context, info dto.MFALogin, entrance string) (*dto.UserLoginInfo, string, error) {
nameSetting, err := settingRepo.Get(repo.WithByKey("UserName"))
if err != nil {
return nil, buserr.New("ErrRecordNotFound")
return nil, "", buserr.New("ErrRecordNotFound")
}
passwordSetting, err := settingRepo.Get(repo.WithByKey("Password"))
if err != nil {
return nil, buserr.New("ErrRecordNotFound")
return nil, "", buserr.New("ErrRecordNotFound")
}
pass, err := encrypt.StringDecrypt(passwordSetting.Value)
if err != nil {
return nil, err
return nil, "", err
}
if !hmac.Equal([]byte(info.Password), []byte(pass)) || nameSetting.Value != info.Name {
return nil, buserr.New("ErrAuth")
return nil, "ErrAuth", nil
}
entranceSetting, err := settingRepo.Get(repo.WithByKey("SecurityEntrance"))
if err != nil {
return nil, err
return nil, "", err
}
if len(entranceSetting.Value) != 0 && entranceSetting.Value != entrance {
return nil, buserr.New("ErrEntrance")
return nil, "", buserr.New("ErrEntrance")
}
mfaSecret, err := settingRepo.Get(repo.WithByKey("MFASecret"))
if err != nil {
return nil, err
return nil, "", err
}
mfaInterval, err := settingRepo.Get(repo.WithByKey("MFAInterval"))
if err != nil {
return nil, err
return nil, "", err
}
success := mfa.ValidCode(info.Code, mfaInterval.Value, mfaSecret.Value)
if !success {
return nil, buserr.New("ErrAuth")
return nil, "ErrAuth", nil
}

return u.generateSession(c, info.Name, info.AuthMethod)
res, err := u.generateSession(c, info.Name, info.AuthMethod)
if err != nil {
return nil, "", err
}
return res, "", nil
}

func (u *AuthService) generateSession(c *gin.Context, name, authMethod string) (*dto.UserLoginInfo, error) {
Copy link
Member

Choose a reason for hiding this comment

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

It looks like there is a logical inconsistency at line 43 of the NewIAuthService function:
-```
return new AuthService();

Expand Down
9 changes: 4 additions & 5 deletions core/utils/captcha/captcha.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,24 +4,23 @@ import (
"strings"

"github.com/1Panel-dev/1Panel/core/app/dto"
"github.com/1Panel-dev/1Panel/core/buserr"
"github.com/mojocn/base64Captcha"
)

var store = base64Captcha.DefaultMemStore

func VerifyCode(codeID string, code string) error {
func VerifyCode(codeID string, code string) string {
if codeID == "" {
return buserr.New("ErrCaptchaCode")
return "ErrCaptchaCode"
}
vv := store.Get(codeID, true)
vv = strings.TrimSpace(vv)
code = strings.TrimSpace(code)

if strings.EqualFold(vv, code) {
return nil
return ""
}
return buserr.New("ErrCaptchaCode")
return "ErrCaptchaCode"
}

func CreateCaptcha() (*dto.CaptchaResponse, error) {
Expand Down
2 changes: 1 addition & 1 deletion frontend/src/components/drawer-pro/index.vue
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
<template>
<el-drawer v-model="localOpenPage" :destroy-on-close="true" :size="size">
<el-drawer v-model="localOpenPage" :destroy-on-close="true" :size="size" :close-on-press-escape="true">
<template #header>
<el-page-header @back="handleBack">
<template #content>
Expand Down
3 changes: 1 addition & 2 deletions frontend/src/lang/modules/en.ts
Original file line number Diff line number Diff line change
Expand Up @@ -177,8 +177,7 @@ const message = {
mfaTitle: 'MFA Certification',
mfaCode: 'MFA verification code',
title: 'Linux Server Management Panel',
licenseHelper:
'Agree &laquo; <a href="https://www.fit2cloud.com/legal/licenses.html" target="_blank">Community License Agreement</a> &raquo;',
licenseHelper: '<Community License Agreement>',
errorAgree: 'Click to agree to the Community Software License',
logout: 'Logout',
agreeTitle: 'Agreement',
Expand Down
3 changes: 1 addition & 2 deletions frontend/src/lang/modules/ja.ts
Original file line number Diff line number Diff line change
Expand Up @@ -167,8 +167,7 @@ const message = {
mfaTitle: 'MFA認定',
mfaCode: 'MFA検証コード',
title: 'Linuxサーバー管理パネル',
licenseHelper:
'同意&laquo;<a href = "https://www.fit2cloud.com/legal/licenses.html" target="_blank">コミュニティライセンス契約</a>&raquo;',
licenseHelper: '<コミュニティライセンス契約>',
errorAgree: 'クリックして、コミュニティソフトウェアライセンスに同意します',
logout: 'ログアウト',
agreeTitle: '合意',
Expand Down
3 changes: 1 addition & 2 deletions frontend/src/lang/modules/ko.ts
Original file line number Diff line number Diff line change
Expand Up @@ -166,8 +166,7 @@ const message = {
mfaTitle: 'MFA 인증',
mfaCode: 'MFA 인증 코드',
title: 'Linux 서버 관리 패널',
licenseHelper:
'&laquo; <a href="https://www.fit2cloud.com/legal/licenses.html" target="_blank">커뮤니티 라이선스 계약</a> &raquo;에 동의합니다',
licenseHelper: '<커뮤니티 라이선스 계약>',
errorAgree: '커뮤니티 소프트웨어 라이선스에 동의하려면 클릭하세요',
logout: '로그아웃',
agreeTitle: '동의',
Expand Down
3 changes: 1 addition & 2 deletions frontend/src/lang/modules/ms.ts
Original file line number Diff line number Diff line change
Expand Up @@ -169,8 +169,7 @@ const message = {
mfaTitle: 'Pengesahan MFA',
mfaCode: 'Kod pengesahan MFA',
title: 'Panel Pengurusan Pelayan Linux',
licenseHelper:
'Setuju &laquo; <a href="https://www.fit2cloud.com/legal/licenses.html" target="_blank">Perjanjian Lesen Komuniti</a> &raquo;',
licenseHelper: '<Perjanjian Lesen Komuniti>',
errorAgree: 'Klik untuk bersetuju dengan Lesen Perisian Komuniti',
logout: 'Log keluar',
agreeTitle: 'Agreement',
Expand Down
3 changes: 1 addition & 2 deletions frontend/src/lang/modules/pt-br.ts
Original file line number Diff line number Diff line change
Expand Up @@ -168,8 +168,7 @@ const message = {
mfaTitle: 'Autenticação MFA',
mfaCode: 'Código de verificação MFA',
title: 'Painel de Gerenciamento de Servidores Linux',
licenseHelper:
'Concordar com &laquo; <a href="https://www.fit2cloud.com/legal/licenses.html" target="_blank">Acordo de Licença Comunitária</a> &raquo;',
licenseHelper: '<Acordo de Licença Comunitária>',
errorAgree: 'Clique para concordar com o Acordo de Licença de Software Comunitário',
logout: 'Sair',
agreeTitle: 'Termo de Aceite',
Expand Down
3 changes: 1 addition & 2 deletions frontend/src/lang/modules/ru.ts
Original file line number Diff line number Diff line change
Expand Up @@ -167,8 +167,7 @@ const message = {
mfaTitle: 'MFA Сертификация',
mfaCode: 'MFA код подтверждения',
title: 'Панель управления Linux сервером',
licenseHelper:
'Согласен &laquo; <a href="https://www.fit2cloud.com/legal/licenses.html" target="_blank">Лицензионное соглашение сообщества</a> &raquo;',
licenseHelper: '<Лицензионное соглашение сообщества>',
errorAgree: 'Нажмите, чтобы согласиться с Лицензией программного обеспечения сообщества',
logout: 'Выход',
agreeTitle: 'Соглашение',
Expand Down
3 changes: 1 addition & 2 deletions frontend/src/lang/modules/tw.ts
Original file line number Diff line number Diff line change
Expand Up @@ -175,8 +175,7 @@ const message = {
mfaTitle: 'MFA 認證',
mfaCode: 'MFA 驗證碼',
title: 'Linux 服務器運維管理面板',
licenseHelper:
'同意 &laquo; <a href="https://www.fit2cloud.com/legal/licenses.html" target="_blank"> 飛致雲社區軟件許可協議</a> &raquo;',
licenseHelper: '《飛致雲社區軟件許可協議》',
errorAgree: '請點擊同意社區軟件許可協議',
agreeTitle: '服務協議及隱私保護',
agreeContent:
Expand Down
3 changes: 1 addition & 2 deletions frontend/src/lang/modules/zh.ts
Original file line number Diff line number Diff line change
Expand Up @@ -175,8 +175,7 @@ const message = {
mfaTitle: 'MFA 认证',
mfaCode: 'MFA 验证码',
title: 'Linux 服务器运维管理面板',
licenseHelper:
'同意 &laquo; <a href="https://www.fit2cloud.com/legal/licenses.html" target="_blank"> 飞致云社区软件许可协议</a> &raquo;',
licenseHelper: '《飞致云社区软件许可协议》',
errorAgree: '请点击同意社区软件许可协议',
agreeTitle: '服务协议及隐私保护',
agreeContent:
Expand Down
3 changes: 1 addition & 2 deletions frontend/src/views/app-store/installed/index.vue
Original file line number Diff line number Diff line change
Expand Up @@ -386,7 +386,7 @@ import AppIgnore from './ignore/index.vue';
import ComposeLogs from '@/components/compose-log/index.vue';
import { App } from '@/api/interface/app';
import Status from '@/components/status/index.vue';
import { getAge, getLanguage } from '@/utils/util';
import { getAge } from '@/utils/util';
import { useRouter } from 'vue-router';
import { MsgSuccess } from '@/utils/message';
import { toFolder } from '@/global/business';
Expand Down Expand Up @@ -432,7 +432,6 @@ const router = useRouter();
const activeName = ref(i18n.global.t('app.installed'));
const mode = ref('installed');
const moreTag = ref('');
const language = getLanguage();
const defaultLink = ref('');

const options = {
Expand Down
2 changes: 0 additions & 2 deletions frontend/src/views/home/app/index.vue
Original file line number Diff line number Diff line change
Expand Up @@ -185,13 +185,11 @@ import { changeLauncherStatus, loadAppLauncher, loadAppLauncherOption } from '@/
import i18n from '@/lang';
import { GlobalStore } from '@/store';
import { MsgSuccess } from '@/utils/message';
import { getLanguage } from '@/utils/util';
import { ref } from 'vue';
import { useRouter } from 'vue-router';
import { toFolder } from '@/global/business';

const router = useRouter();
const language = getLanguage();
const globalStore = GlobalStore();

let loading = ref(false);
Expand Down
Loading
Loading