mirror of
https://gitee.com/dromara/mayfly-go
synced 2025-11-03 16:00:25 +08:00
refactor: oauth2登录重构
This commit is contained in:
120
server/internal/auth/api/account_login.go
Normal file
120
server/internal/auth/api/account_login.go
Normal file
@@ -0,0 +1,120 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"mayfly-go/internal/auth/api/form"
|
||||
"mayfly-go/internal/common/utils"
|
||||
msgapp "mayfly-go/internal/msg/application"
|
||||
sysapp "mayfly-go/internal/sys/application"
|
||||
sysentity "mayfly-go/internal/sys/domain/entity"
|
||||
"mayfly-go/pkg/biz"
|
||||
"mayfly-go/pkg/cache"
|
||||
"mayfly-go/pkg/captcha"
|
||||
"mayfly-go/pkg/ginx"
|
||||
"mayfly-go/pkg/otp"
|
||||
"mayfly-go/pkg/req"
|
||||
"mayfly-go/pkg/utils/cryptox"
|
||||
"strconv"
|
||||
"time"
|
||||
)
|
||||
|
||||
type AccountLogin struct {
|
||||
AccountApp sysapp.Account
|
||||
MsgApp msgapp.Msg
|
||||
ConfigApp sysapp.Config
|
||||
}
|
||||
|
||||
/** 用户账号密码登录 **/
|
||||
|
||||
// @router /auth/accounts/login [post]
|
||||
func (a *AccountLogin) Login(rc *req.Ctx) {
|
||||
loginForm := ginx.BindJsonAndValid(rc.GinCtx, new(form.LoginForm))
|
||||
|
||||
accountLoginSecurity := a.ConfigApp.GetConfig(sysentity.ConfigKeyAccountLoginSecurity).ToAccountLoginSecurity()
|
||||
// 判断是否有开启登录验证码校验
|
||||
if accountLoginSecurity.UseCaptcha {
|
||||
// 校验验证码
|
||||
biz.IsTrue(captcha.Verify(loginForm.Cid, loginForm.Captcha), "验证码错误")
|
||||
}
|
||||
|
||||
username := loginForm.Username
|
||||
|
||||
clientIp := getIpAndRegion(rc)
|
||||
rc.ReqParam = fmt.Sprintf("username: %s | ip: %s", username, clientIp)
|
||||
|
||||
originPwd, err := cryptox.DefaultRsaDecrypt(loginForm.Password, true)
|
||||
biz.ErrIsNilAppendErr(err, "解密密码错误: %s")
|
||||
|
||||
account := &sysentity.Account{Username: username}
|
||||
err = a.AccountApp.GetAccount(account, "Id", "Name", "Username", "Password", "Status", "LastLoginTime", "LastLoginIp", "OtpSecret")
|
||||
|
||||
failCountKey := fmt.Sprintf("account:login:failcount:%s", username)
|
||||
nowFailCount := cache.GetInt(failCountKey)
|
||||
loginFailCount := accountLoginSecurity.LoginFailCount
|
||||
loginFailMin := accountLoginSecurity.LoginFailMin
|
||||
biz.IsTrue(nowFailCount < loginFailCount, "登录失败超过%d次, 请%d分钟后再试", loginFailCount, loginFailMin)
|
||||
|
||||
if err != nil || !cryptox.CheckPwdHash(originPwd, account.Password) {
|
||||
nowFailCount++
|
||||
cache.SetStr(failCountKey, strconv.Itoa(nowFailCount), time.Minute*time.Duration(loginFailMin))
|
||||
panic(biz.NewBizErr(fmt.Sprintf("用户名或密码错误【当前登录失败%d次】", nowFailCount)))
|
||||
}
|
||||
|
||||
// 校验密码强度(新用户第一次登录密码与账号名一致)
|
||||
biz.IsTrueBy(utils.CheckAccountPasswordLever(originPwd), biz.NewBizErrCode(401, "您的密码安全等级较低,请修改后重新登录"))
|
||||
rc.ResData = LastLoginCheck(account, accountLoginSecurity, clientIp)
|
||||
}
|
||||
|
||||
type OtpVerifyInfo struct {
|
||||
AccountId uint64
|
||||
Username string
|
||||
OptStatus int
|
||||
AccessToken string
|
||||
OtpSecret string
|
||||
}
|
||||
|
||||
// OTP双因素校验
|
||||
func (a *AccountLogin) OtpVerify(rc *req.Ctx) {
|
||||
otpVerify := new(form.OtpVerfiy)
|
||||
ginx.BindJsonAndValid(rc.GinCtx, otpVerify)
|
||||
|
||||
tokenKey := fmt.Sprintf("otp:token:%s", otpVerify.OtpToken)
|
||||
otpInfoJson := cache.GetStr(tokenKey)
|
||||
biz.NotEmpty(otpInfoJson, "otpToken错误或失效, 请重新登陆获取")
|
||||
otpInfo := new(OtpVerifyInfo)
|
||||
json.Unmarshal([]byte(otpInfoJson), otpInfo)
|
||||
|
||||
failCountKey := fmt.Sprintf("account:otp:failcount:%d", otpInfo.AccountId)
|
||||
failCount := cache.GetInt(failCountKey)
|
||||
biz.IsTrue(failCount < 5, "双因素校验失败超过5次, 请10分钟后再试")
|
||||
|
||||
otpStatus := otpInfo.OptStatus
|
||||
accessToken := otpInfo.AccessToken
|
||||
accountId := otpInfo.AccountId
|
||||
otpSecret := otpInfo.OtpSecret
|
||||
|
||||
if !otp.Validate(otpVerify.Code, otpSecret) {
|
||||
cache.SetStr(failCountKey, strconv.Itoa(failCount+1), time.Minute*time.Duration(10))
|
||||
panic(biz.NewBizErr("双因素认证授权码不正确"))
|
||||
}
|
||||
|
||||
// 如果是未注册状态,则更新account表的otpSecret信息
|
||||
if otpStatus == OtpStatusNoReg {
|
||||
update := &sysentity.Account{OtpSecret: otpSecret}
|
||||
update.Id = accountId
|
||||
update.OtpSecretEncrypt()
|
||||
a.AccountApp.Update(update)
|
||||
}
|
||||
|
||||
la := &sysentity.Account{Username: otpInfo.Username}
|
||||
la.Id = accountId
|
||||
go saveLogin(la, getIpAndRegion(rc))
|
||||
|
||||
cache.Del(tokenKey)
|
||||
rc.ResData = accessToken
|
||||
}
|
||||
|
||||
func (a *AccountLogin) Logout(rc *req.Ctx) {
|
||||
req.GetPermissionCodeRegistery().Remove(rc.LoginAccount.Id)
|
||||
}
|
||||
119
server/internal/auth/api/common.go
Normal file
119
server/internal/auth/api/common.go
Normal file
@@ -0,0 +1,119 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
msgapp "mayfly-go/internal/msg/application"
|
||||
msgentity "mayfly-go/internal/msg/domain/entity"
|
||||
sysapp "mayfly-go/internal/sys/application"
|
||||
sysentity "mayfly-go/internal/sys/domain/entity"
|
||||
"mayfly-go/pkg/biz"
|
||||
"mayfly-go/pkg/cache"
|
||||
"mayfly-go/pkg/otp"
|
||||
"mayfly-go/pkg/req"
|
||||
"mayfly-go/pkg/utils/jsonx"
|
||||
"mayfly-go/pkg/utils/netx"
|
||||
"mayfly-go/pkg/utils/stringx"
|
||||
"mayfly-go/pkg/utils/timex"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
OtpStatusNone = -1 // 未启用otp校验
|
||||
OtpStatusReg = 1 // 用户otp secret已注册
|
||||
OtpStatusNoReg = 2 // 用户otp secret未注册
|
||||
)
|
||||
|
||||
// 最后的登录校验(共用)。校验通过返回登录成功响应结果map
|
||||
func LastLoginCheck(account *sysentity.Account, accountLoginSecurity *sysentity.AccountLoginSecurity, loginIp string) map[string]any {
|
||||
biz.IsTrue(account.IsEnable(), "该账号不可用")
|
||||
username := account.Username
|
||||
|
||||
res := map[string]any{
|
||||
"name": account.Name,
|
||||
"username": username,
|
||||
"lastLoginTime": account.LastLoginTime,
|
||||
"lastLoginIp": account.LastLoginIp,
|
||||
}
|
||||
|
||||
// 默认为不校验otp
|
||||
otpStatus := OtpStatusNone
|
||||
// 访问系统使用的token
|
||||
accessToken := req.CreateToken(account.Id, username)
|
||||
// 若系统配置中设置开启otp双因素校验,则进行otp校验
|
||||
if accountLoginSecurity.UseOtp {
|
||||
otpInfo, otpurl, otpToken := useOtp(account, accountLoginSecurity.OtpIssuer, accessToken)
|
||||
otpStatus = otpInfo.OptStatus
|
||||
if otpurl != "" {
|
||||
res["otpUrl"] = otpurl
|
||||
}
|
||||
accessToken = otpToken
|
||||
} else {
|
||||
// 不进行otp二次校验则直接返回accessToken
|
||||
// 保存登录消息
|
||||
go saveLogin(account, loginIp)
|
||||
}
|
||||
|
||||
// 赋值otp状态
|
||||
res["otp"] = otpStatus
|
||||
res["token"] = accessToken
|
||||
return res
|
||||
}
|
||||
|
||||
func useOtp(account *sysentity.Account, otpIssuer, accessToken string) (*OtpVerifyInfo, string, string) {
|
||||
account.OtpSecretDecrypt()
|
||||
otpSecret := account.OtpSecret
|
||||
// 修改状态为已注册
|
||||
otpStatus := OtpStatusReg
|
||||
otpUrl := ""
|
||||
// 该token用于otp双因素校验
|
||||
token := stringx.Rand(32)
|
||||
// 未注册otp secret或重置了秘钥
|
||||
if otpSecret == "" || otpSecret == "-" {
|
||||
otpStatus = OtpStatusNoReg
|
||||
key, err := otp.NewTOTP(otp.GenerateOpts{
|
||||
AccountName: account.Username,
|
||||
Issuer: otpIssuer,
|
||||
})
|
||||
biz.ErrIsNilAppendErr(err, "otp生成失败: %s")
|
||||
otpUrl = key.URL()
|
||||
otpSecret = key.Secret()
|
||||
}
|
||||
// 缓存otpInfo, 只有双因素校验通过才可返回真正的accessToken
|
||||
otpInfo := &OtpVerifyInfo{
|
||||
AccountId: account.Id,
|
||||
Username: account.Username,
|
||||
OptStatus: otpStatus,
|
||||
OtpSecret: otpSecret,
|
||||
AccessToken: accessToken,
|
||||
}
|
||||
cache.SetStr(fmt.Sprintf("otp:token:%s", token), jsonx.ToStr(otpInfo), time.Minute*time.Duration(3))
|
||||
return otpInfo, otpUrl, token
|
||||
}
|
||||
|
||||
// 获取ip与归属地信息
|
||||
func getIpAndRegion(rc *req.Ctx) string {
|
||||
clientIp := rc.GinCtx.ClientIP()
|
||||
return fmt.Sprintf("%s %s", clientIp, netx.Ip2Region(clientIp))
|
||||
}
|
||||
|
||||
// 保存更新账号登录信息
|
||||
func saveLogin(account *sysentity.Account, ip string) {
|
||||
// 更新账号最后登录时间
|
||||
now := time.Now()
|
||||
updateAccount := &sysentity.Account{LastLoginTime: &now}
|
||||
updateAccount.Id = account.Id
|
||||
updateAccount.LastLoginIp = ip
|
||||
// 偷懒为了方便直接获取accountApp
|
||||
sysapp.GetAccountApp().Update(updateAccount)
|
||||
|
||||
// 创建登录消息
|
||||
loginMsg := &msgentity.Msg{
|
||||
RecipientId: int64(account.Id),
|
||||
Msg: fmt.Sprintf("于[%s]-[%s]登录", ip, timex.DefaultFormat(now)),
|
||||
Type: 1,
|
||||
}
|
||||
loginMsg.CreateTime = &now
|
||||
loginMsg.Creator = account.Username
|
||||
loginMsg.CreatorId = account.Id
|
||||
msgapp.GetMsgApp().Create(loginMsg)
|
||||
}
|
||||
@@ -1,6 +1,5 @@
|
||||
package form
|
||||
|
||||
// 登录表单
|
||||
type LoginForm struct {
|
||||
Username string `json:"username" binding:"required"`
|
||||
Password string `binding:"required"`
|
||||
219
server/internal/auth/api/oauth2_login.go
Normal file
219
server/internal/auth/api/oauth2_login.go
Normal file
@@ -0,0 +1,219 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"mayfly-go/internal/auth/api/vo"
|
||||
"mayfly-go/internal/auth/application"
|
||||
"mayfly-go/internal/auth/domain/entity"
|
||||
msgapp "mayfly-go/internal/msg/application"
|
||||
sysapp "mayfly-go/internal/sys/application"
|
||||
sysentity "mayfly-go/internal/sys/domain/entity"
|
||||
"mayfly-go/pkg/biz"
|
||||
"mayfly-go/pkg/cache"
|
||||
"mayfly-go/pkg/model"
|
||||
"mayfly-go/pkg/req"
|
||||
"mayfly-go/pkg/utils/jsonx"
|
||||
"mayfly-go/pkg/utils/stringx"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"golang.org/x/oauth2"
|
||||
)
|
||||
|
||||
type Oauth2Login struct {
|
||||
Oauth2App application.Oauth2
|
||||
ConfigApp sysapp.Config
|
||||
AccountApp sysapp.Account
|
||||
MsgApp msgapp.Msg
|
||||
}
|
||||
|
||||
func (a *Oauth2Login) OAuth2Login(rc *req.Ctx) {
|
||||
client, _ := a.getOAuthClient()
|
||||
state := stringx.Rand(32)
|
||||
cache.SetStr("oauth2:state:"+state, "login", 5*time.Minute)
|
||||
rc.GinCtx.Redirect(http.StatusFound, client.AuthCodeURL(state))
|
||||
}
|
||||
|
||||
func (a *Oauth2Login) OAuth2Bind(rc *req.Ctx) {
|
||||
client, _ := a.getOAuthClient()
|
||||
state := stringx.Rand(32)
|
||||
cache.SetStr("oauth2:state:"+state, "bind:"+strconv.FormatUint(rc.LoginAccount.Id, 10),
|
||||
5*time.Minute)
|
||||
rc.GinCtx.Redirect(http.StatusFound, client.AuthCodeURL(state))
|
||||
}
|
||||
|
||||
func (a *Oauth2Login) OAuth2Callback(rc *req.Ctx) {
|
||||
client, oauth := a.getOAuthClient()
|
||||
|
||||
code := rc.GinCtx.Query("code")
|
||||
biz.NotEmpty(code, "code不能为空")
|
||||
|
||||
state := rc.GinCtx.Query("state")
|
||||
biz.NotEmpty(state, "state不能为空")
|
||||
|
||||
stateAction := cache.GetStr("oauth2:state:" + state)
|
||||
biz.NotEmpty(stateAction, "state已过期, 请重新登录")
|
||||
|
||||
token, err := client.Exchange(rc.GinCtx, code)
|
||||
biz.ErrIsNilAppendErr(err, "获取token失败: %s")
|
||||
|
||||
// 获取用户信息
|
||||
httpCli := client.Client(rc.GinCtx.Request.Context(), token)
|
||||
resp, err := httpCli.Get(oauth.ResourceURL)
|
||||
biz.ErrIsNilAppendErr(err, "获取用户信息失败: %s")
|
||||
defer resp.Body.Close()
|
||||
|
||||
b, err := io.ReadAll(resp.Body)
|
||||
biz.ErrIsNilAppendErr(err, "读取响应的用户信息失败: %s")
|
||||
|
||||
// UserIdentifier格式为 type:fieldPath。如:string:user.username 或 number:user.id
|
||||
userIdTypeAndFieldPath := strings.Split(oauth.UserIdentifier, ":")
|
||||
biz.IsTrue(len(userIdTypeAndFieldPath) == 2, "oauth2配置属性'UserIdentifier'不符合规则")
|
||||
|
||||
// 解析用户唯一标识
|
||||
userIdFieldPath := userIdTypeAndFieldPath[1]
|
||||
userId := ""
|
||||
if userIdTypeAndFieldPath[0] == "string" {
|
||||
userId, err = jsonx.GetStringByBytes(b, userIdFieldPath)
|
||||
biz.ErrIsNilAppendErr(err, "解析用户唯一标识失败: %s")
|
||||
} else {
|
||||
intUserId, err := jsonx.GetIntByBytes(b, userIdFieldPath)
|
||||
biz.ErrIsNilAppendErr(err, "解析用户唯一标识失败: %s")
|
||||
userId = fmt.Sprintf("%d", intUserId)
|
||||
}
|
||||
biz.NotBlank(userId, "用户唯一标识字段值不能为空")
|
||||
|
||||
// 判断是登录还是绑定
|
||||
if stateAction == "login" {
|
||||
a.doLoginAction(rc, userId, oauth)
|
||||
} else if sAccountId, ok := strings.CutPrefix(stateAction, "bind:"); ok {
|
||||
// 绑定
|
||||
accountId, err := strconv.ParseUint(sAccountId, 10, 64)
|
||||
biz.ErrIsNilAppendErr(err, "绑定用户失败: %s")
|
||||
|
||||
account := new(sysentity.Account)
|
||||
account.Id = accountId
|
||||
err = a.AccountApp.GetAccount(account, "username")
|
||||
biz.ErrIsNilAppendErr(err, "该账号不存在")
|
||||
rc.ReqParam = fmt.Sprintf("oauth2 bind username: %s", account.Username)
|
||||
|
||||
err = a.Oauth2App.GetOAuthAccount(&entity.Oauth2Account{
|
||||
AccountId: accountId,
|
||||
}, "account_id", "identity")
|
||||
biz.IsTrue(err != nil, "该账号已被绑定")
|
||||
|
||||
now := time.Now()
|
||||
err = a.Oauth2App.BindOAuthAccount(&entity.Oauth2Account{
|
||||
AccountId: accountId,
|
||||
Identity: userId,
|
||||
CreateTime: &now,
|
||||
UpdateTime: &now,
|
||||
})
|
||||
biz.ErrIsNilAppendErr(err, "绑定用户失败: %s")
|
||||
res := map[string]any{
|
||||
"action": "oauthBind",
|
||||
"bind": true,
|
||||
}
|
||||
b, err = json.Marshal(res)
|
||||
biz.ErrIsNil(err, "数据序列化失败")
|
||||
rc.GinCtx.Header("Content-Type", "text/html; charset=utf-8")
|
||||
rc.GinCtx.Writer.WriteHeader(http.StatusOK)
|
||||
_, _ = rc.GinCtx.Writer.WriteString("<html>" +
|
||||
"<script>top.opener.postMessage(" + string(b) + ")</script>" +
|
||||
"</html>")
|
||||
} else {
|
||||
panic(biz.NewBizErr("state不合法"))
|
||||
}
|
||||
}
|
||||
|
||||
// 指定登录操作
|
||||
func (a *Oauth2Login) doLoginAction(rc *req.Ctx, userId string, oauth *sysentity.ConfigOauth2Login) {
|
||||
clientIp := getIpAndRegion(rc)
|
||||
rc.ReqParam = fmt.Sprintf("oauth2 login username: %s | ip: %s", userId, clientIp)
|
||||
|
||||
// 查询用户是否存在
|
||||
oauthAccount := &entity.Oauth2Account{Identity: userId}
|
||||
err := a.Oauth2App.GetOAuthAccount(oauthAccount, "account_id", "identity")
|
||||
|
||||
var accountId uint64
|
||||
// 不存在,进行注册
|
||||
if err != nil {
|
||||
biz.IsTrue(oauth.AutoRegister, "系统未开启自动注册, 请先让管理员添加对应账号")
|
||||
now := time.Now()
|
||||
account := &sysentity.Account{
|
||||
Model: model.Model{
|
||||
CreateTime: &now,
|
||||
CreatorId: 0,
|
||||
Creator: "oauth2",
|
||||
UpdateTime: &now,
|
||||
},
|
||||
Name: userId,
|
||||
Username: userId,
|
||||
}
|
||||
a.AccountApp.Create(account)
|
||||
// 绑定
|
||||
err := a.Oauth2App.BindOAuthAccount(&entity.Oauth2Account{
|
||||
AccountId: account.Id,
|
||||
Identity: oauthAccount.Identity,
|
||||
CreateTime: &now,
|
||||
UpdateTime: &now,
|
||||
})
|
||||
biz.ErrIsNilAppendErr(err, "绑定用户失败: %s")
|
||||
accountId = account.Id
|
||||
} else {
|
||||
accountId = oauthAccount.AccountId
|
||||
}
|
||||
|
||||
// 进行登录
|
||||
account := &sysentity.Account{
|
||||
Model: model.Model{DeletedModel: model.DeletedModel{Id: accountId}},
|
||||
}
|
||||
err = a.AccountApp.GetAccount(account, "Id", "Name", "Username", "Password", "Status", "LastLoginTime", "LastLoginIp", "OtpSecret")
|
||||
biz.ErrIsNilAppendErr(err, "获取用户信息失败: %s")
|
||||
|
||||
res := LastLoginCheck(account, a.ConfigApp.GetConfig(sysentity.ConfigKeyAccountLoginSecurity).ToAccountLoginSecurity(), clientIp)
|
||||
res["action"] = "oauthLogin"
|
||||
b, err := json.Marshal(res)
|
||||
biz.ErrIsNil(err, "数据序列化失败")
|
||||
rc.GinCtx.Header("Content-Type", "text/html; charset=utf-8")
|
||||
rc.GinCtx.Writer.WriteHeader(http.StatusOK)
|
||||
_, _ = rc.GinCtx.Writer.WriteString("<html>" +
|
||||
"<script>top.opener.postMessage(" + string(b) + ")</script>" +
|
||||
"</html>")
|
||||
}
|
||||
|
||||
func (a *Oauth2Login) getOAuthClient() (*oauth2.Config, *sysentity.ConfigOauth2Login) {
|
||||
oath2LoginConfig := a.ConfigApp.GetConfig(sysentity.ConfigKeyOauth2Login).ToOauth2Login()
|
||||
biz.IsTrue(oath2LoginConfig.Enable, "请先配置oauth2或启用oauth2登录")
|
||||
biz.IsTrue(oath2LoginConfig.ClientId != "", "oauth2 clientId不能为空")
|
||||
|
||||
client := &oauth2.Config{
|
||||
ClientID: oath2LoginConfig.ClientId,
|
||||
ClientSecret: oath2LoginConfig.ClientSecret,
|
||||
Endpoint: oauth2.Endpoint{
|
||||
AuthURL: oath2LoginConfig.AuthorizationURL,
|
||||
TokenURL: oath2LoginConfig.AccessTokenURL,
|
||||
},
|
||||
RedirectURL: oath2LoginConfig.RedirectURL + "/api/auth/oauth2/callback",
|
||||
Scopes: strings.Split(oath2LoginConfig.Scopes, ","),
|
||||
}
|
||||
return client, oath2LoginConfig
|
||||
}
|
||||
|
||||
func (a *Oauth2Login) Oauth2Status(ctx *req.Ctx) {
|
||||
res := &vo.Oauth2Status{}
|
||||
oauth2LoginConfig := a.ConfigApp.GetConfig(sysentity.ConfigKeyOauth2Login).ToOauth2Login()
|
||||
res.Enable = oauth2LoginConfig.Enable
|
||||
if res.Enable {
|
||||
err := a.Oauth2App.GetOAuthAccount(&entity.Oauth2Account{
|
||||
AccountId: ctx.LoginAccount.Id,
|
||||
}, "account_id", "identity")
|
||||
res.Bind = err == nil
|
||||
}
|
||||
|
||||
ctx.ResData = res
|
||||
}
|
||||
6
server/internal/auth/api/vo/vo.go
Normal file
6
server/internal/auth/api/vo/vo.go
Normal file
@@ -0,0 +1,6 @@
|
||||
package vo
|
||||
|
||||
type Oauth2Status struct {
|
||||
Enable bool `json:"enable"`
|
||||
Bind bool `json:"bind"`
|
||||
}
|
||||
11
server/internal/auth/application/application.go
Normal file
11
server/internal/auth/application/application.go
Normal file
@@ -0,0 +1,11 @@
|
||||
package application
|
||||
|
||||
import "mayfly-go/internal/auth/infrastructure/persistence"
|
||||
|
||||
var (
|
||||
authApp = newAuthApp(persistence.GetOauthAccountRepo())
|
||||
)
|
||||
|
||||
func GetAuthApp() Oauth2 {
|
||||
return authApp
|
||||
}
|
||||
38
server/internal/auth/application/oauth2.go
Normal file
38
server/internal/auth/application/oauth2.go
Normal file
@@ -0,0 +1,38 @@
|
||||
package application
|
||||
|
||||
import (
|
||||
"mayfly-go/internal/auth/domain/entity"
|
||||
"mayfly-go/internal/auth/domain/repository"
|
||||
"mayfly-go/pkg/biz"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type Oauth2 interface {
|
||||
GetOAuthAccount(condition *entity.Oauth2Account, cols ...string) error
|
||||
|
||||
BindOAuthAccount(e *entity.Oauth2Account) error
|
||||
}
|
||||
|
||||
func newAuthApp(oauthAccountRepo repository.Oauth2Account) Oauth2 {
|
||||
return &oauth2AppImpl{
|
||||
oauthAccountRepo: oauthAccountRepo,
|
||||
}
|
||||
}
|
||||
|
||||
type oauth2AppImpl struct {
|
||||
oauthAccountRepo repository.Oauth2Account
|
||||
}
|
||||
|
||||
func (a *oauth2AppImpl) GetOAuthAccount(condition *entity.Oauth2Account, cols ...string) error {
|
||||
err := a.oauthAccountRepo.GetOAuthAccount(condition, cols...)
|
||||
if err != nil {
|
||||
// 排除其他报错,如表不存在等
|
||||
biz.IsTrue(err == gorm.ErrRecordNotFound, "查询失败: %s", err.Error())
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (a *oauth2AppImpl) BindOAuthAccount(e *entity.Oauth2Account) error {
|
||||
return a.oauthAccountRepo.SaveOAuthAccount(e)
|
||||
}
|
||||
@@ -5,7 +5,7 @@ import (
|
||||
"time"
|
||||
)
|
||||
|
||||
type OAuthAccount struct {
|
||||
type Oauth2Account struct {
|
||||
model.DeletedModel
|
||||
|
||||
AccountId uint64 `json:"accountId" gorm:"column:account_id;index:account_id,unique"`
|
||||
@@ -15,6 +15,6 @@ type OAuthAccount struct {
|
||||
UpdateTime *time.Time `json:"updateTime"`
|
||||
}
|
||||
|
||||
func (OAuthAccount) TableName() string {
|
||||
return "t_oauth_account"
|
||||
func (Oauth2Account) TableName() string {
|
||||
return "t_oauth2_account"
|
||||
}
|
||||
10
server/internal/auth/domain/repository/oauth2.go
Normal file
10
server/internal/auth/domain/repository/oauth2.go
Normal file
@@ -0,0 +1,10 @@
|
||||
package repository
|
||||
|
||||
import "mayfly-go/internal/auth/domain/entity"
|
||||
|
||||
type Oauth2Account interface {
|
||||
// GetOAuthAccount 根据identity获取第三方账号信息
|
||||
GetOAuthAccount(condition *entity.Oauth2Account, cols ...string) error
|
||||
|
||||
SaveOAuthAccount(e *entity.Oauth2Account) error
|
||||
}
|
||||
24
server/internal/auth/infrastructure/persistence/oauth2.go
Normal file
24
server/internal/auth/infrastructure/persistence/oauth2.go
Normal file
@@ -0,0 +1,24 @@
|
||||
package persistence
|
||||
|
||||
import (
|
||||
"mayfly-go/internal/auth/domain/entity"
|
||||
"mayfly-go/internal/auth/domain/repository"
|
||||
"mayfly-go/pkg/gormx"
|
||||
)
|
||||
|
||||
type oauth2AccountRepoImpl struct{}
|
||||
|
||||
func newAuthAccountRepo() repository.Oauth2Account {
|
||||
return new(oauth2AccountRepoImpl)
|
||||
}
|
||||
|
||||
func (a *oauth2AccountRepoImpl) GetOAuthAccount(condition *entity.Oauth2Account, cols ...string) error {
|
||||
return gormx.GetBy(condition, cols...)
|
||||
}
|
||||
|
||||
func (a *oauth2AccountRepoImpl) SaveOAuthAccount(e *entity.Oauth2Account) error {
|
||||
if e.Id == 0 {
|
||||
return gormx.Insert(e)
|
||||
}
|
||||
return gormx.UpdateById(e)
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package persistence
|
||||
|
||||
import "mayfly-go/internal/auth/domain/repository"
|
||||
|
||||
var (
|
||||
authAccountRepo = newAuthAccountRepo()
|
||||
)
|
||||
|
||||
func GetOauthAccountRepo() repository.Oauth2Account {
|
||||
return authAccountRepo
|
||||
}
|
||||
54
server/internal/auth/router/router.go
Normal file
54
server/internal/auth/router/router.go
Normal file
@@ -0,0 +1,54 @@
|
||||
package router
|
||||
|
||||
import (
|
||||
"mayfly-go/internal/auth/api"
|
||||
"mayfly-go/internal/auth/application"
|
||||
msgapp "mayfly-go/internal/msg/application"
|
||||
sysapp "mayfly-go/internal/sys/application"
|
||||
"mayfly-go/pkg/req"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func Init(router *gin.RouterGroup) {
|
||||
accountLogin := &api.AccountLogin{
|
||||
ConfigApp: sysapp.GetConfigApp(),
|
||||
AccountApp: sysapp.GetAccountApp(),
|
||||
MsgApp: msgapp.GetMsgApp(),
|
||||
}
|
||||
|
||||
oauth2Login := &api.Oauth2Login{
|
||||
Oauth2App: application.GetAuthApp(),
|
||||
ConfigApp: sysapp.GetConfigApp(),
|
||||
AccountApp: sysapp.GetAccountApp(),
|
||||
MsgApp: msgapp.GetMsgApp(),
|
||||
}
|
||||
|
||||
rg := router.Group("/auth")
|
||||
|
||||
reqs := [...]*req.Conf{
|
||||
|
||||
// 用户账号密码登录
|
||||
req.NewPost("/accounts/login", accountLogin.Login).Log(req.NewLogSave("用户登录")).DontNeedToken(),
|
||||
|
||||
// 用户退出登录
|
||||
req.NewPost("/accounts/logout", accountLogin.Logout),
|
||||
|
||||
// 用户otp双因素校验
|
||||
req.NewPost("/accounts/otp-verify", accountLogin.OtpVerify).DontNeedToken(),
|
||||
|
||||
/*--------oauth2登录相关----------*/
|
||||
|
||||
// oauth2登录
|
||||
req.NewGet("/oauth2/login", oauth2Login.OAuth2Login).DontNeedToken(),
|
||||
|
||||
req.NewGet("/oauth2/bind", oauth2Login.OAuth2Bind),
|
||||
|
||||
// oauth2回调地址
|
||||
req.NewGet("/oauth2/callback", oauth2Login.OAuth2Callback).Log(req.NewLogSave("oauth2回调")).NoRes().DontNeedToken(),
|
||||
|
||||
req.NewGet("/oauth2/status", oauth2Login.Oauth2Status),
|
||||
}
|
||||
|
||||
req.BatchSetGroup(rg, reqs[:])
|
||||
}
|
||||
@@ -3,8 +3,29 @@ package utils
|
||||
import (
|
||||
"mayfly-go/pkg/biz"
|
||||
"mayfly-go/pkg/config"
|
||||
"regexp"
|
||||
)
|
||||
|
||||
// 检查用户密码安全等级
|
||||
func CheckAccountPasswordLever(ps string) bool {
|
||||
if len(ps) < 8 {
|
||||
return false
|
||||
}
|
||||
num := `[0-9]{1}`
|
||||
a_z := `[a-zA-Z]{1}`
|
||||
symbol := `[!@#~$%^&*()+|_.,]{1}`
|
||||
if b, err := regexp.MatchString(num, ps); !b || err != nil {
|
||||
return false
|
||||
}
|
||||
if b, err := regexp.MatchString(a_z, ps); !b || err != nil {
|
||||
return false
|
||||
}
|
||||
if b, err := regexp.MatchString(symbol, ps); !b || err != nil {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// 使用config.yml的aes.key进行密码加密
|
||||
func PwdAesEncrypt(password string) string {
|
||||
if password == "" {
|
||||
|
||||
@@ -1,28 +1,19 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"mayfly-go/internal/common/utils"
|
||||
msgapp "mayfly-go/internal/msg/application"
|
||||
msgentity "mayfly-go/internal/msg/domain/entity"
|
||||
"mayfly-go/internal/sys/api/form"
|
||||
"mayfly-go/internal/sys/api/vo"
|
||||
"mayfly-go/internal/sys/application"
|
||||
"mayfly-go/internal/sys/domain/entity"
|
||||
"mayfly-go/pkg/biz"
|
||||
"mayfly-go/pkg/cache"
|
||||
"mayfly-go/pkg/captcha"
|
||||
"mayfly-go/pkg/ginx"
|
||||
"mayfly-go/pkg/model"
|
||||
"mayfly-go/pkg/otp"
|
||||
"mayfly-go/pkg/req"
|
||||
"mayfly-go/pkg/utils/collx"
|
||||
"mayfly-go/pkg/utils/cryptox"
|
||||
"mayfly-go/pkg/utils/jsonx"
|
||||
"mayfly-go/pkg/utils/netx"
|
||||
"mayfly-go/pkg/utils/stringx"
|
||||
"mayfly-go/pkg/utils/timex"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
@@ -42,163 +33,6 @@ type Account struct {
|
||||
ConfigApp application.Config
|
||||
}
|
||||
|
||||
/** 登录者个人相关操作 **/
|
||||
|
||||
// @router /accounts/login [post]
|
||||
func (a *Account) Login(rc *req.Ctx) {
|
||||
loginForm := ginx.BindJsonAndValid(rc.GinCtx, new(form.LoginForm))
|
||||
|
||||
accountLoginSecurity := a.ConfigApp.GetConfig(entity.ConfigKeyAccountLoginSecurity).ToAccountLoginSecurity()
|
||||
// 判断是否有开启登录验证码校验
|
||||
if accountLoginSecurity.UseCaptcha {
|
||||
// 校验验证码
|
||||
biz.IsTrue(captcha.Verify(loginForm.Cid, loginForm.Captcha), "验证码错误")
|
||||
}
|
||||
|
||||
username := loginForm.Username
|
||||
|
||||
clientIp := getIpAndRegion(rc)
|
||||
rc.ReqParam = fmt.Sprintf("username: %s | ip: %s", username, clientIp)
|
||||
|
||||
originPwd, err := cryptox.DefaultRsaDecrypt(loginForm.Password, true)
|
||||
biz.ErrIsNilAppendErr(err, "解密密码错误: %s")
|
||||
|
||||
account := &entity.Account{Username: username}
|
||||
err = a.AccountApp.GetAccount(account, "Id", "Name", "Username", "Password", "Status", "LastLoginTime", "LastLoginIp", "OtpSecret")
|
||||
|
||||
failCountKey := fmt.Sprintf("account:login:failcount:%s", username)
|
||||
nowFailCount := cache.GetInt(failCountKey)
|
||||
loginFailCount := accountLoginSecurity.LoginFailCount
|
||||
loginFailMin := accountLoginSecurity.LoginFailMin
|
||||
biz.IsTrue(nowFailCount < loginFailCount, "登录失败超过%d次, 请%d分钟后再试", loginFailCount, loginFailMin)
|
||||
|
||||
if err != nil || !cryptox.CheckPwdHash(originPwd, account.Password) {
|
||||
nowFailCount++
|
||||
cache.SetStr(failCountKey, strconv.Itoa(nowFailCount), time.Minute*time.Duration(loginFailMin))
|
||||
panic(biz.NewBizErr(fmt.Sprintf("用户名或密码错误【当前登录失败%d次】", nowFailCount)))
|
||||
}
|
||||
biz.IsTrue(account.IsEnable(), "该账号不可用")
|
||||
|
||||
// 校验密码强度(新用户第一次登录密码与账号名一致)
|
||||
biz.IsTrueBy(CheckPasswordLever(originPwd), biz.NewBizErrCode(401, "您的密码安全等级较低,请修改后重新登录"))
|
||||
|
||||
res := map[string]any{
|
||||
"name": account.Name,
|
||||
"username": username,
|
||||
"lastLoginTime": account.LastLoginTime,
|
||||
"lastLoginIp": account.LastLoginIp,
|
||||
}
|
||||
|
||||
// 默认为不校验otp
|
||||
otpStatus := OtpStatusNone
|
||||
// 访问系统使用的token
|
||||
accessToken := req.CreateToken(account.Id, username)
|
||||
// 若系统配置中设置开启otp双因素校验,则进行otp校验
|
||||
if accountLoginSecurity.UseOtp {
|
||||
otpInfo, otpurl, otpToken := useOtp(account, accountLoginSecurity.OtpIssuer, accessToken)
|
||||
otpStatus = otpInfo.OptStatus
|
||||
if otpurl != "" {
|
||||
res["otpUrl"] = otpurl
|
||||
}
|
||||
accessToken = otpToken
|
||||
} else {
|
||||
// 不进行otp二次校验则直接返回accessToken
|
||||
// 保存登录消息
|
||||
go saveLogin(a.AccountApp, a.MsgApp, account, clientIp)
|
||||
}
|
||||
|
||||
// 赋值otp状态
|
||||
res["otp"] = otpStatus
|
||||
res["token"] = accessToken
|
||||
rc.ResData = res
|
||||
}
|
||||
|
||||
func useOtp(account *entity.Account, otpIssuer, accessToken string) (*OtpVerifyInfo, string, string) {
|
||||
account.OtpSecretDecrypt()
|
||||
otpSecret := account.OtpSecret
|
||||
// 修改状态为已注册
|
||||
otpStatus := OtpStatusReg
|
||||
otpUrl := ""
|
||||
// 该token用于otp双因素校验
|
||||
token := stringx.Rand(32)
|
||||
// 未注册otp secret或重置了秘钥
|
||||
if otpSecret == "" || otpSecret == "-" {
|
||||
otpStatus = OtpStatusNoReg
|
||||
key, err := otp.NewTOTP(otp.GenerateOpts{
|
||||
AccountName: account.Username,
|
||||
Issuer: otpIssuer,
|
||||
})
|
||||
biz.ErrIsNilAppendErr(err, "otp生成失败: %s")
|
||||
otpUrl = key.URL()
|
||||
otpSecret = key.Secret()
|
||||
}
|
||||
// 缓存otpInfo, 只有双因素校验通过才可返回真正的accessToken
|
||||
otpInfo := &OtpVerifyInfo{
|
||||
AccountId: account.Id,
|
||||
Username: account.Username,
|
||||
OptStatus: otpStatus,
|
||||
OtpSecret: otpSecret,
|
||||
AccessToken: accessToken,
|
||||
}
|
||||
cache.SetStr(fmt.Sprintf("otp:token:%s", token), jsonx.ToStr(otpInfo), time.Minute*time.Duration(3))
|
||||
return otpInfo, otpUrl, token
|
||||
}
|
||||
|
||||
// 获取ip与归属地信息
|
||||
func getIpAndRegion(rc *req.Ctx) string {
|
||||
clientIp := rc.GinCtx.ClientIP()
|
||||
return fmt.Sprintf("%s %s", clientIp, netx.Ip2Region(clientIp))
|
||||
}
|
||||
|
||||
type OtpVerifyInfo struct {
|
||||
AccountId uint64
|
||||
Username string
|
||||
OptStatus int
|
||||
AccessToken string
|
||||
OtpSecret string
|
||||
}
|
||||
|
||||
// OTP双因素校验
|
||||
func (a *Account) OtpVerify(rc *req.Ctx) {
|
||||
otpVerify := new(form.OtpVerfiy)
|
||||
ginx.BindJsonAndValid(rc.GinCtx, otpVerify)
|
||||
|
||||
tokenKey := fmt.Sprintf("otp:token:%s", otpVerify.OtpToken)
|
||||
otpInfoJson := cache.GetStr(tokenKey)
|
||||
biz.NotEmpty(otpInfoJson, "otpToken错误或失效, 请重新登陆获取")
|
||||
otpInfo := new(OtpVerifyInfo)
|
||||
json.Unmarshal([]byte(otpInfoJson), otpInfo)
|
||||
|
||||
failCountKey := fmt.Sprintf("account:otp:failcount:%d", otpInfo.AccountId)
|
||||
failCount := cache.GetInt(failCountKey)
|
||||
biz.IsTrue(failCount < 5, "双因素校验失败超过5次, 请10分钟后再试")
|
||||
|
||||
otpStatus := otpInfo.OptStatus
|
||||
accessToken := otpInfo.AccessToken
|
||||
accountId := otpInfo.AccountId
|
||||
otpSecret := otpInfo.OtpSecret
|
||||
|
||||
if !otp.Validate(otpVerify.Code, otpSecret) {
|
||||
cache.SetStr(failCountKey, strconv.Itoa(failCount+1), time.Minute*time.Duration(10))
|
||||
panic(biz.NewBizErr("双因素认证授权码不正确"))
|
||||
}
|
||||
|
||||
// 如果是未注册状态,则更新account表的otpSecret信息
|
||||
if otpStatus == OtpStatusNoReg {
|
||||
update := &entity.Account{OtpSecret: otpSecret}
|
||||
update.Id = accountId
|
||||
update.OtpSecretEncrypt()
|
||||
a.AccountApp.Update(update)
|
||||
}
|
||||
|
||||
la := &entity.Account{Username: otpInfo.Username}
|
||||
la.Id = accountId
|
||||
go saveLogin(a.AccountApp, a.MsgApp, la, getIpAndRegion(rc))
|
||||
|
||||
cache.Del(tokenKey)
|
||||
rc.ResData = accessToken
|
||||
}
|
||||
|
||||
// 获取当前登录用户的菜单与权限码
|
||||
func (a *Account) GetPermissions(rc *req.Ctx) {
|
||||
account := rc.LoginAccount
|
||||
@@ -239,7 +73,7 @@ func (a *Account) ChangePassword(rc *req.Ctx) {
|
||||
|
||||
originNewPwd, err := cryptox.DefaultRsaDecrypt(form.NewPassword, true)
|
||||
biz.ErrIsNilAppendErr(err, "解密新密码错误: %s")
|
||||
biz.IsTrue(CheckPasswordLever(originNewPwd), "密码强度必须8位以上且包含字⺟⼤⼩写+数字+特殊符号")
|
||||
biz.IsTrue(utils.CheckAccountPasswordLever(originNewPwd), "密码强度必须8位以上且包含字⺟⼤⼩写+数字+特殊符号")
|
||||
|
||||
updateAccount := new(entity.Account)
|
||||
updateAccount.Id = account.Id
|
||||
@@ -250,46 +84,6 @@ func (a *Account) ChangePassword(rc *req.Ctx) {
|
||||
rc.LoginAccount = &model.LoginAccount{Id: account.Id, Username: account.Username}
|
||||
}
|
||||
|
||||
func CheckPasswordLever(ps string) bool {
|
||||
if len(ps) < 8 {
|
||||
return false
|
||||
}
|
||||
num := `[0-9]{1}`
|
||||
a_z := `[a-zA-Z]{1}`
|
||||
symbol := `[!@#~$%^&*()+|_.,]{1}`
|
||||
if b, err := regexp.MatchString(num, ps); !b || err != nil {
|
||||
return false
|
||||
}
|
||||
if b, err := regexp.MatchString(a_z, ps); !b || err != nil {
|
||||
return false
|
||||
}
|
||||
if b, err := regexp.MatchString(symbol, ps); !b || err != nil {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// 保存更新账号登录信息
|
||||
func saveLogin(accountApp application.Account, msgApp msgapp.Msg, account *entity.Account, ip string) {
|
||||
// 更新账号最后登录时间
|
||||
now := time.Now()
|
||||
updateAccount := &entity.Account{LastLoginTime: &now}
|
||||
updateAccount.Id = account.Id
|
||||
updateAccount.LastLoginIp = ip
|
||||
accountApp.Update(updateAccount)
|
||||
|
||||
// 创建登录消息
|
||||
loginMsg := &msgentity.Msg{
|
||||
RecipientId: int64(account.Id),
|
||||
Msg: fmt.Sprintf("于[%s]-[%s]登录", ip, timex.DefaultFormat(now)),
|
||||
Type: 1,
|
||||
}
|
||||
loginMsg.CreateTime = &now
|
||||
loginMsg.Creator = account.Username
|
||||
loginMsg.CreatorId = account.Id
|
||||
msgApp.Create(loginMsg)
|
||||
}
|
||||
|
||||
// 获取个人账号信息
|
||||
func (a *Account) AccountInfo(rc *req.Ctx) {
|
||||
ap := new(vo.AccountPersonVO)
|
||||
@@ -308,7 +102,7 @@ func (a *Account) UpdateAccount(rc *req.Ctx) {
|
||||
updateAccount.Id = rc.LoginAccount.Id
|
||||
|
||||
if updateAccount.Password != "" {
|
||||
biz.IsTrue(CheckPasswordLever(updateAccount.Password), "密码强度必须8位以上且包含字⺟⼤⼩写+数字+特殊符号")
|
||||
biz.IsTrue(utils.CheckAccountPasswordLever(updateAccount.Password), "密码强度必须8位以上且包含字⺟⼤⼩写+数字+特殊符号")
|
||||
updateAccount.Password = cryptox.PwdHash(updateAccount.Password)
|
||||
}
|
||||
a.AccountApp.Update(updateAccount)
|
||||
@@ -336,7 +130,7 @@ func (a *Account) SaveAccount(rc *req.Ctx) {
|
||||
a.AccountApp.Create(account)
|
||||
} else {
|
||||
if account.Password != "" {
|
||||
biz.IsTrue(CheckPasswordLever(account.Password), "密码强度必须8位以上且包含字⺟⼤⼩写+数字+特殊符号")
|
||||
biz.IsTrue(utils.CheckAccountPasswordLever(account.Password), "密码强度必须8位以上且包含字⺟⼤⼩写+数字+特殊符号")
|
||||
account.Password = cryptox.PwdHash(account.Password)
|
||||
}
|
||||
a.AccountApp.Update(account)
|
||||
|
||||
@@ -1,339 +0,0 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"golang.org/x/oauth2"
|
||||
"gorm.io/gorm"
|
||||
"io"
|
||||
msgapp "mayfly-go/internal/msg/application"
|
||||
form2 "mayfly-go/internal/sys/api/form"
|
||||
"mayfly-go/internal/sys/api/vo"
|
||||
"mayfly-go/internal/sys/application"
|
||||
"mayfly-go/internal/sys/domain/entity"
|
||||
"mayfly-go/pkg/biz"
|
||||
"mayfly-go/pkg/cache"
|
||||
"mayfly-go/pkg/ginx"
|
||||
"mayfly-go/pkg/global"
|
||||
"mayfly-go/pkg/model"
|
||||
"mayfly-go/pkg/req"
|
||||
"mayfly-go/pkg/utils/stringx"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
AuthOAuth2Name string = "OAuth2.0客户端配置"
|
||||
AuthOAuth2Key string = "AuthOAuth2"
|
||||
AuthOAuth2Param string = "[{\"name\":\"Client ID\",\"model\":\"clientID\",\"placeholder\":\"客户端id\"}," +
|
||||
"{\"name\":\"Client Secret\",\"model\":\"clientSecret\",\"placeholder\":\"客户端密钥\"}," +
|
||||
"{\"name\":\"Authorization URL\",\"model\":\"authorizationURL\",\"placeholder\":\"https://example.com/oauth/authorize\"}," +
|
||||
"{\"name\":\"Access Token URL\",\"model\":\"accessTokenURL\",\"placeholder\":\"https://example.com/oauth/token\"}," +
|
||||
"{\"name\":\"Resource URL\",\"model\":\"resourceURL\",\"placeholder\":\"https://example.com/oauth/token\"}," +
|
||||
"{\"name\":\"Redirect URL\",\"model\":\"redirectURL\",\"placeholder\":\"http://mayfly地址/\"}," +
|
||||
"{\"name\":\"User identifier\",\"model\":\"userIdentifier\",\"placeholder\":\"\"}," +
|
||||
"{\"name\":\"Scopes\",\"model\":\"scopes\",\"placeholder\":\"read_user\"}," +
|
||||
"{\"name\":\"自动注册\",\"model\":\"autoRegister\",\"placeholder\":\"开启自动注册将会自动注册账号, 否则需要手动创建账号后再进行绑定\",\"type\":\"checkbox\"}]"
|
||||
AuthOAuth2Remark string = "自定义oauth2.0 server登录"
|
||||
)
|
||||
|
||||
type Auth struct {
|
||||
ConfigApp application.Config
|
||||
AuthApp application.Auth
|
||||
AccountApp application.Account
|
||||
MsgApp msgapp.Msg
|
||||
}
|
||||
|
||||
func (a *Auth) OAuth2Login(rc *req.Ctx) {
|
||||
client, _, err := a.getOAuthClient()
|
||||
if err != nil {
|
||||
biz.ErrIsNil(err, "获取oauth2 client失败: "+err.Error())
|
||||
return
|
||||
}
|
||||
state := stringx.Rand(32)
|
||||
cache.SetStr("oauth2:state:"+state, "login", 5*time.Minute)
|
||||
rc.GinCtx.Redirect(http.StatusFound, client.AuthCodeURL(state))
|
||||
}
|
||||
|
||||
func (a *Auth) OAuth2Callback(rc *req.Ctx) {
|
||||
client, oauth, err := a.getOAuthClient()
|
||||
if err != nil {
|
||||
biz.ErrIsNil(err, "获取oauth2 client失败: "+err.Error())
|
||||
}
|
||||
code := rc.GinCtx.Query("code")
|
||||
if code == "" {
|
||||
biz.ErrIsNil(errors.New("code不能为空"), "code不能为空")
|
||||
}
|
||||
state := rc.GinCtx.Query("state")
|
||||
if state == "" {
|
||||
biz.ErrIsNil(errors.New("state不能为空"), "state不能为空")
|
||||
}
|
||||
stateAction := cache.GetStr("oauth2:state:" + state)
|
||||
if stateAction == "" {
|
||||
biz.ErrIsNil(errors.New("state已过期,请重新登录"), "state已过期,请重新登录")
|
||||
}
|
||||
token, err := client.Exchange(rc.GinCtx, code)
|
||||
if err != nil {
|
||||
biz.ErrIsNil(err, "获取token失败: "+err.Error())
|
||||
}
|
||||
// 获取用户信息
|
||||
httpCli := client.Client(rc.GinCtx.Request.Context(), token)
|
||||
resp, err := httpCli.Get(oauth.ResourceURL)
|
||||
if err != nil {
|
||||
biz.ErrIsNil(err, "获取用户信息失败: "+err.Error())
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
b, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
biz.ErrIsNil(err, "获取用户信息失败: "+err.Error())
|
||||
}
|
||||
userInfo := make(map[string]interface{})
|
||||
err = json.Unmarshal(b, &userInfo)
|
||||
if err != nil {
|
||||
biz.ErrIsNil(err, "解析用户信息失败: "+err.Error())
|
||||
}
|
||||
|
||||
// 获取用户唯一标识
|
||||
keys := strings.Split(oauth.UserIdentifier, ".")
|
||||
var identifier interface{} = userInfo
|
||||
endKey := keys[len(keys)-1]
|
||||
keys = keys[:len(keys)-1]
|
||||
for _, key := range keys {
|
||||
identifier = identifier.(map[string]interface{})[key]
|
||||
}
|
||||
identifier = identifier.(map[string]interface{})[endKey]
|
||||
userId := ""
|
||||
switch identifier.(type) {
|
||||
case string:
|
||||
userId = identifier.(string)
|
||||
case int, int32, int64:
|
||||
userId = fmt.Sprintf("%d", identifier)
|
||||
case float32, float64:
|
||||
userId = fmt.Sprintf("%.0f", identifier.(float64))
|
||||
}
|
||||
// 查询用户是否存在
|
||||
oauthAccount := &entity.OAuthAccount{Identity: userId}
|
||||
err = a.AuthApp.GetOAuthAccount(oauthAccount, "account_id", "identity")
|
||||
// 判断是登录还是绑定
|
||||
if stateAction == "login" {
|
||||
var accountId uint64
|
||||
if err != nil {
|
||||
if err != gorm.ErrRecordNotFound {
|
||||
biz.ErrIsNil(err, "查询用户失败: "+err.Error())
|
||||
}
|
||||
// 不存在,进行注册
|
||||
if !oauth.AutoRegister {
|
||||
biz.ErrIsNil(errors.New("未绑定账号, 请先注册"), "未绑定账号, 请先注册")
|
||||
}
|
||||
now := time.Now()
|
||||
account := &entity.Account{
|
||||
Model: model.Model{
|
||||
CreateTime: &now,
|
||||
CreatorId: 0,
|
||||
Creator: "oauth2",
|
||||
UpdateTime: &now,
|
||||
},
|
||||
Name: userId,
|
||||
Username: userId,
|
||||
}
|
||||
a.AccountApp.Create(account)
|
||||
// 绑定
|
||||
if err := a.AuthApp.BindOAuthAccount(&entity.OAuthAccount{
|
||||
AccountId: account.Id,
|
||||
Identity: oauthAccount.Identity,
|
||||
CreateTime: &now,
|
||||
UpdateTime: &now,
|
||||
}); err != nil {
|
||||
biz.ErrIsNil(err, "绑定用户失败: "+err.Error())
|
||||
}
|
||||
accountId = account.Id
|
||||
} else {
|
||||
accountId = oauthAccount.AccountId
|
||||
}
|
||||
// 进行登录
|
||||
account := &entity.Account{
|
||||
Model: model.Model{DeletedModel: model.DeletedModel{Id: accountId}},
|
||||
}
|
||||
if err := a.AccountApp.GetAccount(account, "Id", "Name", "Username", "Password", "Status", "LastLoginTime", "LastLoginIp", "OtpSecret"); err != nil {
|
||||
biz.ErrIsNil(err, "获取用户信息失败: "+err.Error())
|
||||
}
|
||||
biz.IsTrue(account.IsEnable(), "该账号不可用")
|
||||
// 访问系统使用的token
|
||||
accessToken := req.CreateToken(accountId, account.Username)
|
||||
// 默认为不校验otp
|
||||
otpStatus := OtpStatusNone
|
||||
clientIp := rc.GinCtx.ClientIP()
|
||||
rc.ReqParam = fmt.Sprintf("oauth2 login username: %s | ip: %s", account.Username, clientIp)
|
||||
|
||||
res := map[string]any{
|
||||
"name": account.Name,
|
||||
"username": account.Username,
|
||||
"lastLoginTime": account.LastLoginTime,
|
||||
"lastLoginIp": account.LastLoginIp,
|
||||
}
|
||||
|
||||
accountLoginSecurity := a.ConfigApp.GetConfig(entity.ConfigKeyAccountLoginSecurity).ToAccountLoginSecurity()
|
||||
// 判断otp
|
||||
if accountLoginSecurity.UseOtp {
|
||||
otpInfo, otpurl, otpToken := useOtp(account, accountLoginSecurity.OtpIssuer, accessToken)
|
||||
otpStatus = otpInfo.OptStatus
|
||||
if otpurl != "" {
|
||||
res["otpUrl"] = otpurl
|
||||
}
|
||||
accessToken = otpToken
|
||||
} else {
|
||||
// 保存登录消息
|
||||
go saveLogin(a.AccountApp, a.MsgApp, account, getIpAndRegion(rc))
|
||||
}
|
||||
// 赋值otp状态
|
||||
res["action"] = "oauthLogin"
|
||||
res["otp"] = otpStatus
|
||||
res["token"] = accessToken
|
||||
b, err = json.Marshal(res)
|
||||
biz.ErrIsNil(err, "数据序列化失败")
|
||||
rc.GinCtx.Header("Content-Type", "text/html; charset=utf-8")
|
||||
rc.GinCtx.Writer.WriteHeader(http.StatusOK)
|
||||
_, _ = rc.GinCtx.Writer.WriteString("<html>" +
|
||||
"<script>top.opener.postMessage(" + string(b) + ")</script>" +
|
||||
"</html>")
|
||||
} else if sAccountId, ok := strings.CutPrefix(stateAction, "bind:"); ok {
|
||||
// 绑定
|
||||
accountId, err := strconv.ParseUint(sAccountId, 10, 64)
|
||||
if err != nil {
|
||||
biz.ErrIsNil(err, "绑定用户失败: "+err.Error())
|
||||
}
|
||||
now := time.Now()
|
||||
if err := a.AuthApp.BindOAuthAccount(&entity.OAuthAccount{
|
||||
AccountId: accountId,
|
||||
Identity: oauthAccount.Identity,
|
||||
CreateTime: &now,
|
||||
UpdateTime: &now,
|
||||
}); err != nil {
|
||||
biz.ErrIsNil(err, "绑定用户失败: "+err.Error())
|
||||
}
|
||||
res := map[string]any{
|
||||
"action": "oauthBind",
|
||||
"bind": true,
|
||||
}
|
||||
b, err = json.Marshal(res)
|
||||
biz.ErrIsNil(err, "数据序列化失败")
|
||||
rc.GinCtx.Header("Content-Type", "text/html; charset=utf-8")
|
||||
rc.GinCtx.Writer.WriteHeader(http.StatusOK)
|
||||
_, _ = rc.GinCtx.Writer.WriteString("<html>" +
|
||||
"<script>top.opener.postMessage(" + string(b) + ")</script>" +
|
||||
"</html>")
|
||||
} else {
|
||||
biz.ErrIsNil(errors.New("state不合法"), "state不合法")
|
||||
}
|
||||
}
|
||||
|
||||
func (a *Auth) getOAuthClient() (*oauth2.Config, *vo.OAuth2VO, error) {
|
||||
config := a.ConfigApp.GetConfig(AuthOAuth2Key)
|
||||
oauth2Vo := &vo.OAuth2VO{}
|
||||
if config.Value != "" {
|
||||
if err := json.Unmarshal([]byte(config.Value), oauth2Vo); err != nil {
|
||||
global.Log.Warnf("解析自定义oauth2配置失败,err:%s", err.Error())
|
||||
return nil, nil, errors.New("解析自定义oauth2配置失败")
|
||||
}
|
||||
}
|
||||
if oauth2Vo.ClientID == "" {
|
||||
biz.ErrIsNil(nil, "请先配置oauth2")
|
||||
return nil, nil, errors.New("请先配置oauth2")
|
||||
}
|
||||
client := &oauth2.Config{
|
||||
ClientID: oauth2Vo.ClientID,
|
||||
ClientSecret: oauth2Vo.ClientSecret,
|
||||
Endpoint: oauth2.Endpoint{
|
||||
AuthURL: oauth2Vo.AuthorizationURL,
|
||||
TokenURL: oauth2Vo.AccessTokenURL,
|
||||
},
|
||||
RedirectURL: oauth2Vo.RedirectURL + "api/sys/auth/oauth2/callback",
|
||||
Scopes: strings.Split(oauth2Vo.Scopes, ","),
|
||||
}
|
||||
return client, oauth2Vo, nil
|
||||
}
|
||||
|
||||
// GetInfo 获取认证平台信息
|
||||
func (a *Auth) GetInfo(rc *req.Ctx) {
|
||||
config := a.ConfigApp.GetConfig(AuthOAuth2Key)
|
||||
oauth2 := &vo.OAuth2VO{}
|
||||
if config.Value != "" {
|
||||
if err := json.Unmarshal([]byte(config.Value), oauth2); err != nil {
|
||||
global.Log.Warnf("解析自定义oauth2配置失败,err:%s", err.Error())
|
||||
biz.ErrIsNil(err, "解析自定义oauth2配置失败")
|
||||
}
|
||||
}
|
||||
rc.ResData = &vo.AuthVO{
|
||||
OAuth2VO: oauth2,
|
||||
}
|
||||
}
|
||||
|
||||
func (a *Auth) SaveOAuth2(rc *req.Ctx) {
|
||||
form := &form2.OAuth2Form{}
|
||||
form = ginx.BindJsonAndValid(rc.GinCtx, form)
|
||||
rc.ReqParam = form
|
||||
// 先获取看看有没有
|
||||
config := a.ConfigApp.GetConfig(AuthOAuth2Key)
|
||||
now := time.Now()
|
||||
if config.Id == 0 {
|
||||
config.CreatorId = rc.LoginAccount.Id
|
||||
config.Creator = rc.LoginAccount.Username
|
||||
config.CreateTime = &now
|
||||
}
|
||||
config.ModifierId = rc.LoginAccount.Id
|
||||
config.Modifier = rc.LoginAccount.Username
|
||||
config.UpdateTime = &now
|
||||
config.Name = AuthOAuth2Name
|
||||
config.Key = AuthOAuth2Key
|
||||
config.Params = AuthOAuth2Param
|
||||
b, err := json.Marshal(form)
|
||||
if err != nil {
|
||||
biz.ErrIsNil(err, "json marshal error")
|
||||
return
|
||||
}
|
||||
config.Value = string(b)
|
||||
config.Remark = AuthOAuth2Remark
|
||||
a.ConfigApp.Save(config)
|
||||
}
|
||||
|
||||
func (a *Auth) OAuth2Bind(rc *req.Ctx) {
|
||||
client, _, err := a.getOAuthClient()
|
||||
if err != nil {
|
||||
biz.ErrIsNil(err, "获取oauth2 client失败: "+err.Error())
|
||||
return
|
||||
}
|
||||
state := stringx.Rand(32)
|
||||
cache.SetStr("oauth2:state:"+state, "bind:"+strconv.FormatUint(rc.LoginAccount.Id, 10),
|
||||
5*time.Minute)
|
||||
rc.GinCtx.Redirect(http.StatusFound, client.AuthCodeURL(state))
|
||||
}
|
||||
|
||||
func (a *Auth) Auth2Status(ctx *req.Ctx) {
|
||||
res := &vo.AuthStatusVO{}
|
||||
config := a.ConfigApp.GetConfig(AuthOAuth2Key)
|
||||
if config.Value != "" {
|
||||
oauth2 := &vo.OAuth2VO{}
|
||||
if err := json.Unmarshal([]byte(config.Value), oauth2); err != nil {
|
||||
global.Log.Warnf("解析自定义oauth2配置失败,err:%s", err.Error())
|
||||
biz.ErrIsNil(err, "解析自定义oauth2配置失败")
|
||||
} else if oauth2.ClientID != "" {
|
||||
res.Enable.OAuth2 = true
|
||||
}
|
||||
}
|
||||
if res.Enable.OAuth2 {
|
||||
err := a.AuthApp.GetOAuthAccount(&entity.OAuthAccount{
|
||||
AccountId: ctx.LoginAccount.Id,
|
||||
}, "account_id", "identity")
|
||||
if err != nil {
|
||||
if err != gorm.ErrRecordNotFound {
|
||||
biz.ErrIsNil(err, "查询用户失败: "+err.Error())
|
||||
}
|
||||
} else {
|
||||
res.Bind.OAuth2 = true
|
||||
}
|
||||
}
|
||||
ctx.ResData = res
|
||||
}
|
||||
@@ -1,14 +1,11 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"mayfly-go/internal/sys/api/form"
|
||||
"mayfly-go/internal/sys/api/vo"
|
||||
"mayfly-go/internal/sys/application"
|
||||
"mayfly-go/internal/sys/domain/entity"
|
||||
"mayfly-go/pkg/biz"
|
||||
"mayfly-go/pkg/ginx"
|
||||
"mayfly-go/pkg/global"
|
||||
"mayfly-go/pkg/req"
|
||||
)
|
||||
|
||||
@@ -51,18 +48,10 @@ func (c *Config) SaveConfig(rc *req.Ctx) {
|
||||
c.ConfigApp.Save(config)
|
||||
}
|
||||
|
||||
// AuthConfig auth相关配置
|
||||
func (c *Config) AuthConfig(rc *req.Ctx) {
|
||||
resp := &vo.Auth2EnableVO{}
|
||||
config := c.ConfigApp.GetConfig(AuthOAuth2Key)
|
||||
oauth2 := &vo.OAuth2VO{}
|
||||
if config.Value != "" {
|
||||
if err := json.Unmarshal([]byte(config.Value), oauth2); err != nil {
|
||||
global.Log.Warnf("解析自定义oauth2配置失败,err:%s", err.Error())
|
||||
biz.ErrIsNil(err, "解析自定义oauth2配置失败")
|
||||
} else if oauth2.ClientID != "" {
|
||||
resp.OAuth2 = true
|
||||
}
|
||||
// 获取oauth2登录配置信息,因为有些字段是敏感字段,故单独使用接口获取
|
||||
func (c *Config) Oauth2Config(rc *req.Ctx) {
|
||||
oauth2LoginConfig := c.ConfigApp.GetConfig(entity.ConfigKeyOauth2Login).ToOauth2Login()
|
||||
rc.ResData = map[string]any{
|
||||
"enable": oauth2LoginConfig.Enable,
|
||||
}
|
||||
rc.ResData = resp
|
||||
}
|
||||
|
||||
@@ -1,13 +0,0 @@
|
||||
package form
|
||||
|
||||
type OAuth2Form struct {
|
||||
ClientID string `json:"clientID" binding:"required"`
|
||||
ClientSecret string `json:"clientSecret" binding:"required"`
|
||||
AuthorizationURL string `json:"authorizationURL" binding:"required,url"`
|
||||
AccessTokenURL string `json:"accessTokenURL" binding:"required,url"`
|
||||
ResourceURL string `json:"resourceURL" binding:"required,url"`
|
||||
RedirectURL string `json:"redirectURL" binding:"required,url"`
|
||||
UserIdentifier string `json:"userIdentifier" binding:"required"`
|
||||
Scopes string `json:"scopes"`
|
||||
AutoRegister bool `json:"autoRegister"`
|
||||
}
|
||||
@@ -1,26 +0,0 @@
|
||||
package vo
|
||||
|
||||
type OAuth2VO struct {
|
||||
ClientID string `json:"clientID"`
|
||||
ClientSecret string `json:"clientSecret"`
|
||||
AuthorizationURL string `json:"authorizationURL"`
|
||||
AccessTokenURL string `json:"accessTokenURL"`
|
||||
ResourceURL string `json:"resourceURL"`
|
||||
RedirectURL string `json:"redirectURL"`
|
||||
UserIdentifier string `json:"userIdentifier"`
|
||||
Scopes string `json:"scopes"`
|
||||
AutoRegister bool `json:"autoRegister"`
|
||||
}
|
||||
|
||||
type AuthVO struct {
|
||||
*OAuth2VO `json:"oauth2"`
|
||||
}
|
||||
|
||||
type Auth2EnableVO struct {
|
||||
OAuth2 bool `json:"oauth2"`
|
||||
}
|
||||
|
||||
type AuthStatusVO struct {
|
||||
Enable Auth2EnableVO `json:"enable"`
|
||||
Bind Auth2EnableVO `json:"bind"`
|
||||
}
|
||||
@@ -6,7 +6,6 @@ import (
|
||||
|
||||
var (
|
||||
accountApp = newAccountApp(persistence.GetAccountRepo())
|
||||
authApp = newAuthApp(persistence.GetOAuthAccountRepo())
|
||||
configApp = newConfigApp(persistence.GetConfigRepo())
|
||||
resourceApp = newResourceApp(persistence.GetResourceRepo())
|
||||
roleApp = newRoleApp(persistence.GetRoleRepo())
|
||||
@@ -17,10 +16,6 @@ func GetAccountApp() Account {
|
||||
return accountApp
|
||||
}
|
||||
|
||||
func GetAuthApp() Auth {
|
||||
return authApp
|
||||
}
|
||||
|
||||
func GetConfigApp() Config {
|
||||
return configApp
|
||||
}
|
||||
|
||||
@@ -1,29 +0,0 @@
|
||||
package application
|
||||
|
||||
import (
|
||||
"mayfly-go/internal/sys/domain/entity"
|
||||
"mayfly-go/internal/sys/domain/repository"
|
||||
)
|
||||
|
||||
type Auth interface {
|
||||
GetOAuthAccount(condition *entity.OAuthAccount, cols ...string) error
|
||||
BindOAuthAccount(e *entity.OAuthAccount) error
|
||||
}
|
||||
|
||||
func newAuthApp(oauthAccountRepo repository.OAuthAccount) Auth {
|
||||
return &authAppImpl{
|
||||
oauthAccountRepo: oauthAccountRepo,
|
||||
}
|
||||
}
|
||||
|
||||
type authAppImpl struct {
|
||||
oauthAccountRepo repository.OAuthAccount
|
||||
}
|
||||
|
||||
func (a *authAppImpl) GetOAuthAccount(condition *entity.OAuthAccount, cols ...string) error {
|
||||
return a.oauthAccountRepo.GetOAuthAccount(condition, cols...)
|
||||
}
|
||||
|
||||
func (a *authAppImpl) BindOAuthAccount(e *entity.OAuthAccount) error {
|
||||
return a.oauthAccountRepo.SaveOAuthAccount(e)
|
||||
}
|
||||
@@ -8,8 +8,7 @@ import (
|
||||
|
||||
const (
|
||||
ConfigKeyAccountLoginSecurity string = "AccountLoginSecurity" // 账号登录安全配置
|
||||
ConfigKeyUseLoginCaptcha string = "UseLoginCaptcha" // 是否使用登录验证码
|
||||
ConfigKeyUseLoginOtp string = "UseLoginOtp" // 是否开启otp双因素校验
|
||||
ConfigKeyOauth2Login string = "Oauth2Login" // oauth2认证登录配置
|
||||
ConfigKeyDbQueryMaxCount string = "DbQueryMaxCount" // 数据库查询的最大数量
|
||||
ConfigKeyDbSaveQuerySQL string = "DbSaveQuerySQL" // 数据库是否记录查询相关sql
|
||||
ConfigUseWartermark string = "UseWartermark" // 是否使用水印
|
||||
@@ -19,8 +18,8 @@ type Config struct {
|
||||
model.Model
|
||||
Name string `json:"name"` // 配置名
|
||||
Key string `json:"key"` // 配置key
|
||||
Params string `json:"params" gorm:"column:params;type:varchar(1000)"`
|
||||
Value string `json:"value" gorm:"column:value;type:varchar(1000)"`
|
||||
Params string `json:"params" gorm:"column:params;type:varchar(1500)"`
|
||||
Value string `json:"value" gorm:"column:value;type:varchar(1500)"`
|
||||
Remark string `json:"remark"`
|
||||
}
|
||||
|
||||
@@ -80,6 +79,36 @@ func (c *Config) ToAccountLoginSecurity() *AccountLoginSecurity {
|
||||
return als
|
||||
}
|
||||
|
||||
type ConfigOauth2Login struct {
|
||||
Enable bool // 是否启用
|
||||
ClientId string `json:"clientId"`
|
||||
ClientSecret string `json:"clientSecret"`
|
||||
AuthorizationURL string `json:"authorizationURL"`
|
||||
AccessTokenURL string `json:"accessTokenURL"`
|
||||
RedirectURL string `json:"redirectURL"`
|
||||
Scopes string `json:"scopes"`
|
||||
ResourceURL string `json:"resourceURL"`
|
||||
UserIdentifier string `json:"userIdentifier"`
|
||||
AutoRegister bool `json:"autoRegister"` // 是否自动注册
|
||||
}
|
||||
|
||||
// 转换为Oauth2Login结构体
|
||||
func (c *Config) ToOauth2Login() *ConfigOauth2Login {
|
||||
jm := c.GetJsonMap()
|
||||
ol := new(ConfigOauth2Login)
|
||||
ol.Enable = convertBool(jm["enable"], false)
|
||||
ol.ClientId = jm["clientId"]
|
||||
ol.ClientSecret = jm["clientSecret"]
|
||||
ol.AuthorizationURL = jm["authorizationURL"]
|
||||
ol.AccessTokenURL = jm["accessTokenURL"]
|
||||
ol.RedirectURL = jm["redirectURL"]
|
||||
ol.Scopes = jm["scopes"]
|
||||
ol.ResourceURL = jm["resourceURL"]
|
||||
ol.UserIdentifier = jm["userIdentifier"]
|
||||
ol.AutoRegister = convertBool(jm["autoRegister"], true)
|
||||
return ol
|
||||
}
|
||||
|
||||
// 转换配置中的值为bool类型(默认"1"或"true"为true,其他为false)
|
||||
func convertBool(value string, defaultValue bool) bool {
|
||||
if value == "" {
|
||||
|
||||
@@ -1,10 +0,0 @@
|
||||
package repository
|
||||
|
||||
import "mayfly-go/internal/sys/domain/entity"
|
||||
|
||||
type OAuthAccount interface {
|
||||
// GetOAuthAccount 根据identity获取第三方账号信息
|
||||
GetOAuthAccount(condition *entity.OAuthAccount, cols ...string) error
|
||||
|
||||
SaveOAuthAccount(e *entity.OAuthAccount) error
|
||||
}
|
||||
@@ -1,24 +0,0 @@
|
||||
package persistence
|
||||
|
||||
import (
|
||||
"mayfly-go/internal/sys/domain/entity"
|
||||
"mayfly-go/internal/sys/domain/repository"
|
||||
"mayfly-go/pkg/gormx"
|
||||
)
|
||||
|
||||
type authAccountRepoImpl struct{}
|
||||
|
||||
func newAuthAccountRepo() repository.OAuthAccount {
|
||||
return new(authAccountRepoImpl)
|
||||
}
|
||||
|
||||
func (a *authAccountRepoImpl) GetOAuthAccount(condition *entity.OAuthAccount, cols ...string) error {
|
||||
return gormx.GetBy(condition, cols...)
|
||||
}
|
||||
|
||||
func (a *authAccountRepoImpl) SaveOAuthAccount(e *entity.OAuthAccount) error {
|
||||
if e.Id == 0 {
|
||||
return gormx.Insert(e)
|
||||
}
|
||||
return gormx.UpdateById(e)
|
||||
}
|
||||
@@ -3,22 +3,17 @@ package persistence
|
||||
import "mayfly-go/internal/sys/domain/repository"
|
||||
|
||||
var (
|
||||
accountRepo = newAccountRepo()
|
||||
authAccountRepo = newAuthAccountRepo()
|
||||
configRepo = newConfigRepo()
|
||||
resourceRepo = newResourceRepo()
|
||||
roleRepo = newRoleRepo()
|
||||
syslogRepo = newSyslogRepo()
|
||||
accountRepo = newAccountRepo()
|
||||
configRepo = newConfigRepo()
|
||||
resourceRepo = newResourceRepo()
|
||||
roleRepo = newRoleRepo()
|
||||
syslogRepo = newSyslogRepo()
|
||||
)
|
||||
|
||||
func GetAccountRepo() repository.Account {
|
||||
return accountRepo
|
||||
}
|
||||
|
||||
func GetOAuthAccountRepo() repository.OAuthAccount {
|
||||
return authAccountRepo
|
||||
}
|
||||
|
||||
func GetConfigRepo() repository.Config {
|
||||
return configRepo
|
||||
}
|
||||
|
||||
@@ -22,11 +22,6 @@ func InitAccountRouter(router *gin.RouterGroup) {
|
||||
addAccountPermission := req.NewPermission("account:add")
|
||||
|
||||
reqs := [...]*req.Conf{
|
||||
// 用户登录
|
||||
req.NewPost("/login", a.Login).Log(req.NewLogSave("用户登录")).DontNeedToken(),
|
||||
|
||||
// otp双因素校验
|
||||
req.NewPost("/otp-verify", a.OtpVerify).DontNeedToken(),
|
||||
|
||||
// 获取个人账号的权限资源信息
|
||||
req.NewGet("/permissions", a.GetPermissions),
|
||||
|
||||
@@ -1,35 +0,0 @@
|
||||
package router
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
msgapp "mayfly-go/internal/msg/application"
|
||||
"mayfly-go/internal/sys/api"
|
||||
"mayfly-go/internal/sys/application"
|
||||
"mayfly-go/pkg/req"
|
||||
)
|
||||
|
||||
func InitSysAuthRouter(router *gin.RouterGroup) {
|
||||
r := &api.Auth{
|
||||
ConfigApp: application.GetConfigApp(),
|
||||
AuthApp: application.GetAuthApp(),
|
||||
AccountApp: application.GetAccountApp(),
|
||||
MsgApp: msgapp.GetMsgApp(),
|
||||
}
|
||||
rg := router.Group("sys/auth")
|
||||
|
||||
baseP := req.NewPermission("system:auth:base")
|
||||
|
||||
reqs := [...]*req.Conf{
|
||||
req.NewGet("", r.GetInfo).RequiredPermission(baseP),
|
||||
|
||||
req.NewPut("/oauth2", r.SaveOAuth2).RequiredPermission(baseP),
|
||||
|
||||
req.NewGet("/status", r.Auth2Status),
|
||||
req.NewGet("/oauth2/bind", r.OAuth2Bind),
|
||||
|
||||
req.NewGet("/oauth2/login", r.OAuth2Login).DontNeedToken(),
|
||||
req.NewGet("/oauth2/callback", r.OAuth2Callback).NoRes().DontNeedToken(),
|
||||
}
|
||||
|
||||
req.BatchSetGroup(rg, reqs[:])
|
||||
}
|
||||
@@ -26,7 +26,7 @@ func InitSysConfigRouter(router *gin.RouterGroup) {
|
||||
entity.ConfigUseWartermark,
|
||||
})).DontNeedToken(),
|
||||
|
||||
req.NewGet("/auth", r.AuthConfig).DontNeedToken(),
|
||||
req.NewGet("/oauth2-login", r.Oauth2Config).DontNeedToken(),
|
||||
|
||||
req.NewPost("", r.SaveConfig).Log(req.NewLogSave("保存系统配置信息")).
|
||||
RequiredPermissionCode("config:save"),
|
||||
|
||||
@@ -10,5 +10,4 @@ func Init(router *gin.RouterGroup) {
|
||||
InitSystemRouter(router)
|
||||
InitSyslogRouter(router)
|
||||
InitSysConfigRouter(router)
|
||||
InitSysAuthRouter(router)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user