123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136 |
- package sso
- import (
- "embed"
- "net/http"
- "github.com/gorilla/sessions"
- "imuslab.com/zoraxy/mod/database"
- "imuslab.com/zoraxy/mod/info/logger"
- )
- var staticFiles embed.FS
- type SSOConfig struct {
- SystemUUID string
- AuthURL string
- PortalServerPort int
- Database *database.Database
- Logger *logger.Logger
- }
- type RegisteredUpstreamApp struct {
- ID string
- Secret string
- Domain []string
- Scopes []string
- SessionDuration int
- }
- type SSOHandler struct {
- cookieStore *sessions.CookieStore
- ssoPortalServer *http.Server
- ssoPortalMux *http.ServeMux
- Oauth2Server *OAuth2Server
- Config *SSOConfig
- Apps map[string]RegisteredUpstreamApp
- }
- func NewSSOHandler(config *SSOConfig) (*SSOHandler, error) {
-
- cookieStore := sessions.NewCookieStore([]byte(config.SystemUUID))
- cookieStore.Options = &sessions.Options{
- Path: "",
- Domain: "",
- MaxAge: 0,
- Secure: false,
- HttpOnly: false,
- SameSite: 0,
- }
-
- err := config.Database.NewTable("sso_users")
- if err != nil {
- return nil, err
- }
-
- thisHandler := SSOHandler{
- cookieStore: cookieStore,
- Config: config,
- }
-
- oauth2Server, err := NewOAuth2Server(config, &thisHandler)
- if err != nil {
- return nil, err
- }
-
- thisHandler.Oauth2Server = oauth2Server
- thisHandler.InitSSOPortal(config.PortalServerPort)
- return &thisHandler, nil
- }
- func (h *SSOHandler) ServeForwardAuth(w http.ResponseWriter, r *http.Request) bool {
-
- originalRequestURL := r.RequestURI
-
- session, err := h.cookieStore.Get(r, "Zoraxy-SSO")
- if err != nil {
-
- http.Redirect(w, r, h.Config.AuthURL+"?m=new&t="+originalRequestURL, http.StatusFound)
- return false
- }
-
- if session.Values["username"] != true {
-
- http.Redirect(w, r, h.Config.AuthURL+"?m=expired&t="+originalRequestURL, http.StatusFound)
- return false
- }
-
- userName := session.Values["username"].(string)
- user, err := h.SSO_GetUser(userName)
- if err != nil {
-
- http.Redirect(w, r, h.Config.AuthURL, http.StatusFound)
- return false
- }
-
- if !user.Subdomains[r.Host].AllowAccess {
-
- http.Error(w, "Forbidden", http.StatusForbidden)
-
- return false
- }
-
- return true
- }
- func (h *SSOHandler) Log(message string, err error) {
- h.Config.Logger.PrintAndLog("SSO", message, err)
- }
|