Exemple #1
0
func init() {
	a := []byte(os.Getenv("GOTHIC_COOKIE_AUTH"))
	if len(a) == 0 {
		a = securecookie.GenerateRandomKey(64)
	}

	e := []byte(os.Getenv("GOTHIC_COOKIE_ENCRYPT"))
	if len(e) == 0 {
		codecs = securecookie.CodecsFromPairs(a)
	} else {
		codecs = securecookie.CodecsFromPairs(a, e)
	}
}
Exemple #2
0
func NewPGStore(dbUrl string, keyPairs ...[]byte) *PGStore {
	db, err := sql.Open("postgres", dbUrl)
	dbmap := &gorp.DbMap{Db: db, Dialect: gorp.PostgresDialect{}}

	dbStore := &PGStore{
		Codecs: securecookie.CodecsFromPairs(keyPairs...),
		Options: &sessions.Options{
			Path:   "/",
			MaxAge: 86400 * 30,
		},
		DbMap: dbmap,
	}

	if err != nil {
		// Ignore and return nil
		return nil
	}

	// Create table if it doesn't exist
	dbmap.AddTableWithName(Session{}, "http_sessions").SetKeys(true, "Id")
	err = dbmap.CreateTablesIfNotExists()

	if err != nil {
		// Ignore and return nil
		return nil
	}

	return dbStore
}
Exemple #3
0
func init() {
	godotenv.Load()
	redisClient = storage.RedisClient(os.Getenv("REDIS_ADDR"), os.Getenv("REDIS_PASS"))
	translator = t.NewTranslateAdapter(
		[]backend_full.IBackendFull{
			backend_full.NewGoogleTranslator(httpclient.GetHttpClient(), os.Getenv("G_TR_KEY")),
			backend_full.NewYandexTranslator(httpclient.GetHttpClient(), os.Getenv("Y_TR_KEY")),
			//			backend_full.NewBingTranslator(os.Getenv("B_TR_KEY")),
		},
		components.NewChain(2),
	)
	//translator.AddParticular(&particular.AbbyyLingvoLiveTranslator{})
	if "" == os.Getenv("APP_SECRET") {
		os.Setenv("APP_SECRET", string(securecookie.GenerateRandomKey(32)))
	}
	cookieStore = &sessions.CookieStore{
		Codecs: securecookie.CodecsFromPairs([]byte(os.Getenv("APP_SECRET"))),
		Options: &sessions.Options{
			Path:   "/",
			MaxAge: 86400 * 30 * 10,
			//			Secure:true,
			HttpOnly: true,
		},
	}
}
Exemple #4
0
// NewRediStore returns a new RediStore.
func NewRediStore(size int, network, address, password string, keyPairs ...[]byte) *RediStore {
	return &RediStore{
		// http://godoc.org/github.com/garyburd/redigo/redis#Pool
		Pool: &redis.Pool{
			MaxIdle:     size,
			IdleTimeout: 240 * time.Second,
			Dial: func() (redis.Conn, error) {
				c, err := redis.Dial(network, address)
				if err != nil {
					return nil, err
				}
				if password != "" {
					if _, err := c.Do("AUTH", password); err != nil {
						c.Close()
						return nil, err
					}
				}
				return c, err
			},
			TestOnBorrow: func(c redis.Conn, t time.Time) error {
				_, err := c.Do("PING")
				return err
			},
		},
		Codecs: securecookie.CodecsFromPairs(keyPairs...),
		Options: &sessions.Options{
			Path:   "/",
			MaxAge: sessionExpire,
		},
	}
}
Exemple #5
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)
	}
}
// This function returns a new Redis Sentinel store.
//
// Keys are defined in pairs to allow key rotation, but the common case is
// to set a single authentication key and optionally an encryption key.
//
// The first key in a pair is used for authentication and the second for
// encryption. The encryption key can be set to nil or omitted in the last
// pair, but the authentication key is required in all pairs.
//
// It is recommended to use an authentication key with 32 or 64 bytes.
// The encryption key, if set, must be either 16, 24, or 32 bytes to select
// AES-128, AES-192, or AES-256 modes.
//
// Use the convenience function securecookie.GenerateRandomKey() to create
// strong keys.
func NewSentinelFailoverStore(clientConfig SentinelClientConfig,
	keyPairs ...[]byte) *SentinelFailoverStore {
	client := clientConfig.newSentinelFailoverClient()
	s := &SentinelFailoverStore{
		RediStore: &redistore.RediStore{
			Codecs: securecookie.CodecsFromPairs(keyPairs...),
			Options: &sessions.Options{
				Path:   "/",
				MaxAge: 86400 * 30,
			},
			DefaultMaxAge: 60 * 60, // 60 minutes
			//maxLength:     4096,
			//keyPrefix:     "session_",
			//serializer: redistore.GobSerializer{},
		},
		failoverOption: clientConfig,
		FailoverClient: client,
		maxLength:      4096,
		keyPrefix:      "session_",
		serializer:     redistore.GobSerializer{},
	}

	s.SetMaxLength(s.maxLength)
	s.SetKeyPrefix(s.keyPrefix)
	s.SetSerializer(s.serializer)
	s.MaxAge(s.Options.MaxAge)
	return s
}
// New is returns a store object using the provided dal.Connection
func New(connection dal.Connection, database string, collection string, maxAge int,
	ensureTTL bool, keyPairs ...[]byte) nSessions.Store {
	if ensureTTL {
		conn := connection.Clone()
		defer conn.Close()
		db := conn.DB(database)
		c := db.C(collection)
		c.EnsureIndex(dal.Index{
			Key:         []string{"modified"},
			Background:  true,
			Sparse:      true,
			ExpireAfter: time.Duration(maxAge) * time.Second,
		})
	}
	return &dalStore{
		Codecs:     securecookie.CodecsFromPairs(keyPairs...),
		Token:      nSessions.NewCookieToken(),
		connection: connection,
		database:   database,
		collection: collection,
		options: &gSessions.Options{
			MaxAge: maxAge,
		},
	}
}
Exemple #8
0
// NewCookieStore returns a new CookieStore.
//
// Keys are defined in pairs to allow key rotation, but the common case is
// to set a single authentication key and optionally an encryption key.
//
// The first key in a pair is used for authentication and the second for
// encryption. The encryption key can be set to nil or omitted in the last
// pair, but the authentication key is required in all pairs.
//
// It is recommended to use an authentication key with 32 or 64 bytes.
// The encryption key, if set, must be either 16, 24, or 32 bytes to select
// AES-128, AES-192, or AES-256 modes.
//
// Use the convenience function securecookie.GenerateRandomKey() to create
// strong keys.
func NewCookieStore(keyPairs ...[]byte) *CookieStore {
	return &CookieStore{
		Codecs: securecookie.CodecsFromPairs(keyPairs...),
		Options: &Options{
			Path:   "/",
			MaxAge: 86400 * 30,
		},
	}
}
Exemple #9
0
// NewPGStore initillizes PGStore with the given keyPairs
func NewPGStore(keyPairs ...[]byte) *PGStore {
	dbStore := &PGStore{
		Codecs: securecookie.CodecsFromPairs(keyPairs...),
		Options: &sessions.Options{
			Path:   settings.App.Session.Path,
			MaxAge: settings.App.Session.MaxAge,
		},
	}
	return dbStore
}
func (h *RedisStoreHandler) GetSessionStore() sessions.Store {
	return &RedisStore{
		Codecs: securecookie.CodecsFromPairs(h.keyPairs...),
		Options: &sessions.Options{
			Path:   "/",
			MaxAge: 86400 * 30,
		},
		storeHandler: h,
	}
}
Exemple #11
0
func NewSqliteStoreFromConnection(db *sql.DB, tableName string, path string, maxAge int, keyPairs ...[]byte) (*SqliteStore, error) {
	// Make sure table name is enclosed.
	tableName = "`" + strings.Trim(tableName, "`") + "`"

	cTableQ := "CREATE TABLE IF NOT EXISTS " +
		tableName + " (id INTEGER PRIMARY KEY, " +
		"session_data LONGBLOB, " +
		"created_on TIMESTAMP DEFAULT 0, " +
		"modified_on TIMESTAMP DEFAULT CURRENT_TIMESTAMP, " +
		"expires_on TIMESTAMP DEFAULT 0);"
	if _, err := db.Exec(cTableQ); err != nil {
		return nil, err
	}

	insQ := "INSERT INTO " + tableName +
		"(id, session_data, created_on, modified_on, expires_on) VALUES (NULL, ?, ?, ?, ?)"
	stmtInsert, stmtErr := db.Prepare(insQ)
	if stmtErr != nil {
		return nil, stmtErr
	}

	delQ := "DELETE FROM " + tableName + " WHERE id = ?"
	stmtDelete, stmtErr := db.Prepare(delQ)
	if stmtErr != nil {
		return nil, stmtErr
	}

	updQ := "UPDATE " + tableName + " SET session_data = ?, created_on = ?, expires_on = ? " +
		"WHERE id = ?"
	stmtUpdate, stmtErr := db.Prepare(updQ)
	if stmtErr != nil {
		return nil, stmtErr
	}

	selQ := "SELECT id, session_data, created_on, modified_on, expires_on from " +
		tableName + " WHERE id = ?"
	stmtSelect, stmtErr := db.Prepare(selQ)
	if stmtErr != nil {
		return nil, stmtErr
	}

	return &SqliteStore{
		db:         db,
		stmtInsert: stmtInsert,
		stmtDelete: stmtDelete,
		stmtUpdate: stmtUpdate,
		stmtSelect: stmtSelect,
		Codecs:     securecookie.CodecsFromPairs(keyPairs...),
		Options: &sessions.Options{
			Path:   path,
			MaxAge: maxAge,
		},
		table: tableName,
	}, nil
}
func NewRethinkDBStore(rethinkdbSession *gorethink.Session, db, table string, keyPairs ...[]byte) *RethinkDBStore {
	return &RethinkDBStore{
		Codecs: securecookie.CodecsFromPairs(keyPairs...),
		Options: &sessions.Options{
			Path:   "/",
			MaxAge: 86400 * 30,
		},
		term:             gorethink.Db(db).Table(table),
		rethinkdbSession: rethinkdbSession,
	}
}
Exemple #13
0
func NewDatabaseStore(keyPairs ...[]byte) *DatabaseStore {
	dbStore := &DatabaseStore{
		Codecs: securecookie.CodecsFromPairs(keyPairs...),
		Options: &sessions.Options{
			Path:   "/",
			MaxAge: 86400 * 30,
		},
	}

	return dbStore
}
Exemple #14
0
// NewSessionStore returns a new DbStore.
//
// The path argument is the directory where sessions will be saved. If empty
// it will use os.TempDir().
//
// See NewCookieStore() for a description of the other parameters.
func NewDbStore(age int) *DbStore {
	sessionStore := &DbStore{
		Codecs: securecookie.CodecsFromPairs([]byte("secret")),
		Options: &Options{
			Path:   "/",
			MaxAge: age, //seconds
		},
	}
	go sessionStore.CheckDbSessions()
	return sessionStore
}
Exemple #15
0
// NewRedisStore returns a new RedisStore
func NewRedisStore(pool *redis.Pool, keyPairs ...[]byte) *RedisStore {

	return &RedisStore{
		Codecs: securecookie.CodecsFromPairs(keyPairs...),
		Options: &sessions.Options{
			Path:   "/",
			MaxAge: 86400 * 30,
		},
		redisPool: pool,
	}
}
Exemple #16
0
func NewMemoryStore(age int) *MemoryStore {
	memoryStore := &MemoryStore{
		Codecs: securecookie.CodecsFromPairs([]byte("secret")),
		Options: &sessions.Options{
			Path:   "/",
			MaxAge: age, //default 30 minutes
		},
		Container: make(map[string]*SessionInfo),
	}
	go memoryStore.CheckMemorySessions()
	return memoryStore
}
// Sessions implemented with a dumb in-memory
// map and no expiration.  Good for local
// development so you don't have to run
// memcached on your laptop just to fire up
// your app and hack away.
func NewDumbMemorySessionStore() *DumbMemoryStore {

	keyPair := []byte("stub")

	return &DumbMemoryStore{
		Codecs: securecookie.CodecsFromPairs(keyPair),
		Options: &sessions.Options{
			Path:   "/",
			MaxAge: 86400 * 30,
		},
		Data: make(map[string]string),
	}
}
Exemple #18
0
// NewFilesystemStore returns a new FilesystemStore.
//
// The path argument is the directory where sessions will be saved. If empty
// it will use os.TempDir().
//
// See NewCookieStore() for a description of the other parameters.
func NewFilesystemStore(path string, keyPairs ...[]byte) *FilesystemStore {
	if path == "" {
		path = os.TempDir()
	}
	return &FilesystemStore{
		Codecs: securecookie.CodecsFromPairs(keyPairs...),
		Options: &Options{
			Path:   "/",
			MaxAge: 86400 * 30,
		},
		path: path,
	}
}
// New returns a new session store.
// See https://github.com/gorilla/sessions/blob/master/store.go for what keyPairs means.
// Especially for dynamostore, keyPairs is be used to authenticate session id.
// Yes, the actual data is stored in DynamoDB table.
func New(dynamodbAPI dynamodbiface.DynamoDBAPI, tableName string, keyPairs ...[]byte) *Store {
	// setting DynamoDB table wrapper
	t := table.New(dynamodbAPI, tableName).WithHashKey(SessionIdHashKeyName, "S")

	s := &Store{
		Table:   t,
		Codecs:  securecookie.CodecsFromPairs(keyPairs...),
		Options: DefaultSessionOpts,
	}
	s.MaxAge(s.Options.MaxAge)

	return s
}
Exemple #20
0
// 新建cookie存储仓
func newCookieStore(keyPairs ...[]byte) *sessions.CookieStore {
	cs := &sessions.CookieStore{
		Codecs: securecookie.CodecsFromPairs(keyPairs...),
		Options: &sessions.Options{
			Path:     "/",
			MaxAge:   0, // 只存为会话,关闭则失效
			HttpOnly: true,
		},
	}

	cs.MaxAge(cs.Options.MaxAge)
	return cs
}
Exemple #21
0
// NewDatastoreStore returns a new DatastoreStore.
//
// The kind argument is the kind name used to store the session data.
// If empty it will use "Session".
//
// See NewCookieStore() for a description of the other parameters.
func NewDatastoreStore(kind string, nonPersistentSessionDuration time.Duration, keyPairs ...[]byte) *DatastoreStore {
	if kind == "" {
		kind = "Session"
	}
	return &DatastoreStore{
		Codecs: securecookie.CodecsFromPairs(keyPairs...),
		Options: &sessions.Options{
			Path:   "/",
			MaxAge: 86400 * 30,
		},
		kind: kind,
		nonPersistentSessionDuration: nonPersistentSessionDuration,
	}
}
Exemple #22
0
// NewMemcacheStore returns a new MemcacheStore.
//
// The keyPrefix argument is the prefix used for memcache keys. If empty it
// will use "gorilla.appengine.sessions.".
//
// See NewCookieStore() for a description of the other parameters.
func NewMemcacheStore(keyPrefix string, nonPersistentSessionDuration time.Duration, keyPairs ...[]byte) *MemcacheStore {
	if keyPrefix == "" {
		keyPrefix = "gorilla.appengine.sessions."
	}
	return &MemcacheStore{
		Codecs: securecookie.CodecsFromPairs(keyPairs...),
		Options: &sessions.Options{
			Path:   "/",
			MaxAge: 86400 * 30,
		},
		prefix: keyPrefix,
		nonPersistentSessionDuration: nonPersistentSessionDuration,
	}
}
Exemple #23
0
func NewLevelDBStore(path string) (LevelDBStore, error) {
	ldb, err := leveldb.OpenFile(path, nil)
	if err != nil {
		return nil, err
	}
	return &leveldbStore{
		db: ldb,
		options: &sessions.Options{
			Path:   "/",
			MaxAge: sessionExpire,
		},
		Codecs: securecookie.CodecsFromPairs([]byte("b80cbe50-6e0d-4dec-ad30-c3480ff79292")),
	}, nil
}
Exemple #24
0
// NewRediStoreWithPool instantiates a RediStore with a *redis.Pool passed in.
func NewRediStoreWithPool(pool *redis.Pool, keyPairs ...[]byte) (*RediStore, error) {
	rs := &RediStore{
		// http://godoc.org/github.com/garyburd/redigo/redis#Pool
		Pool:   pool,
		Codecs: securecookie.CodecsFromPairs(keyPairs...),
		Options: &sessions.Options{
			Path:   "/",
			MaxAge: sessionExpire,
		},
		DefaultMaxAge: 60 * 20, // 20 minutes seems like a reasonable default
		maxLength:     4096,
	}
	_, err := rs.ping()
	return rs, err
}
Exemple #25
0
// NewStore creates a new *Store instance.
func NewStore(db *gorm.DB, config *Config, keyPairs ...[]byte) *Store {
	q := &query{}
	q.DB = db
	return &Store{
		q:      q,
		codecs: securecookie.CodecsFromPairs(keyPairs...),
		options: &sessions.Options{
			Path:     config.SessionPath,
			Domain:   config.SessionDomain,
			MaxAge:   config.SessionMaxAge,
			Secure:   config.SessionSecure,
			HttpOnly: config.SessionHTTPOnly,
		},
	}
}
Exemple #26
0
// New creates and returns a session store.
func New(db *bolt.DB, config Config, keyPairs ...[]byte) (*Store, error) {
	config.setDefault()
	store := &Store{
		codecs: securecookie.CodecsFromPairs(keyPairs...),
		config: config,
		db:     db,
	}
	err := db.Update(func(tx *bolt.Tx) error {
		_, err := tx.CreateBucketIfNotExists(config.DBOptions.BucketName)
		return err
	})
	if err != nil {
		return nil, err
	}
	return store, nil
}
func NewDynamoStoreWithRegionObj(accessKey string, secretKey string, tableName string, region aws.Region, keyPairs ...[]byte) (*DynamoStore, error) {
	awsAuth := aws.Auth{
		AccessKey: accessKey,
		SecretKey: secretKey,
	}

	server := dynamodb.New(awsAuth, region)
	table := server.NewTable(tableName, dynamodb.PrimaryKey{KeyAttribute: dynamodb.NewStringAttribute("Id", "")})

	dynStore := &DynamoStore{
		Table:  table,
		Codecs: securecookie.CodecsFromPairs(keyPairs...),
	}

	return dynStore, nil
}
// NewMemcacheStore returns a new MemcacheStore.
// You need to provide the memcache client and
// an optional prefix for the keys we store
func NewMemcacheStore(client *memcache.Client, keyPrefix string, keyPairs ...[]byte) *MemcacheStore {

	if client == nil {
		panic("Cannot have nil memcache client")
	}

	return &MemcacheStore{
		Codecs: securecookie.CodecsFromPairs(keyPairs...),
		Options: &sessions.Options{
			Path:   "/",
			MaxAge: 86400 * 30,
		},
		KeyPrefix:   keyPrefix,
		Client:      client,
		StoreMethod: StoreMethodSecureCookie,
	}
}
Exemple #29
0
// NewSessionStore returns a new FileStore.
//
// The path argument is the directory where sessions will be saved. If empty
// it will use os.TempDir().
//
// See NewCookieStore() for a description of the other parameters.
func NewFileStore(age int) *FileStore {
	path := "."
	if path[len(path)-1] != '/' {
		path += "/"
	}
	sessionStore := &FileStore{
		Codecs: securecookie.CodecsFromPairs([]byte("secret")),
		Options: &Options{
			Path: "/",
			//			MaxAge: 86400 * 30,
			MaxAge: age, //30 minutes
		},
		path: path,
	}
	go sessionStore.CheckFileSessions()
	return sessionStore
}
Exemple #30
0
// NewRethinkStore returns a new RethinkStore.
//
// Takes in the database address, database name, session table,
// max idle connections, max open connections, and session key pairs.
func NewRethinkStore(addr, db, table string, idle, open int, keyPairs ...[]byte) (*RethinkStore, error) {
	session, err := r.Connect(r.ConnectOpts{
		Address:  addr,
		Database: db,
		MaxIdle:  idle,
		MaxOpen:  open,
	})
	if err != nil {
		return nil, err
	}
	return &RethinkStore{
		Rethink: session,
		Table:   table,
		Codecs:  securecookie.CodecsFromPairs(keyPairs...),
		Options: &sessions.Options{
			Path:   "/",
			MaxAge: sessionExpire,
		},
	}, nil
}