tiny-url-ex/middleware.plugin/1-auth/main.go

48 lines
789 B
Go

package main
import (
"git.xdrm.io/example/aicra/db"
"git.xdrm.io/go/aicra/driver"
"net/http"
"strings"
)
func main() {}
type AuthMiddleware int
func Export() driver.Middleware { return new(AuthMiddleware) }
// Authentication middleware
func (amw AuthMiddleware) Inspect(req http.Request, scope *[]string) {
// 1. get authorization header
token := req.Header.Get("Authorization")
// fail if no header
if len(token) < 1 {
return
}
// 2. fail on invalid token format
if len(token) != 128 || strings.ContainsAny(token, "$-_") {
return
}
// 3. get role for this token
cli := db.Connect()
if cli == nil {
return
}
defer cli.Close()
role := cli.Get(db.TOKEN, token)
if role == nil {
return
}
// add role to scope
*scope = append(*scope, string(role))
}