- OAuth认证系统(Gitea + Lua扩展) - Git自动化操作(本地/SSH远程) - 实时进度WebSocket推送 - 现代化Tab界面UI - Cobra CLI命令行(init/version/serve) - 完整构建系统(Makefile + Taskfile) - UPX压缩支持(体积减少70%)
85 lines
1.9 KiB
Go
85 lines
1.9 KiB
Go
package handlers
|
||
|
||
import (
|
||
"cs-bridge/internal/http/middleware"
|
||
"cs-bridge/internal/oauth"
|
||
"net/http"
|
||
|
||
"github.com/go-chi/chi/v5"
|
||
)
|
||
|
||
func OauthLogin(mgr *oauth.Manager) http.HandlerFunc {
|
||
return func(w http.ResponseWriter, r *http.Request) {
|
||
name := chi.URLParam(r, "provider")
|
||
p, err := mgr.Get(name)
|
||
if err != nil {
|
||
http.Error(w, err.Error(), 404)
|
||
return
|
||
}
|
||
|
||
state := oauth.NewState()
|
||
session, err := middleware.GetSession(r)
|
||
session.Values["oauth_state"] = state
|
||
session.Values["oauth_provider"] = name
|
||
session.Save(r, w)
|
||
|
||
redirectURL, _ := p.AuthURL(state)
|
||
|
||
http.Redirect(w, r, redirectURL, http.StatusFound)
|
||
}
|
||
}
|
||
|
||
func OauthCallBack(mgr *oauth.Manager) http.HandlerFunc {
|
||
return func(w http.ResponseWriter, r *http.Request) {
|
||
name := chi.URLParam(r, "provider")
|
||
p, err := mgr.Get(name)
|
||
if err != nil {
|
||
http.Error(w, err.Error(), 404)
|
||
return
|
||
}
|
||
|
||
session, _ := middleware.GetSession(r)
|
||
expectedState, ok := session.Values["oauth_state"].(string)
|
||
if !ok {
|
||
http.Error(w, "missing oauth state", 400)
|
||
return
|
||
}
|
||
|
||
goState := r.URL.Query().Get("state")
|
||
if goState != expectedState {
|
||
http.Error(w, "invaild oauth state2", 400)
|
||
return
|
||
}
|
||
|
||
delete(session.Values, "oauth_state")
|
||
|
||
code := r.URL.Query().Get("code")
|
||
token, err := p.Exchange(code)
|
||
if err != nil {
|
||
http.Error(w, err.Error(), 404)
|
||
return
|
||
}
|
||
|
||
userInfo, err := p.UserInfo(token)
|
||
if err != nil {
|
||
http.Error(w, err.Error(), 500)
|
||
return
|
||
}
|
||
|
||
// 只保存用户ID,避免session过大
|
||
session.Values["uid"] = userInfo.UserId
|
||
session.Values["username"] = userInfo.Username
|
||
|
||
// 获取登录前保存的URL
|
||
redirectURL := "/"
|
||
if savedURL, ok := session.Values["redirect_after_login"].(string); ok && savedURL != "" {
|
||
redirectURL = savedURL
|
||
delete(session.Values, "redirect_after_login") // 使用后删除
|
||
}
|
||
|
||
session.Save(r, w)
|
||
|
||
http.Redirect(w, r, redirectURL, http.StatusFound)
|
||
}
|
||
}
|