package filter

import (
	"net/http"
	"regexp"

	"github.com/go-xweb/xweb"
)

//session过滤器
type sessfilter struct {
	App         *xweb.App
	SessionName string
	MatchUrl    []*regexp.Regexp
}

//实现过滤器方法
func (s *sessfilter) Do(w http.ResponseWriter, req *http.Request) bool {
	requestPath := req.URL.Path
	b := true
	for _, cr := range s.MatchUrl {
		if !cr.MatchString(requestPath) {
			continue
		}
		b = false
		session := s.App.SessionManager.Session(req, w)
		loginuser := session.Get(s.SessionName)
		has := (loginuser != nil && loginuser != "")
		if has {
			b = true
		} else {
			b = false
		}
		break
	}
	if !b { //session失效
		s.App.Redirect(w, requestPath, "/")
	}
	return b
}
