invitea/router/session.go

87 lines
2.0 KiB
Go
Raw Normal View History

package router
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 {
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"]))
r = r.WithContext(context.WithValue(r.Context(), "username", sess.Values["username"]))
next.ServeHTTP(w, r)
})
}
func (s *SessionStore) RequireAuth(next http.Handler) http.Handler {
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
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
return s.Store.Save(r, w, sess)
}
func NewSessionStore(sessionSecret, giteURL string) *SessionStore {
store := sessions.NewCookieStore([]byte(sessionSecret))
store.MaxAge(0)
return &SessionStore{
Store: store,
GiteaURL: giteURL,
}
}