forked from free-lancers/electricity_bill_calc_service
		
	feat(security):增加用于确定用户登录情况的中间件。
This commit is contained in:
		
							
								
								
									
										56
									
								
								security/security.go
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										56
									
								
								security/security.go
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,56 @@ | ||||
| package security | ||||
|  | ||||
| import ( | ||||
| 	"electricity_bill_calc/cache" | ||||
| 	"electricity_bill_calc/model" | ||||
| 	"net/http" | ||||
| 	"strings" | ||||
|  | ||||
| 	"github.com/gin-gonic/gin" | ||||
| ) | ||||
|  | ||||
| // 用于解析Authorization头,并从缓存中获取用户会话信息注入上下文的中间件。 | ||||
| // 如果没有获取到用户会话信息,将直接跳过会话信息注入。 | ||||
| // ! 仅通过该中间件是不能保证上下文中一定保存有用户会话信息的。 | ||||
| func SessionRecovery(c *gin.Context) { | ||||
| 	auth := c.Request.Header.Get("Authorization") | ||||
| 	if len(auth) > 0 { | ||||
| 		token := strings.Fields(auth)[1] | ||||
| 		session, err := cache.RetreiveSession(token) | ||||
|  | ||||
| 		if err == nil { | ||||
| 			c.Set("session", session) | ||||
| 		} | ||||
| 	} | ||||
| 	c.Next() | ||||
| } | ||||
|  | ||||
| // 用于强制确定用户已经登录了系统,即具有有效的用户会话 | ||||
| // ! 通过该中间件以后,是可以保证上下文中一定具有用户会话信息的。 | ||||
| func MustAuthenticated(c *gin.Context) { | ||||
| 	session, exists := c.Get("session") | ||||
| 	if _, ok := session.(*model.Session); !exists || session == nil || !ok { | ||||
| 		c.AbortWithStatus(http.StatusForbidden) | ||||
| 	} | ||||
| 	c.Next() | ||||
| } | ||||
|  | ||||
| // 用于对用户会话进行是否企业用户的判断 | ||||
| // ! 通过该中间件以后,是可以保证上下文中一定具有用户会话信息的。 | ||||
| func EnterpriseAuthorize(c *gin.Context) { | ||||
| 	session, exists := c.Get("session") | ||||
| 	if sess, ok := session.(*model.Session); !exists || !ok || sess.Type != 0 { | ||||
| 		c.AbortWithStatus(http.StatusForbidden) | ||||
| 	} | ||||
| 	c.Next() | ||||
| } | ||||
|  | ||||
| // 用于对用户会话进行是否监管用户或运维用户的判断 | ||||
| // ! 通过该中间件以后,是可以保证上下文中一定具有用户会话信息的。 | ||||
| func ManagementAuthorize(c *gin.Context) { | ||||
| 	session, exists := c.Get("session") | ||||
| 	if sess, ok := session.(*model.Session); !exists || !ok || (sess.Type != 1 && sess.Type != 2) { | ||||
| 		c.AbortWithStatus(http.StatusForbidden) | ||||
| 	} | ||||
| 	c.Next() | ||||
| } | ||||
		Reference in New Issue
	
	Block a user