2020-07-29 21:11:28 +00:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/base64"
|
|
|
|
"fmt"
|
|
|
|
"os"
|
2020-08-19 21:30:54 +00:00
|
|
|
"strconv"
|
2020-07-29 21:11:28 +00:00
|
|
|
"strings"
|
|
|
|
"time"
|
2020-08-16 12:36:54 +00:00
|
|
|
|
|
|
|
"github.com/dgrijalva/jwt-go"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
|
|
"github.com/lithammer/shortuuid/v3"
|
2020-07-29 21:11:28 +00:00
|
|
|
)
|
|
|
|
|
2020-08-16 12:36:54 +00:00
|
|
|
func (app *appContext) webAuth() gin.HandlerFunc {
|
|
|
|
return app.authenticate
|
2020-07-29 21:11:28 +00:00
|
|
|
}
|
|
|
|
|
2020-08-16 12:36:54 +00:00
|
|
|
func (app *appContext) authenticate(gc *gin.Context) {
|
2020-07-29 21:11:28 +00:00
|
|
|
header := strings.SplitN(gc.Request.Header.Get("Authorization"), " ", 2)
|
|
|
|
if header[0] != "Basic" {
|
2020-08-16 12:36:54 +00:00
|
|
|
app.debug.Println("Invalid authentication header")
|
2020-07-29 21:11:28 +00:00
|
|
|
respond(401, "Unauthorized", gc)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
auth, _ := base64.StdEncoding.DecodeString(header[1])
|
|
|
|
creds := strings.SplitN(string(auth), ":", 2)
|
|
|
|
token, err := jwt.Parse(creds[0], func(token *jwt.Token) (interface{}, error) {
|
|
|
|
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
|
2020-08-16 12:36:54 +00:00
|
|
|
app.debug.Printf("Invalid JWT signing method %s", token.Header["alg"])
|
2020-07-29 21:11:28 +00:00
|
|
|
return nil, fmt.Errorf("Unexpected signing method %v", token.Header["alg"])
|
|
|
|
}
|
|
|
|
return []byte(os.Getenv("JFA_SECRET")), nil
|
|
|
|
})
|
|
|
|
if err != nil {
|
2020-08-16 12:36:54 +00:00
|
|
|
app.debug.Printf("Auth denied: %s", err)
|
2020-07-29 21:11:28 +00:00
|
|
|
respond(401, "Unauthorized", gc)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
claims, ok := token.Claims.(jwt.MapClaims)
|
2020-07-31 21:07:09 +00:00
|
|
|
var userId string
|
2020-07-31 11:48:37 +00:00
|
|
|
var jfId string
|
2020-08-19 21:30:54 +00:00
|
|
|
expiryUnix, err := strconv.ParseInt(claims["exp"].(string), 10, 64)
|
|
|
|
if err != nil {
|
|
|
|
app.debug.Printf("Auth denied: %s", err)
|
|
|
|
respond(401, "Unauthorized", gc)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
expiry := time.Unix(expiryUnix, 0)
|
|
|
|
if ok && token.Valid && claims["type"].(string) == "bearer" && expiry.After(time.Now()) {
|
2020-07-31 21:07:09 +00:00
|
|
|
userId = claims["id"].(string)
|
2020-07-31 11:48:37 +00:00
|
|
|
jfId = claims["jfid"].(string)
|
2020-07-29 21:11:28 +00:00
|
|
|
} else {
|
2020-08-16 12:36:54 +00:00
|
|
|
app.debug.Printf("Invalid token")
|
2020-07-29 21:11:28 +00:00
|
|
|
respond(401, "Unauthorized", gc)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
match := false
|
2020-08-16 12:36:54 +00:00
|
|
|
for _, user := range app.users {
|
2020-07-29 21:11:28 +00:00
|
|
|
if user.UserID == userId {
|
|
|
|
match = true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if !match {
|
2020-08-16 12:36:54 +00:00
|
|
|
app.debug.Printf("Couldn't find user ID %s", userId)
|
2020-07-29 21:11:28 +00:00
|
|
|
respond(401, "Unauthorized", gc)
|
|
|
|
return
|
|
|
|
}
|
2020-07-31 11:48:37 +00:00
|
|
|
gc.Set("jfId", jfId)
|
2020-07-31 21:07:09 +00:00
|
|
|
gc.Set("userId", userId)
|
2020-08-16 12:36:54 +00:00
|
|
|
app.debug.Println("Authentication successful")
|
2020-07-29 21:11:28 +00:00
|
|
|
gc.Next()
|
|
|
|
}
|
|
|
|
|
2020-08-16 12:36:54 +00:00
|
|
|
func (app *appContext) GetToken(gc *gin.Context) {
|
|
|
|
app.info.Println("Token requested (login attempt)")
|
2020-07-29 21:11:28 +00:00
|
|
|
header := strings.SplitN(gc.Request.Header.Get("Authorization"), " ", 2)
|
|
|
|
if header[0] != "Basic" {
|
2020-08-16 12:36:54 +00:00
|
|
|
app.debug.Println("Invalid authentication header")
|
2020-07-29 21:11:28 +00:00
|
|
|
respond(401, "Unauthorized", gc)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
auth, _ := base64.StdEncoding.DecodeString(header[1])
|
|
|
|
creds := strings.SplitN(string(auth), ":", 2)
|
|
|
|
match := false
|
2020-08-19 21:30:54 +00:00
|
|
|
var userId, jfId string
|
2020-08-16 12:36:54 +00:00
|
|
|
for _, user := range app.users {
|
2020-07-29 21:11:28 +00:00
|
|
|
if user.Username == creds[0] && user.Password == creds[1] {
|
2020-08-20 19:20:31 +00:00
|
|
|
if creds[0] != "" && creds[1] != "" {
|
|
|
|
match = true
|
|
|
|
app.debug.Println("Found existing user")
|
|
|
|
userId = user.UserID
|
|
|
|
}
|
2020-07-29 21:11:28 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
if !match {
|
2020-08-16 12:36:54 +00:00
|
|
|
if !app.jellyfinLogin {
|
|
|
|
app.info.Println("Auth failed: Invalid username and/or password")
|
2020-07-29 21:11:28 +00:00
|
|
|
respond(401, "Unauthorized", gc)
|
|
|
|
return
|
|
|
|
}
|
2020-08-20 19:20:31 +00:00
|
|
|
cookie, err := gc.Cookie("refresh")
|
|
|
|
if err == nil && cookie != "" && creds[0] == "" && creds[1] == "" {
|
|
|
|
fmt.Println("Checking:", cookie)
|
|
|
|
for _, token := range app.invalidTokens {
|
|
|
|
if cookie == token {
|
|
|
|
app.debug.Printf("Auth denied: Refresh token in blocklist")
|
|
|
|
respond(401, "Unauthorized", gc)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
|
|
|
token, err := jwt.Parse(cookie, func(token *jwt.Token) (interface{}, error) {
|
2020-08-19 21:30:54 +00:00
|
|
|
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
|
|
|
|
app.debug.Printf("Invalid JWT signing method %s", token.Header["alg"])
|
|
|
|
return nil, fmt.Errorf("Unexpected signing method %v", token.Header["alg"])
|
|
|
|
}
|
|
|
|
return []byte(os.Getenv("JFA_SECRET")), nil
|
|
|
|
})
|
|
|
|
if err != nil {
|
|
|
|
app.debug.Printf("Auth denied: %s", err)
|
|
|
|
respond(401, "Unauthorized", gc)
|
2020-08-01 13:08:55 +00:00
|
|
|
return
|
|
|
|
}
|
2020-08-19 21:30:54 +00:00
|
|
|
claims, ok := token.Claims.(jwt.MapClaims)
|
|
|
|
expiryUnix, err := strconv.ParseInt(claims["exp"].(string), 10, 64)
|
|
|
|
if err != nil {
|
|
|
|
app.debug.Printf("Auth denied: %s", err)
|
|
|
|
respond(401, "Unauthorized", gc)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
expiry := time.Unix(expiryUnix, 0)
|
|
|
|
if ok && token.Valid && claims["type"].(string) == "refresh" && expiry.After(time.Now()) {
|
|
|
|
userId = claims["id"].(string)
|
|
|
|
jfId = claims["jfid"].(string)
|
|
|
|
} else {
|
|
|
|
app.debug.Printf("Invalid token (invalid or not refresh type)")
|
|
|
|
respond(401, "Unauthorized", gc)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
var status int
|
|
|
|
var err error
|
|
|
|
var user map[string]interface{}
|
|
|
|
user, status, err = app.authJf.authenticate(creds[0], creds[1])
|
|
|
|
if status != 200 || err != nil {
|
|
|
|
if status == 401 || status == 400 {
|
|
|
|
app.info.Println("Auth failed: Invalid username and/or password")
|
|
|
|
respond(401, "Invalid username/password", gc)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
app.err.Printf("Auth failed: Couldn't authenticate with Jellyfin: Code %d", status)
|
|
|
|
respond(500, "Jellyfin error", gc)
|
|
|
|
return
|
|
|
|
} else {
|
|
|
|
jfId = user["Id"].(string)
|
|
|
|
if app.config.Section("ui").Key("admin_only").MustBool(true) {
|
|
|
|
if !user["Policy"].(map[string]interface{})["IsAdministrator"].(bool) {
|
|
|
|
app.debug.Printf("Auth failed: User \"%s\" isn't admin", creds[0])
|
|
|
|
respond(401, "Unauthorized", gc)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
newuser := User{}
|
|
|
|
newuser.UserID = shortuuid.New()
|
|
|
|
userId = newuser.UserID
|
|
|
|
// uuid, nothing else identifiable!
|
|
|
|
app.debug.Printf("Token generated for user \"%s\"", creds[0])
|
|
|
|
app.users = append(app.users, newuser)
|
|
|
|
}
|
2020-07-29 21:11:28 +00:00
|
|
|
}
|
|
|
|
}
|
2020-08-19 21:30:54 +00:00
|
|
|
token, refresh, err := CreateToken(userId, jfId)
|
2020-07-29 21:11:28 +00:00
|
|
|
if err != nil {
|
|
|
|
respond(500, "Error generating token", gc)
|
|
|
|
}
|
2020-08-20 19:20:31 +00:00
|
|
|
resp := map[string]string{"token": token}
|
|
|
|
gc.SetCookie("refresh", refresh, (3600 * 24), "/", gc.Request.URL.Hostname(), true, true)
|
2020-07-29 21:11:28 +00:00
|
|
|
gc.JSON(200, resp)
|
|
|
|
}
|
|
|
|
|
2020-08-19 21:30:54 +00:00
|
|
|
func CreateToken(userId string, jfId string) (string, string, error) {
|
|
|
|
var token, refresh string
|
|
|
|
var err error
|
2020-07-29 21:11:28 +00:00
|
|
|
claims := jwt.MapClaims{
|
|
|
|
"valid": true,
|
|
|
|
"id": userId,
|
2020-08-19 21:30:54 +00:00
|
|
|
"exp": strconv.FormatInt(time.Now().Add(time.Minute*20).Unix(), 10),
|
2020-07-31 11:48:37 +00:00
|
|
|
"jfid": jfId,
|
2020-08-19 21:30:54 +00:00
|
|
|
"type": "bearer",
|
2020-07-29 21:11:28 +00:00
|
|
|
}
|
2020-07-31 11:48:37 +00:00
|
|
|
|
2020-07-29 21:11:28 +00:00
|
|
|
tk := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
2020-08-19 21:30:54 +00:00
|
|
|
token, err = tk.SignedString([]byte(os.Getenv("JFA_SECRET")))
|
2020-07-29 21:11:28 +00:00
|
|
|
if err != nil {
|
2020-08-19 21:30:54 +00:00
|
|
|
return "", "", err
|
2020-07-29 21:11:28 +00:00
|
|
|
}
|
2020-08-19 21:30:54 +00:00
|
|
|
|
|
|
|
claims = jwt.MapClaims{
|
|
|
|
"valid": true,
|
|
|
|
"id": userId,
|
|
|
|
"exp": strconv.FormatInt(time.Now().Add(time.Hour*24).Unix(), 10),
|
|
|
|
"jfid": jfId,
|
|
|
|
"type": "refresh",
|
|
|
|
}
|
|
|
|
|
|
|
|
tk = jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
|
|
|
refresh, err = tk.SignedString([]byte(os.Getenv("JFA_SECRET")))
|
|
|
|
if err != nil {
|
|
|
|
return "", "", err
|
|
|
|
}
|
|
|
|
|
|
|
|
return token, refresh, nil
|
2020-07-29 21:11:28 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func respond(code int, message string, gc *gin.Context) {
|
|
|
|
resp := map[string]string{"error": message}
|
|
|
|
gc.JSON(code, resp)
|
|
|
|
gc.Abort()
|
|
|
|
}
|