Exemplo n.º 1
0
func TestErrorLog(t *testing.T) {
	Convey("Given engine with error log", t, func() {
		ml := mockErrorLogger{bytes.NewBuffer(nil)}

		r := gin.New()
		r.Use(
			func(c *gin.Context) {
				c.Set("log_id", "id")
				c.Next()
			},
			ErrorLog(ml),
		)

		route := "/api/v1/user"
		r.GET(route, func(c *gin.Context) {
			c.AbortWithError(http.StatusUnauthorized, errors.New(errors.ErrUnauthorized, "", "authtoken is expired"))
		})

		Convey("When request", func() {
			req, _ := http.NewRequest("GET", route, nil)
			resp := httptest.NewRecorder()
			r.ServeHTTP(resp, req)

			Convey("status code should be 401", func() {
				So(resp.Code, ShouldEqual, 401)
			})

			expected := "id: \"GET /api/v1/user HTTP/1.1\" 401 authtoken is expired"
			Convey("log should be "+expected, func() {
				So(ml.String(), ShouldEqual, expected)
			})
		})
	})
}
Exemplo n.º 2
0
// Authenticate authenticates a token and return the original model.Authtoken
func (au Authority) Authenticate(token string) (model.Authtoken, error) {
	bytes, err := hex.DecodeString(token)
	if err != nil {
		return model.Authtoken{},
			errors.New(errors.ErrServerInternal, "hack??", fmt.Sprintf("auth error %v", err))
	}

	for i := range au.privateKeys {
		bytes = xxtea.Decrypt(bytes, au.privateKeys[i])
	}

	authtoken := bytes2authtoken(bytes)
	if time.Since(authtoken.created) > au.tokenLifeTime {
		return model.Authtoken{},
			errors.New(errors.ErrUnauthorized, "", "token has been expired")
	}

	return authtoken.authtoken, nil
}
Exemplo n.º 3
0
// Recover is recover middleware
func Recover(logger fatalLogger) gin.HandlerFunc {
	return func(c *gin.Context) {
		defer func() {
			if e := recover(); e != nil {
				err := errors.New(
					errors.ErrServerInternal,
					"",
					fmt.Sprintf("panic reason -> %v", e),
					true, // true print stack backtrace
				)
				c.AbortWithError(http.StatusInternalServerError, err)

				if logger != nil {
					logger.Fatalf("%s", err.DetailedError())
				}
			}
		}()

		c.Next()
	}
}