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

48 lines
789 B
Go
Raw Normal View History

2018-07-07 21:09:19 +00:00
package main
import (
"git.xdrm.io/example/aicra/db"
2018-10-01 13:15:02 +00:00
"git.xdrm.io/go/aicra/driver"
2018-07-07 21:09:19 +00:00
"net/http"
"strings"
2018-07-07 21:09:19 +00:00
)
2018-10-01 13:15:02 +00:00
func main() {}
type AuthMiddleware int
func Export() driver.Middleware { return new(AuthMiddleware) }
2018-07-07 21:09:19 +00:00
// Authentication middleware
2018-10-01 13:15:02 +00:00
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))
2018-07-07 21:09:19 +00:00
}