2022-03-11 18:03:01 +00:00
|
|
|
package router
|
2022-03-12 04:34:27 +00:00
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"net/http"
|
|
|
|
|
|
|
|
"code.gitea.io/sdk/gitea"
|
|
|
|
"github.com/gorilla/sessions"
|
|
|
|
"github.com/markbates/goth/gothic"
|
|
|
|
)
|
|
|
|
|
|
|
|
const sessionCookie = "_invitea_session"
|
|
|
|
|
|
|
|
type SessionStore struct {
|
|
|
|
Store sessions.Store
|
|
|
|
GiteaURL string
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *SessionStore) Middleware(next http.Handler) http.Handler {
|
2023-03-01 04:47:18 +00:00
|
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
|
|
sess, err := s.Store.Get(r, sessionCookie)
|
|
|
|
if err != nil {
|
|
|
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
r = r.WithContext(context.WithValue(r.Context(), "isAdmin", sess.Values["isAdmin"]))
|
2023-03-04 06:02:24 +00:00
|
|
|
r = r.WithContext(context.WithValue(r.Context(), "username", sess.Values["username"]))
|
2023-03-01 04:47:18 +00:00
|
|
|
next.ServeHTTP(w, r)
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *SessionStore) RequireAuth(next http.Handler) http.Handler {
|
2022-03-12 04:34:27 +00:00
|
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
|
|
sess, err := s.Store.Get(r, sessionCookie)
|
|
|
|
if err != nil {
|
|
|
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
if _, ok := sess.Values["authenticated"]; !ok {
|
|
|
|
gothic.BeginAuthHandler(w, r)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
next.ServeHTTP(w, r)
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *SessionStore) Auth(w http.ResponseWriter, r *http.Request, token string) error {
|
|
|
|
client, err := gitea.NewClient(s.GiteaURL, gitea.SetToken(token))
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
profile, _, err := client.GetMyUserInfo()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
sess, err := s.Store.New(r, sessionCookie)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
sess.Values["authenticated"] = true
|
|
|
|
sess.Values["isAdmin"] = profile.IsAdmin
|
2023-03-04 06:02:24 +00:00
|
|
|
sess.Values["username"] = profile.UserName
|
|
|
|
return s.Store.Save(r, w, sess)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *SessionStore) Logout(w http.ResponseWriter, r *http.Request) error {
|
|
|
|
sess, err := s.Store.Get(r, sessionCookie)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
sess.Options.MaxAge = -1
|
2022-03-12 04:34:27 +00:00
|
|
|
return s.Store.Save(r, w, sess)
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewSessionStore(sessionSecret, giteURL string) *SessionStore {
|
|
|
|
store := sessions.NewCookieStore([]byte(sessionSecret))
|
2023-03-04 06:02:24 +00:00
|
|
|
store.MaxAge(0)
|
2022-03-12 04:34:27 +00:00
|
|
|
return &SessionStore{
|
|
|
|
Store: store,
|
|
|
|
GiteaURL: giteURL,
|
|
|
|
}
|
|
|
|
}
|