navidrome/server/app/auth.go

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

216 lines
6.2 KiB
Go
Raw Normal View History

2020-01-20 15:54:29 +01:00
package app
import (
"context"
"encoding/json"
"errors"
2020-01-20 15:54:29 +01:00
"net/http"
"strings"
"time"
"github.com/deluan/rest"
"github.com/dgrijalva/jwt-go"
"github.com/go-chi/jwtauth"
"github.com/google/uuid"
"github.com/navidrome/navidrome/conf"
2020-01-24 01:44:08 +01:00
"github.com/navidrome/navidrome/consts"
"github.com/navidrome/navidrome/core/auth"
"github.com/navidrome/navidrome/log"
2020-01-24 01:44:08 +01:00
"github.com/navidrome/navidrome/model"
2020-05-13 22:49:55 +02:00
"github.com/navidrome/navidrome/model/request"
"github.com/navidrome/navidrome/utils/gravatar"
2020-01-20 15:54:29 +01:00
)
var (
ErrFirstTime = errors.New("no users created")
2020-01-20 15:54:29 +01:00
)
func Login(ds model.DataStore) func(w http.ResponseWriter, r *http.Request) {
2020-02-06 22:48:35 +01:00
auth.InitTokenAuth(ds)
2020-01-20 15:54:29 +01:00
return func(w http.ResponseWriter, r *http.Request) {
username, password, err := getCredentialsFromBody(r)
if err != nil {
log.Error(r, "Parsing request body", err)
2020-04-26 18:35:26 +02:00
_ = rest.RespondWithError(w, http.StatusUnprocessableEntity, err.Error())
2020-01-20 15:54:29 +01:00
return
}
handleLogin(ds, username, password, w, r)
}
}
func handleLogin(ds model.DataStore, username string, password string, w http.ResponseWriter, r *http.Request) {
user, err := validateLogin(ds.User(r.Context()), username, password)
if err != nil {
2020-04-26 18:35:26 +02:00
_ = rest.RespondWithError(w, http.StatusInternalServerError, "Unknown error authentication user. Please try again")
return
}
if user == nil {
log.Warn(r, "Unsuccessful login", "username", username, "request", r.Header)
2020-04-26 18:35:26 +02:00
_ = rest.RespondWithError(w, http.StatusUnauthorized, "Invalid username or password")
return
}
2020-02-06 22:48:35 +01:00
tokenString, err := auth.CreateToken(user)
if err != nil {
2020-04-26 18:35:26 +02:00
_ = rest.RespondWithError(w, http.StatusInternalServerError, "Unknown error authenticating user. Please try again")
return
}
payload := map[string]interface{}{
"message": "User '" + username + "' authenticated successfully",
"token": tokenString,
"id": user.ID,
"name": user.Name,
"username": username,
"isAdmin": user.IsAdmin,
}
if conf.Server.EnableGravatar && user.Email != "" {
payload["avatar"] = gravatar.Url(user.Email, 50)
}
_ = rest.RespondWithJSON(w, http.StatusOK, payload)
}
func getCredentialsFromBody(r *http.Request) (username string, password string, err error) {
data := make(map[string]string)
decoder := json.NewDecoder(r.Body)
if err = decoder.Decode(&data); err != nil {
log.Error(r, "parsing request body", err)
2020-04-26 18:35:26 +02:00
err = errors.New("invalid request payload")
return
}
username = data["username"]
password = data["password"]
return username, password, nil
}
func CreateAdmin(ds model.DataStore) func(w http.ResponseWriter, r *http.Request) {
2020-02-06 22:48:35 +01:00
auth.InitTokenAuth(ds)
return func(w http.ResponseWriter, r *http.Request) {
username, password, err := getCredentialsFromBody(r)
2020-01-20 15:54:29 +01:00
if err != nil {
log.Error(r, "parsing request body", err)
2020-04-26 18:35:26 +02:00
_ = rest.RespondWithError(w, http.StatusUnprocessableEntity, err.Error())
2020-01-20 15:54:29 +01:00
return
}
c, err := ds.User(r.Context()).CountAll()
if err != nil {
2020-04-26 18:35:26 +02:00
_ = rest.RespondWithError(w, http.StatusInternalServerError, err.Error())
2020-01-20 15:54:29 +01:00
return
}
if c > 0 {
2020-04-26 18:35:26 +02:00
_ = rest.RespondWithError(w, http.StatusForbidden, "Cannot create another first admin")
return
}
err = createDefaultUser(r.Context(), ds, username, password)
2020-01-20 15:54:29 +01:00
if err != nil {
2020-04-26 18:35:26 +02:00
_ = rest.RespondWithError(w, http.StatusInternalServerError, err.Error())
return
2020-01-20 15:54:29 +01:00
}
handleLogin(ds, username, password, w, r)
}
}
func createDefaultUser(ctx context.Context, ds model.DataStore, username, password string) error {
log.Warn("Creating initial user", "user", username)
now := time.Now()
initialUser := model.User{
ID: uuid.NewString(),
UserName: username,
Name: strings.Title(username),
Email: "",
2021-05-02 20:13:17 +02:00
NewPassword: password,
IsAdmin: true,
LastLoginAt: &now,
}
err := ds.User(ctx).Put(&initialUser)
if err != nil {
log.Error("Could not create initial user", "user", initialUser, err)
2020-01-20 15:54:29 +01:00
}
return nil
2020-01-20 15:54:29 +01:00
}
2020-01-20 15:54:29 +01:00
func validateLogin(userRepo model.UserRepository, userName, password string) (*model.User, error) {
u, err := userRepo.FindByUsername(userName)
if err == model.ErrNotFound {
return nil, nil
}
if err != nil {
return nil, err
}
if u.Password != password {
return nil, nil
}
err = userRepo.UpdateLastLoginAt(u.ID)
if err != nil {
log.Error("Could not update LastLoginAt", "user", userName)
}
return u, nil
}
func contextWithUser(ctx context.Context, ds model.DataStore, claims jwt.MapClaims) context.Context {
userName := claims["sub"].(string)
user, _ := ds.User(ctx).FindByUsername(userName)
2020-05-13 22:49:55 +02:00
return request.WithUser(ctx, *user)
2020-01-20 15:54:29 +01:00
}
func getToken(ds model.DataStore, ctx context.Context) (*jwt.Token, error) {
token, claims, err := jwtauth.FromContext(ctx)
2020-01-20 15:54:29 +01:00
valid := err == nil && token != nil && token.Valid
valid = valid && claims["sub"] != nil
if valid {
return token, nil
}
2020-01-20 15:54:29 +01:00
c, err := ds.User(ctx).CountAll()
firstTime := c == 0 && err == nil
if firstTime {
return nil, ErrFirstTime
}
return nil, errors.New("invalid authentication")
}
2020-01-20 15:54:29 +01:00
// This method maps the custom authorization header to the default 'Authorization', used by the jwtauth library
func mapAuthHeader() func(next http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
bearer := r.Header.Get(consts.UIAuthorizationHeader)
r.Header.Set("Authorization", bearer)
next.ServeHTTP(w, r)
})
}
}
func authenticator(ds model.DataStore) func(next http.Handler) http.Handler {
2020-02-06 22:48:35 +01:00
auth.InitTokenAuth(ds)
2020-01-20 15:54:29 +01:00
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
token, err := getToken(ds, r.Context())
if err == ErrFirstTime {
2020-04-26 18:35:26 +02:00
_ = rest.RespondWithJSON(w, http.StatusUnauthorized, map[string]string{"message": ErrFirstTime.Error()})
return
}
if err != nil {
2020-04-26 18:35:26 +02:00
_ = rest.RespondWithError(w, http.StatusUnauthorized, "Not authenticated")
return
}
claims := token.Claims.(jwt.MapClaims)
newCtx := contextWithUser(r.Context(), ds, claims)
2020-02-06 22:48:35 +01:00
newTokenString, err := auth.TouchToken(token)
if err != nil {
log.Error(r, "signing new token", err)
2020-04-26 18:35:26 +02:00
_ = rest.RespondWithError(w, http.StatusUnauthorized, "Not authenticated")
return
}
w.Header().Set(consts.UIAuthorizationHeader, newTokenString)
next.ServeHTTP(w, r.WithContext(newCtx))
})
}
2020-01-20 15:54:29 +01:00
}