forked from mtusi2026/mtusi2026lab2
feat(auth): add session login, logout and bearer middleware
This commit is contained in:
@@ -0,0 +1,37 @@
|
||||
package httpx
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"mtusi2026-messenger/internal/dto"
|
||||
)
|
||||
|
||||
const (
|
||||
BasicChallenge = `Basic realm="messenger", charset="UTF-8"`
|
||||
BearerChallenge = `Bearer realm="messenger"`
|
||||
)
|
||||
|
||||
func BearerToken(r *http.Request) (string, bool) {
|
||||
const prefix = "Bearer "
|
||||
|
||||
header := r.Header.Get("Authorization")
|
||||
if len(header) <= len(prefix) || !strings.EqualFold(header[:len(prefix)], prefix) {
|
||||
return "", false
|
||||
}
|
||||
|
||||
token := strings.TrimSpace(header[len(prefix):])
|
||||
|
||||
return token, token != ""
|
||||
}
|
||||
|
||||
func WriteUnauthorized(w http.ResponseWriter, challenge, requestID string) {
|
||||
w.Header().Set("WWW-Authenticate", challenge)
|
||||
WriteError(
|
||||
w,
|
||||
http.StatusUnauthorized,
|
||||
dto.ErrorCodeUnauthorized,
|
||||
"unauthorized",
|
||||
requestID,
|
||||
)
|
||||
}
|
||||
Reference in New Issue
Block a user