feat: 新增第三方登录认证和管理
This commit is contained in:
@@ -23,38 +23,84 @@ func Setup(router *gin.Engine) {
|
||||
)
|
||||
|
||||
// 账号身份操作
|
||||
account := controller.NewAccount
|
||||
accountGroup := router.Group("/auth")
|
||||
{
|
||||
router.POST("/auth/login",
|
||||
accountGroup.POST("/login",
|
||||
middleware.RateLimit(middleware.LimitOption{
|
||||
Time: 180,
|
||||
Count: 15,
|
||||
Type: middleware.LIMIT_IP,
|
||||
}),
|
||||
controller.NewAccount.Login,
|
||||
account.Login,
|
||||
)
|
||||
router.POST("/auth/logout",
|
||||
accountGroup.POST("/logout",
|
||||
middleware.RateLimit(middleware.LimitOption{
|
||||
Time: 120,
|
||||
Count: 15,
|
||||
Type: middleware.LIMIT_IP,
|
||||
}),
|
||||
controller.NewAccount.Logout,
|
||||
account.Logout,
|
||||
)
|
||||
router.POST("/auth/refresh-token",
|
||||
accountGroup.POST("/refresh-token",
|
||||
middleware.RateLimit(middleware.LimitOption{
|
||||
Time: 60,
|
||||
Count: 5,
|
||||
Type: middleware.LIMIT_IP,
|
||||
}),
|
||||
controller.NewAccount.RefreshToken,
|
||||
account.RefreshToken,
|
||||
)
|
||||
router.GET("/me",
|
||||
middleware.AuthorizeUser(nil),
|
||||
controller.NewAccount.Me,
|
||||
account.Me,
|
||||
)
|
||||
router.GET("/router",
|
||||
middleware.AuthorizeUser(nil),
|
||||
controller.NewAccount.Router,
|
||||
account.Router,
|
||||
)
|
||||
}
|
||||
|
||||
// 登录认证源
|
||||
{
|
||||
accountGroup.GET("/login/source",
|
||||
middleware.RateLimit(middleware.LimitOption{
|
||||
Time: 300,
|
||||
Count: 60,
|
||||
Type: middleware.LIMIT_IP,
|
||||
}),
|
||||
account.LoginSource,
|
||||
)
|
||||
accountGroup.POST("/login/ldap",
|
||||
middleware.RateLimit(middleware.LimitOption{
|
||||
Time: 180,
|
||||
Count: 15,
|
||||
Type: middleware.LIMIT_IP,
|
||||
}),
|
||||
account.LDAP,
|
||||
)
|
||||
accountGroup.POST("/login/smtp",
|
||||
middleware.RateLimit(middleware.LimitOption{
|
||||
Time: 180,
|
||||
Count: 15,
|
||||
Type: middleware.LIMIT_IP,
|
||||
}),
|
||||
account.SMTP,
|
||||
)
|
||||
accountGroup.GET("/login/oauth2/authorize",
|
||||
middleware.RateLimit(middleware.LimitOption{
|
||||
Time: 180,
|
||||
Count: 15,
|
||||
Type: middleware.LIMIT_IP,
|
||||
}),
|
||||
account.OAuth2CodeURL,
|
||||
)
|
||||
accountGroup.POST("/login/oauth2/token",
|
||||
middleware.RateLimit(middleware.LimitOption{
|
||||
Time: 180,
|
||||
Count: 15,
|
||||
Type: middleware.LIMIT_IP,
|
||||
}),
|
||||
account.OAuth2Token,
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -4,16 +4,13 @@ import (
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"be.ems/src/framework/config"
|
||||
"be.ems/src/framework/constants"
|
||||
"be.ems/src/framework/i18n"
|
||||
"be.ems/src/framework/reqctx"
|
||||
"be.ems/src/framework/resp"
|
||||
"be.ems/src/framework/token"
|
||||
"be.ems/src/framework/utils/parse"
|
||||
"be.ems/src/modules/auth/model"
|
||||
"be.ems/src/modules/auth/service"
|
||||
systemModelVO "be.ems/src/modules/system/model/vo"
|
||||
systemService "be.ems/src/modules/system/service"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
@@ -33,95 +30,6 @@ type AccountController struct {
|
||||
sysLogLoginService *systemService.SysLogLogin // 系统登录访问
|
||||
}
|
||||
|
||||
// Login 系统登录
|
||||
//
|
||||
// POST /auth/login
|
||||
//
|
||||
// @Tags common/authorization
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param data body object true "Request Param"
|
||||
// @Success 200 {object} object "Response Results"
|
||||
// @Summary System Login
|
||||
// @Description System Login
|
||||
// @Router /auth/login [post]
|
||||
func (s AccountController) Login(c *gin.Context) {
|
||||
language := reqctx.AcceptLanguage(c)
|
||||
var body model.LoginBody
|
||||
if err := c.ShouldBindJSON(&body); err != nil {
|
||||
errMsgs := fmt.Sprintf("bind err: %s", resp.FormatBindError(err))
|
||||
c.JSON(422, resp.CodeMsg(resp.CODE_PARAM_PARSER, errMsgs))
|
||||
return
|
||||
}
|
||||
|
||||
// 当前请求信息
|
||||
ipaddr, location := reqctx.IPAddrLocation(c)
|
||||
os, browser := reqctx.UaOsBrowser(c)
|
||||
|
||||
// 校验验证码 根据错误信息,创建系统访问记录
|
||||
if err := s.accountService.ValidateCaptcha(body.Code, body.UUID); err != nil {
|
||||
msg := fmt.Sprintf("%s code %s", err.Error(), body.Code)
|
||||
s.sysLogLoginService.Insert(
|
||||
body.Username, constants.STATUS_NO, msg,
|
||||
[4]string{ipaddr, location, os, browser},
|
||||
)
|
||||
c.JSON(200, resp.ErrMsg(i18n.TKey(language, err.Error())))
|
||||
return
|
||||
}
|
||||
|
||||
// 登录用户信息
|
||||
info, err := s.accountService.ByUsername(body.Username, body.Password)
|
||||
if err != nil {
|
||||
s.sysLogLoginService.Insert(
|
||||
body.Username, constants.STATUS_NO, err.Error(),
|
||||
[4]string{ipaddr, location, os, browser},
|
||||
)
|
||||
c.JSON(200, resp.ErrMsg(i18n.TKey(language, err.Error())))
|
||||
return
|
||||
}
|
||||
|
||||
data := map[string]any{}
|
||||
|
||||
if !config.IsSystemUser(info.UserId) {
|
||||
// 强制改密码
|
||||
forcePasswdChange, err := s.accountService.PasswordCountOrExpireTime(info.User.LoginCount, info.User.PasswordUpdateTime)
|
||||
if err != nil {
|
||||
c.JSON(200, resp.ErrMsg(i18n.TKey(language, err.Error())))
|
||||
return
|
||||
}
|
||||
if forcePasswdChange {
|
||||
data["forcePasswdChange"] = true
|
||||
}
|
||||
}
|
||||
|
||||
deviceFingerprint := reqctx.DeviceFingerprint(c, info.UserId)
|
||||
|
||||
// 生成访问令牌
|
||||
accessToken, expiresIn := token.UserTokenCreate(info.UserId, deviceFingerprint, "access")
|
||||
if accessToken == "" || expiresIn == 0 {
|
||||
c.JSON(200, resp.ErrMsg("token generation failed"))
|
||||
return
|
||||
}
|
||||
// 生成刷新令牌
|
||||
refreshToken, refreshExpiresIn := token.UserTokenCreate(info.UserId, deviceFingerprint, "refresh")
|
||||
|
||||
// 记录令牌,创建系统访问记录
|
||||
token.UserInfoCreate(&info, deviceFingerprint, [4]string{ipaddr, location, os, browser})
|
||||
s.accountService.UpdateLoginDateAndIP(info)
|
||||
s.sysLogLoginService.Insert(
|
||||
body.Username, constants.STATUS_YES, "app.common.loginSuccess",
|
||||
[4]string{ipaddr, location, os, browser},
|
||||
)
|
||||
|
||||
data["tokenType"] = constants.HEADER_PREFIX
|
||||
data["accessToken"] = accessToken
|
||||
data["expiresIn"] = expiresIn
|
||||
data["refreshToken"] = refreshToken
|
||||
data["refreshExpiresIn"] = refreshExpiresIn
|
||||
data["userId"] = info.UserId
|
||||
c.JSON(200, resp.OkData(data))
|
||||
}
|
||||
|
||||
// Logout 系统登出
|
||||
//
|
||||
// POST /auth/logout
|
||||
@@ -222,82 +130,10 @@ func (s AccountController) RefreshToken(c *gin.Context) {
|
||||
}))
|
||||
}
|
||||
|
||||
// Me 登录用户信息
|
||||
// LoginSource 登录认证源
|
||||
//
|
||||
// GET /me
|
||||
//
|
||||
// @Tags common/authorization
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Success 200 {object} object "Response Results"
|
||||
// @Security TokenAuth
|
||||
// @Summary Login User Information
|
||||
// @Description Login User Information
|
||||
// @Router /me [get]
|
||||
func (s AccountController) Me(c *gin.Context) {
|
||||
language := reqctx.AcceptLanguage(c)
|
||||
info, err := reqctx.LoginUser(c)
|
||||
if err != nil {
|
||||
c.JSON(401, resp.CodeMsg(resp.CODE_AUTH_INVALID, err.Error()))
|
||||
return
|
||||
}
|
||||
|
||||
// 角色权限集合,系统管理员拥有所有权限
|
||||
isSystemUser := config.IsSystemUser(info.UserId)
|
||||
roles, perms := s.accountService.RoleAndMenuPerms(info.UserId, isSystemUser)
|
||||
|
||||
info.User.NickName = i18n.TKey(language, info.User.NickName)
|
||||
info.User.Remark = i18n.TKey(language, info.User.Remark)
|
||||
info.User.Dept.DeptName = i18n.TKey(language, info.User.Dept.DeptName)
|
||||
for ri := range info.User.Roles {
|
||||
info.User.Roles[ri].RoleName = i18n.TKey(language, info.User.Roles[ri].RoleName)
|
||||
}
|
||||
|
||||
data := map[string]any{
|
||||
"user": info.User,
|
||||
"roles": roles,
|
||||
"permissions": perms,
|
||||
}
|
||||
if !isSystemUser {
|
||||
// 强制改密码
|
||||
forcePasswdChange, _ := s.accountService.PasswordCountOrExpireTime(info.User.LoginCount, info.User.PasswordUpdateTime)
|
||||
if forcePasswdChange {
|
||||
data["forcePasswdChange"] = true
|
||||
}
|
||||
}
|
||||
// GET /auth/login/source
|
||||
func (s AccountController) LoginSource(c *gin.Context) {
|
||||
data := s.accountService.LoginSource()
|
||||
c.JSON(200, resp.OkData(data))
|
||||
}
|
||||
|
||||
// Router 登录用户路由信息
|
||||
//
|
||||
// GET /router
|
||||
//
|
||||
// @Tags common/authorization
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Success 200 {object} object "Response Results"
|
||||
// @Security TokenAuth
|
||||
// @Summary Login User Routing Information
|
||||
// @Description Login User Routing Information
|
||||
// @Router /router [get]
|
||||
func (s AccountController) Router(c *gin.Context) {
|
||||
loginUserId := reqctx.LoginUserToUserID(c)
|
||||
|
||||
// 前端路由,系统管理员拥有所有
|
||||
isSystemUser := config.IsSystemUser(loginUserId)
|
||||
buildMenus := s.accountService.RouteMenus(loginUserId, isSystemUser)
|
||||
// 闭包函数处理多语言
|
||||
language := reqctx.AcceptLanguage(c)
|
||||
var converI18n func(language string, arr *[]systemModelVO.Router)
|
||||
converI18n = func(language string, arr *[]systemModelVO.Router) {
|
||||
for i := range *arr {
|
||||
(*arr)[i].Meta.Title = i18n.TKey(language, (*arr)[i].Meta.Title)
|
||||
if len((*arr)[i].Children) > 0 {
|
||||
converI18n(language, &(*arr)[i].Children)
|
||||
}
|
||||
}
|
||||
}
|
||||
converI18n(language, &buildMenus)
|
||||
|
||||
c.JSON(200, resp.OkData(buildMenus))
|
||||
}
|
||||
|
||||
93
src/modules/auth/controller/account_info.go
Normal file
93
src/modules/auth/controller/account_info.go
Normal file
@@ -0,0 +1,93 @@
|
||||
package controller
|
||||
|
||||
import (
|
||||
"be.ems/src/framework/config"
|
||||
"be.ems/src/framework/i18n"
|
||||
"be.ems/src/framework/reqctx"
|
||||
"be.ems/src/framework/resp"
|
||||
systemModelVO "be.ems/src/modules/system/model/vo"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// Me 登录用户信息
|
||||
//
|
||||
// GET /me
|
||||
//
|
||||
// @Tags common/authorization
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Success 200 {object} object "Response Results"
|
||||
// @Security TokenAuth
|
||||
// @Summary Login User Information
|
||||
// @Description Login User Information
|
||||
// @Router /me [get]
|
||||
func (s AccountController) Me(c *gin.Context) {
|
||||
language := reqctx.AcceptLanguage(c)
|
||||
info, err := reqctx.LoginUser(c)
|
||||
if err != nil {
|
||||
c.JSON(401, resp.CodeMsg(resp.CODE_AUTH_INVALID, err.Error()))
|
||||
return
|
||||
}
|
||||
|
||||
// 角色权限集合,系统管理员拥有所有权限
|
||||
isSystemUser := config.IsSystemUser(info.UserId)
|
||||
roles, perms := s.accountService.RoleAndMenuPerms(info.UserId, isSystemUser)
|
||||
|
||||
info.User.NickName = i18n.TKey(language, info.User.NickName)
|
||||
info.User.Remark = i18n.TKey(language, info.User.Remark)
|
||||
if info.User.Dept != nil {
|
||||
info.User.Dept.DeptName = i18n.TKey(language, info.User.Dept.DeptName)
|
||||
}
|
||||
for ri := range info.User.Roles {
|
||||
info.User.Roles[ri].RoleName = i18n.TKey(language, info.User.Roles[ri].RoleName)
|
||||
}
|
||||
|
||||
data := map[string]any{
|
||||
"user": info.User,
|
||||
"roles": roles,
|
||||
"permissions": perms,
|
||||
}
|
||||
if !isSystemUser {
|
||||
// 强制改密码
|
||||
forcePasswdChange, _ := s.accountService.PasswordCountOrExpireTime(info.User.LoginCount, info.User.PasswordUpdateTime)
|
||||
if forcePasswdChange {
|
||||
data["forcePasswdChange"] = true
|
||||
}
|
||||
}
|
||||
c.JSON(200, resp.OkData(data))
|
||||
}
|
||||
|
||||
// Router 登录用户路由信息
|
||||
//
|
||||
// GET /router
|
||||
//
|
||||
// @Tags common/authorization
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Success 200 {object} object "Response Results"
|
||||
// @Security TokenAuth
|
||||
// @Summary Login User Routing Information
|
||||
// @Description Login User Routing Information
|
||||
// @Router /router [get]
|
||||
func (s AccountController) Router(c *gin.Context) {
|
||||
loginUserId := reqctx.LoginUserToUserID(c)
|
||||
|
||||
// 前端路由,系统管理员拥有所有
|
||||
isSystemUser := config.IsSystemUser(loginUserId)
|
||||
buildMenus := s.accountService.RouteMenus(loginUserId, isSystemUser)
|
||||
// 闭包函数处理多语言
|
||||
language := reqctx.AcceptLanguage(c)
|
||||
var converI18n func(language string, arr *[]systemModelVO.Router)
|
||||
converI18n = func(language string, arr *[]systemModelVO.Router) {
|
||||
for i := range *arr {
|
||||
(*arr)[i].Meta.Title = i18n.TKey(language, (*arr)[i].Meta.Title)
|
||||
if len((*arr)[i].Children) > 0 {
|
||||
converI18n(language, &(*arr)[i].Children)
|
||||
}
|
||||
}
|
||||
}
|
||||
converI18n(language, &buildMenus)
|
||||
|
||||
c.JSON(200, resp.OkData(buildMenus))
|
||||
}
|
||||
80
src/modules/auth/controller/account_ldap.go
Normal file
80
src/modules/auth/controller/account_ldap.go
Normal file
@@ -0,0 +1,80 @@
|
||||
package controller
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"be.ems/src/framework/constants"
|
||||
"be.ems/src/framework/i18n"
|
||||
"be.ems/src/framework/reqctx"
|
||||
"be.ems/src/framework/resp"
|
||||
"be.ems/src/framework/token"
|
||||
"be.ems/src/modules/auth/model"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// LDAP LDAP认证登录
|
||||
//
|
||||
// POST /auth/ldap
|
||||
//
|
||||
// @Tags common/authorization
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param data body object true "Request Param"
|
||||
// @Success 200 {object} object "Response Results"
|
||||
// @Summary System Login
|
||||
// @Description System Login
|
||||
// @Router /auth/ldap [post]
|
||||
func (s AccountController) LDAP(c *gin.Context) {
|
||||
language := reqctx.AcceptLanguage(c)
|
||||
var body model.LoginSourceBody
|
||||
if err := c.ShouldBindJSON(&body); err != nil {
|
||||
errMsgs := fmt.Sprintf("bind err: %s", resp.FormatBindError(err))
|
||||
c.JSON(422, resp.CodeMsg(resp.CODE_PARAM_PARSER, errMsgs))
|
||||
return
|
||||
}
|
||||
|
||||
// 当前请求信息
|
||||
ipaddr, location := reqctx.IPAddrLocation(c)
|
||||
os, browser := reqctx.UaOsBrowser(c)
|
||||
|
||||
// 登录用户信息
|
||||
info, err := s.accountService.ByLDAP(body)
|
||||
if err != nil {
|
||||
s.sysLogLoginService.Insert(
|
||||
body.Username, constants.STATUS_NO, err.Error(),
|
||||
[4]string{ipaddr, location, os, browser},
|
||||
)
|
||||
c.JSON(200, resp.ErrMsg(i18n.TKey(language, err.Error())))
|
||||
return
|
||||
}
|
||||
|
||||
data := map[string]any{}
|
||||
|
||||
deviceFingerprint := reqctx.DeviceFingerprint(c, info.UserId)
|
||||
|
||||
// 生成访问令牌
|
||||
accessToken, expiresIn := token.UserTokenCreate(info.UserId, deviceFingerprint, "access")
|
||||
if accessToken == "" || expiresIn == 0 {
|
||||
c.JSON(200, resp.ErrMsg("token generation failed"))
|
||||
return
|
||||
}
|
||||
// 生成刷新令牌
|
||||
refreshToken, refreshExpiresIn := token.UserTokenCreate(info.UserId, deviceFingerprint, "refresh")
|
||||
|
||||
// 记录令牌,创建系统访问记录
|
||||
token.UserInfoCreate(&info, deviceFingerprint, [4]string{ipaddr, location, os, browser})
|
||||
s.accountService.UpdateLoginDateAndIP(info)
|
||||
s.sysLogLoginService.Insert(
|
||||
body.Username, constants.STATUS_YES, "app.common.loginSuccess",
|
||||
[4]string{ipaddr, location, os, browser},
|
||||
)
|
||||
|
||||
data["tokenType"] = constants.HEADER_PREFIX
|
||||
data["accessToken"] = accessToken
|
||||
data["expiresIn"] = expiresIn
|
||||
data["refreshToken"] = refreshToken
|
||||
data["refreshExpiresIn"] = refreshExpiresIn
|
||||
data["userId"] = info.UserId
|
||||
c.JSON(200, resp.OkData(data))
|
||||
}
|
||||
107
src/modules/auth/controller/account_oauth2.go
Normal file
107
src/modules/auth/controller/account_oauth2.go
Normal file
@@ -0,0 +1,107 @@
|
||||
package controller
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"be.ems/src/framework/constants"
|
||||
"be.ems/src/framework/i18n"
|
||||
"be.ems/src/framework/reqctx"
|
||||
"be.ems/src/framework/resp"
|
||||
"be.ems/src/framework/token"
|
||||
"be.ems/src/modules/auth/model"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// OAuth2CodeURL OAuth2认证跳转登录URL
|
||||
//
|
||||
// GET /auth/login/oauth2/authorize
|
||||
//
|
||||
// @Tags common/authorization
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param data body object true "Request Param"
|
||||
// @Success 200 {object} object "Response Results"
|
||||
// @Summary System Login
|
||||
// @Description System Login
|
||||
// @Router /auth/login/oauth2/authorize [get]
|
||||
func (s AccountController) OAuth2CodeURL(c *gin.Context) {
|
||||
state := c.Query("state")
|
||||
if state == "" {
|
||||
c.JSON(422, resp.CodeMsg(resp.CODE_PARAM_CHEACK, "bind err: state is empty"))
|
||||
return
|
||||
}
|
||||
|
||||
redirectURL, err := s.accountService.ByOAuth2CodeURL(state)
|
||||
if err != nil {
|
||||
c.JSON(200, resp.ErrMsg(err.Error()))
|
||||
return
|
||||
}
|
||||
c.Redirect(302, redirectURL)
|
||||
}
|
||||
|
||||
// OAuth2 OAuth2认证登录
|
||||
//
|
||||
// POST /auth/login/oauth2/token
|
||||
//
|
||||
// @Tags common/authorization
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param data body object true "Request Param"
|
||||
// @Success 200 {object} object "Response Results"
|
||||
// @Summary System Login
|
||||
// @Description System Login
|
||||
// @Router /auth/login/oauth2/token [post]
|
||||
func (s AccountController) OAuth2Token(c *gin.Context) {
|
||||
language := reqctx.AcceptLanguage(c)
|
||||
var body model.LoginSourceOauth2Body
|
||||
if err := c.ShouldBindJSON(&body); err != nil {
|
||||
errMsgs := fmt.Sprintf("bind err: %s", resp.FormatBindError(err))
|
||||
c.JSON(422, resp.CodeMsg(resp.CODE_PARAM_PARSER, errMsgs))
|
||||
return
|
||||
}
|
||||
|
||||
// 当前请求信息
|
||||
ipaddr, location := reqctx.IPAddrLocation(c)
|
||||
os, browser := reqctx.UaOsBrowser(c)
|
||||
|
||||
// 登录用户信息
|
||||
info, err := s.accountService.ByOAuth2(body)
|
||||
if err != nil {
|
||||
s.sysLogLoginService.Insert(
|
||||
body.State, constants.STATUS_NO, err.Error(),
|
||||
[4]string{ipaddr, location, os, browser},
|
||||
)
|
||||
c.JSON(200, resp.ErrMsg(i18n.TKey(language, err.Error())))
|
||||
return
|
||||
}
|
||||
|
||||
data := map[string]any{}
|
||||
|
||||
deviceFingerprint := reqctx.DeviceFingerprint(c, info.UserId)
|
||||
|
||||
// 生成访问令牌
|
||||
accessToken, expiresIn := token.UserTokenCreate(info.UserId, deviceFingerprint, "access")
|
||||
if accessToken == "" || expiresIn == 0 {
|
||||
c.JSON(200, resp.ErrMsg("token generation failed"))
|
||||
return
|
||||
}
|
||||
// 生成刷新令牌
|
||||
refreshToken, refreshExpiresIn := token.UserTokenCreate(info.UserId, deviceFingerprint, "refresh")
|
||||
|
||||
// 记录令牌,创建系统访问记录
|
||||
token.UserInfoCreate(&info, deviceFingerprint, [4]string{ipaddr, location, os, browser})
|
||||
s.accountService.UpdateLoginDateAndIP(info)
|
||||
s.sysLogLoginService.Insert(
|
||||
body.State, constants.STATUS_YES, "app.common.loginSuccess",
|
||||
[4]string{ipaddr, location, os, browser},
|
||||
)
|
||||
|
||||
data["tokenType"] = constants.HEADER_PREFIX
|
||||
data["accessToken"] = accessToken
|
||||
data["expiresIn"] = expiresIn
|
||||
data["refreshToken"] = refreshToken
|
||||
data["refreshExpiresIn"] = refreshExpiresIn
|
||||
data["userId"] = info.UserId
|
||||
c.JSON(200, resp.OkData(data))
|
||||
}
|
||||
80
src/modules/auth/controller/account_smtp.go
Normal file
80
src/modules/auth/controller/account_smtp.go
Normal file
@@ -0,0 +1,80 @@
|
||||
package controller
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"be.ems/src/framework/constants"
|
||||
"be.ems/src/framework/i18n"
|
||||
"be.ems/src/framework/reqctx"
|
||||
"be.ems/src/framework/resp"
|
||||
"be.ems/src/framework/token"
|
||||
"be.ems/src/modules/auth/model"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// SMTP SMTP认证登录
|
||||
//
|
||||
// POST /auth/smtp
|
||||
//
|
||||
// @Tags common/authorization
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param data body object true "Request Param"
|
||||
// @Success 200 {object} object "Response Results"
|
||||
// @Summary System Login
|
||||
// @Description System Login
|
||||
// @Router /auth/smtp [post]
|
||||
func (s AccountController) SMTP(c *gin.Context) {
|
||||
language := reqctx.AcceptLanguage(c)
|
||||
var body model.LoginSourceBody
|
||||
if err := c.ShouldBindJSON(&body); err != nil {
|
||||
errMsgs := fmt.Sprintf("bind err: %s", resp.FormatBindError(err))
|
||||
c.JSON(422, resp.CodeMsg(resp.CODE_PARAM_PARSER, errMsgs))
|
||||
return
|
||||
}
|
||||
|
||||
// 当前请求信息
|
||||
ipaddr, location := reqctx.IPAddrLocation(c)
|
||||
os, browser := reqctx.UaOsBrowser(c)
|
||||
|
||||
// 登录用户信息
|
||||
info, err := s.accountService.BySMTP(body)
|
||||
if err != nil {
|
||||
s.sysLogLoginService.Insert(
|
||||
body.Username, constants.STATUS_NO, err.Error(),
|
||||
[4]string{ipaddr, location, os, browser},
|
||||
)
|
||||
c.JSON(200, resp.ErrMsg(i18n.TKey(language, err.Error())))
|
||||
return
|
||||
}
|
||||
|
||||
data := map[string]any{}
|
||||
|
||||
deviceFingerprint := reqctx.DeviceFingerprint(c, info.UserId)
|
||||
|
||||
// 生成访问令牌
|
||||
accessToken, expiresIn := token.UserTokenCreate(info.UserId, deviceFingerprint, "access")
|
||||
if accessToken == "" || expiresIn == 0 {
|
||||
c.JSON(200, resp.ErrMsg("token generation failed"))
|
||||
return
|
||||
}
|
||||
// 生成刷新令牌
|
||||
refreshToken, refreshExpiresIn := token.UserTokenCreate(info.UserId, deviceFingerprint, "refresh")
|
||||
|
||||
// 记录令牌,创建系统访问记录
|
||||
token.UserInfoCreate(&info, deviceFingerprint, [4]string{ipaddr, location, os, browser})
|
||||
s.accountService.UpdateLoginDateAndIP(info)
|
||||
s.sysLogLoginService.Insert(
|
||||
body.Username, constants.STATUS_YES, "app.common.loginSuccess",
|
||||
[4]string{ipaddr, location, os, browser},
|
||||
)
|
||||
|
||||
data["tokenType"] = constants.HEADER_PREFIX
|
||||
data["accessToken"] = accessToken
|
||||
data["expiresIn"] = expiresIn
|
||||
data["refreshToken"] = refreshToken
|
||||
data["refreshExpiresIn"] = refreshExpiresIn
|
||||
data["userId"] = info.UserId
|
||||
c.JSON(200, resp.OkData(data))
|
||||
}
|
||||
104
src/modules/auth/controller/account_system.go
Normal file
104
src/modules/auth/controller/account_system.go
Normal file
@@ -0,0 +1,104 @@
|
||||
package controller
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"be.ems/src/framework/config"
|
||||
"be.ems/src/framework/constants"
|
||||
"be.ems/src/framework/i18n"
|
||||
"be.ems/src/framework/reqctx"
|
||||
"be.ems/src/framework/resp"
|
||||
"be.ems/src/framework/token"
|
||||
"be.ems/src/modules/auth/model"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// Login 系统登录
|
||||
//
|
||||
// POST /auth/login
|
||||
//
|
||||
// @Tags common/authorization
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param data body object true "Request Param"
|
||||
// @Success 200 {object} object "Response Results"
|
||||
// @Summary System Login
|
||||
// @Description System Login
|
||||
// @Router /auth/login [post]
|
||||
func (s AccountController) Login(c *gin.Context) {
|
||||
language := reqctx.AcceptLanguage(c)
|
||||
var body model.LoginBody
|
||||
if err := c.ShouldBindJSON(&body); err != nil {
|
||||
errMsgs := fmt.Sprintf("bind err: %s", resp.FormatBindError(err))
|
||||
c.JSON(422, resp.CodeMsg(resp.CODE_PARAM_PARSER, errMsgs))
|
||||
return
|
||||
}
|
||||
|
||||
// 当前请求信息
|
||||
ipaddr, location := reqctx.IPAddrLocation(c)
|
||||
os, browser := reqctx.UaOsBrowser(c)
|
||||
|
||||
// 校验验证码 根据错误信息,创建系统访问记录
|
||||
if err := s.accountService.ValidateCaptcha(body.Code, body.UUID); err != nil {
|
||||
msg := fmt.Sprintf("%s code %s", err.Error(), body.Code)
|
||||
s.sysLogLoginService.Insert(
|
||||
body.Username, constants.STATUS_NO, msg,
|
||||
[4]string{ipaddr, location, os, browser},
|
||||
)
|
||||
c.JSON(200, resp.ErrMsg(i18n.TKey(language, err.Error())))
|
||||
return
|
||||
}
|
||||
|
||||
// 登录用户信息
|
||||
info, err := s.accountService.ByUsername(body.Username, body.Password)
|
||||
if err != nil {
|
||||
s.sysLogLoginService.Insert(
|
||||
body.Username, constants.STATUS_NO, err.Error(),
|
||||
[4]string{ipaddr, location, os, browser},
|
||||
)
|
||||
c.JSON(200, resp.ErrMsg(i18n.TKey(language, err.Error())))
|
||||
return
|
||||
}
|
||||
|
||||
data := map[string]any{}
|
||||
|
||||
if !config.IsSystemUser(info.UserId) {
|
||||
// 强制改密码
|
||||
forcePasswdChange, err := s.accountService.PasswordCountOrExpireTime(info.User.LoginCount, info.User.PasswordUpdateTime)
|
||||
if err != nil {
|
||||
c.JSON(200, resp.ErrMsg(i18n.TKey(language, err.Error())))
|
||||
return
|
||||
}
|
||||
if forcePasswdChange {
|
||||
data["forcePasswdChange"] = true
|
||||
}
|
||||
}
|
||||
|
||||
deviceFingerprint := reqctx.DeviceFingerprint(c, info.UserId)
|
||||
|
||||
// 生成访问令牌
|
||||
accessToken, expiresIn := token.UserTokenCreate(info.UserId, deviceFingerprint, "access")
|
||||
if accessToken == "" || expiresIn == 0 {
|
||||
c.JSON(200, resp.ErrMsg("token generation failed"))
|
||||
return
|
||||
}
|
||||
// 生成刷新令牌
|
||||
refreshToken, refreshExpiresIn := token.UserTokenCreate(info.UserId, deviceFingerprint, "refresh")
|
||||
|
||||
// 记录令牌,创建系统访问记录
|
||||
token.UserInfoCreate(&info, deviceFingerprint, [4]string{ipaddr, location, os, browser})
|
||||
s.accountService.UpdateLoginDateAndIP(info)
|
||||
s.sysLogLoginService.Insert(
|
||||
body.Username, constants.STATUS_YES, "app.common.loginSuccess",
|
||||
[4]string{ipaddr, location, os, browser},
|
||||
)
|
||||
|
||||
data["tokenType"] = constants.HEADER_PREFIX
|
||||
data["accessToken"] = accessToken
|
||||
data["expiresIn"] = expiresIn
|
||||
data["refreshToken"] = refreshToken
|
||||
data["refreshExpiresIn"] = refreshExpiresIn
|
||||
data["userId"] = info.UserId
|
||||
c.JSON(200, resp.OkData(data))
|
||||
}
|
||||
@@ -2,15 +2,8 @@ package model
|
||||
|
||||
// LoginBody 用户登录对象
|
||||
type LoginBody struct {
|
||||
// Username 用户名
|
||||
Username string `json:"username" binding:"required"`
|
||||
|
||||
// Password 用户密码
|
||||
Password string `json:"password" binding:"required"`
|
||||
|
||||
// Code 验证码
|
||||
Code string `json:"code"`
|
||||
|
||||
// UUID 验证码唯一标识
|
||||
UUID string `json:"uuid"`
|
||||
Username string `json:"username" binding:"required"` // Username 用户名
|
||||
Password string `json:"password" binding:"required"` // Password 用户密码
|
||||
Code string `json:"code"` // Code 验证码
|
||||
UUID string `json:"uuid"` // UUID 验证码唯一标识
|
||||
}
|
||||
|
||||
22
src/modules/auth/model/login_source_vo.go
Normal file
22
src/modules/auth/model/login_source_vo.go
Normal file
@@ -0,0 +1,22 @@
|
||||
package model
|
||||
|
||||
// LoginSourceVo 认证源登录对象
|
||||
type LoginSourceVo struct {
|
||||
UID string `json:"uid"` // UID 认证源UID
|
||||
Name string `json:"name"` // Name 认证源名称
|
||||
Type string `json:"type"` // Type 认证源类型
|
||||
Icon string `json:"icon"` // Icon 认证源图标
|
||||
}
|
||||
|
||||
// LoginSourceBody 认证源用户登录对象
|
||||
type LoginSourceBody struct {
|
||||
Username string `json:"username" binding:"required"` // Username 用户名
|
||||
Password string `json:"password" binding:"required"` // Password 用户密码
|
||||
UID string `json:"uid" binding:"required"` // UID 认证源唯一标识
|
||||
}
|
||||
|
||||
// LoginSourceOauth2Body 认证源OAuth2用户登录对象
|
||||
type LoginSourceOauth2Body struct {
|
||||
Code string `json:"code" binding:"required"` // Code 授权码
|
||||
State string `json:"state" binding:"required"` // State 状态-认证源唯一标识
|
||||
}
|
||||
@@ -2,21 +2,10 @@ package model
|
||||
|
||||
// RegisterBody 用户注册对象
|
||||
type RegisterBody struct {
|
||||
// Username 用户名
|
||||
Username string `json:"username" binding:"required"`
|
||||
|
||||
// Password 用户密码
|
||||
Password string `json:"password" binding:"required"`
|
||||
|
||||
// ConfirmPassword 用户确认密码
|
||||
ConfirmPassword string `json:"confirmPassword" binding:"required"`
|
||||
|
||||
// Code 验证码
|
||||
Code string `json:"code"`
|
||||
|
||||
// UUID 验证码唯一标识
|
||||
UUID string `json:"uuid"`
|
||||
|
||||
// UserType 标记用户类型
|
||||
UserType string `json:"userType"`
|
||||
Username string `json:"username" binding:"required"` // Username 用户名
|
||||
Password string `json:"password" binding:"required"` // Password 用户密码
|
||||
ConfirmPassword string `json:"confirmPassword" binding:"required"` // ConfirmPassword 用户确认密码
|
||||
Code string `json:"code"` // Code 验证码
|
||||
UUID string `json:"uuid"` // UUID 验证码唯一标识
|
||||
UserType string `json:"userType"` // UserType 标记用户类型
|
||||
}
|
||||
|
||||
@@ -2,102 +2,32 @@ package service
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"be.ems/src/framework/config"
|
||||
"be.ems/src/framework/constants"
|
||||
"be.ems/src/framework/database/redis"
|
||||
"be.ems/src/framework/token"
|
||||
"be.ems/src/framework/utils/crypto"
|
||||
"be.ems/src/framework/utils/parse"
|
||||
systemModelVO "be.ems/src/modules/system/model/vo"
|
||||
"be.ems/src/modules/auth/model"
|
||||
systemModel "be.ems/src/modules/system/model"
|
||||
systemService "be.ems/src/modules/system/service"
|
||||
)
|
||||
|
||||
// 实例化服务层 Account 结构体
|
||||
var NewAccount = &Account{
|
||||
sysUserService: systemService.NewSysUser,
|
||||
sysConfigService: systemService.NewSysConfig,
|
||||
sysRoleService: systemService.NewSysRole,
|
||||
sysMenuService: systemService.NewSysMenu,
|
||||
sysUserService: systemService.NewSysUser,
|
||||
sysConfigService: systemService.NewSysConfig,
|
||||
sysRoleService: systemService.NewSysRole,
|
||||
sysMenuService: systemService.NewSysMenu,
|
||||
sysLogSourceService: systemService.NewSysLoginSource,
|
||||
}
|
||||
|
||||
// 账号身份操作服务 服务层处理
|
||||
type Account struct {
|
||||
sysUserService *systemService.SysUser // 用户信息服务
|
||||
sysConfigService *systemService.SysConfig // 参数配置服务
|
||||
sysRoleService *systemService.SysRole // 角色服务
|
||||
sysMenuService *systemService.SysMenu // 菜单服务
|
||||
}
|
||||
|
||||
// ValidateCaptcha 校验验证码
|
||||
func (s *Account) ValidateCaptcha(code, uuid string) error {
|
||||
// 验证码检查,从数据库配置获取验证码开关 true开启,false关闭
|
||||
captchaEnabledStr := s.sysConfigService.FindValueByKey("sys.account.captchaEnabled")
|
||||
if !parse.Boolean(captchaEnabledStr) {
|
||||
return nil
|
||||
}
|
||||
if code == "" || uuid == "" {
|
||||
// 验证码信息错误
|
||||
return fmt.Errorf("captcha.err")
|
||||
}
|
||||
verifyKey := constants.CACHE_CAPTCHA_CODE + ":" + uuid
|
||||
captcha, _ := redis.Get("", verifyKey)
|
||||
if captcha == "" {
|
||||
// 验证码已失效
|
||||
return fmt.Errorf("captcha.errValid")
|
||||
}
|
||||
_ = redis.Del("", verifyKey)
|
||||
if captcha != code {
|
||||
// 验证码错误
|
||||
return fmt.Errorf("captcha.err")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ByUsername 登录创建用户信息
|
||||
func (s Account) ByUsername(username, password string) (token.UserInfo, error) {
|
||||
info := token.UserInfo{}
|
||||
|
||||
// 检查密码重试次数
|
||||
retryKey, retryCount, lockTime, err := s.passwordRetryCount(username)
|
||||
if err != nil {
|
||||
return info, err
|
||||
}
|
||||
|
||||
// 查询用户登录账号
|
||||
sysUser := s.sysUserService.FindByUserName(username)
|
||||
if sysUser.UserName != username {
|
||||
return info, fmt.Errorf("login.errNameOrPasswd")
|
||||
}
|
||||
if sysUser.DelFlag == constants.STATUS_YES {
|
||||
return info, fmt.Errorf("login.errDelFlag")
|
||||
}
|
||||
if sysUser.StatusFlag == constants.STATUS_NO {
|
||||
return info, fmt.Errorf("login.errStatus")
|
||||
}
|
||||
|
||||
// 检验用户密码
|
||||
compareBool := crypto.BcryptCompare(password, sysUser.Password)
|
||||
if compareBool {
|
||||
s.CleanLoginRecordCache(sysUser.UserName) // 清除错误记录次数
|
||||
} else {
|
||||
_ = redis.Set("", retryKey, retryCount+1, lockTime)
|
||||
return info, fmt.Errorf("login.errNameOrPasswd")
|
||||
}
|
||||
|
||||
// 登录用户信息
|
||||
info.UserId = sysUser.UserId
|
||||
info.DeptId = sysUser.DeptId
|
||||
info.User = sysUser
|
||||
// 用户权限组标识
|
||||
if config.IsSystemUser(sysUser.UserId) {
|
||||
info.Permissions = []string{constants.SYS_PERMISSION_SYSTEM}
|
||||
} else {
|
||||
perms := s.sysMenuService.FindPermsByUserId(sysUser.UserId)
|
||||
info.Permissions = parse.RemoveDuplicates(perms)
|
||||
}
|
||||
return info, nil
|
||||
sysUserService *systemService.SysUser // 用户信息服务
|
||||
sysConfigService *systemService.SysConfig // 参数配置服务
|
||||
sysRoleService *systemService.SysRole // 角色服务
|
||||
sysMenuService *systemService.SysMenu // 菜单服务
|
||||
sysLogSourceService *systemService.SysLoginSource // 认证源
|
||||
}
|
||||
|
||||
// ByUserId 用户ID刷新令牌创建用户信息
|
||||
@@ -140,86 +70,43 @@ func (s Account) UpdateLoginDateAndIP(info token.UserInfo) bool {
|
||||
return s.sysUserService.Update(user) > 0
|
||||
}
|
||||
|
||||
// CleanLoginRecordCache 清除错误记录次数
|
||||
func (s Account) CleanLoginRecordCache(userName string) bool {
|
||||
cacheKey := fmt.Sprintf("%s:%s", constants.CACHE_PWD_ERR_COUNT, userName)
|
||||
hasKey, err := redis.Has("", cacheKey)
|
||||
if hasKey > 0 && err == nil {
|
||||
return redis.Del("", cacheKey) == nil
|
||||
// LoginSource 登录认证源
|
||||
func (s Account) LoginSource() []model.LoginSourceVo {
|
||||
rows := s.sysLogSourceService.FindByActive("")
|
||||
data := make([]model.LoginSourceVo, 0)
|
||||
for _, v := range rows {
|
||||
data = append(data, model.LoginSourceVo{
|
||||
UID: v.UID,
|
||||
Name: v.Name,
|
||||
Type: v.Type,
|
||||
Icon: v.Icon,
|
||||
})
|
||||
}
|
||||
return false
|
||||
return data
|
||||
}
|
||||
|
||||
// passwordRetryCount 密码重试次数
|
||||
func (s Account) passwordRetryCount(userName string) (string, int64, time.Duration, error) {
|
||||
// 从数据库配置获取登录次数和错误锁定时间
|
||||
maxRetryCountStr := s.sysConfigService.FindValueByKey("sys.user.maxRetryCount")
|
||||
lockTimeStr := s.sysConfigService.FindValueByKey("sys.user.lockTime")
|
||||
// 验证登录次数和错误锁定时间
|
||||
maxRetryCount := parse.Number(maxRetryCountStr)
|
||||
lockTime := parse.Number(lockTimeStr)
|
||||
// initLoginSourceUser 初始化登录源用户
|
||||
func (s *Account) initLoginSourceUser(uid, sType, username, password string) systemModel.SysUser {
|
||||
sysUser := systemModel.SysUser{
|
||||
UserName: username,
|
||||
NickName: username, // 昵称使用名称账号
|
||||
Password: password, // 原始密码
|
||||
UserType: sType,
|
||||
UserSource: uid,
|
||||
Sex: "0", // 性别未选择
|
||||
StatusFlag: constants.STATUS_YES, // 账号状态激活
|
||||
DeptId: 101, // 归属部门为根节点
|
||||
CreateBy: sType, // 创建来源
|
||||
}
|
||||
|
||||
// 验证缓存记录次数
|
||||
retryKey := fmt.Sprintf("%s:%s", constants.CACHE_PWD_ERR_COUNT, userName)
|
||||
retryCount, err := redis.Get("", retryKey)
|
||||
if retryCount == "" || err != nil {
|
||||
retryCount = "0"
|
||||
// 新增用户的角色管理
|
||||
sysUser.RoleIds = []int64{5}
|
||||
// 新增用户的岗位管理
|
||||
sysUser.PostIds = []int64{}
|
||||
|
||||
insertId := s.sysUserService.Insert(sysUser)
|
||||
if insertId > 0 {
|
||||
sysUser.UserId = insertId
|
||||
}
|
||||
// 是否超过错误值
|
||||
retryCountInt64 := parse.Number(retryCount)
|
||||
if retryCountInt64 >= int64(maxRetryCount) {
|
||||
// msg := fmt.Sprintf("密码输入错误 %d 次,帐户锁定 %d 分钟", maxRetryCount, lockTime)
|
||||
msg := fmt.Errorf("login.errRetryPasswd") // 密码输入错误多次,帐户已被锁定
|
||||
return retryKey, retryCountInt64, time.Duration(lockTime) * time.Minute, fmt.Errorf("%s", msg)
|
||||
}
|
||||
return retryKey, retryCountInt64, time.Duration(lockTime) * time.Minute, nil
|
||||
}
|
||||
|
||||
// PasswordCountOrExpireTime 首次登录或密码过期时间
|
||||
func (s Account) PasswordCountOrExpireTime(loginCount, passwordUpdateTime int64) (bool, error) {
|
||||
forcePasswdChange := false
|
||||
// 从数据库配置获取-首次登录密码修改
|
||||
fristPasswdChangeStr := s.sysConfigService.FindValueByKey("sys.user.fristPasswdChange")
|
||||
if parse.Boolean(fristPasswdChangeStr) {
|
||||
forcePasswdChange = loginCount < 1 || passwordUpdateTime == 0
|
||||
}
|
||||
|
||||
// 非首次登录,判断密码是否过期
|
||||
if !forcePasswdChange {
|
||||
alert, err := s.sysUserService.ValidatePasswordExpireTime(passwordUpdateTime)
|
||||
if err != nil {
|
||||
return alert, err
|
||||
}
|
||||
forcePasswdChange = alert
|
||||
}
|
||||
return forcePasswdChange, nil
|
||||
}
|
||||
|
||||
// RoleAndMenuPerms 角色和菜单数据权限
|
||||
func (s Account) RoleAndMenuPerms(userId int64, isSystemUser bool) ([]string, []string) {
|
||||
if isSystemUser {
|
||||
return []string{constants.SYS_ROLE_SYSTEM_KEY}, []string{constants.SYS_PERMISSION_SYSTEM}
|
||||
}
|
||||
// 角色key
|
||||
var roleGroup []string
|
||||
roles := s.sysRoleService.FindByUserId(userId)
|
||||
for _, role := range roles {
|
||||
roleGroup = append(roleGroup, role.RoleKey)
|
||||
}
|
||||
// 菜单权限key
|
||||
perms := s.sysMenuService.FindPermsByUserId(userId)
|
||||
return parse.RemoveDuplicates(roleGroup), parse.RemoveDuplicates(perms)
|
||||
}
|
||||
|
||||
// RouteMenus 前端路由所需要的菜单
|
||||
func (s Account) RouteMenus(userId int64, isSystemUser bool) []systemModelVO.Router {
|
||||
var buildMenus []systemModelVO.Router
|
||||
if isSystemUser {
|
||||
menus := s.sysMenuService.BuildTreeMenusByUserId(0)
|
||||
buildMenus = s.sysMenuService.BuildRouteMenus(menus, "")
|
||||
} else {
|
||||
menus := s.sysMenuService.BuildTreeMenusByUserId(userId)
|
||||
buildMenus = s.sysMenuService.BuildRouteMenus(menus, "")
|
||||
}
|
||||
return buildMenus
|
||||
return s.sysUserService.FindByUserName(username, sType, uid)
|
||||
}
|
||||
|
||||
36
src/modules/auth/service/account_info.go
Normal file
36
src/modules/auth/service/account_info.go
Normal file
@@ -0,0 +1,36 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"be.ems/src/framework/constants"
|
||||
"be.ems/src/framework/utils/parse"
|
||||
systemModelVO "be.ems/src/modules/system/model/vo"
|
||||
)
|
||||
|
||||
// RoleAndMenuPerms 角色和菜单数据权限
|
||||
func (s Account) RoleAndMenuPerms(userId int64, isSystemUser bool) ([]string, []string) {
|
||||
if isSystemUser {
|
||||
return []string{constants.SYS_ROLE_SYSTEM_KEY}, []string{constants.SYS_PERMISSION_SYSTEM}
|
||||
}
|
||||
// 角色key
|
||||
var roleGroup []string
|
||||
roles := s.sysRoleService.FindByUserId(userId)
|
||||
for _, role := range roles {
|
||||
roleGroup = append(roleGroup, role.RoleKey)
|
||||
}
|
||||
// 菜单权限key
|
||||
perms := s.sysMenuService.FindPermsByUserId(userId)
|
||||
return parse.RemoveDuplicates(roleGroup), parse.RemoveDuplicates(perms)
|
||||
}
|
||||
|
||||
// RouteMenus 前端路由所需要的菜单
|
||||
func (s Account) RouteMenus(userId int64, isSystemUser bool) []systemModelVO.Router {
|
||||
var buildMenus []systemModelVO.Router
|
||||
if isSystemUser {
|
||||
menus := s.sysMenuService.BuildTreeMenusByUserId(0)
|
||||
buildMenus = s.sysMenuService.BuildRouteMenus(menus, "")
|
||||
} else {
|
||||
menus := s.sysMenuService.BuildTreeMenusByUserId(userId)
|
||||
buildMenus = s.sysMenuService.BuildRouteMenus(menus, "")
|
||||
}
|
||||
return buildMenus
|
||||
}
|
||||
108
src/modules/auth/service/account_ldap.go
Normal file
108
src/modules/auth/service/account_ldap.go
Normal file
@@ -0,0 +1,108 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
|
||||
"github.com/go-ldap/ldap/v3"
|
||||
|
||||
"be.ems/src/framework/config"
|
||||
"be.ems/src/framework/constants"
|
||||
"be.ems/src/framework/token"
|
||||
"be.ems/src/framework/utils/parse"
|
||||
"be.ems/src/modules/auth/model"
|
||||
systemModelVo "be.ems/src/modules/system/model/vo"
|
||||
)
|
||||
|
||||
// ByLDAP 登录创建用户信息
|
||||
func (s *Account) ByLDAP(body model.LoginSourceBody) (token.UserInfo, error) {
|
||||
info := token.UserInfo{}
|
||||
rows := s.sysLogSourceService.FindByActive(body.UID)
|
||||
if len(rows) != 1 {
|
||||
return info, fmt.Errorf("ldap auth source not exist")
|
||||
}
|
||||
item := rows[0]
|
||||
if item.Config == "" {
|
||||
return info, fmt.Errorf("ldap auth source config is empty")
|
||||
}
|
||||
var source systemModelVo.SysLoginSourceLDAP
|
||||
if err := json.Unmarshal([]byte(item.Config), &source); err != nil {
|
||||
return info, err
|
||||
}
|
||||
|
||||
// 校验LDAP用户
|
||||
err := ldapAuth(source, body.Username, body.Password)
|
||||
if err != nil {
|
||||
return info, err
|
||||
}
|
||||
|
||||
// 查询用户登录账号
|
||||
sysUser := s.sysUserService.FindByUserName(body.Username, item.Type, item.UID)
|
||||
if sysUser.UserId == 0 || sysUser.UserName == "" {
|
||||
sysUser = s.initLoginSourceUser(item.UID, item.Type, body.Username, body.Password)
|
||||
}
|
||||
if sysUser.UserId == 0 || sysUser.UserName != body.Username {
|
||||
return info, fmt.Errorf("login.errNameOrPasswd")
|
||||
}
|
||||
if sysUser.DelFlag == constants.STATUS_YES {
|
||||
return info, fmt.Errorf("login.errDelFlag")
|
||||
}
|
||||
if sysUser.StatusFlag == constants.STATUS_NO {
|
||||
return info, fmt.Errorf("login.errStatus")
|
||||
}
|
||||
|
||||
// 登录用户信息
|
||||
info.UserId = sysUser.UserId
|
||||
info.DeptId = sysUser.DeptId
|
||||
info.User = sysUser
|
||||
// 用户权限组标识
|
||||
if config.IsSystemUser(sysUser.UserId) {
|
||||
info.Permissions = []string{constants.SYS_PERMISSION_SYSTEM}
|
||||
} else {
|
||||
perms := s.sysMenuService.FindPermsByUserId(sysUser.UserId)
|
||||
info.Permissions = parse.RemoveDuplicates(perms)
|
||||
}
|
||||
return info, nil
|
||||
}
|
||||
|
||||
// ldapAuth 校验LDAP用户
|
||||
func ldapAuth(source systemModelVo.SysLoginSourceLDAP, username, password string) error {
|
||||
// 连接LDAP
|
||||
l, err := ldap.DialURL(source.URL)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer l.Close()
|
||||
|
||||
// 绑定DN校验
|
||||
if source.BindDN != "" && source.BindPassword != "" {
|
||||
if err := l.Bind(source.BindDN, source.BindPassword); err != nil {
|
||||
return fmt.Errorf("ldap user bind %s", err)
|
||||
}
|
||||
}
|
||||
|
||||
// 搜索用户
|
||||
searchRequest := ldap.NewSearchRequest(
|
||||
source.BaseDN,
|
||||
ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false,
|
||||
fmt.Sprintf(source.UserFilter, ldap.EscapeFilter(username)),
|
||||
[]string{"dn", "uid"},
|
||||
nil,
|
||||
)
|
||||
sr, err := l.Search(searchRequest)
|
||||
if err != nil {
|
||||
return fmt.Errorf("ldap user search %s", err)
|
||||
}
|
||||
// for _, entry := range sr.Entries {
|
||||
// fmt.Printf("%s ==== %v\n", entry.DN, entry.GetAttributeValue("uid"))
|
||||
// }
|
||||
if len(sr.Entries) != 1 {
|
||||
return fmt.Errorf("ldap user does not exist or too many entries returned")
|
||||
}
|
||||
|
||||
// 校验密码
|
||||
if err = l.Bind(sr.Entries[0].DN, password); err != nil {
|
||||
return fmt.Errorf("ldap user bind %s", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
168
src/modules/auth/service/account_oauth2.go
Normal file
168
src/modules/auth/service/account_oauth2.go
Normal file
@@ -0,0 +1,168 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"reflect"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"golang.org/x/oauth2"
|
||||
|
||||
"be.ems/src/framework/config"
|
||||
"be.ems/src/framework/constants"
|
||||
"be.ems/src/framework/token"
|
||||
"be.ems/src/framework/utils/parse"
|
||||
"be.ems/src/modules/auth/model"
|
||||
systemModelVo "be.ems/src/modules/system/model/vo"
|
||||
)
|
||||
|
||||
// ByOAuth2CodeURL 获取OAuth2登录URL
|
||||
func (s *Account) ByOAuth2CodeURL(state string) (string, error) {
|
||||
rows := s.sysLogSourceService.FindByActive(state)
|
||||
if len(rows) != 1 {
|
||||
return "", fmt.Errorf("oauth2 auth source not exist")
|
||||
}
|
||||
item := rows[0]
|
||||
if item.Config == "" {
|
||||
return "", fmt.Errorf("oauth2 auth source config is empty")
|
||||
}
|
||||
var source systemModelVo.SysLoginSourceOAuth2
|
||||
json.Unmarshal([]byte(item.Config), &source)
|
||||
|
||||
conf := oauth2.Config{
|
||||
ClientID: source.ClientID,
|
||||
ClientSecret: source.ClientSecret,
|
||||
RedirectURL: source.RedirectURL,
|
||||
Scopes: source.Scopes,
|
||||
Endpoint: oauth2.Endpoint{
|
||||
AuthURL: source.AuthURL,
|
||||
TokenURL: source.TokenURL,
|
||||
},
|
||||
}
|
||||
return conf.AuthCodeURL(state, oauth2.AccessTypeOffline), nil
|
||||
}
|
||||
|
||||
// ByOAuth2 登录创建用户信息
|
||||
func (s *Account) ByOAuth2(body model.LoginSourceOauth2Body) (token.UserInfo, error) {
|
||||
info := token.UserInfo{}
|
||||
rows := s.sysLogSourceService.FindByActive(body.State)
|
||||
if len(rows) != 1 {
|
||||
return info, fmt.Errorf("oauth2 auth source not exist")
|
||||
}
|
||||
item := rows[0]
|
||||
if item.Config == "" {
|
||||
return info, fmt.Errorf("oauth2 auth source config is empty")
|
||||
}
|
||||
var source systemModelVo.SysLoginSourceOAuth2
|
||||
if err := json.Unmarshal([]byte(item.Config), &source); err != nil {
|
||||
return info, err
|
||||
}
|
||||
|
||||
// 校验OAuth2用户
|
||||
account, err := oauth2Auth(source, body.Code)
|
||||
if err != nil {
|
||||
return info, err
|
||||
}
|
||||
|
||||
// 查询用户登录账号
|
||||
sysUser := s.sysUserService.FindByUserName(account, item.Type, item.UID)
|
||||
if sysUser.UserId == 0 || sysUser.UserName == "" {
|
||||
sysUser = s.initLoginSourceUser(item.UID, item.Type, account, account)
|
||||
}
|
||||
if sysUser.UserId == 0 || sysUser.UserName != account {
|
||||
return info, fmt.Errorf("login.errNameOrPasswd")
|
||||
}
|
||||
if sysUser.DelFlag == constants.STATUS_YES {
|
||||
return info, fmt.Errorf("login.errDelFlag")
|
||||
}
|
||||
if sysUser.StatusFlag == constants.STATUS_NO {
|
||||
return info, fmt.Errorf("login.errStatus")
|
||||
}
|
||||
|
||||
// 登录用户信息
|
||||
info.UserId = sysUser.UserId
|
||||
info.DeptId = sysUser.DeptId
|
||||
info.User = sysUser
|
||||
// 用户权限组标识
|
||||
if config.IsSystemUser(sysUser.UserId) {
|
||||
info.Permissions = []string{constants.SYS_PERMISSION_SYSTEM}
|
||||
} else {
|
||||
perms := s.sysMenuService.FindPermsByUserId(sysUser.UserId)
|
||||
info.Permissions = parse.RemoveDuplicates(perms)
|
||||
}
|
||||
return info, nil
|
||||
}
|
||||
|
||||
// oauth2Auth 校验OAuth2用户
|
||||
func oauth2Auth(source systemModelVo.SysLoginSourceOAuth2, code string) (string, error) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
conf := oauth2.Config{
|
||||
ClientID: source.ClientID,
|
||||
ClientSecret: source.ClientSecret,
|
||||
RedirectURL: source.RedirectURL,
|
||||
Scopes: source.Scopes,
|
||||
Endpoint: oauth2.Endpoint{
|
||||
AuthURL: source.AuthURL,
|
||||
TokenURL: source.TokenURL,
|
||||
},
|
||||
}
|
||||
token, err := conf.Exchange(ctx, code)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
// 使用token创建HTTP客户端 请求用户信息
|
||||
resp, err := conf.Client(ctx, token).Get(source.UserURL)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
// 解析用户信息
|
||||
var userInfo map[string]any
|
||||
if err := json.NewDecoder(resp.Body).Decode(&userInfo); err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
// 读取嵌套数据
|
||||
value, found := getValueByPath(userInfo, source.AccountField)
|
||||
if !found {
|
||||
return "", fmt.Errorf("oauth2 auth source account field not exist")
|
||||
}
|
||||
return fmt.Sprintf("%v", value), nil
|
||||
}
|
||||
|
||||
// getValueByPath 从嵌套的 map[string]any 获取嵌套键对应的值
|
||||
func getValueByPath(data map[string]any, path string) (any, bool) {
|
||||
keys := strings.Split(path, ".") // 按照 "." 拆分路径
|
||||
return getValue(data, keys)
|
||||
}
|
||||
|
||||
// getValue 是递归查找嵌套 map 的函数
|
||||
func getValue(data map[string]any, keys []string) (any, bool) {
|
||||
if len(keys) == 0 {
|
||||
return data, false
|
||||
}
|
||||
|
||||
// 获取当前键
|
||||
key := keys[0]
|
||||
|
||||
// 获取当前键的值
|
||||
val, ok := data[key]
|
||||
if !ok {
|
||||
return nil, false // 找不到键,返回 false
|
||||
}
|
||||
|
||||
// 如果还有嵌套键,继续查找
|
||||
if len(keys) > 1 {
|
||||
// 递归查找嵌套 map
|
||||
if reflect.TypeOf(val).Kind() == reflect.Map {
|
||||
// 将 `any` 转换为 `map[string]any` 类型
|
||||
if nestedMap, ok := val.(map[string]any); ok {
|
||||
return getValue(nestedMap, keys[1:])
|
||||
}
|
||||
}
|
||||
}
|
||||
return val, true
|
||||
}
|
||||
88
src/modules/auth/service/account_smtp.go
Normal file
88
src/modules/auth/service/account_smtp.go
Normal file
@@ -0,0 +1,88 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
|
||||
"github.com/wneessen/go-mail"
|
||||
|
||||
"be.ems/src/framework/config"
|
||||
"be.ems/src/framework/constants"
|
||||
"be.ems/src/framework/token"
|
||||
"be.ems/src/framework/utils/parse"
|
||||
"be.ems/src/modules/auth/model"
|
||||
systemModelVo "be.ems/src/modules/system/model/vo"
|
||||
)
|
||||
|
||||
// BySMTP 登录创建用户信息
|
||||
func (s *Account) BySMTP(body model.LoginSourceBody) (token.UserInfo, error) {
|
||||
info := token.UserInfo{}
|
||||
rows := s.sysLogSourceService.FindByActive(body.UID)
|
||||
if len(rows) != 1 {
|
||||
return info, fmt.Errorf("smtp auth source not exist")
|
||||
}
|
||||
item := rows[0]
|
||||
if item.Config == "" {
|
||||
return info, fmt.Errorf("smtp auth source config is empty")
|
||||
}
|
||||
var source systemModelVo.SysLoginSourceSMTP
|
||||
if err := json.Unmarshal([]byte(item.Config), &source); err != nil {
|
||||
return info, err
|
||||
}
|
||||
|
||||
// 校验SMTP用户
|
||||
err := smtpAuth(source, body.Username, body.Password)
|
||||
if err != nil {
|
||||
return info, err
|
||||
}
|
||||
|
||||
// 查询用户登录账号
|
||||
sysUser := s.sysUserService.FindByUserName(body.Username, item.Type, item.UID)
|
||||
if sysUser.UserId == 0 || sysUser.UserName == "" {
|
||||
sysUser = s.initLoginSourceUser(item.UID, item.Type, body.Username, body.Password)
|
||||
}
|
||||
if sysUser.UserId == 0 || sysUser.UserName != body.Username {
|
||||
return info, fmt.Errorf("login.errNameOrPasswd")
|
||||
}
|
||||
if sysUser.DelFlag == constants.STATUS_YES {
|
||||
return info, fmt.Errorf("login.errDelFlag")
|
||||
}
|
||||
if sysUser.StatusFlag == constants.STATUS_NO {
|
||||
return info, fmt.Errorf("login.errStatus")
|
||||
}
|
||||
|
||||
// 登录用户信息
|
||||
info.UserId = sysUser.UserId
|
||||
info.DeptId = sysUser.DeptId
|
||||
info.User = sysUser
|
||||
// 用户权限组标识
|
||||
if config.IsSystemUser(sysUser.UserId) {
|
||||
info.Permissions = []string{constants.SYS_PERMISSION_SYSTEM}
|
||||
} else {
|
||||
perms := s.sysMenuService.FindPermsByUserId(sysUser.UserId)
|
||||
info.Permissions = parse.RemoveDuplicates(perms)
|
||||
}
|
||||
return info, nil
|
||||
}
|
||||
|
||||
// smtpAuth 校验SMTP用户
|
||||
func smtpAuth(source systemModelVo.SysLoginSourceSMTP, username, password string) error {
|
||||
client, err := mail.NewClient(source.Host,
|
||||
mail.WithSMTPAuth(mail.SMTPAuthAutoDiscover),
|
||||
mail.WithUsername(username),
|
||||
mail.WithPort(source.Port),
|
||||
mail.WithPassword(password),
|
||||
mail.WithTLSConfig(&tls.Config{InsecureSkipVerify: true}),
|
||||
)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to create mail client %s", err)
|
||||
}
|
||||
// 连接到邮件SMTP服务器
|
||||
if err = client.DialWithContext(context.Background()); err != nil {
|
||||
return err
|
||||
}
|
||||
defer client.Close()
|
||||
return nil
|
||||
}
|
||||
138
src/modules/auth/service/account_sysstem.go
Normal file
138
src/modules/auth/service/account_sysstem.go
Normal file
@@ -0,0 +1,138 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"be.ems/src/framework/config"
|
||||
"be.ems/src/framework/constants"
|
||||
"be.ems/src/framework/database/redis"
|
||||
"be.ems/src/framework/token"
|
||||
"be.ems/src/framework/utils/crypto"
|
||||
"be.ems/src/framework/utils/parse"
|
||||
)
|
||||
|
||||
// ValidateCaptcha 校验验证码
|
||||
func (s Account) ValidateCaptcha(code, uuid string) error {
|
||||
// 验证码检查,从数据库配置获取验证码开关 true开启,false关闭
|
||||
captchaEnabledStr := s.sysConfigService.FindValueByKey("sys.account.captchaEnabled")
|
||||
if !parse.Boolean(captchaEnabledStr) {
|
||||
return nil
|
||||
}
|
||||
if code == "" || uuid == "" {
|
||||
// 验证码信息错误
|
||||
return fmt.Errorf("captcha.err")
|
||||
}
|
||||
verifyKey := constants.CACHE_CAPTCHA_CODE + ":" + uuid
|
||||
captcha, _ := redis.Get("", verifyKey)
|
||||
if captcha == "" {
|
||||
// 验证码已失效
|
||||
return fmt.Errorf("captcha.errValid")
|
||||
}
|
||||
_ = redis.Del("", verifyKey)
|
||||
if captcha != code {
|
||||
// 验证码错误
|
||||
return fmt.Errorf("captcha.err")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ByUsername 登录创建用户信息
|
||||
func (s Account) ByUsername(username, password string) (token.UserInfo, error) {
|
||||
info := token.UserInfo{}
|
||||
|
||||
// 检查密码重试次数
|
||||
retryKey, retryCount, lockTime, err := s.passwordRetryCount(username)
|
||||
if err != nil {
|
||||
return info, err
|
||||
}
|
||||
|
||||
// 查询用户登录账号
|
||||
sysUser := s.sysUserService.FindByUserName(username, "System", "#")
|
||||
if sysUser.UserName != username {
|
||||
return info, fmt.Errorf("login.errNameOrPasswd")
|
||||
}
|
||||
if sysUser.DelFlag == constants.STATUS_YES {
|
||||
return info, fmt.Errorf("login.errDelFlag")
|
||||
}
|
||||
if sysUser.StatusFlag == constants.STATUS_NO {
|
||||
return info, fmt.Errorf("login.errStatus")
|
||||
}
|
||||
|
||||
// 检验用户密码
|
||||
compareBool := crypto.BcryptCompare(password, sysUser.Password)
|
||||
if compareBool {
|
||||
s.CleanLoginRecordCache(sysUser.UserName) // 清除错误记录次数
|
||||
} else {
|
||||
_ = redis.Set("", retryKey, retryCount+1, lockTime)
|
||||
return info, fmt.Errorf("login.errNameOrPasswd")
|
||||
}
|
||||
|
||||
// 登录用户信息
|
||||
info.UserId = sysUser.UserId
|
||||
info.DeptId = sysUser.DeptId
|
||||
info.User = sysUser
|
||||
// 用户权限组标识
|
||||
if config.IsSystemUser(sysUser.UserId) {
|
||||
info.Permissions = []string{constants.SYS_PERMISSION_SYSTEM}
|
||||
} else {
|
||||
perms := s.sysMenuService.FindPermsByUserId(sysUser.UserId)
|
||||
info.Permissions = parse.RemoveDuplicates(perms)
|
||||
}
|
||||
return info, nil
|
||||
}
|
||||
|
||||
// CleanLoginRecordCache 清除错误记录次数
|
||||
func (s Account) CleanLoginRecordCache(userName string) bool {
|
||||
cacheKey := fmt.Sprintf("%s:%s", constants.CACHE_PWD_ERR_COUNT, userName)
|
||||
hasKey, err := redis.Has("", cacheKey)
|
||||
if hasKey > 0 && err == nil {
|
||||
return redis.Del("", cacheKey) == nil
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// passwordRetryCount 密码重试次数
|
||||
func (s Account) passwordRetryCount(userName string) (string, int64, time.Duration, error) {
|
||||
// 从数据库配置获取登录次数和错误锁定时间
|
||||
maxRetryCountStr := s.sysConfigService.FindValueByKey("sys.user.maxRetryCount")
|
||||
lockTimeStr := s.sysConfigService.FindValueByKey("sys.user.lockTime")
|
||||
// 验证登录次数和错误锁定时间
|
||||
maxRetryCount := parse.Number(maxRetryCountStr)
|
||||
lockTime := parse.Number(lockTimeStr)
|
||||
|
||||
// 验证缓存记录次数
|
||||
retryKey := fmt.Sprintf("%s:%s", constants.CACHE_PWD_ERR_COUNT, userName)
|
||||
retryCount, err := redis.Get("", retryKey)
|
||||
if retryCount == "" || err != nil {
|
||||
retryCount = "0"
|
||||
}
|
||||
// 是否超过错误值
|
||||
retryCountInt64 := parse.Number(retryCount)
|
||||
if retryCountInt64 >= int64(maxRetryCount) {
|
||||
// msg := fmt.Sprintf("密码输入错误 %d 次,帐户锁定 %d 分钟", maxRetryCount, lockTime)
|
||||
msg := fmt.Errorf("login.errRetryPasswd") // 密码输入错误多次,帐户已被锁定
|
||||
return retryKey, retryCountInt64, time.Duration(lockTime) * time.Minute, fmt.Errorf("%s", msg)
|
||||
}
|
||||
return retryKey, retryCountInt64, time.Duration(lockTime) * time.Minute, nil
|
||||
}
|
||||
|
||||
// PasswordCountOrExpireTime 首次登录或密码过期时间
|
||||
func (s Account) PasswordCountOrExpireTime(loginCount, passwordUpdateTime int64) (bool, error) {
|
||||
forcePasswdChange := false
|
||||
// 从数据库配置获取-首次登录密码修改
|
||||
fristPasswdChangeStr := s.sysConfigService.FindValueByKey("sys.user.fristPasswdChange")
|
||||
if parse.Boolean(fristPasswdChangeStr) {
|
||||
forcePasswdChange = loginCount < 1 || passwordUpdateTime == 0
|
||||
}
|
||||
|
||||
// 非首次登录,判断密码是否过期
|
||||
if !forcePasswdChange {
|
||||
alert, err := s.sysUserService.ValidatePasswordExpireTime(passwordUpdateTime)
|
||||
if err != nil {
|
||||
return alert, err
|
||||
}
|
||||
forcePasswdChange = alert
|
||||
}
|
||||
return forcePasswdChange, nil
|
||||
}
|
||||
@@ -61,12 +61,14 @@ func (s Register) ByUserName(username, password string) (int64, error) {
|
||||
|
||||
sysUser := systemModel.SysUser{
|
||||
UserName: username,
|
||||
NickName: username, // 昵称使用名称账号
|
||||
Password: password, // 原始密码
|
||||
NickName: username, // 昵称使用名称账号
|
||||
Password: password, // 原始密码
|
||||
UserType: "System",
|
||||
UserSource: "#",
|
||||
Sex: "0", // 性别未选择
|
||||
StatusFlag: constants.STATUS_YES, // 账号状态激活
|
||||
DeptId: 100, // 归属部门为根节点
|
||||
CreateBy: "register", // 创建来源
|
||||
DeptId: 101, // 归属部门为根节点
|
||||
CreateBy: "System", // 创建来源
|
||||
}
|
||||
|
||||
// 新增用户的角色管理
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
package controller
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
@@ -10,54 +10,54 @@ import (
|
||||
"be.ems/src/framework/reqctx"
|
||||
"be.ems/src/framework/resp"
|
||||
"be.ems/src/framework/utils/parse"
|
||||
"be.ems/src/modules/oauth2/model"
|
||||
"be.ems/src/modules/oauth2/service"
|
||||
"be.ems/src/modules/system/model"
|
||||
"be.ems/src/modules/system/service"
|
||||
)
|
||||
|
||||
// NewOauth2Client 实例化控制层
|
||||
var NewOauth2Client = &Oauth2ClientController{
|
||||
oauth2ClientService: service.NewOauth2ClientService,
|
||||
// NewLoginSource 实例化控制层
|
||||
var NewSysLoginSource = &SysLoginSourceController{
|
||||
sysLoginSourceService: service.NewSysLoginSource,
|
||||
}
|
||||
|
||||
// Oauth2ClientController 客户端授权管理 控制层处理
|
||||
// SysLoginSourceController 认证源管理 控制层处理
|
||||
//
|
||||
// PATH /oauth2/client
|
||||
type Oauth2ClientController struct {
|
||||
oauth2ClientService *service.Oauth2ClientService // 用户授权第三方应用信息服务
|
||||
// PATH /sys/login-source
|
||||
type SysLoginSourceController struct {
|
||||
sysLoginSourceService *service.SysLoginSource // 认证源信息服务
|
||||
}
|
||||
|
||||
// List 列表
|
||||
//
|
||||
// GET /list
|
||||
func (s Oauth2ClientController) List(c *gin.Context) {
|
||||
func (s SysLoginSourceController) List(c *gin.Context) {
|
||||
query := reqctx.QueryMap(c)
|
||||
rows, total := s.oauth2ClientService.FindByPage(query)
|
||||
rows, total := s.sysLoginSourceService.FindByPage(query)
|
||||
c.JSON(200, resp.OkData(map[string]any{"rows": rows, "total": total}))
|
||||
}
|
||||
|
||||
// Info 信息
|
||||
//
|
||||
// GET /:clientId
|
||||
func (s Oauth2ClientController) Info(c *gin.Context) {
|
||||
clientId := c.Param("clientId")
|
||||
if clientId == "" {
|
||||
c.JSON(422, resp.CodeMsg(resp.CODE_PARAM_CHEACK, "bind err: clientId is empty"))
|
||||
// GET /:id
|
||||
func (s SysLoginSourceController) Info(c *gin.Context) {
|
||||
id := c.Param("id")
|
||||
if id == "" {
|
||||
c.JSON(422, resp.CodeMsg(resp.CODE_PARAM_CHEACK, "bind err: id is empty"))
|
||||
return
|
||||
}
|
||||
|
||||
info := s.oauth2ClientService.FindByClientId(clientId)
|
||||
if info.ClientId == clientId {
|
||||
info := s.sysLoginSourceService.FindById(parse.Number(id))
|
||||
if info.Id == parse.Number(id) {
|
||||
c.JSON(200, resp.OkData(info))
|
||||
return
|
||||
}
|
||||
c.JSON(200, resp.ErrMsg("clientId does not exist"))
|
||||
c.JSON(200, resp.ErrMsg("id does not exist"))
|
||||
}
|
||||
|
||||
// Add 新增
|
||||
//
|
||||
// POST /
|
||||
func (s Oauth2ClientController) Add(c *gin.Context) {
|
||||
var body model.Oauth2Client
|
||||
func (s SysLoginSourceController) Add(c *gin.Context) {
|
||||
var body model.SysLoginSource
|
||||
if err := c.ShouldBindBodyWithJSON(&body); err != nil {
|
||||
errMsgs := fmt.Sprintf("bind err: %s", resp.FormatBindError(err))
|
||||
c.JSON(422, resp.CodeMsg(resp.CODE_PARAM_PARSER, errMsgs))
|
||||
@@ -67,23 +67,19 @@ func (s Oauth2ClientController) Add(c *gin.Context) {
|
||||
c.JSON(422, resp.CodeMsg(resp.CODE_PARAM_CHEACK, "bind err: id not is empty"))
|
||||
return
|
||||
}
|
||||
|
||||
// 本地IP地址不支持
|
||||
localHosts := []string{"127.0.0.1", "localhost", "::ffff:", "::1"}
|
||||
localHost := false
|
||||
for _, host := range localHosts {
|
||||
if strings.Contains(body.IPWhite, host) {
|
||||
localHost = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if localHost {
|
||||
c.JSON(200, resp.ErrMsg("no support local host"))
|
||||
if len(body.Config) < 7 || !json.Valid([]byte(body.Config)) {
|
||||
c.JSON(200, resp.ErrMsg("config json format error"))
|
||||
return
|
||||
}
|
||||
configStr, err := s.sysLoginSourceService.CheckConfigJSON(body.Type, body.Config)
|
||||
if err != nil {
|
||||
c.JSON(200, resp.ErrMsg(err.Error()))
|
||||
return
|
||||
}
|
||||
body.Config = configStr
|
||||
|
||||
body.CreateBy = reqctx.LoginUserToUserName(c)
|
||||
insertId := s.oauth2ClientService.Insert(body)
|
||||
insertId := s.sysLoginSourceService.Insert(body)
|
||||
if insertId > 0 {
|
||||
c.JSON(200, resp.OkData(insertId))
|
||||
return
|
||||
@@ -94,8 +90,8 @@ func (s Oauth2ClientController) Add(c *gin.Context) {
|
||||
// Edit 更新
|
||||
//
|
||||
// PUT /
|
||||
func (s Oauth2ClientController) Edit(c *gin.Context) {
|
||||
var body model.Oauth2Client
|
||||
func (s SysLoginSourceController) Edit(c *gin.Context) {
|
||||
var body model.SysLoginSource
|
||||
if err := c.ShouldBindBodyWithJSON(&body); err != nil {
|
||||
errMsgs := fmt.Sprintf("bind err: %s", resp.FormatBindError(err))
|
||||
c.JSON(422, resp.CodeMsg(resp.CODE_PARAM_PARSER, errMsgs))
|
||||
@@ -105,33 +101,32 @@ func (s Oauth2ClientController) Edit(c *gin.Context) {
|
||||
c.JSON(422, resp.CodeMsg(resp.CODE_PARAM_CHEACK, "bind err: id is empty"))
|
||||
return
|
||||
}
|
||||
|
||||
// 本地IP地址不支持
|
||||
localHosts := []string{"127.0.0.1", "localhost", "::ffff:", "::1"}
|
||||
localHost := false
|
||||
for _, host := range localHosts {
|
||||
if strings.Contains(body.IPWhite, host) {
|
||||
localHost = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if localHost {
|
||||
c.JSON(200, resp.ErrMsg("no support local host"))
|
||||
if len(body.Config) < 7 || !json.Valid([]byte(body.Config)) {
|
||||
c.JSON(200, resp.ErrMsg("config json format error"))
|
||||
return
|
||||
}
|
||||
configStr, err := s.sysLoginSourceService.CheckConfigJSON(body.Type, body.Config)
|
||||
if err != nil {
|
||||
c.JSON(200, resp.ErrMsg(err.Error()))
|
||||
return
|
||||
}
|
||||
body.Config = configStr
|
||||
|
||||
// 查询信息
|
||||
info := s.oauth2ClientService.FindById(body.Id)
|
||||
if info.ClientId == "" || info.Id != body.Id {
|
||||
info := s.sysLoginSourceService.FindById(body.Id)
|
||||
if info.Id != body.Id {
|
||||
c.JSON(200, resp.ErrMsg("modification failed, data not exist"))
|
||||
return
|
||||
}
|
||||
|
||||
info.Title = body.Title
|
||||
info.IPWhite = body.IPWhite
|
||||
info.Type = body.Type
|
||||
info.Name = body.Name
|
||||
info.Icon = body.Icon
|
||||
info.Config = body.Config
|
||||
info.ActiveFlag = body.ActiveFlag
|
||||
info.Remark = body.Remark
|
||||
info.UpdateBy = reqctx.LoginUserToUserName(c)
|
||||
rowsAffected := s.oauth2ClientService.Update(info)
|
||||
rowsAffected := s.sysLoginSourceService.Update(info)
|
||||
if rowsAffected > 0 {
|
||||
c.JSON(200, resp.Ok(nil))
|
||||
return
|
||||
@@ -142,7 +137,7 @@ func (s Oauth2ClientController) Edit(c *gin.Context) {
|
||||
// Remove 删除
|
||||
//
|
||||
// DELETE /:id
|
||||
func (s Oauth2ClientController) Remove(c *gin.Context) {
|
||||
func (s SysLoginSourceController) Remove(c *gin.Context) {
|
||||
language := reqctx.AcceptLanguage(c)
|
||||
id := c.Param("id")
|
||||
if id == "" {
|
||||
@@ -158,7 +153,7 @@ func (s Oauth2ClientController) Remove(c *gin.Context) {
|
||||
ids = append(ids, parse.Number(v))
|
||||
}
|
||||
|
||||
rows, err := s.oauth2ClientService.DeleteByIds(ids)
|
||||
rows, err := s.sysLoginSourceService.DeleteByIds(ids)
|
||||
if err != nil {
|
||||
c.JSON(200, resp.ErrMsg(err.Error()))
|
||||
return
|
||||
@@ -550,15 +550,19 @@ func (s *SysUserController) Export(c *gin.Context) {
|
||||
"C1": i18n.TKey(language, "user.export.nick"),
|
||||
"D1": i18n.TKey(language, "user.export.role"),
|
||||
"E1": i18n.TKey(language, "user.export.deptName"),
|
||||
"F1": i18n.TKey(language, "user.export.loginIP"),
|
||||
"G1": i18n.TKey(language, "user.export.loginDate"),
|
||||
"H1": i18n.TKey(language, "user.export.status"),
|
||||
"F1": i18n.TKey(language, "user.export.userType"),
|
||||
"G1": i18n.TKey(language, "user.export.loginIP"),
|
||||
"H1": i18n.TKey(language, "user.export.loginDate"),
|
||||
"I1": i18n.TKey(language, "user.export.status"),
|
||||
// "F1": i18n.TKey(language, "user.export.sex"),
|
||||
// "E1": i18n.TKey(language, "user.export.phone"),
|
||||
// "D1": i18n.TKey(language, "user.export.email"),
|
||||
// "I1": i18n.TKey(language, "user.export.deptID"),
|
||||
// "K1": i18n.TKey(language, "user.export.deptLeader"),
|
||||
}
|
||||
// 读取用户性别字典数据
|
||||
dictSysUserType := service.NewSysDictType.FindDataByType("sys_user_type")
|
||||
|
||||
// 读取用户性别字典数据
|
||||
// dictSysUserSex := s.sysDictDataService.SelectDictDataByType("sys_user_sex")
|
||||
// 从第二行开始的数据
|
||||
@@ -573,6 +577,14 @@ func (s *SysUserController) Export(c *gin.Context) {
|
||||
// break
|
||||
// }
|
||||
// }
|
||||
// 用户类型
|
||||
userType := row.UserType
|
||||
for _, v := range dictSysUserType {
|
||||
if row.UserType == v.DataValue && row.UserSource != "#" {
|
||||
userType = i18n.TKey(language, v.DataLabel) + " " + row.UserSource
|
||||
break
|
||||
}
|
||||
}
|
||||
// 帐号状态
|
||||
statusValue := i18n.TKey(language, "dictData.disable")
|
||||
if row.StatusFlag == "1" {
|
||||
@@ -581,7 +593,11 @@ func (s *SysUserController) Export(c *gin.Context) {
|
||||
// 用户角色, 默认导出首个
|
||||
userRole := ""
|
||||
if len(row.Roles) > 0 {
|
||||
userRole = i18n.TKey(language, row.Roles[0].RoleName)
|
||||
arr := make([]string, 0)
|
||||
for _, v := range row.Roles {
|
||||
arr = append(arr, i18n.TKey(language, v.RoleName))
|
||||
}
|
||||
userRole = strings.Join(arr, ",")
|
||||
}
|
||||
dataCells = append(dataCells, map[string]any{
|
||||
"A" + idx: row.UserId,
|
||||
@@ -589,9 +605,10 @@ func (s *SysUserController) Export(c *gin.Context) {
|
||||
"C" + idx: row.NickName,
|
||||
"D" + idx: userRole,
|
||||
"E" + idx: row.Dept.DeptName,
|
||||
"F" + idx: row.LoginIp,
|
||||
"G" + idx: date.ParseDateToStr(row.LoginTime, date.YYYY_MM_DDTHH_MM_SSZ),
|
||||
"H" + idx: statusValue,
|
||||
"F" + idx: userType,
|
||||
"G" + idx: row.LoginIp,
|
||||
"H" + idx: date.ParseDateToStr(row.LoginTime, date.YYYY_MM_DDTHH_MM_SSZ),
|
||||
"I" + idx: statusValue,
|
||||
// "E" + idx: row.PhoneNumber,
|
||||
// "F" + idx: sysUserSex,
|
||||
// "D" + idx: row.Email,
|
||||
@@ -725,7 +742,7 @@ func (s *SysUserController) Import(c *gin.Context) {
|
||||
}
|
||||
|
||||
// 验证是否存在这个用户
|
||||
newSysUser := s.sysUserService.FindByUserName(row["B"])
|
||||
newSysUser := s.sysUserService.FindByUserName(row["B"], "System", "#")
|
||||
newSysUser.Password = initPassword
|
||||
newSysUser.UserName = row["B"]
|
||||
newSysUser.NickName = row["C"]
|
||||
|
||||
22
src/modules/system/model/sys_login_source.go
Normal file
22
src/modules/system/model/sys_login_source.go
Normal file
@@ -0,0 +1,22 @@
|
||||
package model
|
||||
|
||||
// SysLoginSource 系统第三方认证源 sys_login_source
|
||||
type SysLoginSource struct {
|
||||
Id int64 `gorm:"column:id;primaryKey;autoIncrement" json:"id"` // ID
|
||||
UID string `gorm:"column:uid" json:"uid"` // UID 16位长度字符串
|
||||
Type string `gorm:"column:type" json:"type" binding:"required,oneof=LDAP SMTP OAuth2"` // 认证类型 LDAP SMTP OAuth2
|
||||
Name string `gorm:"column:name" json:"name" binding:"required"` // 认证名称
|
||||
Icon string `gorm:"column:icon" json:"icon"` // 图标
|
||||
ActiveFlag string `gorm:"column:active_flag" json:"activeFlag"` // 激活标记(0未激活 1激活)
|
||||
SyncFlag string `gorm:"column:sync_flag" json:"syncFlag"` // 同步标记(0未同步 1同步)
|
||||
Config string `gorm:"column:config" json:"config" binding:"required"` // 配置JSON字符串
|
||||
CreateBy string `gorm:"column:create_by" json:"createBy"` // 创建者
|
||||
CreateTime int64 `gorm:"column:create_time" json:"createTime"` // 创建时间
|
||||
UpdateBy string `gorm:"column:update_by" json:"updateBy"` // 更新者
|
||||
UpdateTime int64 `gorm:"column:update_time" json:"updateTime"` // 更新时间
|
||||
Remark string `gorm:"column:remark" json:"remark"` // 备注
|
||||
}
|
||||
|
||||
func (*SysLoginSource) TableName() string {
|
||||
return "sys_login_source"
|
||||
}
|
||||
@@ -11,6 +11,8 @@ type SysUser struct {
|
||||
Sex string `json:"sex" gorm:"column:sex"` // 用户性别(0未选择 1男 2女)
|
||||
Avatar string `json:"avatar" gorm:"column:avatar"` // 头像地址
|
||||
Password string `json:"-" gorm:"column:password"` // 密码
|
||||
UserType string `json:"userType" gorm:"column:user_type"` // 用户类型(System系统用户)
|
||||
UserSource string `json:"userSource" gorm:"column:user_source"` // 用户来源UID (系统#))
|
||||
StatusFlag string `json:"statusFlag" gorm:"column:status_flag"` // 账号状态(0停用 1正常)
|
||||
DelFlag string `json:"-" gorm:"column:del_flag"` // 删除标记(0存在 1删除)
|
||||
PasswordUpdateTime int64 `json:"passwordUpdateTime" gorm:"column:password_update_time"` // 密码更新时间
|
||||
|
||||
28
src/modules/system/model/vo/login_source.go
Normal file
28
src/modules/system/model/vo/login_source.go
Normal file
@@ -0,0 +1,28 @@
|
||||
package vo
|
||||
|
||||
// SysLoginSourceLDAP LDAP认证源
|
||||
type SysLoginSourceLDAP struct {
|
||||
URL string `json:"url"` // LDAP 服务器(ldap://192.168.9.58:11389)
|
||||
BaseDN string `json:"baseDN"` // base DN(dc=example,dc=org)
|
||||
UserFilter string `json:"userFilter"` // 用户过滤规则((&(objectClass=organizationalPerson)(uid=%s)))
|
||||
BindDN string `json:"bindDN"` // 绑定 DN(cn=admin,dc=example,dc=org)
|
||||
BindPassword string `json:"bindPassword"` // 绑定密码(adminpassword)
|
||||
}
|
||||
|
||||
// SysLoginSourceSMTP SMTP认证源
|
||||
type SysLoginSourceSMTP struct {
|
||||
Host string `json:"host"` // SMTP 服务器(smtp.gmail.com)
|
||||
Port int `json:"port"` // SMTP 端口(587)
|
||||
}
|
||||
|
||||
// SysLoginSourceOAuth2 OAuth2认证源
|
||||
type SysLoginSourceOAuth2 struct {
|
||||
ClientID string `json:"clientID"` // 客户端ID
|
||||
ClientSecret string `json:"clientSecret"` // 客户端密钥
|
||||
AuthURL string `json:"authURL"` // 认证URL
|
||||
TokenURL string `json:"tokenURL"` // 令牌URL
|
||||
Scopes []string `json:"scopes"` // 授权范围
|
||||
RedirectURL string `json:"redirectURL"` // 重定向URL
|
||||
UserURL string `json:"userURL"` // 用户信息URL
|
||||
AccountField string `json:"accountField"` // 账号字段从用户信息中获取
|
||||
}
|
||||
150
src/modules/system/repository/sys_login_source.go
Normal file
150
src/modules/system/repository/sys_login_source.go
Normal file
@@ -0,0 +1,150 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"be.ems/src/framework/database/db"
|
||||
"be.ems/src/framework/logger"
|
||||
"be.ems/src/modules/system/model"
|
||||
)
|
||||
|
||||
// NewSysLoginSource 实例化数据层
|
||||
var NewSysLoginSource = &SysLoginSource{}
|
||||
|
||||
// SysLoginSource 认证源数据层处理
|
||||
type SysLoginSource struct{}
|
||||
|
||||
// SelectByPage 分页查询集合
|
||||
func (r SysLoginSource) SelectByPage(query map[string]string) ([]model.SysLoginSource, int64) {
|
||||
tx := db.DB("").Model(&model.SysLoginSource{})
|
||||
// 查询条件拼接
|
||||
if v, ok := query["name"]; ok && v != "" {
|
||||
tx = tx.Where("name like ?", v+"%")
|
||||
}
|
||||
if v, ok := query["type"]; ok && v != "" {
|
||||
tx = tx.Where("type = ?", v)
|
||||
}
|
||||
if v, ok := query["beginTime"]; ok && v != "" {
|
||||
if len(v) == 10 {
|
||||
v = fmt.Sprintf("%s000", v)
|
||||
}
|
||||
tx = tx.Where("create_time >= ?", v)
|
||||
}
|
||||
if v, ok := query["endTime"]; ok && v != "" {
|
||||
if len(v) == 10 {
|
||||
v = fmt.Sprintf("%s999", v)
|
||||
}
|
||||
tx = tx.Where("create_time <= ?", v)
|
||||
}
|
||||
|
||||
// 查询结果
|
||||
var total int64 = 0
|
||||
rows := []model.SysLoginSource{}
|
||||
|
||||
// 查询数量为0直接返回
|
||||
if err := tx.Count(&total).Error; err != nil || total <= 0 {
|
||||
return rows, total
|
||||
}
|
||||
|
||||
// 查询数据分页
|
||||
pageNum, pageSize := db.PageNumSize(query["pageNum"], query["pageSize"])
|
||||
tx = tx.Limit(pageSize).Offset(pageSize * pageNum)
|
||||
err := tx.Find(&rows).Error
|
||||
if err != nil {
|
||||
return rows, total
|
||||
}
|
||||
return rows, total
|
||||
}
|
||||
|
||||
// Select 查询集合
|
||||
func (r SysLoginSource) Select(param model.SysLoginSource) []model.SysLoginSource {
|
||||
tx := db.DB("").Model(&model.SysLoginSource{})
|
||||
// 查询条件拼接
|
||||
if param.UID != "" {
|
||||
tx = tx.Where("uid = ?", param.UID)
|
||||
}
|
||||
if param.Type != "" {
|
||||
tx = tx.Where("type = ?", param.Type)
|
||||
}
|
||||
if param.Name != "" {
|
||||
tx = tx.Where("name = ?", param.Name)
|
||||
}
|
||||
if param.ActiveFlag != "" {
|
||||
tx = tx.Where("active_flag = ?", param.ActiveFlag)
|
||||
}
|
||||
|
||||
// 查询数据
|
||||
rows := []model.SysLoginSource{}
|
||||
if err := tx.Find(&rows).Error; err != nil {
|
||||
return rows
|
||||
}
|
||||
return rows
|
||||
}
|
||||
|
||||
// SelectByIds 通过ID查询信息
|
||||
func (r SysLoginSource) SelectByIds(ids []int64) []model.SysLoginSource {
|
||||
rows := []model.SysLoginSource{}
|
||||
if len(ids) <= 0 {
|
||||
return rows
|
||||
}
|
||||
tx := db.DB("").Model(&model.SysLoginSource{})
|
||||
// 构建查询条件
|
||||
tx = tx.Where("id in ?", ids)
|
||||
// 查询数据
|
||||
if err := tx.Find(&rows).Error; err != nil {
|
||||
logger.Errorf("query find err => %v", err.Error())
|
||||
return rows
|
||||
}
|
||||
return rows
|
||||
}
|
||||
|
||||
// Insert 新增信息 返回新增数据ID
|
||||
func (r SysLoginSource) Insert(param model.SysLoginSource) int64 {
|
||||
if param.CreateBy != "" {
|
||||
ms := time.Now().UnixMilli()
|
||||
param.UpdateBy = param.CreateBy
|
||||
param.UpdateTime = ms
|
||||
param.CreateTime = ms
|
||||
}
|
||||
// 执行插入
|
||||
if err := db.DB("").Create(¶m).Error; err != nil {
|
||||
logger.Errorf("insert err => %v", err.Error())
|
||||
return 0
|
||||
}
|
||||
return param.Id
|
||||
}
|
||||
|
||||
// Update 修改信息 返回受影响行数
|
||||
func (r SysLoginSource) Update(param model.SysLoginSource) int64 {
|
||||
if param.Id <= 0 {
|
||||
return 0
|
||||
}
|
||||
if param.UpdateBy != "" {
|
||||
param.UpdateTime = time.Now().UnixMilli()
|
||||
}
|
||||
tx := db.DB("").Model(&model.SysLoginSource{})
|
||||
// 构建查询条件
|
||||
tx = tx.Where("id = ?", param.Id)
|
||||
tx = tx.Omit("id", "create_by", "create_time")
|
||||
// 执行更新
|
||||
if err := tx.Updates(param).Error; err != nil {
|
||||
logger.Errorf("update err => %v", err.Error())
|
||||
return 0
|
||||
}
|
||||
return tx.RowsAffected
|
||||
}
|
||||
|
||||
// DeleteByIds 批量删除信息 返回受影响行数
|
||||
func (r SysLoginSource) DeleteByIds(ids []int64) int64 {
|
||||
if len(ids) <= 0 {
|
||||
return 0
|
||||
}
|
||||
tx := db.DB("").Where("id in ?", ids)
|
||||
// 执行删除
|
||||
if err := tx.Delete(&model.SysLoginSource{}).Error; err != nil {
|
||||
logger.Errorf("delete err => %v", err.Error())
|
||||
return 0
|
||||
}
|
||||
return tx.RowsAffected
|
||||
}
|
||||
@@ -83,14 +83,15 @@ func (r SysMenu) Insert(sysMenu model.SysMenu) int64 {
|
||||
}
|
||||
|
||||
// 根据菜单类型重置参数
|
||||
if sysMenu.MenuType == constants.MENU_TYPE_BUTTON {
|
||||
switch sysMenu.MenuType {
|
||||
case constants.MENU_TYPE_BUTTON:
|
||||
sysMenu.Component = ""
|
||||
sysMenu.FrameFlag = "1"
|
||||
sysMenu.CacheFlag = "1"
|
||||
sysMenu.VisibleFlag = "1"
|
||||
sysMenu.MenuPath = ""
|
||||
sysMenu.Icon = "#"
|
||||
} else if sysMenu.MenuType == constants.MENU_TYPE_DIR {
|
||||
case constants.MENU_TYPE_DIR:
|
||||
sysMenu.Component = ""
|
||||
sysMenu.FrameFlag = "1"
|
||||
sysMenu.CacheFlag = "1"
|
||||
@@ -118,14 +119,15 @@ func (r SysMenu) Update(sysMenu model.SysMenu) int64 {
|
||||
}
|
||||
|
||||
// 根据菜单类型重置参数
|
||||
if sysMenu.MenuType == constants.MENU_TYPE_BUTTON {
|
||||
switch sysMenu.MenuType {
|
||||
case constants.MENU_TYPE_BUTTON:
|
||||
sysMenu.Component = ""
|
||||
sysMenu.FrameFlag = "1"
|
||||
sysMenu.CacheFlag = "1"
|
||||
sysMenu.VisibleFlag = "1"
|
||||
sysMenu.MenuPath = ""
|
||||
sysMenu.Icon = "#"
|
||||
} else if sysMenu.MenuType == constants.MENU_TYPE_DIR {
|
||||
case constants.MENU_TYPE_DIR:
|
||||
sysMenu.Component = ""
|
||||
sysMenu.FrameFlag = "1"
|
||||
sysMenu.CacheFlag = "1"
|
||||
|
||||
@@ -31,6 +31,12 @@ func (r SysUser) SelectByPage(query map[string]string, dataScopeSQL string) ([]m
|
||||
if v, ok := query["phone"]; ok && v != "" {
|
||||
tx = tx.Where("phone like ?", fmt.Sprintf("%s%%", v))
|
||||
}
|
||||
if v, ok := query["userType"]; ok && v != "" {
|
||||
tx = tx.Where("user_type = ?", v)
|
||||
}
|
||||
if v, ok := query["userSource"]; ok && v != "" {
|
||||
tx = tx.Where("user_source = ?", v)
|
||||
}
|
||||
if v, ok := query["statusFlag"]; ok && v != "" {
|
||||
tx = tx.Where("status_flag = ?", v)
|
||||
}
|
||||
@@ -198,6 +204,12 @@ func (r SysUser) CheckUnique(sysUser model.SysUser) int64 {
|
||||
if sysUser.Email != "" {
|
||||
tx = tx.Where("email = ?", sysUser.Email)
|
||||
}
|
||||
if sysUser.UserType != "" {
|
||||
tx = tx.Where("user_type = ?", sysUser.UserType)
|
||||
}
|
||||
if sysUser.UserSource != "" {
|
||||
tx = tx.Where("user_source = ?", sysUser.UserSource)
|
||||
}
|
||||
|
||||
// 查询数据
|
||||
var id int64 = 0
|
||||
@@ -209,14 +221,20 @@ func (r SysUser) CheckUnique(sysUser model.SysUser) int64 {
|
||||
}
|
||||
|
||||
// SelectByUserName 通过登录账号查询信息
|
||||
func (r SysUser) SelectByUserName(userName string) model.SysUser {
|
||||
func (r SysUser) SelectByUserName(userName, userType, userSource string) model.SysUser {
|
||||
item := model.SysUser{}
|
||||
if userName == "" {
|
||||
return item
|
||||
}
|
||||
if userType == "" {
|
||||
userType = "System"
|
||||
}
|
||||
if userSource == "" {
|
||||
userSource = "#"
|
||||
}
|
||||
tx := db.DB("").Model(&model.SysUser{})
|
||||
// 构建查询条件
|
||||
tx = tx.Where("user_name = ? and del_flag = '0'", userName)
|
||||
tx = tx.Where("user_name = ? and user_type = ? and user_source = ? and del_flag = '0'", userName, userType, userSource)
|
||||
// 查询数据
|
||||
if err := tx.Limit(1).Find(&item).Error; err != nil {
|
||||
logger.Errorf("query find err => %v", err.Error())
|
||||
|
||||
95
src/modules/system/service/sys_login_source.go
Normal file
95
src/modules/system/service/sys_login_source.go
Normal file
@@ -0,0 +1,95 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
|
||||
"be.ems/src/framework/utils/generate"
|
||||
"be.ems/src/modules/system/model"
|
||||
"be.ems/src/modules/system/model/vo"
|
||||
"be.ems/src/modules/system/repository"
|
||||
)
|
||||
|
||||
// NewSysLoginSource 实例化服务层
|
||||
var NewSysLoginSource = &SysLoginSource{
|
||||
sysLoginSourceRepository: repository.NewSysLoginSource,
|
||||
}
|
||||
|
||||
// SysLoginSource 认证源 服务层处理
|
||||
type SysLoginSource struct {
|
||||
sysLoginSourceRepository *repository.SysLoginSource // 认证源表
|
||||
}
|
||||
|
||||
// FindByPage 分页查询
|
||||
func (s SysLoginSource) FindByPage(query map[string]string) ([]model.SysLoginSource, int64) {
|
||||
return s.sysLoginSourceRepository.SelectByPage(query)
|
||||
}
|
||||
|
||||
// FindById 查询ID
|
||||
func (s SysLoginSource) FindById(id int64) model.SysLoginSource {
|
||||
rows := s.sysLoginSourceRepository.SelectByIds([]int64{id})
|
||||
if len(rows) > 0 {
|
||||
return rows[0]
|
||||
}
|
||||
return model.SysLoginSource{}
|
||||
}
|
||||
|
||||
// Insert 新增
|
||||
func (s SysLoginSource) Insert(param model.SysLoginSource) int64 {
|
||||
param.UID = generate.Code(8)
|
||||
return s.sysLoginSourceRepository.Insert(param)
|
||||
}
|
||||
|
||||
// Update 更新
|
||||
func (s SysLoginSource) Update(param model.SysLoginSource) int64 {
|
||||
return s.sysLoginSourceRepository.Update(param)
|
||||
}
|
||||
|
||||
// DeleteByIds 批量删除
|
||||
func (s SysLoginSource) DeleteByIds(ids []int64) (int64, error) {
|
||||
// 检查是否存在
|
||||
arr := s.sysLoginSourceRepository.SelectByIds(ids)
|
||||
if len(arr) <= 0 {
|
||||
// return 0, fmt.Errorf("没有权限访问认证源数据!")
|
||||
return 0, fmt.Errorf("no permission to access authentication source data")
|
||||
}
|
||||
if len(arr) == len(ids) {
|
||||
return s.sysLoginSourceRepository.DeleteByIds(ids), nil
|
||||
}
|
||||
// return 0, fmt.Errorf("删除认证源信息失败!")
|
||||
return 0, fmt.Errorf("failed to delete authentication source information")
|
||||
}
|
||||
|
||||
// FindByActive 查询激活
|
||||
func (s SysLoginSource) FindByActive(uid string) []model.SysLoginSource {
|
||||
param := model.SysLoginSource{
|
||||
ActiveFlag: "1",
|
||||
}
|
||||
if uid != "" {
|
||||
param.UID = uid
|
||||
}
|
||||
return s.sysLoginSourceRepository.Select(param)
|
||||
}
|
||||
|
||||
// CheckConfigJSON 检查配置JSON
|
||||
func (s SysLoginSource) CheckConfigJSON(sType, sConfig string) (string, error) {
|
||||
var source any
|
||||
switch sType {
|
||||
case "LDAP":
|
||||
source = new(vo.SysLoginSourceLDAP)
|
||||
case "SMTP":
|
||||
source = new(vo.SysLoginSourceSMTP)
|
||||
case "OAuth2":
|
||||
source = new(vo.SysLoginSourceOAuth2)
|
||||
default:
|
||||
return "", fmt.Errorf("unsupported login source type: %s", sType)
|
||||
}
|
||||
if err := json.Unmarshal([]byte(sConfig), &source); err != nil {
|
||||
return "", fmt.Errorf("config json format error for %s type: %s", sType, err.Error())
|
||||
}
|
||||
configByte, err := json.Marshal(source)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("config json format error")
|
||||
}
|
||||
return string(configByte), nil
|
||||
}
|
||||
@@ -189,7 +189,9 @@ func (s SysUser) DeleteByIds(userIds []int64) (int64, error) {
|
||||
// CheckUniqueByUserName 检查用户名称是否唯一
|
||||
func (s SysUser) CheckUniqueByUserName(userName string, userId int64) bool {
|
||||
uniqueId := s.sysUserRepository.CheckUnique(model.SysUser{
|
||||
UserName: userName,
|
||||
UserName: userName,
|
||||
UserType: "System",
|
||||
UserSource: "#",
|
||||
})
|
||||
if uniqueId == userId {
|
||||
return true
|
||||
@@ -200,7 +202,9 @@ func (s SysUser) CheckUniqueByUserName(userName string, userId int64) bool {
|
||||
// CheckUniqueByPhone 检查手机号码是否唯一
|
||||
func (s SysUser) CheckUniqueByPhone(phone string, userId int64) bool {
|
||||
uniqueId := s.sysUserRepository.CheckUnique(model.SysUser{
|
||||
Phone: phone,
|
||||
Phone: phone,
|
||||
UserType: "System",
|
||||
UserSource: "#",
|
||||
})
|
||||
if uniqueId == userId {
|
||||
return true
|
||||
@@ -211,7 +215,9 @@ func (s SysUser) CheckUniqueByPhone(phone string, userId int64) bool {
|
||||
// CheckUniqueByEmail 检查Email是否唯一
|
||||
func (s SysUser) CheckUniqueByEmail(email string, userId int64) bool {
|
||||
uniqueId := s.sysUserRepository.CheckUnique(model.SysUser{
|
||||
Email: email,
|
||||
Email: email,
|
||||
UserType: "System",
|
||||
UserSource: "#",
|
||||
})
|
||||
if uniqueId == userId {
|
||||
return true
|
||||
@@ -220,8 +226,10 @@ func (s SysUser) CheckUniqueByEmail(email string, userId int64) bool {
|
||||
}
|
||||
|
||||
// FindByUserName 通过用户名查询用户信息
|
||||
func (s SysUser) FindByUserName(userName string) model.SysUser {
|
||||
userinfo := s.sysUserRepository.SelectByUserName(userName)
|
||||
// userType 系统sys
|
||||
// userSource 系统#
|
||||
func (s SysUser) FindByUserName(userName, userType, userSource string) model.SysUser {
|
||||
userinfo := s.sysUserRepository.SelectByUserName(userName, userType, userSource)
|
||||
if userinfo.UserName != userName {
|
||||
return userinfo
|
||||
}
|
||||
|
||||
@@ -429,6 +429,35 @@ func Setup(router *gin.Engine) {
|
||||
controller.NewSysUser.Import,
|
||||
)
|
||||
}
|
||||
|
||||
// 第三方认证-配置认证源
|
||||
sysLoginSource := controller.NewSysLoginSource
|
||||
sysLoginSourceGroup := router.Group("/system/login-source")
|
||||
{
|
||||
sysLoginSourceGroup.GET("/list",
|
||||
middleware.AuthorizeUser(map[string][]string{"hasPerms": {"system:loginSource:list"}}),
|
||||
sysLoginSource.List,
|
||||
)
|
||||
sysLoginSourceGroup.GET("/:id",
|
||||
middleware.AuthorizeUser(map[string][]string{"hasPerms": {"system:loginSource:query"}}),
|
||||
sysLoginSource.Info,
|
||||
)
|
||||
sysLoginSourceGroup.POST("",
|
||||
middleware.AuthorizeUser(map[string][]string{"hasPerms": {"system:loginSource:add"}}),
|
||||
middleware.OperateLog(middleware.OptionNew("log.operate.title.sysLoginSource", middleware.BUSINESS_TYPE_INSERT)),
|
||||
sysLoginSource.Add,
|
||||
)
|
||||
sysLoginSourceGroup.PUT("",
|
||||
middleware.AuthorizeUser(map[string][]string{"hasPerms": {"system:loginSource:edit"}}),
|
||||
middleware.OperateLog(middleware.OptionNew("log.operate.title.sysLoginSource", middleware.BUSINESS_TYPE_UPDATE)),
|
||||
sysLoginSource.Edit,
|
||||
)
|
||||
sysLoginSourceGroup.DELETE("/:id",
|
||||
middleware.AuthorizeUser(map[string][]string{"hasPerms": {"system:loginSource:remove"}}),
|
||||
middleware.OperateLog(middleware.OptionNew("log.operate.title.sysLoginSource", middleware.BUSINESS_TYPE_DELETE)),
|
||||
sysLoginSource.Remove,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// InitLoad 初始参数
|
||||
|
||||
Reference in New Issue
Block a user