Noah Petherbridge
1ecff195ac
* Add support for JWT tokens to authenticate users from your external app. * JWT backed users can have profile pictures, profile URLs, and operator status (admin). Note that no operator features exist yet. * Add WelcomeMessages to settings.toml for default ChatServer messages to write to each public channel directed at a new user logging in. * Markdown support for chat messages!
55 lines
1.2 KiB
Go
55 lines
1.2 KiB
Go
package jwt
|
|
|
|
import (
|
|
"encoding/json"
|
|
"errors"
|
|
"html/template"
|
|
|
|
"git.kirsle.net/apps/barertc/pkg/config"
|
|
"github.com/golang-jwt/jwt/v4"
|
|
)
|
|
|
|
// Custom JWT Claims.
|
|
type Claims struct {
|
|
// Custom claims.
|
|
IsAdmin bool `json:"op"`
|
|
Avatar string `json:"img"`
|
|
ProfileURL string `json:"url"`
|
|
|
|
// Standard claims. Notes:
|
|
// subject = username
|
|
jwt.RegisteredClaims
|
|
}
|
|
|
|
// ToJSON serializes the claims to JavaScript.
|
|
func (c Claims) ToJSON() template.JS {
|
|
data, _ := json.Marshal(c)
|
|
return template.JS(data)
|
|
}
|
|
|
|
// ParseAndValidate returns the Claims, a boolean authOK, and any errors.
|
|
func ParseAndValidate(tokenStr string) (*Claims, bool, error) {
|
|
// Handle a JWT authentication token.
|
|
var (
|
|
claims = &Claims{}
|
|
authOK bool
|
|
)
|
|
if tokenStr != "" {
|
|
token, err := jwt.ParseWithClaims(tokenStr, &Claims{}, func(token *jwt.Token) (interface{}, error) {
|
|
return []byte(config.Current.JWT.SecretKey), nil
|
|
})
|
|
if err != nil {
|
|
return nil, false, err
|
|
}
|
|
|
|
if parsed, ok := token.Claims.(*Claims); ok && token.Valid {
|
|
claims = parsed
|
|
authOK = true
|
|
} else {
|
|
return nil, false, errors.New("claims did not parse OK")
|
|
}
|
|
}
|
|
|
|
return claims, authOK, nil
|
|
}
|