Example #1
0
func (s *RedisStore) New(r *http.Request, name string) (*sessions.Session, error) {
	session := sessions.NewSession(s, name)
	session.Options = &(*s.Options)
	session.IsNew = true
	var err error
	if c, errCookie := r.Cookie(name); errCookie == nil {
		// TEMP: Check if previous CookieStore
		err = securecookie.DecodeMulti(name, c.Value, &session.Values, s.Codecs...)
		if err == nil {
			err = s.save(session)
			if err == nil {
				session.IsNew = false
			}
		} else {
			err = securecookie.DecodeMulti(name, c.Value, &session.ID, s.Codecs...)
			if err == nil {
				err = s.load(session)
				if err == nil {
					session.IsNew = false
				}
			}
		}
	}
	return session, err
}
// New returns a session for the given name without adding it to the registry.
func (m *MongoStore) New(r *http.Request, name string) (
	*sessions.Session, error) {
	session := sessions.NewSession(m, name)
	session.Options = &sessions.Options{
		Path:     m.Options.Path,
		MaxAge:   m.Options.MaxAge,
		Domain:   m.Options.Domain,
		Secure:   m.Options.Secure,
		HttpOnly: m.Options.HttpOnly,
	}
	session.IsNew = true
	var err error
	if cook, errToken := m.Token.GetToken(r, name); errToken == nil {
		err = securecookie.DecodeMulti(name, cook, &session.ID, m.Codecs...)
		if err == nil {
			err = m.load(session)
			if err == nil {
				session.IsNew = false
			} else {
				err = nil
			}
		}
	}
	return session, err
}
Example #3
0
// load reads a file and decodes its content into session.Values.
func (s *FileStore) load(session *Session) error {
	filename := s.path + "session_" + session.ID
	fp, err := os.OpenFile(filename, os.O_RDONLY, 0777)
	if err != nil {
		return err
	}
	defer fp.Close()
	var fdata []byte
	buf := make([]byte, 128)
	for {
		var n int
		n, err = fp.Read(buf[0:])
		fdata = append(fdata, buf[0:n]...)
		if err != nil {
			if err == io.EOF {
				break
			}
			return err
		}
	}
	if err = securecookie.DecodeMulti(session.Name(), string(fdata),
		&session.Values, s.Codecs...); err != nil {
		return err
	}
	return nil
}
Example #4
0
func SessionCookieFilter(cookieName string, opts *CookieOpts, keyPairs ...[]byte) restful.FilterFunction {
	codecs := securecookie.CodecsFromPairs(keyPairs...)

	return func(req *restful.Request, resp *restful.Response, chain *restful.FilterChain) {

		session := NewSession()
		if cookie, err := req.Request.Cookie(cookieName); err == nil {
			if err = securecookie.DecodeMulti(cookieName, cookie.Value, &session.store, codecs...); err == nil {

			} else {
				logrus.Warn(err)
			}
		} else {
			if err != http.ErrNoCookie {
				logrus.Warn(err)
			}
		}
		req.SetAttribute(AttrSessionKey, session)

		// I don't know how to write cookie in restful, so I use underneath negroni before hook
		resp.ResponseWriter.(negroni.ResponseWriter).Before(func(rw negroni.ResponseWriter) {
			if !session.IsModified() {
				return
			}
			if encoded, err := securecookie.EncodeMulti(cookieName, session.store, codecs...); err == nil {
				cookie := NewCookie(cookieName, encoded, opts)
				http.SetCookie(rw, cookie)
			}
		})

		chain.ProcessFilter(req, resp)
	}
}
Example #5
0
//load fetches a session by ID from the database and decodes its content into session.Values
func (s *Store) load(session *sessions.Session) error {
	ss, err := s.q.GetSessionByKey(session.ID)
	if err != nil {
		return err
	}
	return securecookie.DecodeMulti(session.Name(), string(ss.Data),
		&session.Values, s.codecs...)
}
// load reads a file and decodes its content into session.Values.
func (s *DumbMemoryStore) load(session *sessions.Session) error {

	if err := securecookie.DecodeMulti(session.Name(), string(s.Data[session.ID]),
		&session.Values, s.Codecs...); err != nil {
		return err
	}
	return nil
}
Example #7
0
//load fetches a session by ID from the database and decodes its content into session.Values
func (db *PGStore) load(session *sessions.Session) error {
	s, err := query.GetSessionByKey(session.ID)
	if err != nil {
		return err
	}
	return securecookie.DecodeMulti(session.Name(), string(s.Data),
		&session.Values, db.Codecs...)
}
Example #8
0
// load db and decodes its content into session.Values.
func (s *DbStore) load(session *Session) error {
	sessionInfo := (&model.SessionInfo{Id: session.ID}).GetSessionInfo()
	if err := securecookie.DecodeMulti(session.Name(), sessionInfo.Content,
		&session.Values, s.Codecs...); err != nil {
		return err
	}
	return nil
}
Example #9
0
// load fetches a session by ID from the database and decodes its content
// into session.Values
func (db *PGStore) load(session *sessions.Session) error {
	var s Session
	err := db.DbMap.SelectOne(&s, "SELECT * FROM http_sessions WHERE key = $1", session.ID)

	if err := securecookie.DecodeMulti(session.Name(), string(s.Data),
		&session.Values, db.Codecs...); err != nil {
		return err
	}

	return err
}
Example #10
0
File: redis.go Project: armen/gapp
// load reads from redis and decodes its content into session.Values.
func (s *RedisStore) load(session *sessions.Session) error {

	c := s.redisPool.Get()
	defer c.Close()

	encoded, err := redis.String(c.Do("GET", "s:"+session.ID))
	if err != nil {
		return err
	}

	return securecookie.DecodeMulti(session.Name(), encoded, &session.Values, s.Codecs...)
}
Example #11
0
// sessionValues extracts session info from the HTTP header. It first looks for a "Authorization" header and then
// it looks for a cookie. It returns a map of the session data.
func sessionValues(r *http.Request) (values map[interface{}]interface{}, err error) {
	err = nil
	// check authorization header
	auth := r.Header.Get("Authorization")
	if strings.HasPrefix(auth, "Cookie") {
		log.Debugf("Authorization header: %v", auth)
		t := strings.Split(auth, " ")
		if len(t) <= 1 {
			err = errors.New("Invalid Authorization header")
		}
		var sessionID string
		if err == nil {
			err = securecookie.DecodeMulti(sessionKey, t[len(t)-1], &sessionID, store.Codecs...)
			log.Debugf("Session ID = %v", sessionID)
		}
		if err == nil {
			if !bson.IsObjectIdHex(sessionID) {
				err = errors.New("Invalid session ID")
			}
		}
		var s mongostore.Session
		if err == nil {
			err = database.C(sessionC).FindId(bson.ObjectIdHex(sessionID)).One(&s)
		}
		if err == nil {
			err = securecookie.DecodeMulti(sessionKey, s.Data, &values, store.Codecs...)
		}
	} else {
		session, err := store.Get(r, sessionKey)
		if err == nil {
			log.Debugf("Cookie found / ID = %v", session.ID)
			values = session.Values
		}
	}
	if err != nil {
		log.Error(err.Error())
	}
	return
}
Example #12
0
// load reads a file and decodes its content into session.Values.
func (s *FilesystemStore) load(session *Session) error {
	filename := s.path + "session_" + session.ID
	fileMutex.RLock()
	defer fileMutex.RUnlock()
	fdata, err := ioutil.ReadFile(filename)
	if err != nil {
		return err
	}
	if err = securecookie.DecodeMulti(session.Name(), string(fdata),
		&session.Values, s.Codecs...); err != nil {
		return err
	}
	return nil
}
Example #13
0
// New returns a session for the given name without adding it to the registry.
//
// The difference between New() and Get() is that calling New() twice will
// decode the session data twice, while Get() registers and reuses the same
// decoded session after the first call.
func (s *CookieStore) New(r *http.Request, name string) (*Session, error) {
	session := NewSession(s, name)
	session.Options = &(*s.Options)
	session.IsNew = true
	var err error
	if c, errCookie := r.Cookie(name); errCookie == nil {
		err = securecookie.DecodeMulti(name, c.Value, &session.Values,
			s.Codecs...)
		if err == nil {
			session.IsNew = false
		}
	}
	return session, err
}
Example #14
0
// New returns a session for the given name without adding it to the registry.
func (s *RethinkStore) New(r *http.Request, name string) (*sessions.Session, error) {
	var err error
	session := sessions.NewSession(s, name)
	session.Options = &(*s.Options)
	session.IsNew = true
	if c, errCookie := r.Cookie(name); errCookie == nil {
		err = securecookie.DecodeMulti(name, c.Value, &session.ID, s.Codecs...)
		if err == nil {
			ok, err := s.load(session)
			session.IsNew = !(err == nil && ok) // not new if no error and data available
		}
	}
	return session, err
}
Example #15
0
func (s *RedisStore) load(session *sessions.Session) error {
	c := s.storeHandler.GetRedisConnection()
	defer c.Close()
	c.Send("GET", "morioka_sess_"+session.ID)
	c.Flush()
	data, err := redis.String(c.Receive())
	if err != nil {
		return err
	}
	if err = securecookie.DecodeMulti(session.Name(), data, &session.Values, s.Codecs...); err != nil {
		return err
	}
	return nil
}
Example #16
0
// New returns a session for the given name without adding it to the registry.
func (d *dalStore) New(r *http.Request, name string) (*gSessions.Session, error) {
	var err error
	session := gSessions.NewSession(d, name)
	options := *d.options
	session.Options = &options
	session.IsNew = true

	if cook, errToken := d.Token.GetToken(r, name); errToken == nil {
		err = securecookie.DecodeMulti(name, cook, &session.ID, d.Codecs...)
		if err == nil {
			ok, err := d.load(session)
			session.IsNew = !(err == nil && ok) // not new if no error and data available
		}
	}
	return session, err
}
Example #17
0
// New returns a session for the given name without adding it to the registry.
//
// See gorilla/sessions FilesystemStore.New().
func (s *RediStore) New(r *http.Request, name string) (*sessions.Session, error) {
	var err error
	session := sessions.NewSession(s, name)
	session.Options = &(*s.Options)
	session.IsNew = true
	if c, errCookie := r.Cookie(name); errCookie == nil {
		err = securecookie.DecodeMulti(name, c.Value, &session.ID, s.Codecs...)
		if err == nil {
			err = s.load(session)
			if err == nil {
				session.IsNew = false
			}
		}
	}
	return session, err
}
Example #18
0
// Returns true if the XSRF token was correct and an error if needed
func checkXsrfToken(req *http.Request, token []uint8) (bool, error) {
	c := appengine.NewContext(req)

	if token == nil {
		c.Errorf("[xsrf] token is nil")
		return false, nil
	}

	var cookie string
	for _, c := range req.Cookies() {
		if c.Name == "XSRF-TOKEN" {
			cookie = c.Value
		}
	}
	if cookie == "" {
		c.Errorf("[xsrf] no cookie")
		return false, nil
	}

	// Inconsistencies between the script & the cookies
	header := req.Header.Get("X-Xsrf-Token")
	if header != cookie {
		c.Errorf("[xsrf] inconsistency between the header & cookie: %s != %s",
			header, cookie)
		return false, nil
	}

	// Check the token itself
	var unsafeToken []uint8
	err := securecookie.DecodeMulti("XSRF-TOKEN", header, &unsafeToken, xsrfCodecs...)
	if err != nil {
		return false, fmt.Errorf("decode failed: %s", err)
	}
	if len(token) != len(unsafeToken) {
		c.Errorf("[xsrf] length check failed: %d != %d", len(token), len(unsafeToken))
		return false, nil
	}
	for i := range token {
		if token[i] != unsafeToken[i] {
			c.Errorf("[xsrf] character %d is not equal", i)
			return false, nil
		}
	}

	return true, nil
}
Example #19
0
// New returns a session for the given name without adding it to the registry.
func (m *mongoStore) New(r *http.Request, name string) (*gSessions.Session, error) {
	session := gSessions.NewSession(m, name)
	session.Options = &gSessions.Options{
		Path:   m.options.Path,
		MaxAge: m.options.MaxAge,
	}
	session.IsNew = true
	var err error
	if cook, errToken := m.Token.GetToken(r, name); errToken == nil {
		err = securecookie.DecodeMulti(name, cook, &session.ID, m.Codecs...)
		if err == nil {
			ok, err := m.load(session)
			session.IsNew = !(err == nil && ok) // not new if no error and data available
		}
	}
	return session, err
}
Example #20
0
// New returns a session for the given name without adding it to the registry.
//
// See CookieStore.New().
func (s *FilesystemStore) New(r *http.Request, name string) (*Session, error) {
	session := NewSession(s, name)
	opts := *s.Options
	session.Options = &opts
	session.IsNew = true
	var err error
	if c, errCookie := r.Cookie(name); errCookie == nil {
		err = securecookie.DecodeMulti(name, c.Value, &session.ID, s.Codecs...)
		if err == nil {
			err = s.load(session)
			if err == nil {
				session.IsNew = false
			}
		}
	}
	return session, err
}
Example #21
0
// New returns a new session for the given name w/o adding it to the registry.
func (db *DatabaseStore) New(r *http.Request, name string) (*sessions.Session, error) {
	session := sessions.NewSession(db, name)
	session.Options = &(*db.Options)
	session.IsNew = true

	var err error
	if c, errCookie := r.Cookie(name); errCookie == nil {
		err = securecookie.DecodeMulti(name, c.Value, &session.ID, db.Codecs...)
		if err == nil {
			err = db.load(session)
			if err == nil {
				session.IsNew = false
			}
		}
	}

	return session, err
}
Example #22
0
func (m *MongoStore) load(session *sessions.Session) error {
	if !bson.IsObjectIdHex(session.ID) {
		return ErrInvalidId
	}

	s := Session{}
	err := m.coll.FindId(bson.ObjectIdHex(session.ID)).One(&s)
	if err != nil {
		return err
	}

	if err := securecookie.DecodeMulti(session.Name(), s.Data, &session.Values,
		m.Codecs...); err != nil {
		return err
	}

	return nil
}
Example #23
0
// New returns a session for the given name without adding it to the registry.
//
// See CookieStore.New().
func (s *MemcacheStore) New(r *http.Request, name string) (*sessions.Session,
	error) {
	session := sessions.NewSession(s, name)
	session.Options = &(*s.Options)
	session.IsNew = true
	var err error
	if cookie, errCookie := r.Cookie(name); errCookie == nil {
		err = securecookie.DecodeMulti(name, cookie.Value, &session.ID,
			s.Codecs...)
		if err == nil {
			c := appengine.NewContext(r)
			err = loadFromMemcache(c, session)
			if err == nil {
				session.IsNew = false
			}
		}
	}
	return session, err
}
Example #24
0
func (d *dalStore) load(session *gSessions.Session) (bool, error) {
	if !dal.IsObjectIDHex(session.ID) {
		return false, nSessions.ErrInvalidId
	}
	conn := d.connection.Clone()
	defer conn.Close()
	db := conn.DB(d.database)
	c := db.C(d.collection)

	s := dalSession{}
	err := c.FindID(dal.ObjectIDHex(session.ID)).One(&s)
	if err != nil {
		return false, err
	}
	if err := securecookie.DecodeMulti(session.Name(), s.Data, &session.Values, d.Codecs...); err != nil {
		return false, err
	}
	return true, nil
}
Example #25
0
// New returns a session for the given name without adding it to the registry.
//
func (s *MemoryStore) New(r *http.Request, name string) (*sessions.Session, error) {
	session := sessions.NewSession(s, name)
	opts := *s.Options
	session.Options = &opts
	session.IsNew = true
	var err error
	if c, errCookie := r.Cookie(name); errCookie == nil {
		Log.Info("MemoryStore reading cookie")
		err = securecookie.DecodeMulti(name, c.Value, &session.ID, s.Codecs...)
		PanicIf(err)
		if err == nil {
			Log.Info("MemoryStore read cookie success")
			err = s.load(session)
			if err == nil {
				session.IsNew = false
			}
		}
	}
	return session, err
}
Example #26
0
//load fetches a session by ID from the database and decodes its content into session.Values
func (db *DatabaseStore) load(session *sessions.Session) error {
	fn := func(dbConn *sql.DB) error {
		// Write record to sessions table.
		row := dbConn.QueryRow("SELECT http_session_id, key, data FROM \""+SESSIONS_TABLE+"\" WHERE key = $1", session.ID)

		var id int
		var key, data string
		if err := row.Scan(&id, &key, &data); err != nil {
			return err
		}

		if err := securecookie.DecodeMulti(session.Name(), string(data),
			&session.Values, db.Codecs...); err != nil {
			return err
		}

		return nil
	}

	return dbLib.ExecuteFn(fn)
}
Example #27
0
func (m *SqliteStore) load(session *sessions.Session) error {
	row := m.stmtSelect.QueryRow(session.ID)
	sess := sessionRow{}
	scanErr := row.Scan(&sess.id, &sess.data, &sess.createdOn, &sess.modifiedOn, &sess.expiresOn)
	if scanErr != nil {
		return scanErr
	}
	if sess.expiresOn.Sub(time.Now()) < 0 {
		log.Printf("Session expired on %s, but it is %s now.", sess.expiresOn, time.Now())
		return errors.New("Session expired")
	}
	err := securecookie.DecodeMulti(session.Name(), sess.data, &session.Values, m.Codecs...)
	if err != nil {
		return err
	}
	session.Values["created_on"] = sess.createdOn
	session.Values["modified_on"] = sess.modifiedOn
	session.Values["expires_on"] = sess.expiresOn
	return nil

}
Example #28
0
func (m *SqliteStore) New(r *http.Request, name string) (*sessions.Session, error) {
	session := sessions.NewSession(m, name)
	session.Options = &sessions.Options{
		Path:   m.Options.Path,
		MaxAge: m.Options.MaxAge,
	}
	session.IsNew = true
	var err error
	if cook, errCookie := r.Cookie(name); errCookie == nil {
		err = securecookie.DecodeMulti(name, cook.Value, &session.ID, m.Codecs...)
		if err == nil {
			err = m.load(session)
			if err == nil {
				session.IsNew = false
			} else {
				err = nil
			}
		}
	}
	return session, err
}
Example #29
0
File: gothic.go Project: oov/gothic
// CompleteAuth completes the authentication process and fetches all of the
// basic information about the user from the provider.
func CompleteAuth(providerName string, w http.ResponseWriter, r *http.Request) (goth.User, error) {
	provider, err := goth.GetProvider(providerName)
	if err != nil {
		return goth.User{}, err
	}

	c, err := r.Cookie(CookieName)
	if err != nil {
		return goth.User{}, err
	}

	var ss string
	err = securecookie.DecodeMulti(CookieName, c.Value, &ss, codecs...)
	if err != nil {
		return goth.User{}, err
	}

	co := CookieOptions
	co.MaxAge = -1
	http.SetCookie(w, cookie(CookieName, "", &co))

	// verify state
	_, stateUnsupported := StateUnsupportedProvider[providerName]
	if len(ss) < stateLen || (!stateUnsupported && r.URL.Query().Get("state") != ss[:stateLen]) {
		return goth.User{}, errors.New("oauth 2.0 state parameter does not match")
	}

	sess, err := provider.UnmarshalSession(ss[stateLen:])
	if err != nil {
		return goth.User{}, err
	}

	_, err = sess.Authorize(provider, r.URL.Query())
	if err != nil {
		return goth.User{}, err
	}

	return provider.FetchUser(sess)
}
Example #30
0
// load reads the session from redis.
func (s *RediStore) load(session *sessions.Session) error {
	conn := s.Pool.Get()
	defer conn.Close()
	if err := conn.Err(); err != nil {
		return err
	}
	data, err := conn.Do("GET", "session_"+session.ID)
	if err != nil {
		return err
	}
	if data == nil {
		return nil // no data was associated with this key
	}
	str, err := redis.String(data, err)
	if err != nil {
		return err
	}
	if err = securecookie.DecodeMulti(session.Name(), str, &session.Values, s.Codecs...); err != nil {
		return err
	}
	return nil
}