GithubHelp home page GithubHelp logo

sessions's People

Contributors

andrewfrench avatar appleboy avatar bos-hieu avatar ddaza avatar dependabot[bot] avatar easonlin404 avatar farmerchillax avatar jmcshane avatar karpawich avatar ktogo avatar maerics avatar micanzhang avatar nerney avatar ota42y avatar ralese avatar rubensayshi avatar saschat avatar silvercory avatar slayercat avatar thedevsaddam avatar thinkerou avatar tockn avatar vincentinttsh avatar vuon9 avatar xuyang2 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

sessions's Issues

How to set `expires` of the cookie?

I use cookie store.

store := sessions.NewCookieStore([]byte("secret"))

How to change the expires of the cookie when I save the session?

session.Set("xxx", "i need to change expires.")
session.Save()

Access Session.IsNew

I want to be able to access the underlying gorilla Session to check the IsNew bool so I can write a middleware that checks for current session. When I “end a session”, if I use the old cookie 🍪 from before logout it will still work.
Expiring token, clearing fields, and saving is not making old cookies fail for same session.

Any help on this error "Key github.com/gin-contrib/sessions does not exist"

I am using this function here
But when I use session in controller/handler it show the error "Key github.com/gin-contrib/sessions does not exist"

Controller code:

session := sessions.Default(c)
		var count int
		v := session.Get("count")
		if v == nil {
			count = 0
		} else {
			count = v.(int)
			count++
		}
		session.Set("count", count)
		session.Save()
		c.JSON(200, gin.H{"count": count})

Any idea or help. Thanks in advance :)

[HELP] can not get passed on authentication

any tip? l can't store my data into session! I come from Iris, code below go down after I turning to Gin Appreciate your patience and suggestion

package main

import (
	"log"
	"strings"
	"net/http"
	"fmt"

	"github.com/gin-contrib/sessions"
	"github.com/gin-gonic/gin"
	"storage"

	. "utils"
	"github.com/robvdl/pongo2gin"
	"github.com/flosch/pongo2"
)

func IsLoginedGroup(group string) gin.HandlerFunc {
	groups := strings.Split(group, "|")    //  OM|GPD|Admin

	return func(ctx *gin.Context) {
		session := sessions.Default(ctx)

		var is_login bool

		value := session.Get("is_authenticated")
		if v, ok := value.(bool); ok {
			is_login = v
		} else {
			is_login = false
		}

		value = session.Get("group")
		if v, ok := value.(string); ok {
			if v != "Admin" {
				if !Contains(groups, v) {
					is_login = false
				}
			}
		} else {
			is_login = false
		}

		value = session.Get("is_root")
		if v, ok := value.(bool); ok && v == true {
			is_login = v
		}

		if !is_login {
			session.Set("orginal", ctx.Request.RequestURI)
			session.Save()

			ctx.Redirect(http.StatusFound, "/login")

			ctx.Abort()
		}

		ctx.Next()
	}
}


///////////////////////////////////////////////////////
func Login(ctx *gin.Context) {
	session := sessions.Default(ctx)
	var error_msg string

	switch ctx.Request.Method {
	case "POST":
		username := ctx.PostForm("username")
		password := ctx.PostForm("password")

		if username != "" && password != "" {
			db := storage.DB

			var n int
			db.Model(&storage.User{}).Where("Username = ?", username).Count(&n)
			if n == 0 {
				error_msg = fmt.Sprintf("username %s don't exist", username)
			}

			if error_msg == "" {
				var group string
				u := storage.User{}
				db.Where("Username = ?", username).Find(&u)

				if err := u.Login(password); err != nil {
					error_msg = err.Error()
				} else {
					if u.GroupId != 0 {
						g := storage.Group{}
						db.Where("ID = ?", u.GroupId).Find(&g)
						group = g.Name
					}

					session.Set("user", u)
					session.Set("group", group)
					session.Set("is_authenticated", true)
					session.Set("is_root", u.IsRoot)
					session.Save()

					if orgin, ok := session.Get("orginal").(string); ok {
						log.Println("131", orgin, "original")
						session.Delete("orginal")
						session.Save()

						ctx.Redirect(http.StatusSeeOther, orgin)
						return
					} else {
						ctx.Redirect(http.StatusSeeOther, "/")
						return
					}
				}
			}
		}
	default:

	}

	ctx.HTML(http.StatusOK, "login.html", pongo2.Context{
		"pagetitle": "Login",
		"tip": error_msg,
	})
}

