parent
4649ddbae2
commit
e871f6e421
@ -0,0 +1,29 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
model "github.com/HFO4/cloudreve/models"
|
||||
"github.com/HFO4/cloudreve/pkg/serializer"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrAuthFailed = serializer.NewError(serializer.CodeNoRightErr, "鉴权失败", nil)
|
||||
ErrExpired = serializer.NewError(serializer.CodeSignExpired, "签名已过期", nil)
|
||||
)
|
||||
|
||||
// General 通用的认证接口
|
||||
var General Auth
|
||||
|
||||
// Auth 鉴权认证
|
||||
type Auth interface {
|
||||
// 对给定Body进行签名,expires为0表示永不过期
|
||||
Sign(body string, expires int64) string
|
||||
// 对给定Body和Sign进行检查
|
||||
Check(body string, sign string) error
|
||||
}
|
||||
|
||||
// Init 初始化通用鉴权器
|
||||
func Init() {
|
||||
General = HMACAuth{
|
||||
SecretKey: []byte(model.GetSettingByName("secret_key")),
|
||||
}
|
||||
}
|
@ -0,0 +1,74 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"github.com/DATA-DOG/go-sqlmock"
|
||||
model "github.com/HFO4/cloudreve/models"
|
||||
"github.com/HFO4/cloudreve/pkg/util"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/jinzhu/gorm"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"testing"
|
||||
)
|
||||
|
||||
var mock sqlmock.Sqlmock
|
||||
|
||||
func TestMain(m *testing.M) {
|
||||
// 设置gin为测试模式
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
// 初始化sqlmock
|
||||
var db *sql.DB
|
||||
var err error
|
||||
db, mock, err = sqlmock.New()
|
||||
if err != nil {
|
||||
panic("An error was not expected when opening a stub database connection")
|
||||
}
|
||||
|
||||
mockDB, _ := gorm.Open("mysql", db)
|
||||
model.DB = mockDB
|
||||
defer db.Close()
|
||||
|
||||
m.Run()
|
||||
}
|
||||
|
||||
func TestHMACAuth_Sign(t *testing.T) {
|
||||
asserts := assert.New(t)
|
||||
auth := HMACAuth{
|
||||
SecretKey: []byte(util.RandStringRunes(256)),
|
||||
}
|
||||
|
||||
asserts.NotEmpty(auth.Sign("content", 0))
|
||||
}
|
||||
|
||||
func TestHMACAuth_Check(t *testing.T) {
|
||||
asserts := assert.New(t)
|
||||
auth := HMACAuth{
|
||||
SecretKey: []byte(util.RandStringRunes(256)),
|
||||
}
|
||||
|
||||
// 正常,永不过期
|
||||
{
|
||||
sign := auth.Sign("content", 0)
|
||||
asserts.NoError(auth.Check("content", sign))
|
||||
}
|
||||
|
||||
// 过期
|
||||
{
|
||||
sign := auth.Sign("content", 1)
|
||||
asserts.Error(auth.Check("content", sign))
|
||||
}
|
||||
|
||||
// 签名格式错误
|
||||
{
|
||||
sign := auth.Sign("content", 1)
|
||||
asserts.Error(auth.Check("content", sign+":"))
|
||||
}
|
||||
}
|
||||
|
||||
func TestInit(t *testing.T) {
|
||||
asserts := assert.New(t)
|
||||
mock.ExpectQuery("SELECT(.+)").WillReturnRows(sqlmock.NewRows([]string{"id", "value"}).AddRow(1, "12312312312312"))
|
||||
Init()
|
||||
asserts.NoError(mock.ExpectationsWereMet())
|
||||
}
|
Loading…
Reference in new issue