gin框架基于cookie的登录验证中间件

cookie_auth.go:

// Copyright 2014 Manu Martinez-Almeida.  All rights reserved.
// Use of this source code is governed by a MIT style
// license that can be found in the LICENSE file.

package middleware

import (
	"crypto/md5"
	"encoding/base64"
	"fmt"
	"strings"

	"github.com/gin-gonic/gin"
)

// AuthUserKey is the cookie name for user credential in basic auth.
const AuthUserKey = "admin"

// Accounts defines a key/value for user/pass list of authorized logins.
type Accounts map[string]string

type authPair struct {
	value string
	user  string
}

type authPairs []authPair

type authResult struct {
	Code    int    `json:"code"`
	Message string `json:"message"`
	Data    string `json:"data"`
}

func (a authPairs) searchCredential(authValue string) (string, bool) {
	if authValue == "" {
		return "", false
	}
	for _, pair := range a {
		if pair.value == authValue {
			return pair.user, true
		}
	}
	return "", false
}

// CookieAuthForRealm returns a Basic HTTP Authorization middleware. It takes as arguments a map[string]string where
// the key is the user name and the value is the password
func CookieAuthForRealm(accounts Accounts) gin.HandlerFunc {
	pairs := processAccounts(accounts)
	return func(c *gin.Context) {
		var user string
		if strings.Contains(c.Request.URL.Path, "logout") {
			c.SetCookie("auth", "", -1, "/", c.GetHeader("Host"), false, true)
			c.JSON(200, authResult{Code: 0, Message: "ok"})
			return
		}
		// Search user in the slice of allowed credentials
		val, _ := c.Cookie("auth")
		foundCookie := false
		if val != "" {
			user, foundCookie = pairs.searchCredential(val)
		}
		if foundCookie {
			c.Set(AuthUserKey, user)
			if strings.Contains(c.Request.URL.Path, "login") {
				c.JSON(200, authResult{Code: 102, Message: "already logged", Data: user})
			}
			return
		}
		name := c.Query("name")
		password := c.Query("password")
		if name == "" || password == "" {
			c.JSON(200, authResult{Code: 100, Message: "not login"})
			return
		}
		encryption := authorizationCookie(name, password)
		user, foundPass := pairs.searchCredential(encryption)
		if foundPass {
			c.SetCookie("auth", encryption, 86400, "/", c.GetHeader("Host"), false, false)
			c.Set(AuthUserKey, user)
			c.JSON(200, authResult{Code: 0, Message: "ok", Data: encryption})
			return
		} else {
			c.JSON(200, authResult{Code: 101, Message: "name or password incorrect"})
			return
		}
		// The user credentials was found, set user's id to key AuthUserKey in this context, the user's id can be read later using
		// c.MustGet(gin.AuthUserKey).
	}
}

// CookieAuth returns a Basic HTTP Authorization middleware. It takes as argument a map[string]string where
// the key is the user name and the value is the password.
func CookieAuth(accounts Accounts) gin.HandlerFunc {
	return CookieAuthForRealm(accounts)
}

func processAccounts(accounts Accounts) authPairs {
	pairs := make(authPairs, 0, len(accounts))
	if len(accounts) == 0 {
		fmt.Println("Empty list of authorized credentials")
		return pairs
	}
	for user, password := range accounts {
		value := authorizationCookie(user, password)
		pairs = append(pairs, authPair{
			value: value,
			user:  user,
		})
	}
	return pairs
}

func authorizationCookie(user, password string) string {
	data := []byte(password)
	has := md5.Sum(data)
	base := user + ":" + fmt.Sprintf("%x", has)
	return base64.StdEncoding.EncodeToString([]byte(base))
}

使用示例:

auth := middleware.CookieAuth(middleware.Accounts(map[string]string{
    "admin": "888",
    "name": "pass",
}))

cms := g.Group("/cms")
cms.Use(auth)
// 设置路由
cms.GET("/login", func(c *gin.Context) {})
cms.GET("/logout", func(c *gin.Context) {})
cms.GET("/otherxxx", func(c *gin.Context) {})

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值