feat(auth): support local username login mode
This commit is contained in:
@@ -4,6 +4,7 @@
|
|||||||
|
|
||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { onMounted } from 'vue'
|
import { onMounted } from 'vue'
|
||||||
|
import { authApi } from '@/api/auth'
|
||||||
import { getToken } from '@/utils/auth'
|
import { getToken } from '@/utils/auth'
|
||||||
import { redirectToSSO } from '@/utils/sso'
|
import { redirectToSSO } from '@/utils/sso'
|
||||||
import { useAuthStore } from '@/stores/auth'
|
import { useAuthStore } from '@/stores/auth'
|
||||||
@@ -20,7 +21,12 @@ onMounted(async () => {
|
|||||||
await authStore.refreshUser()
|
await authStore.refreshUser()
|
||||||
} catch {
|
} catch {
|
||||||
authStore.clearAuth()
|
authStore.clearAuth()
|
||||||
redirectToSSO()
|
const { data } = await authApi.getConfig()
|
||||||
|
if (data.sso_enabled) {
|
||||||
|
redirectToSSO()
|
||||||
|
} else {
|
||||||
|
window.location.assign('/login')
|
||||||
|
}
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
</script>
|
</script>
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ import { getToken } from '@/utils/auth'
|
|||||||
|
|
||||||
export interface LoginRequest {
|
export interface LoginRequest {
|
||||||
username: string
|
username: string
|
||||||
password: string
|
password?: string
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface UserInfo {
|
export interface UserInfo {
|
||||||
@@ -20,9 +20,48 @@ export interface LoginResponse {
|
|||||||
user: UserInfo
|
user: UserInfo
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface AuthConfig {
|
||||||
|
sso_enabled: boolean
|
||||||
|
}
|
||||||
|
|
||||||
export const authApi = {
|
export const authApi = {
|
||||||
login(_data: LoginRequest): Promise<ApiResponse<LoginResponse>> {
|
async getConfig(): Promise<ApiResponse<AuthConfig>> {
|
||||||
return Promise.reject(new Error('password login is disabled'))
|
const response = await fetch('/auth/api/v1/config', {
|
||||||
|
headers: {
|
||||||
|
Accept: 'application/json',
|
||||||
|
},
|
||||||
|
})
|
||||||
|
const data = await response.json().catch(() => ({}))
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error(data.error || `HTTP ${response.status}`)
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
code: 0,
|
||||||
|
message: 'success',
|
||||||
|
data: {
|
||||||
|
sso_enabled: data.sso_enabled !== false,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
async login(data: LoginRequest): Promise<ApiResponse<LoginResponse>> {
|
||||||
|
const response = await fetch('/auth/api/v1/login', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
Accept: 'application/json',
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
},
|
||||||
|
body: JSON.stringify({ username: data.username }),
|
||||||
|
})
|
||||||
|
const result = await response.json().catch(() => ({}))
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error(result.error || `HTTP ${response.status}`)
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
code: 0,
|
||||||
|
message: 'success',
|
||||||
|
data: result,
|
||||||
|
}
|
||||||
},
|
},
|
||||||
|
|
||||||
async logout(): Promise<ApiResponse<null>> {
|
async logout(): Promise<ApiResponse<null>> {
|
||||||
|
|||||||
@@ -61,7 +61,16 @@ request.interceptors.response.use(
|
|||||||
|
|
||||||
if (status === 401) {
|
if (status === 401) {
|
||||||
removeToken()
|
removeToken()
|
||||||
redirectToSSO()
|
fetch('/auth/api/v1/config', { headers: { Accept: 'application/json' } })
|
||||||
|
.then((response) => response.json())
|
||||||
|
.then((data) => {
|
||||||
|
if (data.sso_enabled === false) {
|
||||||
|
window.location.assign('/login')
|
||||||
|
} else {
|
||||||
|
redirectToSSO()
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.catch(() => redirectToSSO())
|
||||||
ElMessage.error(backendMessage || '未授权,请重新登录')
|
ElMessage.error(backendMessage || '未授权,请重新登录')
|
||||||
} else {
|
} else {
|
||||||
const message = backendMessage || httpMessageMap[status] || `请求失败 (${status})`
|
const message = backendMessage || httpMessageMap[status] || `请求失败 (${status})`
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import { createRouter, createWebHistory } from 'vue-router'
|
|||||||
import { getToken } from '@/utils/auth'
|
import { getToken } from '@/utils/auth'
|
||||||
import { consumeSSOToken, redirectToSSO } from '@/utils/sso'
|
import { consumeSSOToken, redirectToSSO } from '@/utils/sso'
|
||||||
import { useAuthStore } from '@/stores/auth'
|
import { useAuthStore } from '@/stores/auth'
|
||||||
|
import { authApi } from '@/api/auth'
|
||||||
|
|
||||||
const router = createRouter({
|
const router = createRouter({
|
||||||
history: createWebHistory(),
|
history: createWebHistory(),
|
||||||
@@ -113,6 +114,10 @@ router.beforeEach(async (to) => {
|
|||||||
const token = authStore.token || getToken()
|
const token = authStore.token || getToken()
|
||||||
|
|
||||||
if (to.meta.requiresAuth !== false && !token) {
|
if (to.meta.requiresAuth !== false && !token) {
|
||||||
|
const { data } = await authApi.getConfig()
|
||||||
|
if (!data.sso_enabled) {
|
||||||
|
return { path: '/login', query: to.fullPath === '/' ? {} : { redirect: to.fullPath } }
|
||||||
|
}
|
||||||
redirectToSSO()
|
redirectToSSO()
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
@@ -121,6 +126,10 @@ router.beforeEach(async (to) => {
|
|||||||
await authStore.refreshUser()
|
await authStore.refreshUser()
|
||||||
} catch {
|
} catch {
|
||||||
authStore.clearAuth()
|
authStore.clearAuth()
|
||||||
|
const { data } = await authApi.getConfig()
|
||||||
|
if (!data.sso_enabled) {
|
||||||
|
return { path: '/login', query: to.fullPath === '/' ? {} : { redirect: to.fullPath } }
|
||||||
|
}
|
||||||
redirectToSSO()
|
redirectToSSO()
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,32 +9,83 @@
|
|||||||
<h2>{{ title }}</h2>
|
<h2>{{ title }}</h2>
|
||||||
<p>{{ subtitle }}</p>
|
<p>{{ subtitle }}</p>
|
||||||
</div>
|
</div>
|
||||||
<el-button type="primary" size="large" class="login-btn" @click="redirectToSSO('', '/')">
|
<div v-if="!ssoEnabled" class="local-login">
|
||||||
|
<el-input
|
||||||
|
v-model="username"
|
||||||
|
size="large"
|
||||||
|
placeholder="输入用户名"
|
||||||
|
@keyup.enter="handleLocalLogin"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<el-button type="primary" size="large" class="login-btn" :loading="loading" @click="handleLoginClick">
|
||||||
{{ buttonText }}
|
{{ buttonText }}
|
||||||
</el-button>
|
</el-button>
|
||||||
<div class="login-footer">
|
<div class="login-footer">
|
||||||
<p>统一 LDAP 账号,同账号同密码</p>
|
<p>{{ footerText }}</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { computed, onMounted } from 'vue'
|
import { computed, onMounted, ref } from 'vue'
|
||||||
import { useRoute } from 'vue-router'
|
import { useRoute, useRouter } from 'vue-router'
|
||||||
import { redirectToSSO } from '@/utils/sso'
|
import { redirectToSSO } from '@/utils/sso'
|
||||||
|
import { useAuth } from '@/composables/useAuth'
|
||||||
|
import { authApi } from '@/api/auth'
|
||||||
|
|
||||||
const route = useRoute()
|
const route = useRoute()
|
||||||
|
const router = useRouter()
|
||||||
|
const { login } = useAuth()
|
||||||
|
const loading = ref(false)
|
||||||
|
const username = ref('')
|
||||||
|
const ssoEnabled = ref(true)
|
||||||
const loggedOut = computed(() => route.query.logged_out === '1')
|
const loggedOut = computed(() => route.query.logged_out === '1')
|
||||||
const title = computed(() => loggedOut.value ? '已退出登录' : '统一基础设施平台')
|
const title = computed(() => loggedOut.value ? '已退出登录' : '统一基础设施平台')
|
||||||
const subtitle = computed(() => loggedOut.value ? '本地登录态已清除' : '正在跳转到 SSO 登录')
|
const subtitle = computed(() => {
|
||||||
const buttonText = computed(() => loggedOut.value ? '重新登录' : '重新跳转')
|
if (!ssoEnabled.value) {
|
||||||
|
return '开发测试模式,输入用户名登录'
|
||||||
|
}
|
||||||
|
return loggedOut.value ? '本地登录态已清除' : '正在跳转到 SSO 登录'
|
||||||
|
})
|
||||||
|
const buttonText = computed(() => {
|
||||||
|
if (!ssoEnabled.value) {
|
||||||
|
return '登录'
|
||||||
|
}
|
||||||
|
return loggedOut.value ? '重新登录' : '重新跳转'
|
||||||
|
})
|
||||||
|
const footerText = computed(() => ssoEnabled.value ? '统一 LDAP 账号,同账号同密码' : 'SSO 已关闭,仅用于开发测试')
|
||||||
|
|
||||||
onMounted(() => {
|
onMounted(async () => {
|
||||||
if (!loggedOut.value) {
|
const { data } = await authApi.getConfig()
|
||||||
|
ssoEnabled.value = data.sso_enabled
|
||||||
|
if (ssoEnabled.value && !loggedOut.value) {
|
||||||
redirectToSSO('', '/')
|
redirectToSSO('', '/')
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
|
const handleLoginClick = () => {
|
||||||
|
if (ssoEnabled.value) {
|
||||||
|
redirectToSSO('', '/')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
handleLocalLogin()
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleLocalLogin = async () => {
|
||||||
|
const value = username.value.trim()
|
||||||
|
if (!value) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
loading.value = true
|
||||||
|
try {
|
||||||
|
await login(value, '')
|
||||||
|
const redirect = typeof route.query.redirect === 'string' ? route.query.redirect : '/'
|
||||||
|
router.replace(redirect)
|
||||||
|
} finally {
|
||||||
|
loading.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<style scoped>
|
<style scoped>
|
||||||
@@ -58,6 +109,10 @@ onMounted(() => {
|
|||||||
width: 100%;
|
width: 100%;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.local-login {
|
||||||
|
margin-bottom: 14px;
|
||||||
|
}
|
||||||
|
|
||||||
.login-header {
|
.login-header {
|
||||||
text-align: center;
|
text-align: center;
|
||||||
margin-bottom: 32px;
|
margin-bottom: 32px;
|
||||||
|
|||||||
+6
-6
@@ -68,19 +68,18 @@ mysql -uroot -p < docs/mysql-init.sql
|
|||||||
|
|
||||||
如果你使用的是 Docker Desktop、OrbStack、Colima 或容器里的 MySQL,应用访问 MySQL 时来源 IP 可能不是 `localhost`,而是类似 `192.168.65.1`。这时 MySQL 账号需要允许远程来源,`docs/mysql-init.sql` 已经包含 `'auth'@'%'`。
|
如果你使用的是 Docker Desktop、OrbStack、Colima 或容器里的 MySQL,应用访问 MySQL 时来源 IP 可能不是 `localhost`,而是类似 `192.168.65.1`。这时 MySQL 账号需要允许远程来源,`docs/mysql-init.sql` 已经包含 `'auth'@'%'`。
|
||||||
|
|
||||||
如果要自动创建本地管理员账号,在 `.env` 里设置:
|
默认启用 SSO:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
BOOTSTRAP_ADMIN_USERNAME=admin
|
SSO_ENABLED=true
|
||||||
BOOTSTRAP_ADMIN_PASSWORD='your-password'
|
|
||||||
```
|
```
|
||||||
|
|
||||||
也可以直接使用环境变量:
|
如果只是本地开发测试,可以关闭 SSO,前端会显示用户名登录框。后端只校验用户名非空;用户不存在时会自动创建本地用户,第一位用户会自动成为管理员:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
MYSQL_DSN='auth:auth@tcp(127.0.0.1:3306)/authserver?charset=utf8mb4&parseTime=True&loc=Local' \
|
MYSQL_DSN='auth:auth@tcp(127.0.0.1:3306)/authserver?charset=utf8mb4&parseTime=True&loc=Local' \
|
||||||
JWT_SECRET='change-this-secret' \
|
JWT_SECRET='change-this-secret' \
|
||||||
BOOTSTRAP_ADMIN_PASSWORD='your-password' \
|
SSO_ENABLED=false \
|
||||||
go run ./cmd/server
|
go run ./cmd/server
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -151,7 +150,8 @@ bash scripts/restart-authserver.sh nginx
|
|||||||
|---|---|---|
|
|---|---|---|
|
||||||
| `GET` | `/healthz` | 服务健康检查 |
|
| `GET` | `/healthz` | 服务健康检查 |
|
||||||
| `GET` | `/readyz` | 数据库连接检查 |
|
| `GET` | `/readyz` | 数据库连接检查 |
|
||||||
| `POST` | `/api/v1/login` | 本地登录 |
|
| `GET` | `/auth/api/v1/config` | 前端登录模式配置,返回 `sso_enabled` |
|
||||||
|
| `POST` | `/auth/api/v1/login` | 本地开发测试登录,仅 `SSO_ENABLED=false` 时可用,只需用户名 |
|
||||||
| `POST` | `/api/v1/login/ldap` | LDAP 登录预留 |
|
| `POST` | `/api/v1/login/ldap` | LDAP 登录预留 |
|
||||||
| `GET` | `/api/v1/login/:provider` | SSO 跳转预留 |
|
| `GET` | `/api/v1/login/:provider` | SSO 跳转预留 |
|
||||||
| `GET` | `/api/v1/login/:provider/callback` | SSO 回调预留 |
|
| `GET` | `/api/v1/login/:provider/callback` | SSO 回调预留 |
|
||||||
|
|||||||
@@ -19,6 +19,7 @@ type Config struct {
|
|||||||
PublicBaseURL string
|
PublicBaseURL string
|
||||||
MySQLDSN string
|
MySQLDSN string
|
||||||
AutoMigrate bool
|
AutoMigrate bool
|
||||||
|
SSOEnabled bool
|
||||||
JWTSecret string
|
JWTSecret string
|
||||||
JWTIssuer string
|
JWTIssuer string
|
||||||
JWTTTLMinutes int
|
JWTTTLMinutes int
|
||||||
@@ -68,6 +69,7 @@ func Load() Config {
|
|||||||
PublicBaseURL: publicBaseURL,
|
PublicBaseURL: publicBaseURL,
|
||||||
MySQLDSN: env("MYSQL_DSN", "auth:auth@tcp(127.0.0.1:3306)/authserver?charset=utf8mb4&parseTime=True&loc=Local"),
|
MySQLDSN: env("MYSQL_DSN", "auth:auth@tcp(127.0.0.1:3306)/authserver?charset=utf8mb4&parseTime=True&loc=Local"),
|
||||||
AutoMigrate: envBool("AUTO_MIGRATE", true),
|
AutoMigrate: envBool("AUTO_MIGRATE", true),
|
||||||
|
SSOEnabled: envBool("SSO_ENABLED", true),
|
||||||
JWTSecret: env("JWT_SECRET", "change-this-secret"),
|
JWTSecret: env("JWT_SECRET", "change-this-secret"),
|
||||||
JWTIssuer: env("JWT_ISSUER", "authserver"),
|
JWTIssuer: env("JWT_ISSUER", "authserver"),
|
||||||
JWTTTLMinutes: envInt("JWT_TTL_MINUTES", 120),
|
JWTTTLMinutes: envInt("JWT_TTL_MINUTES", 120),
|
||||||
|
|||||||
@@ -0,0 +1,78 @@
|
|||||||
|
package handler
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"net/http"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/1024XEngineer/xinfra/server/internal/config"
|
||||||
|
"github.com/1024XEngineer/xinfra/server/internal/service"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
)
|
||||||
|
|
||||||
|
type AuthHandler struct {
|
||||||
|
cfg config.Config
|
||||||
|
auth *service.AuthService
|
||||||
|
}
|
||||||
|
|
||||||
|
type localLoginRequest struct {
|
||||||
|
Username string `json:"username"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewAuthHandler(cfg config.Config, authService *service.AuthService) *AuthHandler {
|
||||||
|
return &AuthHandler{cfg: cfg, auth: authService}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *AuthHandler) Config(c *gin.Context) {
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"sso_enabled": h.cfg.SSOEnabled,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *AuthHandler) LocalLogin(c *gin.Context) {
|
||||||
|
if h.cfg.SSOEnabled {
|
||||||
|
c.JSON(http.StatusForbidden, gin.H{"error": "local login is disabled when sso is enabled"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
var req localLoginRequest
|
||||||
|
if err := c.ShouldBindJSON(&req); err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
result, err := h.auth.LocalLogin(strings.TrimSpace(req.Username), c.ClientIP(), c.Request.UserAgent())
|
||||||
|
if err != nil {
|
||||||
|
switch {
|
||||||
|
case errors.Is(err, service.ErrInvalidCredential):
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||||
|
case errors.Is(err, service.ErrUserDisabled):
|
||||||
|
c.JSON(http.StatusForbidden, gin.H{"error": err.Error()})
|
||||||
|
default:
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
http.SetCookie(c.Writer, &http.Cookie{
|
||||||
|
Name: AuthSessionCookieName,
|
||||||
|
Value: result.Token,
|
||||||
|
Path: "/auth/",
|
||||||
|
HttpOnly: true,
|
||||||
|
SameSite: http.SameSiteLaxMode,
|
||||||
|
MaxAge: int(time.Until(result.ExpiresAt).Seconds()),
|
||||||
|
})
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"token": result.Token,
|
||||||
|
"expires_in": int(h.cfg.JWTTTL().Seconds()),
|
||||||
|
"user": gin.H{
|
||||||
|
"id": result.User.ID,
|
||||||
|
"username": result.User.Username,
|
||||||
|
"display_name": result.User.DisplayName,
|
||||||
|
"email": result.User.Email,
|
||||||
|
"business_line": "",
|
||||||
|
"is_admin": result.User.IsAdmin,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -72,6 +72,7 @@ func registerAuthServerRoutes(r *gin.Engine, deps Dependencies) {
|
|||||||
wayneRoleBindingService := service.NewWayneRoleBindingService(deps.Config)
|
wayneRoleBindingService := service.NewWayneRoleBindingService(deps.Config)
|
||||||
|
|
||||||
healthHandler := handler.NewHealthHandler(deps.DB)
|
healthHandler := handler.NewHealthHandler(deps.DB)
|
||||||
|
authHandler := handler.NewAuthHandler(deps.Config, authService)
|
||||||
userHandler := handler.NewUserHandler()
|
userHandler := handler.NewUserHandler()
|
||||||
wayenHandler := handler.NewWayenHandler(deps.DB, wayenService, auditService)
|
wayenHandler := handler.NewWayenHandler(deps.DB, wayenService, auditService)
|
||||||
wayneRoleBindingHandler := handler.NewWayneRoleBindingHandler(wayneRoleBindingService, auditService)
|
wayneRoleBindingHandler := handler.NewWayneRoleBindingHandler(wayneRoleBindingService, auditService)
|
||||||
@@ -89,6 +90,8 @@ func registerAuthServerRoutes(r *gin.Engine, deps Dependencies) {
|
|||||||
|
|
||||||
v1 := r.Group("/auth/api/v1")
|
v1 := r.Group("/auth/api/v1")
|
||||||
{
|
{
|
||||||
|
v1.GET("/config", authHandler.Config)
|
||||||
|
v1.POST("/login", authHandler.LocalLogin)
|
||||||
v1.GET("/login/internal-sso", samlHandler.Login)
|
v1.GET("/login/internal-sso", samlHandler.Login)
|
||||||
v1.POST("/logout", samlHandler.Logout)
|
v1.POST("/logout", samlHandler.Logout)
|
||||||
v1.GET("/saml/metadata", samlHandler.Metadata)
|
v1.GET("/saml/metadata", samlHandler.Metadata)
|
||||||
|
|||||||
@@ -39,6 +39,55 @@ func NewAuthService(cfg config.Config, db *gorm.DB, audit *AuditService) *AuthSe
|
|||||||
return &AuthService{cfg: cfg, db: db, audit: audit}
|
return &AuthService{cfg: cfg, db: db, audit: audit}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (s *AuthService) LocalLogin(username, clientIP, userAgent string) (*LoginResult, error) {
|
||||||
|
username = strings.TrimSpace(username)
|
||||||
|
if username == "" {
|
||||||
|
return nil, ErrInvalidCredential
|
||||||
|
}
|
||||||
|
|
||||||
|
var result *LoginResult
|
||||||
|
err := s.db.Transaction(func(tx *gorm.DB) error {
|
||||||
|
user, err := findOrCreateLocalUser(tx, username)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if user.Status != "active" {
|
||||||
|
s.audit.Write(AuditEntry{ActorUserID: user.ID, ActorUsername: user.Username, ClientIP: clientIP, UserAgent: userAgent, Action: "local.login.failed", Decision: "deny", Reason: "user_disabled"})
|
||||||
|
return ErrUserDisabled
|
||||||
|
}
|
||||||
|
|
||||||
|
token, tokenID, expiresAt, err := auth.Sign(s.cfg.JWTSecret, s.cfg.JWTIssuer, s.cfg.JWTTTL(), user.ID, user.Username, user.Email, user.IsAdmin)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
now := time.Now()
|
||||||
|
if err := tx.Model(&model.User{}).Where("id = ?", user.ID).Update("last_login_at", now).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := tx.Create(&model.AccessToken{
|
||||||
|
UserID: user.ID,
|
||||||
|
TokenID: tokenID,
|
||||||
|
TokenType: "access",
|
||||||
|
ClientIP: clientIP,
|
||||||
|
UserAgent: userAgent,
|
||||||
|
ExpiresAt: expiresAt,
|
||||||
|
}).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
user.LastLoginAt = &now
|
||||||
|
result = &LoginResult{Token: token, TokenID: tokenID, ExpiresAt: expiresAt, User: user}
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
s.audit.Write(AuditEntry{ActorUserID: result.User.ID, ActorUsername: result.User.Username, ClientIP: clientIP, UserAgent: userAgent, Action: "local.login.success", Decision: "allow"})
|
||||||
|
return result, nil
|
||||||
|
}
|
||||||
|
|
||||||
func (s *AuthService) SAMLLogin(info *sso.SAMLDebugInfo, clientIP, userAgent string) (*LoginResult, error) {
|
func (s *AuthService) SAMLLogin(info *sso.SAMLDebugInfo, clientIP, userAgent string) (*LoginResult, error) {
|
||||||
subject := strings.TrimSpace(info.NameID)
|
subject := strings.TrimSpace(info.NameID)
|
||||||
email := firstSAMLAttribute(info.Attributes,
|
email := firstSAMLAttribute(info.Attributes,
|
||||||
@@ -119,6 +168,41 @@ func (s *AuthService) SAMLLogin(info *sso.SAMLDebugInfo, clientIP, userAgent str
|
|||||||
return result, nil
|
return result, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func findOrCreateLocalUser(tx *gorm.DB, username string) (model.User, error) {
|
||||||
|
email := ""
|
||||||
|
if looksLikeEmail(username) {
|
||||||
|
email = username
|
||||||
|
}
|
||||||
|
|
||||||
|
var user model.User
|
||||||
|
query := tx.Where("username = ? AND deleted_at IS NULL", username)
|
||||||
|
if email != "" {
|
||||||
|
query = query.Or("email = ? AND deleted_at IS NULL", email)
|
||||||
|
}
|
||||||
|
if err := query.First(&user).Error; err == nil {
|
||||||
|
return user, nil
|
||||||
|
} else if !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||||
|
return model.User{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
var count int64
|
||||||
|
if err := tx.Model(&model.User{}).Where("deleted_at IS NULL").Count(&count).Error; err != nil {
|
||||||
|
return model.User{}, err
|
||||||
|
}
|
||||||
|
user = model.User{
|
||||||
|
Username: username,
|
||||||
|
DisplayName: username,
|
||||||
|
Email: email,
|
||||||
|
Source: "local",
|
||||||
|
Status: "active",
|
||||||
|
IsAdmin: count == 0,
|
||||||
|
}
|
||||||
|
if err := tx.Create(&user).Error; err != nil {
|
||||||
|
return user, err
|
||||||
|
}
|
||||||
|
return user, nil
|
||||||
|
}
|
||||||
|
|
||||||
func findOrCreateSAMLUser(tx *gorm.DB, subject, email, displayName string) (model.User, error) {
|
func findOrCreateSAMLUser(tx *gorm.DB, subject, email, displayName string) (model.User, error) {
|
||||||
username := samlUsername(email, subject)
|
username := samlUsername(email, subject)
|
||||||
if displayName == "" {
|
if displayName == "" {
|
||||||
|
|||||||
Reference in New Issue
Block a user