chore: move server package to root

This commit is contained in:
Noah Hsu
2022-06-26 19:10:14 +08:00
parent 4cef3adc90
commit c67f128f15
9 changed files with 39 additions and 39 deletions

50
server/common/auth.go Normal file
View File

@ -0,0 +1,50 @@
package common
import (
"github.com/golang-jwt/jwt/v4"
"github.com/pkg/errors"
"time"
)
var SecretKey []byte
type UserClaims struct {
Username string `json:"username"`
jwt.RegisteredClaims
}
func GenerateToken(username string) (tokenString string, err error) {
claim := UserClaims{
Username: username,
RegisteredClaims: jwt.RegisteredClaims{
ExpiresAt: jwt.NewNumericDate(time.Now().Add(12 * time.Hour)),
IssuedAt: jwt.NewNumericDate(time.Now()),
NotBefore: jwt.NewNumericDate(time.Now()),
}}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claim)
tokenString, err = token.SignedString(SecretKey)
return tokenString, err
}
func ParseToken(tokenString string) (*UserClaims, error) {
token, err := jwt.ParseWithClaims(tokenString, &UserClaims{}, func(token *jwt.Token) (interface{}, error) {
return SecretKey, nil
})
if err != nil {
if ve, ok := err.(*jwt.ValidationError); ok {
if ve.Errors&jwt.ValidationErrorMalformed != 0 {
return nil, errors.New("that's not even a token")
} else if ve.Errors&jwt.ValidationErrorExpired != 0 {
return nil, errors.New("token is expired")
} else if ve.Errors&jwt.ValidationErrorNotValidYet != 0 {
return nil, errors.New("token not active yet")
} else {
return nil, errors.New("couldn't handle this token")
}
}
}
if claims, ok := token.Claims.(*UserClaims); ok && token.Valid {
return claims, nil
}
return nil, errors.New("couldn't handle this token")
}

44
server/common/common.go Normal file
View File

@ -0,0 +1,44 @@
package common
import (
"github.com/gin-gonic/gin"
log "github.com/sirupsen/logrus"
)
func ErrorResp(c *gin.Context, err error, code int, l ...bool) {
if len(l) != 0 && l[0] {
log.Errorf("%+v", err)
}
c.JSON(200, Resp{
Code: code,
Message: err.Error(),
Data: nil,
})
c.Abort()
}
func ErrorStrResp(c *gin.Context, str string, code int) {
log.Error(str)
c.JSON(200, Resp{
Code: code,
Message: str,
Data: nil,
})
c.Abort()
}
func SuccessResp(c *gin.Context, data ...interface{}) {
if len(data) == 0 {
c.JSON(200, Resp{
Code: 200,
Message: "success",
Data: nil,
})
return
}
c.JSON(200, Resp{
Code: 200,
Message: "success",
Data: data[0],
})
}

6
server/common/req.go Normal file
View File

@ -0,0 +1,6 @@
package common
type PageReq struct {
PageIndex int `json:"page_index" form:"page_index"`
PageSize int `json:"page_size" form:"page_size"`
}

12
server/common/resp.go Normal file
View File

@ -0,0 +1,12 @@
package common
type Resp struct {
Code int `json:"code"`
Message string `json:"message"`
Data interface{} `json:"data"`
}
type PageResp struct {
Content interface{} `json:"content"`
Total int64 `json:"total"`
}

View File

@ -0,0 +1,65 @@
package controllers
import (
"github.com/Xhofe/go-cache"
"github.com/alist-org/alist/v3/internal/db"
"github.com/alist-org/alist/v3/internal/model"
common2 "github.com/alist-org/alist/v3/server/common"
"github.com/gin-gonic/gin"
"time"
)
var loginCache = cache.NewMemCache[int]()
var (
defaultDuration = time.Minute * 5
defaultTimes = 5
)
type LoginReq struct {
Username string `json:"username"`
Password string `json:"password"`
}
func Login(c *gin.Context) {
// check count of login
ip := c.ClientIP()
count, ok := loginCache.Get(ip)
if ok && count >= defaultTimes {
common2.ErrorStrResp(c, "Too many unsuccessful sign-in attempts have been made using an incorrect password. Try again later.", 403)
loginCache.Expire(ip, defaultDuration)
return
}
// check username
var req LoginReq
if err := c.ShouldBind(&req); err != nil {
common2.ErrorResp(c, err, 400)
return
}
user, err := db.GetUserByName(req.Username)
if err != nil {
common2.ErrorResp(c, err, 400)
return
}
// validate password
if err := user.ValidatePassword(req.Password); err != nil {
common2.ErrorResp(c, err, 400)
loginCache.Set(ip, count+1)
return
}
// generate token
token, err := common2.GenerateToken(user.Username)
if err != nil {
common2.ErrorResp(c, err, 400)
return
}
common2.SuccessResp(c, gin.H{"token": token})
loginCache.Del(ip)
}
// CurrentUser get current user by token
// if token is empty, return guest user
func CurrentUser(c *gin.Context) {
user := c.MustGet("user").(*model.User)
user.Password = ""
common2.SuccessResp(c, gin.H{"user": user})
}

