router.go 2.2 KB
Newer Older
J
Jason 已提交
1
package api
J
Jason 已提交
2 3 4 5

import (
	"github.com/gin-contrib/sessions"
	"github.com/gin-gonic/gin"
J
Jason 已提交
6
	"git.zgwit.com/iot/dtu-admin/conf"
J
Jason 已提交
7 8 9
	"net/http"
)

J
Jason 已提交
10 11 12 13 14
type paramFilter struct {
	Key   string   `form:"key"`
	Value []string `form:"value"`
}

J
Jason 已提交
15
type paramSearch struct {
J
Jason 已提交
16 17 18 19 20 21
	Offset    int           `form:"offset"`
	Length    int           `form:"length"`
	SortKey   string        `form:"sortKey"`
	SortOrder string        `form:"sortOrder"`
	Filters   []paramFilter `form:"filters"`
	Keyword   string        `form:"keyword"`
J
Jason 已提交
22 23 24
}

type paramId struct {
25
	Id int `uri:"id"`
J
Jason 已提交
26 27 28
}

type paramId2 struct {
29 30
	Id  int `uri:"id"`
	Id2 int `uri:"id2"`
J
Jason 已提交
31 32
}

33
func mustLogin(c *gin.Context) {
J
Jason 已提交
34 35
	session := sessions.Default(c)
	if user := session.Get("user"); user != nil {
36 37
		c.Next()
	} else {
J
Jason 已提交
38 39
		//TODO 检查OAuth2返回的code,进一步获取用户信息,放置到session中

40 41 42 43 44
		c.JSON(http.StatusUnauthorized, gin.H{"ok": false, "error": "Unauthorized"})
		c.Abort()
	}
}

J
Jason 已提交
45
func RegisterRoutes(app *gin.RouterGroup) {
46

J
Jason 已提交
47 48 49 50 51 52 53 54 55 56 57 58 59
	if conf.Config.SysAdmin.Enable {
		//检查 session,必须登录
		app.Use(mustLogin)

		app.GET("/monitor/:id/:id2", monitor)
	} else if conf.Config.BaseAuth.Enable {
		app.GET("/monitor/:id/:id2", monitor)

		//检查HTTP认证
		app.Use(gin.BasicAuth(gin.Accounts(conf.Config.BaseAuth.Users)))
	} else {
		//支持匿名访问
	}
J
 
Jason 已提交
60 61

	//TODO 转移至子目录,并使用中间件,检查session及权限
J
Jason 已提交
62
	app.POST("/channels", channels)
J
顶替  
Jason 已提交
63 64 65 66 67 68
	app.POST("/channel", channelCreate)
	app.DELETE("/channel/:id", channelDelete)
	app.PUT("/channel/:id", channelModify)
	app.GET("/channel/:id", channelGet)
	app.GET("/channel/:id/start", channelStart)
	app.GET("/channel/:id/stop", channelStop)
J
 
Jason 已提交
69

70 71
	app.POST("/channel/:id/links")

J
Jason 已提交
72
	app.POST("/links", links)
73 74 75
	app.DELETE("/link/:id", linkDelete)
	app.PUT("/link/:id", linkModify)
	app.GET("/link/:id", linkGet)
J
 
Jason 已提交
76

J
Jason 已提交
77 78
}

J
顶替  
Jason 已提交
79
func replyOk(ctx *gin.Context, data interface{}) {
J
Jason 已提交
80 81 82 83 84 85
	ctx.JSON(http.StatusOK, gin.H{
		"ok":   true,
		"data": data,
	})
}

J
顶替  
Jason 已提交
86
func replyFail(ctx *gin.Context, err string) {
J
Jason 已提交
87 88 89 90 91 92
	ctx.JSON(http.StatusOK, gin.H{
		"ok":    false,
		"error": err,
	})
}

J
顶替  
Jason 已提交
93 94 95 96 97 98 99
func replyError(ctx *gin.Context, err error) {
	ctx.JSON(http.StatusOK, gin.H{
		"ok":    false,
		"error": err.Error(),
	})
}

J
Jason 已提交
100 101 102
func nop(c *gin.Context) {
	c.String(http.StatusForbidden, "Unsupported")
}