mirror of
https://github.com/halejohn/Cloudreve.git
synced 2026-01-26 09:34:57 +08:00
Feat: User/Me
This commit is contained in:
38
middleware/auth.go
Normal file
38
middleware/auth.go
Normal file
@@ -0,0 +1,38 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"cloudreve/models"
|
||||
"cloudreve/pkg/serializer"
|
||||
"github.com/gin-contrib/sessions"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// CurrentUser 获取登录用户
|
||||
func CurrentUser() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
session := sessions.Default(c)
|
||||
uid := session.Get("user_id")
|
||||
if uid != nil {
|
||||
user, err := model.GetUserByID(uid)
|
||||
if err == nil {
|
||||
c.Set("user", &user)
|
||||
}
|
||||
}
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
// AuthRequired 需要登录
|
||||
func AuthRequired() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
if user, _ := c.Get("user"); user != nil {
|
||||
if _, ok := user.(*model.User); ok {
|
||||
c.Next()
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
c.JSON(200, serializer.CheckLogin())
|
||||
c.Abort()
|
||||
}
|
||||
}
|
||||
@@ -6,10 +6,13 @@ import (
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// Store session存储
|
||||
var Store memstore.Store
|
||||
|
||||
// Session 初始化session
|
||||
func Session(secret string) gin.HandlerFunc {
|
||||
store := memstore.NewStore([]byte(secret))
|
||||
//Also set Secure: true if using SSL, you should though
|
||||
store.Options(sessions.Options{HttpOnly: true, MaxAge: 7 * 86400, Path: "/"})
|
||||
return sessions.Sessions("cloudreve-session", store)
|
||||
Store = memstore.NewStore([]byte(secret))
|
||||
// Also set Secure: true if using SSL, you should though
|
||||
Store.Options(sessions.Options{HttpOnly: true, MaxAge: 7 * 86400, Path: "/"})
|
||||
return sessions.Sessions("cloudreve-session", Store)
|
||||
}
|
||||
|
||||
20
middleware/session_test.go
Normal file
20
middleware/session_test.go
Normal file
@@ -0,0 +1,20 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestSession(t *testing.T) {
|
||||
asserts := assert.New(t)
|
||||
|
||||
handler := Session("2333")
|
||||
asserts.NotNil(handler)
|
||||
asserts.NotNil(Store)
|
||||
asserts.IsType(emptyFunc(), handler)
|
||||
}
|
||||
|
||||
func emptyFunc() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {}
|
||||
}
|
||||
Reference in New Issue
Block a user