View File

@ -0,0 +1,71 @@
package controllers
import (
"github.com/alist-org/alist/v3/internal/db"
"github.com/alist-org/alist/v3/internal/model"
"github.com/alist-org/alist/v3/pkg/utils"
common2 "github.com/alist-org/alist/v3/server/common"
"github.com/gin-gonic/gin"
log "github.com/sirupsen/logrus"
"strconv"
)
func ListMetas(c *gin.Context) {
var req common2.PageReq
if err := c.ShouldBind(&req); err != nil {
common2.ErrorResp(c, err, 400)
return
}
log.Debugf("%+v", req)
metas, total, err := db.GetMetas(req.PageIndex, req.PageSize)
if err != nil {
common2.ErrorResp(c, err, 500, true)
return
}
common2.SuccessResp(c, common2.PageResp{
Content: metas,
Total: total,
})
}
func CreateMeta(c *gin.Context) {
var req model.Meta
if err := c.ShouldBind(&req); err != nil {
common2.ErrorResp(c, err, 400)
return
}
req.Path = utils.StandardizePath(req.Path)
if err := db.CreateMeta(&req); err != nil {
common2.ErrorResp(c, err, 500)
} else {
common2.SuccessResp(c)
}
}
func UpdateMeta(c *gin.Context) {
var req model.Meta
if err := c.ShouldBind(&req); err != nil {
common2.ErrorResp(c, err, 400)
return
}
req.Path = utils.StandardizePath(req.Path)
if err := db.UpdateMeta(&req); err != nil {
common2.ErrorResp(c, err, 500)
} else {
common2.SuccessResp(c)
}
}
func DeleteMeta(c *gin.Context) {
idStr := c.Query("id")
id, err := strconv.Atoi(idStr)
if err != nil {
common2.ErrorResp(c, err, 400)
return
}
if err := db.DeleteMetaById(uint(id)); err != nil {
common2.ErrorResp(c, err, 500)
return
}
common2.SuccessResp(c)
}

View File

@ -0,0 +1,49 @@
package middlewares
import (
"github.com/alist-org/alist/v3/internal/db"
"github.com/alist-org/alist/v3/internal/model"
common2 "github.com/alist-org/alist/v3/server/common"
"github.com/gin-gonic/gin"
)
// Auth is a middleware that checks if the user is logged in.
// if token is empty, set user to guest
func Auth(c *gin.Context) {
token := c.GetHeader("Authorization")
if token == "" {
guest, err := db.GetGuest()
if err != nil {
common2.ErrorResp(c, err, 500, true)
c.Abort()
return
}
c.Set("user", guest)
c.Next()
return
}
userClaims, err := common2.ParseToken(token)
if err != nil {
common2.ErrorResp(c, err, 401)
c.Abort()
return
}
user, err := db.GetUserByName(userClaims.Username)
if err != nil {
common2.ErrorResp(c, err, 401)
c.Abort()
return
}
c.Set("user", user)
c.Next()
}
func AuthAdmin(c *gin.Context) {
user := c.MustGet("user").(*model.User)
if !user.IsAdmin() {
common2.ErrorStrResp(c, "You are not an admin", 403)
c.Abort()
} else {
c.Next()
}
}

34
server/router.go Normal file
View File

@ -0,0 +1,34 @@
package server
import (
"github.com/alist-org/alist/v3/internal/conf"
"github.com/alist-org/alist/v3/server/common"
controllers2 "github.com/alist-org/alist/v3/server/controllers"
"github.com/alist-org/alist/v3/server/middlewares"
"github.com/gin-contrib/cors"
"github.com/gin-gonic/gin"
)
func Init(r *gin.Engine) {
common.SecretKey = []byte(conf.Conf.JwtSecret)
Cors(r)
api := r.Group("/api", middlewares.Auth)
api.POST("/auth/login", controllers2.Login)
api.GET("/auth/current", controllers2.CurrentUser)
admin := api.Group("/admin", middlewares.AuthAdmin)
meta := admin.Group("/meta")
meta.GET("/list", controllers2.ListMetas)
meta.POST("/create", controllers2.CreateMeta)
meta.POST("/update", controllers2.UpdateMeta)
meta.POST("/delete", controllers2.DeleteMeta)
}
func Cors(r *gin.Engine) {
config := cors.DefaultConfig()
config.AllowAllOrigins = true
config.AllowHeaders = append(config.AllowHeaders, "Authorization", "range")
r.Use(cors.New(config))
}