add authorized handler middleware

This commit is contained in:
leo 2021-11-18 18:10:19 +08:00
parent 4de286d8f7
commit 4a5a10fc2b
3 changed files with 33 additions and 4 deletions

View File

@ -28,8 +28,13 @@ func GetLedgerConfigMap() map[string]Config {
return ledgerConfigMap
}
func GetLedgerConfig(ledgerId string) Config {
return ledgerConfigMap[ledgerId]
func GetLedgerConfig(ledgerId string) *Config {
for k, v := range ledgerConfigMap {
if k == ledgerId {
return &v
}
}
return nil
}
func GetLedgerConfigByMail(mail string) *Config {

View File

@ -20,9 +20,29 @@ func LoadServerCache() error {
return script.LoadLedgerConfigMap()
}
func AuthorizedHandler() gin.HandlerFunc {
return func(c *gin.Context) {
ledgerId := c.GetHeader("ledgerId")
ledgerConfig := script.GetLedgerConfig(ledgerId)
if ledgerConfig != nil {
c.Set("LedgerConfig", &ledgerConfig)
c.Next()
} else {
service.Unauthorized(c)
c.Abort()
}
}
}
func RegisterRouter(router *gin.Engine) {
router.StaticFS("/", http.Dir("./public"))
router.POST("/api/ledger", service.OpenOrCreateLedger)
authorized := router.Group("/api/auth/")
authorized.Use(AuthorizedHandler())
{
// need authorized
//authorized.POST("/tags")
}
}
func main() {

View File

@ -10,11 +10,15 @@ func OK(c *gin.Context, data string) {
}
func BadRequest(c *gin.Context, message string) {
c.JSON(http.StatusBadRequest, gin.H{"code": 400, "message": message})
c.JSON(http.StatusOK, gin.H{"code": 400, "message": message})
}
func Unauthorized(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"code": 401})
}
func InternalError(c *gin.Context, message string) {
c.JSON(http.StatusInternalServerError, gin.H{"code": 500, "message": message})
c.JSON(http.StatusOK, gin.H{"code": 500, "message": message})
}
func LedgerIsNotExist(c *gin.Context) {