添加 OIDC 和 OAuth2 服务器的基础结构,包括配置、数据库模型、服务、处理器和路由。新增登录页面模板,支持用户认证和授权流程。
This commit is contained in:
81
handlers/auth.go
Normal file
81
handlers/auth.go
Normal file
@@ -0,0 +1,81 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"oidc-oauth2-server/services"
|
||||
|
||||
"github.com/gin-contrib/sessions"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
type AuthHandler struct {
|
||||
authService *services.AuthService
|
||||
}
|
||||
|
||||
type LoginData struct {
|
||||
Error string
|
||||
RedirectURI string
|
||||
State string
|
||||
ClientID string
|
||||
ResponseType string
|
||||
Scope string
|
||||
}
|
||||
|
||||
func NewAuthHandler(authService *services.AuthService) *AuthHandler {
|
||||
return &AuthHandler{
|
||||
authService: authService,
|
||||
}
|
||||
}
|
||||
|
||||
// ShowLogin 显示登录页面
|
||||
func (h *AuthHandler) ShowLogin(c *gin.Context) {
|
||||
data := LoginData{
|
||||
RedirectURI: c.Query("redirect_uri"),
|
||||
State: c.Query("state"),
|
||||
ClientID: c.Query("client_id"),
|
||||
ResponseType: c.Query("response_type"),
|
||||
Scope: c.Query("scope"),
|
||||
}
|
||||
c.HTML(http.StatusOK, "login.html", data)
|
||||
}
|
||||
|
||||
// HandleLogin 处理登录请求
|
||||
func (h *AuthHandler) HandleLogin(c *gin.Context) {
|
||||
username := c.PostForm("username")
|
||||
password := c.PostForm("password")
|
||||
|
||||
user, err := h.authService.Authenticate(username, password)
|
||||
if err != nil {
|
||||
data := LoginData{
|
||||
Error: "用户名或密码错误",
|
||||
RedirectURI: c.PostForm("redirect_uri"),
|
||||
State: c.PostForm("state"),
|
||||
ClientID: c.PostForm("client_id"),
|
||||
ResponseType: c.PostForm("response_type"),
|
||||
Scope: c.PostForm("scope"),
|
||||
}
|
||||
c.HTML(http.StatusOK, "login.html", data)
|
||||
return
|
||||
}
|
||||
|
||||
// 设置用户会话
|
||||
session := sessions.Default(c)
|
||||
session.Set("user_id", user.ID)
|
||||
session.Save()
|
||||
|
||||
// 重定向回授权页面
|
||||
redirectURI := c.PostForm("redirect_uri")
|
||||
if redirectURI == "" {
|
||||
redirectURI = "/authorize"
|
||||
}
|
||||
|
||||
query := c.Request.URL.Query()
|
||||
query.Set("client_id", c.PostForm("client_id"))
|
||||
query.Set("response_type", c.PostForm("response_type"))
|
||||
query.Set("scope", c.PostForm("scope"))
|
||||
query.Set("state", c.PostForm("state"))
|
||||
query.Set("redirect_uri", redirectURI)
|
||||
|
||||
c.Redirect(http.StatusFound, "/authorize?"+query.Encode())
|
||||
}
|
||||
Reference in New Issue
Block a user