Example #1
0
// Perms is a middleware function that attempts to cache the
// user's remote repository permissions (ie in GitHub) to minimize
// remote calls that might be expensive, slow or rate-limited.
func Perms(c *gin.Context) {
	var (
		owner   = c.Param("owner")
		name    = c.Param("name")
		user, _ = c.Get("user")
	)

	if user == nil {
		c.Next()
		return
	}

	// if the item already exists in the cache
	// we can continue the middleware chain and
	// exit afterwards.
	v := cache.GetPerms(c,
		user.(*model.User),
		owner,
		name,
	)
	if v != nil {
		c.Set("perm", v)
		c.Next()
		return
	}

	// otherwise, if the item isn't cached we execute
	// the middleware chain and then cache the permissions
	// after the request is processed.
	c.Next()

	perm, ok := c.Get("perm")
	if ok {
		cache.SetPerms(c,
			user.(*model.User),
			perm.(*model.Perm),
			owner,
			name,
		)
	}
}
Example #2
0
func TestPermCache(t *testing.T) {

	g := goblin.Goblin(t)
	g.Describe("Perm Cache", func() {

		var c *gin.Context
		g.BeforeEach(func() {
			c = new(gin.Context)
			cache.ToContext(c, cache.Default())
		})

		g.It("should skip when no user session", func() {
			c.Params = gin.Params{
				gin.Param{Key: "owner", Value: "octocat"},
				gin.Param{Key: "name", Value: "hello-world"},
			}

			Perms(c)

			_, ok := c.Get("perm")
			g.Assert(ok).IsFalse()
		})

		g.It("should get perms from cache", func() {
			c.Params = gin.Params{
				gin.Param{Key: "owner", Value: "octocat"},
				gin.Param{Key: "name", Value: "hello-world"},
			}
			c.Set("user", fakeUser)
			cache.SetPerms(c, fakeUser, fakePerm, "octocat", "hello-world")

			Perms(c)

			perm, ok := c.Get("perm")
			g.Assert(ok).IsTrue()
			g.Assert(perm).Equal(fakePerm)
		})

	})
}