func main() {
	r := gin.Default()

	r.HTMLRender = pongo2gin.Default()

	store := sessions.NewCookieStore([]byte("secret"))
	r.Use(sessions.Sessions("mysession", store))

	r.GET("/login", Login)
	r.POST("/login", Login)

	r.GET("/test", func(c *gin.Context) {
		session := sessions.Default(c)
		v := session.Get("count")
		if count, ok := v.(int); ok{
			//session.Clear()
			//session.Save()
			c.JSON(200, gin.H{"count": count})
		}
	})

	r.GET("/incr", IsLoginedGroup("OM"), func(c *gin.Context) {
		session := sessions.Default(c)

		var count int
		v := session.Get("count")
		if v == nil {
			count = 0
		} else {
			count = v.(int)
			count++
		}
		session.Set("count", count)
		session.Save()
		c.JSON(200, gin.H{"count": count})
	})


	r.Run(":8000")
}

Session no longer working with OAuth package?

I try to run this tutorial here, the "Putting it All Together" section:
https://skarlso.github.io/2016/06/12/google-signin-with-go/

This code:

func authHandler(c *gin.Context) {
	// Handle the exchange code to initiate a transport.
	session := sessions.Default(c)
	retrievedState := session.Get("state")
	if retrievedState != c.Query("state") {
		c.AbortWithError(http.StatusUnauthorized, fmt.Errorf("Invalid session state: %s", retrievedState))
		return
	}

fails, with Invalid Session State error being triggered. The value of session.Get("state") is nil.

Steps to Reproduce:
Copy the code from this tutorial to a new folder, call it main.go.
Create a file called creds.json with your google-auth credentials.
Run the code from this tutorial, taking out the templates/* section if that folder doesn't exist.
curl http://127.0.0.1:9090/login will return you a URL. Go to this URL, log in, and then inspect the output of your Go terminal.

I have made a mistake in the case.

error msg

cannot use store (type cookie.Store) as type "shop/vendor/github.com/gin-contrib/sessions".Store in argument to "shop/vendor/github.com/gin-contrib/sessions".Sessions

code detail

router := gin.Default()
store := cookie.NewStore([]byte("secret"))
router.Use(sessions.Sessions("mysession", store))

Unable to allow cookie subdomains using options.Domain

When trying to allow subdomains using options

   store.Options(sessions.Options{
      Domain: ".foo.bar.baz",
    })

The response is sent to the browser w/o the leading period
I.E.

Set-Cookie:test=......; Domain=foo.bar.baz

Desired behavior: allow leading periods, so the browser will respect the cookie across subdomains

Deleting session from the redis db!

Is there a way to delete the session of the user after it's no longer needed? I've tried session.Clear(), but it still leaves the session id in the database. Could this be fixed?

Gin Gonic sessions still using old path for two libraries

Hi,

I see two issues when we try to download and build our project with gin gonic sessions.

a) Sessions is still using "github.com/boj/redistore" whereas this module has moved to "gopkg.in/boj/redistore.v1" due to which it is not sure if some fixes in the new path are there in the old path or not

b) gin-contrib/sessions/redis/redis.go still refers to "github.com/garyburd/redigo/redis" whereas this library as moved to "github.com/gomodule/redigo/redis"

If these two could be updated, it would avoid manual change whenever moving to a new system.

This is my first query in github.com and so I am sorry if this doesn't classify as an issue or it has to be raised in a different way.

go mod required

go.mod: golang.org/x maybe change
golang.org/x ==>godoc.org/golang.org/x
or golang.org/x ==>github.com/golang ( use the mirror, better)

Hook for session create

Hi - is there a way to configure a handler/hook for when a new session is created? We want to create a special logging and db write perhaps for analyzing initial bounce rates for example (before someone may have logged in). Please let me know, thank you!

Pings

Every time a Get/Set is called it pings the redis server first which is a huge waste of time. This is happening because every Get/Set request calls NewRediStore from redistore and that causes a ping.

From my understanding it should only be calling NewRediStore on boot since that is when it makes the pool, not every request.

Thanks!
Spencer

Delete sessions by value

So, let's say I create a session and save the username to the session, which I then use throughout my api. Any user can have multiple sessions. Then, let's say they change their username. Now, if someone changes their username to the username they previously had, as the usernames are the primary key, they now have access to the new user with that username. So:

  1. User a creates username tom
  2. tom is saved to session
  3. tom changes username to zeke
  4. new user creates account with username tom
  5. zeke now has access to tom's account information, because he has a session with the username value set to tom.

So, I guess I can just make a SERIAL key as the session id, but that still leaves the problem of any session data saved will be stale if it changes, like username. So, is there any way to get all session with the id value set to 1234 example, or do I just need to retrieve all data from the database, just in case it has changed, even if it doesn't change very often?

Why vendoring ?

It is preferred not to store any 3rd party packages in vendor when you do not have any main package as this will lead to un-usability of this package.

Here is the issue I have faced. My repo does not vendor any packages.

/router.go:33: cannot use "github.com/gin-contrib/sessions".Sessions("cpsession", store) 
(type "github.com/gin-contrib/sessions/vendor/github.com/gin-gonic/gin".HandlerFunc) as 
type "github.com/gin-gonic/gin".HandlerFunc in argument to router.Use

Maybe use a gopkg for gin-gonic?

Using tagged gin-gonic like go get gopkg.in/gin-gonic/gin.v1 is much preferred since these releases are considered stable over current develop and also applications using this library and prefers gopkg will not have duplicate libs with different import paths

If agreed, can give a PR with the change

Call Save() in the middleware?

As far as I can tell, the sessions middleware that is provided in this package, aka gin.HandlerFunc doesn't call the Save() method after the rest of the middleware stack has ran, I can't think of a real reason to not save at this point (I've resorted to creating my own middleware that I insert into the stack after the sessions one to automatically call save.

This is currently the middleware:

func Sessions(name string, store Store) gin.HandlerFunc {
	return func(c *gin.Context) {
		s := &session{name, c.Request, store, nil, false, c.Writer}
		c.Set(DefaultKey, s)
		defer context.Clear(c.Request)
		c.Next()
	}
}

In my eyes, after the c.Next() we'd call s.Save() to actually persist any changes to the session. Thoughts?

import errors.

error:

cannot use "github.com/goiotc/vendor/github.com/gin-contrib/sessions".Sessions("mysession", store) (type "github.com/goiotc/vendor/gopkg.in/gin-gonic/gin.v1".HandlerFunc) as type "github.com/goiotc/vendor/github.com/gin-gonic/gin".HandlerFunc in argument to router.Use

How to change the value of redis

The user's role is saved in the session, the session is stored in redis.
I want to change the role of the user in role management.
How can i do it?

type not registered for interface

if queryUser.CheckPassword(userData.Password) {
		if queryUser.Status == model.UserStatusInActive {
			encodedEmail := base64.StdEncoding.EncodeToString([]byte(queryUser.Email))
			c.JSON(http.StatusOK, gin.H{
				"retCode": model.SUCCESS,
				"retContent": gin.H{
					"email": encodedEmail,
				},
			})
			return
		}

		session := sessions.Default(c)

		session.Set("user", queryUser.ID)
		ok:=session.Save()
		log.Debug("save ok :%v",ok)
		c.JSON(http.StatusOK, gin.H{
			"retCode": model.SUCCESS,
			"retContent": gin.H{
				"data": queryUser,
			},
		})
	}

log print:
save ok :gob : type not registered for interface :model.User
why i cann't save it?only int ?

Error

So, I'm geting this error...it looks like someone was devleoping and used the wrong repo that was probably temporary...Is there any way I can fix this? Also, is there a stable branch I can use for sure, or do I need to specify a specific commit? It might be wise to have a dev branch for potentially breaking changes

# github.com/gin-contrib/sessions/redis
../../gin-contrib/sessions/redis/redis.go:51:42: cannot use pool (type *"github.com/garyburd/redigo/redis".Pool) as type *"github.com/gomodule/redigo/redis".Pool in argument to redistore.NewRediStoreWithPool

undefined: "github.com/gin-contrib/sessions".NewRedisStore

Hi, Faced such a problem

go build 
undefined: "github.com/gin-contrib/sessions".NewRedisStore
        router := gin.Default()
        store, _ := sessions.NewRedisStore(10, "tcp", "localhost:6379", "", []byte("secret"))
        router.Use(sessions.Sessions("session", store))
        //store := sessions.NewCookieStore([]byte("secret"))

        store.Options(sessions.Options{
                MaxAge: 30 * 60, //30mins
                Path:   "/",
        })

Key "github.com/gin-contrib/sessions" does not exist

I am trying to write a middleware for auth checking :

package utils

import (
	"net/http"
	"strings"

	"github.com/gin-contrib/sessions"
	"github.com/gin-gonic/gin"
	//"log"
)

func AuthMiddleware() gin.HandlerFunc  {
	return func(c *gin.Context) {
		if strings.HasPrefix(c.Request.URL.Path, "/login") ||
			strings.HasPrefix(c.Request.URL.Path, "/signup") {
			return
		}
		if strings.HasPrefix(c.Request.URL.Path, "/static") {
			return
		}

		session := sessions.Default(c)
		bunny := session.Get("authenticated")
		if bunny == nil || bunny == false {
			c.Redirect(http.StatusPermanentRedirect, "/")
		} else {
			c.Next()
		}

	}
}

and main.go :

func main() {
	router := gin.Default()
	router.Use(helmet.Default())
	router.Use(gzip.Gzip(gzip.BestCompression))
	router.Use(utils.AuthMiddleware())
 .............

When I run the app I got this error:

2017/12/28 21:25:14 [Recovery] panic recovered:
GET /dashboard/ HTTP/1.1
Host: localhost:8000
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.5
Connection: keep-alive
Cookie: csrftoken=09GUULqjFZS35Nwdqu2U8Nz10qUc3fEejscY8qkY0k7tne8dnStBVMGsKQ77Lu6A
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:57.0) Gecko/20100101 Firefox/57.0


Key "github.com/gin-contrib/sessions" does not exist
/home/prism/go/src/runtime/panic.go:491 (0x42b702)
        gopanic: reflectcall(nil, unsafe.Pointer(d.fn), deferArgs(d), uint32(d.siz), uint32(d.siz))
/home/prism/Desktop/code/golang/src/github.com/gin-gonic/gin/context.go:200 (0x8f0fd2)
        (*Context).MustGet: panic("Key \"" + key + "\" does not exist")
/home/prism/Desktop/code/golang/src/github.com/gin-contrib/sessions/sessions.go:146 (0x93b66f)
        Default: return c.MustGet(DefaultKey).(Session)
/home/prism/Desktop/code/golang/src/github.com/pyprism/Hiren-UpBot/utils/login.go:22 (0x93c4cc)
        AuthMiddleware.func1: session := sessions.Default(c)
/home/prism/Desktop/code/golang/src/github.com/gin-gonic/gin/context.go:107 (0x8f0952)
        (*Context).Next: c.handlers[c.index](c)
/home/prism/Desktop/code/golang/src/github.com/gin-contrib/gzip/gzip.go:47 (0x905df5)
        Gzip.func2: c.Next()
/home/prism/Desktop/code/golang/src/github.com/gin-gonic/gin/context.go:107 (0x8f0952)
        (*Context).Next: c.handlers[c.index](c)
/home/prism/Desktop/code/golang/src/github.com/gin-gonic/gin/recovery.go:46 (0x902c29)
        RecoveryWithWriter.func1: c.Next()
/home/prism/Desktop/code/golang/src/github.com/gin-gonic/gin/context.go:107 (0x8f0952)
        (*Context).Next: c.handlers[c.index](c)
/home/prism/Desktop/code/golang/src/github.com/gin-gonic/gin/logger.go:83 (0x901f5b)
        LoggerWithWriter.func1: c.Next()
/home/prism/Desktop/code/golang/src/github.com/gin-gonic/gin/context.go:107 (0x8f0952)
        (*Context).Next: c.handlers[c.index](c)
/home/prism/Desktop/code/golang/src/github.com/gin-gonic/gin/gin.go:352 (0x8f9a65)
        (*Engine).handleHTTPRequest: c.Next()
/home/prism/Desktop/code/golang/src/github.com/gin-gonic/gin/gin.go:319 (0x8f91fa)
        (*Engine).ServeHTTP: engine.handleHTTPRequest(c)
/home/prism/go/src/net/http/server.go:2619 (0x671323)
        serverHandler.ServeHTTP: handler.ServeHTTP(rw, req)
/home/prism/go/src/net/http/server.go:1801 (0x66d46c)
        (*conn).serve: serverHandler{c.server}.ServeHTTP(w, w.req)
/home/prism/go/src/runtime/asm_amd64.s:2337 (0x459980)
        goexit: BYTE    $0x90   // NOP

[GIN-debug] [WARNING] Headers were already written. Wanted to override status code 200 with 500
[GIN] 2017/12/28 - 21:25:14 | 500 |   62.082686ms |             ::1 | GET      /dashboard/

any idea how to solve this error ?

Delete() is not working as expected

I have a logout route where I delete every session key :

func Logout(c *gin.Context) {
	session := sessions.Default(c)
	session.Delete("username")
	session.Delete("authenticated")
	session.Save()
	c.Redirect(http.StatusMovedPermanently, "/")
}

and a home view :

func Home(c *gin.Context) {
	session := sessions.Default(c)
	bunny := session.Get("authenticated")
	log.Println(bunny)  
	c.HTML(http.StatusOK, "home.tmpl", gin.H{"title": "home"})
}

main.go

func main() {
	router := gin.Default()

	//middleware
	router.Use(helmet.Default())
	router.Use(gzip.Gzip(gzip.BestCompression))
	router.Static("/static", "./static")
	router.LoadHTMLGlob("templates/*")

	// cookie based session
	store := sessions.NewCookieStore([]byte(viper.GetString("secret_key")))
	router.Use(sessions.Sessions("bunny", store))
	router.Use(utils.AuthMiddleware())

	// routers
	router.GET("/", views.Login)
	router.POST("/", views.Login)
	router.GET("/logout/", views.Logout)
	router.GET("/dashboard/", views.Home)

After logout If I visit home view the bunny variable printing true which I previously set during login.
So some how session.Delete() is not working . How to delete session key in Logout properly ?

How to set cookie base session manually

I am writing a unit test, and my program using github.com/gin-contrib/sessions with cookie. The testing function handles an HTTP POST, and client should send POST request with session cookie, however, this cookie is got from another POST request, now the unit test is fail because it doesn't have the session cookie. So I want to set session manually to finish the unit test, but I don't know how to do it. Anyone could help me?

[Suggestion] Separate “Store”s using external packages

Problem

Now this package depends on many external packages such as redistore, memcache, mongoDB that are not needed for everyone. Even if you simply want to use cookie store, you must wait to fetch all of them. It is annoying.

Simply go getting example

go get -v github.com/gin-contrib/sessions
github.com/gin-contrib/sessions (download)
github.com/boj/redistore (download)
github.com/garyburd/redigo (download)
github.com/gorilla/securecookie (download)
github.com/gorilla/sessions (download)
github.com/gorilla/context (download)
github.com/bradfitz/gomemcache (download)
github.com/bradleypeabody/gorilla-sessions-memcache (download)
github.com/gin-gonic/gin (download)
github.com/gin-contrib/sse (download)
github.com/golang/protobuf (download)
github.com/ugorji/go (download)
Fetching https://gopkg.in/go-playground/validator.v8?go-get=1
Parsing meta tags from https://gopkg.in/go-playground/validator.v8?go-get=1 (status code 200)
get "gopkg.in/go-playground/validator.v8": found meta tag get.metaImport{Prefix:"gopkg.in/go-playground/validator.v8", VCS:"git", RepoRoot:"https://gopkg.in/go-playground/validator.v8"} at https://gopkg.in/go-playground/validator.v8?go-get=1
gopkg.in/go-playground/validator.v8 (download)
Fetching https://gopkg.in/yaml.v2?go-get=1
Parsing meta tags from https://gopkg.in/yaml.v2?go-get=1 (status code 200)
get "gopkg.in/yaml.v2": found meta tag get.metaImport{Prefix:"gopkg.in/yaml.v2", VCS:"git", RepoRoot:"https://gopkg.in/yaml.v2"} at https://gopkg.in/yaml.v2?go-get=1
gopkg.in/yaml.v2 (download)
github.com/mattn/go-isatty (download)
github.com/kidstuff/mongostore (download)
Fetching https://gopkg.in/mgo.v2?go-get=1
Parsing meta tags from https://gopkg.in/mgo.v2?go-get=1 (status code 200)
get "gopkg.in/mgo.v2": found meta tag get.metaImport{Prefix:"gopkg.in/mgo.v2", VCS:"git", RepoRoot:"https://gopkg.in/mgo.v2"} at https://gopkg.in/mgo.v2?go-get=1
gopkg.in/mgo.v2 (download)
Fetching https://gopkg.in/mgo.v2/bson?go-get=1
Parsing meta tags from https://gopkg.in/mgo.v2/bson?go-get=1 (status code 200)
get "gopkg.in/mgo.v2/bson": found meta tag get.metaImport{Prefix:"gopkg.in/mgo.v2", VCS:"git", RepoRoot:"https://gopkg.in/mgo.v2"} at https://gopkg.in/mgo.v2/bson?go-get=1
get "gopkg.in/mgo.v2/bson": verifying non-authoritative meta tag
Fetching https://gopkg.in/mgo.v2?go-get=1
Parsing meta tags from https://gopkg.in/mgo.v2?go-get=1 (status code 200)
github.com/garyburd/redigo/internal
github.com/mattn/go-isatty
github.com/gorilla/securecookie
github.com/gorilla/context
github.com/bradfitz/gomemcache/memcache
github.com/garyburd/redigo/redis
github.com/gin-contrib/sse
github.com/gorilla/sessions
github.com/gin-gonic/gin/json
github.com/golang/protobuf/proto
github.com/ugorji/go/codec
github.com/bradleypeabody/gorilla-sessions-memcache
github.com/boj/redistore
gopkg.in/go-playground/validator.v8
gopkg.in/yaml.v2
gopkg.in/mgo.v2/internal/json
gopkg.in/mgo.v2/internal/scram
gopkg.in/mgo.v2/bson
gopkg.in/mgo.v2
github.com/kidstuff/mongostore
github.com/gin-gonic/gin/render
github.com/gin-gonic/gin/binding
github.com/gin-gonic/gin
github.com/gin-contrib/sessions

dep example

minimal main.go
package main

import (
    "github.com/gin-contrib/sessions"
    "github.com/gin-gonic/gin"
)

func main() {
    r := gin.New()
    store := sessions.NewCookieStore([]byte("hogehoge"))
    r.Use(sessions.Sessions("hoge", store))
    r.Run(":8080")
}

dep inited and it shows it has unnecessary packages in vendor.

PROJECT                                              CONSTRAINT     VERSION        REVISION  LATEST   PKGS USED
github.com/boj/redistore                             v1.2           v1.2           fc11376   v1.2     1
github.com/bradfitz/gomemcache                       branch master  branch master  1952afa   1952afa  1
github.com/bradleypeabody/gorilla-sessions-memcache  branch master  branch master  75ee37d   75ee37d  1
github.com/garyburd/redigo                           v1.6.0         v1.6.0         a69d193   v1.6.0   2
github.com/gin-contrib/sessions                      branch master  branch master  fda3be6   fda3be6  1
github.com/gin-contrib/sse                           branch master  branch master  22d885f   22d885f  1
github.com/gin-gonic/gin                             ^1.2.0         v1.2           d459835   v1.2     3
github.com/golang/protobuf                           v1.0.0         v1.0.0         9255415   v1.0.0   1
github.com/gorilla/context                           v1.1           v1.1           1ea2538   v1.1     1
github.com/gorilla/securecookie                      v1.1.1         v1.1.1         e59506c   v1.1.1   1
github.com/gorilla/sessions                          v1.1           v1.1           ca9ada4   v1.1     1
github.com/kidstuff/mongostore                       branch master  branch master  db2a8b4   db2a8b4  1
github.com/mattn/go-isatty                           v0.0.3         v0.0.3         0360b2a   v0.0.3   1
github.com/ugorji/go                                 v1.1.1         v1.1.1         b4c50a2   v1.1.1   1
golang.org/x/sys                                     branch master  branch master  79b0c68   79b0c68  1
gopkg.in/go-playground/validator.v8                  v8.18.2        v8.18.2        5f1438d   v8.18.2  1
gopkg.in/mgo.v2                                      branch v2      branch v2      3f83fa5   3f83fa5  5
gopkg.in/yaml.v2                                     v2.2.1         v2.2.1         5420a8b   v2.2.1   1

But using my forked repo, they disappears successfully.

minimal main.go with my forked repo
package main

import (
    "github.com/delphinus/sessions"
    "github.com/gin-gonic/gin"
)

func main() {
    r := gin.New()
    store := sessions.NewCookieStore([]byte("hogehoge"))
    r.Use(sessions.Sessions("hoge", store))
    r.Run(":8080")
}
PROJECT                              CONSTRAINT     VERSION        REVISION  LATEST   PKGS USED
github.com/delphinus/sessions        branch master  branch master  9830bc2   9830bc2  1
github.com/gin-contrib/sse           branch master  branch master  22d885f   22d885f  1
github.com/gin-gonic/gin             ^1.2.0         v1.2           d459835   v1.2     3
github.com/golang/protobuf           v1.0.0         v1.0.0         9255415   v1.0.0   1
github.com/gorilla/context           v1.1           v1.1           1ea2538   v1.1     1
github.com/gorilla/securecookie      v1.1.1         v1.1.1         e59506c   v1.1.1   1
github.com/gorilla/sessions          v1.1           v1.1           ca9ada4   v1.1     1
github.com/mattn/go-isatty           v0.0.3         v0.0.3         0360b2a   v0.0.3   1
github.com/ugorji/go                 v1.1.1         v1.1.1         b4c50a2   v1.1.1   1
golang.org/x/sys                     branch master  branch master  79b0c68   79b0c68  1
gopkg.in/go-playground/validator.v8  v8.18.2        v8.18.2        5f1438d   v8.18.2  1
gopkg.in/yaml.v2                     v2.2.1         v2.2.1         5420a8b   v2.2.1   1

Suggestion

So I suggest that codes of all external store, MongoStore, RedisStore, MemcachedStore, should be separated in individual repositories.

  • At first, I will PR for gin-contrib/sessions with removing such “Store”s.
  • I want admins to create separated repositories.
    • github.com/gin-contrib/mongostore
    • github.com/gin-contrib/redisstore
    • github.com/gin-contrib/memcachedstore

kidstuff/mongostore is outdated

It seems kidstuff/mongostore is outdated

github.com/gin-contrib/sessions/mongo

../gin-contrib/sessions/mongo/mongo.go:15:40: cannot use c (type *"gopkg.in/mgo.v2".Collection) as type *"github.com/globalsign/mgo".Collection in argument to mongostore.NewMongoStore

how to know which client is who?

From the example, I know how to get the "count" from the session,
but how do I know which client is connect to the server?
For example, there are A and B user connect to the server. I suppose that I have to identify the connection is A or B.

call Save get error

This is my code snippet:

store := sessions.NewCookieStore([]byte("secret"))
router.Use(sessions.Sessions("test", store))
session := sessions.Default(context)
session.Set("uid", session)
if err := session.Save(); err != nil {
	log.Errorf("failed to save session, error: %+v", err)
}

i get this error:

securecookie: error - caused by: securecookie: error - caused by: gob: type not registered for interface: sessions.session

Is this a bug or my code is not completed?

About the error eater.

In real production, every error is important, but this project eats some errors:

func (s *session) Session() *sessions.Session {
	if s.session == nil {
		var err error
		s.session, err = s.store.Get(s.request, s.name)
		// error eater here
		if err != nil {
			log.Printf(errorFormat, err)
		}
	}
	return s.session
}

and it makes whole Session interface not reliable:

type Session interface {
	// Get returns the session value associated to the given key.
	Get(key interface{}) interface{}
	// Set sets the session value associated to the given key.
	Set(key interface{}, val interface{})
	// Delete removes the session value associated to the given key.
	Delete(key interface{})
	// Clear deletes all values in the session.
	Clear()
	// AddFlash adds a flash message to the session.
	// A single variadic argument is accepted, and it is optional: it defines the flash key.
	// If not defined "_flash" is used by default.
	AddFlash(value interface{}, vars ...string)
	// Flashes returns a slice of flash messages from the session.
	// A single variadic argument is accepted, and it is optional: it defines the flash key.
	// If not defined "_flash" is used by default.
	Flashes(vars ...string) []interface{}
	// Options sets confuguration for a session.
	Options(Options)
	// Save saves all sessions used during the current request.
	Save() error
}

so, in my project, i do need to rewrite it to get the error of memcached/redis server down, and make sure our users will not get any broken contents.

maybe golang's error is realy boring, but an error eater would be a serious problem too.

i'd forked and modified it to match my project's requirement: commit record

How to use flashes in a template?

I can't seem to find an example of how to do this. My method feels like a hack.

I've got my login handler, and I want to show errors if authentication fails. So I'm adding the error to session via AddFlash(). I understand that once the flashes are read from, they are no longer available.

func login(c *gin.Context) {

	username := c.PostForm("username")
	password := c.PostForm("password")

	u := &User{}

	if err := db.Where("username = ? AND password = ?", username, password).First(&u); err != nil {
		session := sessions.Default(c)
		session.AddFlash(err.Error)
		session.Save()
		c.HTML(http.StatusOK, "login.html", gin.H{
			"title": "Login", "session": session,  // SHOULD I HAVE TO PASS SESSION TO MY TEMPLATE?!
		})
	} else {
		session := sessions.Default(c)
		session.Set("user", u.ID)
		session.Save()
		c.HTML(http.StatusOK, "index.html", gin.H{
			"title": "Login", "user": u,
		})
	}
}

And I'm displaying the flashes thusly:

{{ range $flash := .session.Flashes }}
Flash: <li>{{ $flash }}</li>
{{ end }}

Should I have to pass the session to my template just to get at the flashes?

gob: decoding into local type *string, received remote type map[interface]interface

I've hit a wall with this error after attempting to load a key from the session. I create a Redis Store using a pre-existing pool and then utilize the session when handling authentication:

session.Set("AUTH_STATE", state)
session.Save()

In an OAuth callback handler I attempt to load the AUTH_STATE from the session (source):

v := session.Get("AUTH_STATE")
if v == nil {
  c.Error(errAuth.WithDetail("Auth state is nil"))
  c.Abort()
  return
}

The AUTH_STATE value is always nil and this error is reported to stderr:

gob: decoding into local type *string, received remote type map[interface]interface

Though it seems the error also occurs whenever the session is loaded at the beginning of every handler after the session is created. I noticed @boj encountered this error while creating redistore, but has since resolved the problem.

I've been banging my head on the table for days over this. I'd greatly appreciate any assistance.

pool type error

I got issue as below

../../gin-contrib/sessions/redis/redis.go:51:42: cannot use pool (type *"github.com/garyburd/redigo/redis".Pool) as type *"github.com/gomodule/redigo/redis".Pool in argument to redistore.NewRediStoreWithPool

I notice that you have update
github.com/garyburd/redigo to github.com/gomodule/redigo
without update github.com/gin-contrib/session

Clear on Server shutdown?

Hi I would like to clear the Session on Server shutdown because that logs my Users out. Is this possible?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.