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

41 lines
632 B
Go
Raw Normal View History

2018-07-07 21:09:19 +00:00
package main
import (
"git.xdrm.io/example/aicra/db"
2018-07-07 21:09:19 +00:00
"net/http"
"strings"
2018-07-07 21:09:19 +00:00
)
// Authentication middleware
func 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
}