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

42 lines
675 B
Go

package main
import (
"git.xdrm.io/example/aicra/db"
"git.xdrm.io/go/aicra/middleware"
"net/http"
"strings"
)
// Authentication middleware
func Inspect(req http.Request, scope *middleware.Scope) {
// 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))
}