Merge branch 'develop' for release v3.17.0
This commit is contained in:
+1
-1
@@ -16,7 +16,7 @@ matrix:
|
||||
- gcc
|
||||
before_install:
|
||||
- eval "${MATRIX_EVAL}"
|
||||
- sudo apt-get install build-essential cmake libboost-all-dev libconfig++-dev libavcodec-dev libavutil-dev libavformat-dev ffmpeg libgraphicsmagick++1-dev libpstreams-dev libconfig++-dev libpstreams-dev libtag1-dev
|
||||
- sudo apt-get install build-essential cmake libboost-all-dev libconfig++-dev libavcodec-dev libavutil-dev libavformat-dev ffmpeg libgraphicsmagick++1-dev libpstreams-dev libconfig++-dev libpstreams-dev libtag1-dev libpam0g-dev
|
||||
- git clone https://github.com/emweb/wt.git wt
|
||||
- pushd wt;
|
||||
- git checkout 4.2.1
|
||||
|
||||
+7
-2
@@ -2,7 +2,6 @@ cmake_minimum_required(VERSION 3.12)
|
||||
|
||||
project(lms)
|
||||
|
||||
|
||||
set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${CMAKE_SOURCE_DIR}/cmake/modules/")
|
||||
|
||||
set(CMAKE_CXX_STANDARD 17)
|
||||
@@ -11,12 +10,18 @@ set(CMAKE_CXX_STANDARD_REQUIRED True)
|
||||
include(CTest)
|
||||
find_package(PkgConfig REQUIRED)
|
||||
find_package(Filesystem REQUIRED)
|
||||
find_package(FFMPEGAV REQUIRED)
|
||||
find_package(Taglib REQUIRED)
|
||||
find_package(Boost REQUIRED COMPONENTS system)
|
||||
find_package(PStreams REQUIRED)
|
||||
find_package(PAM)
|
||||
pkg_check_modules(GRAPHICSMAGICKXX REQUIRED GraphicsMagick++)
|
||||
|
||||
add_subdirectory(src)
|
||||
|
||||
install(DIRECTORY approot DESTINATION share/lms)
|
||||
install(DIRECTORY docroot DESTINATION share/lms)
|
||||
install(FILES systemd/default.service DESTINATION share/lms)
|
||||
install(FILES conf/systemd/default.service DESTINATION share/lms)
|
||||
install(FILES conf/pam/lms DESTINATION share/lms)
|
||||
install(FILES conf/lms.conf DESTINATION share/lms)
|
||||
|
||||
|
||||
@@ -23,6 +23,7 @@ A [demo](http://lms.demo.poupon.io) instance is available, with the following li
|
||||
* MusicBrainzID support to handle duplicated artist and release names
|
||||
* Disc subtitles support
|
||||
* _Systemd_ integration
|
||||
* _PAM_ authentication backend
|
||||
* Subsonic API, with the following additional features:
|
||||
* Playlists
|
||||
* Starred Album/Artist/Tracks
|
||||
@@ -90,9 +91,11 @@ __Notes__:
|
||||
* a C++17 compiler is needed
|
||||
* ffmpeg version 4 minimum is required
|
||||
```sh
|
||||
apt-get install g++ cmake libboost-system-dev libavutil-dev libavformat-dev libgraphicsmagick++1-dev libconfig++-dev libpstreams-dev ffmpeg libtag1-dev
|
||||
apt-get install g++ cmake libboost-system-dev libavutil-dev libavformat-dev libgraphicsmagick++1-dev libconfig++-dev libpstreams-dev ffmpeg libtag1-dev libpam0g-dev
|
||||
```
|
||||
|
||||
__Note__: package libpam0g-dev is optional (only for using PAM authentication)
|
||||
|
||||
You also need _Wt4_, which is not packaged yet on _Debian_. See [installation instructions](https://www.webtoolkit.eu/wt/doc/reference/html/InstallationUnix.html).</br>
|
||||
No optional requirement is needed, except openSSL if you plan not to deploy behind a reverse proxy (which is not recommended).
|
||||
|
||||
|
||||
@@ -20,7 +20,15 @@
|
||||
${admin-login-info class="help-block"}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="form-group">
|
||||
<label class="control-label col-lg-3" for="${id:auth-mode}">
|
||||
${tr:Lms.Admin.User.auth-mode}
|
||||
</label>
|
||||
<div class="col-lg-9">
|
||||
${auth-mode}
|
||||
${auth-mode-info class="help-block"}
|
||||
</div>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label class="col-lg-3 control-label" for="${id:password}">
|
||||
${tr:Lms.password}
|
||||
@@ -30,7 +38,6 @@
|
||||
${password-info class="help-block"}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="form-group">
|
||||
<label class="col-lg-3 control-label" for="${id:password-confirm}">
|
||||
${tr:Lms.password-confirm}
|
||||
|
||||
@@ -30,6 +30,15 @@
|
||||
</div>
|
||||
</div>
|
||||
${</if-has-login>}
|
||||
<div class="form-group">
|
||||
<label class="control-label col-lg-3" for="${id:auth-mode}">
|
||||
${tr:Lms.Admin.User.auth-mode}
|
||||
</label>
|
||||
<div class="col-lg-9">
|
||||
${auth-mode}
|
||||
${auth-mode-info class="help-block"}
|
||||
</div>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label class="control-label col-lg-3" for="${id:password}">
|
||||
${tr:Lms.password-new}
|
||||
|
||||
@@ -16,6 +16,7 @@
|
||||
<message id="Lms.password-bad-login-combination">Bad login / password combination</message>
|
||||
<message id="Lms.password-client-throttled">Login throttled, please try again later</message>
|
||||
<message id="Lms.password-confirm">Confirm password</message>
|
||||
<message id="Lms.password-must-not-be-empty">Password must not be empty</message>
|
||||
<message id="Lms.password-new">New password</message>
|
||||
<message id="Lms.password-old">Old password</message>
|
||||
<message id="Lms.password-too-weak">Password too weak</message>
|
||||
@@ -81,6 +82,9 @@
|
||||
<message id="Lms.Admin.Users.menu-users"><i class="fa fa-fw fa-users" aria-hidden="true"></i> Users</message>
|
||||
|
||||
<!--User-->
|
||||
<message id="Lms.Admin.User.auth-mode">Authentication mode</message>
|
||||
<message id="Lms.Admin.User.auth-mode.internal">Internal</message>
|
||||
<message id="Lms.Admin.User.auth-mode.pam">PAM</message>
|
||||
<message id="Lms.Admin.User.demo-account">Demo account</message>
|
||||
<message id="Lms.Admin.User.demo-account-already-exists">Demo account already exists!</message>
|
||||
<message id="Lms.Admin.User.demo-password-invalid">Demo password must be the login name!</message>
|
||||
|
||||
@@ -16,6 +16,7 @@
|
||||
<message id="Lms.password-bad-login-combination">Mauvaise combinaison login / mot de passe</message>
|
||||
<message id="Lms.password-client-throttled">Trop de tentatives de connexion, veuillez réessayer plus tard</message>
|
||||
<message id="Lms.password-confirm">Confirmation du mot de passe</message>
|
||||
<message id="Lms.password-must-not-be-empty">Le mot de passe ne doit pas être vide</message>
|
||||
<message id="Lms.password-new">Nouveau mot de passe</message>
|
||||
<message id="Lms.password-old">Ancien mot de passe</message>
|
||||
<message id="Lms.password-too-weak">Mot de passe trop faible</message>
|
||||
@@ -81,6 +82,9 @@
|
||||
<message id="Lms.Admin.Users.menu-users"><i class="fa fa-fw fa-users" aria-hidden="true"></i> Utilisateurs</message>
|
||||
|
||||
<!--User-->
|
||||
<message id="Lms.Admin.User.auth-mode">Mode d'authentification</message>
|
||||
<message id="Lms.Admin.User.auth-mode.internal">Interne</message>
|
||||
<message id="Lms.Admin.User.auth-mode.pam">PAM</message>
|
||||
<message id="Lms.Admin.User.demo-account">Compte de démonstration</message>
|
||||
<message id="Lms.Admin.User.demo-account-already-exists">Le compte de démonstration existe déjà !</message>
|
||||
<message id="Lms.Admin.User.demo-password-invalid">Le password doit être égal au login !</message>
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
# Quick and dirty av* includes discoverer
|
||||
|
||||
find_path(AVCODEC_INCLUDE_DIR NAMES libavcodec/avcodec.h PATH_SUFFIXES ffmpeg)
|
||||
find_library(AVCODEC_LIBRARY avcodec)
|
||||
|
||||
find_path(AVFORMAT_INCLUDE_DIR NAMES libavformat/avformat.h PATH_SUFFIXES ffmpeg)
|
||||
find_library(AVFORMAT_LIBRARY avformat)
|
||||
|
||||
find_path(AVUTIL_INCLUDE_DIR NAMES libavutil/avutil.h PATH_SUFFIXES ffmpeg)
|
||||
find_library(AVUTIL_LIBRARY avutil)
|
||||
|
||||
include(FindPackageHandleStandardArgs)
|
||||
|
||||
FIND_PACKAGE_HANDLE_STANDARD_ARGS(
|
||||
FFMPEGAV
|
||||
FOUND_VAR FFMPEGAV_FOUND
|
||||
REQUIRED_VARS AVUTIL_LIBRARY AVFORMAT_LIBRARY
|
||||
)
|
||||
|
||||
mark_as_advanced(AVFORMAT_LIBRARY)
|
||||
mark_as_advanced(AVUTIL_LIBRARY)
|
||||
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
# From http://code.google.com/p/pam-face-authentication/source/browse/branches/pam_face_authentication/cmake/modules/FindPAM.cmake?r=336
|
||||
|
||||
# - Try to find the PAM libraries
|
||||
# Once done this will define
|
||||
#
|
||||
# PAM_FOUND - system has pam
|
||||
# PAM_INCLUDE_DIR - the pam include directory
|
||||
# PAM_LIBRARIES - libpam library
|
||||
|
||||
if (PAM_INCLUDE_DIR AND PAM_LIBRARY)
|
||||
# Already in cache, be silent
|
||||
set(PAM_FIND_QUIETLY TRUE)
|
||||
endif (PAM_INCLUDE_DIR AND PAM_LIBRARY)
|
||||
|
||||
find_path(PAM_INCLUDE_DIR NAMES security/pam_appl.h pam/pam_appl.h)
|
||||
find_library(PAM_LIBRARY pam)
|
||||
find_library(DL_LIBRARY dl)
|
||||
|
||||
if (PAM_INCLUDE_DIR AND PAM_LIBRARY)
|
||||
set(PAM_FOUND TRUE)
|
||||
if (DL_LIBRARY)
|
||||
set(PAM_LIBRARIES ${PAM_LIBRARY} ${DL_LIBRARY})
|
||||
else (DL_LIBRARY)
|
||||
set(PAM_LIBRARIES ${PAM_LIBRARY})
|
||||
endif (DL_LIBRARY)
|
||||
|
||||
if (EXISTS ${PAM_INCLUDE_DIR}/pam/pam_appl.h)
|
||||
# darwin claims to be something special
|
||||
set(HAVE_PAM_PAM_APPL_H 1)
|
||||
endif (EXISTS ${PAM_INCLUDE_DIR}/pam/pam_appl.h)
|
||||
|
||||
if (NOT DEFINED PAM_MESSAGE_CONST)
|
||||
include(CheckCXXSourceCompiles)
|
||||
# XXX does this work with plain c?
|
||||
check_cxx_source_compiles("
|
||||
#if ${HAVE_PAM_PAM_APPL_H}+0
|
||||
# include <pam/pam_appl.h>
|
||||
#else
|
||||
# include <security/pam_appl.h>
|
||||
#endif
|
||||
static int PAM_conv(
|
||||
int num_msg,
|
||||
const struct pam_message **msg, /* this is the culprit */
|
||||
struct pam_response **resp,
|
||||
void *ctx)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
int main(void)
|
||||
{
|
||||
struct pam_conv PAM_conversation = {
|
||||
&PAM_conv, /* this bombs out if the above does not match */
|
||||
0
|
||||
};
|
||||
return 0;
|
||||
}
|
||||
" PAM_MESSAGE_CONST)
|
||||
endif (NOT DEFINED PAM_MESSAGE_CONST)
|
||||
set(PAM_MESSAGE_CONST ${PAM_MESSAGE_CONST} CACHE BOOL "PAM expects a conversation function with const pam_message")
|
||||
|
||||
endif (PAM_INCLUDE_DIR AND PAM_LIBRARY)
|
||||
|
||||
if (PAM_FOUND)
|
||||
if (NOT PAM_FIND_QUIETLY)
|
||||
message(STATUS "Found PAM: ${PAM_LIBRARIES}")
|
||||
endif (NOT PAM_FIND_QUIETLY)
|
||||
else (PAM_FOUND)
|
||||
if (PAM_FIND_REQUIRED)
|
||||
message(FATAL_ERROR "PAM was not found")
|
||||
endif(PAM_FIND_REQUIRED)
|
||||
endif (PAM_FOUND)
|
||||
|
||||
mark_as_advanced(PAM_INCLUDE_DIR PAM_LIBRARY DL_LIBRARY PAM_MESSAGE_CONST)
|
||||
@@ -0,0 +1,17 @@
|
||||
# If already in cache, be silent
|
||||
if(PSTREAMS_INCLUDE_DIRS)
|
||||
set (PSTREAMS_FIND_QUIETLY TRUE)
|
||||
endif()
|
||||
|
||||
FIND_PATH(PSTREAMS_INCLUDE_DIR NAMES pstream.h
|
||||
PATH_SUFFIXES pstreams
|
||||
HINTS ${PSTREAMS_ROOT}/include $ENV{PSTREAMS_ROOT})
|
||||
|
||||
set(PSTREAMS_INCLUDE_DIRS ${PSTREAMS_INCLUDE_DIR})
|
||||
|
||||
# Handle the QUIETLY and REQUIRED arguments and set PSTREAMS_FOUND to TRUE if
|
||||
# all listed variables are TRUE.
|
||||
INCLUDE(FindPackageHandleStandardArgs)
|
||||
FIND_PACKAGE_HANDLE_STANDARD_ARGS(Pstreams DEFAULT_MSG PSTREAMS_INCLUDE_DIRS)
|
||||
|
||||
MARK_AS_ADVANCED(PSTREAMS_INCLUDE_DIRS)
|
||||
@@ -0,0 +1,87 @@
|
||||
# - Try to find the Taglib library
|
||||
# Once done this will define
|
||||
#
|
||||
# TAGLIB_FOUND - system has the taglib library
|
||||
# TAGLIB_CFLAGS - the taglib cflags
|
||||
# TAGLIB_LIBRARIES - The libraries needed to use taglib
|
||||
|
||||
# Copyright (c) 2006, Laurent Montel, <montel@kde.org>
|
||||
#
|
||||
# Redistribution and use is allowed according to the terms of the BSD license.
|
||||
# For details see the accompanying COPYING-CMAKE-SCRIPTS file.
|
||||
|
||||
IF(TAGLIB_FOUND)
|
||||
MESSAGE(STATUS "Using manually specified taglib locations")
|
||||
ELSE()
|
||||
|
||||
if(NOT TAGLIB_MIN_VERSION)
|
||||
set(TAGLIB_MIN_VERSION "1.6")
|
||||
endif(NOT TAGLIB_MIN_VERSION)
|
||||
|
||||
if(NOT WIN32)
|
||||
find_program(TAGLIBCONFIG_EXECUTABLE NAMES taglib-config PATHS
|
||||
${BIN_INSTALL_DIR}
|
||||
)
|
||||
endif(NOT WIN32)
|
||||
|
||||
#reset vars
|
||||
set(TAGLIB_LIBRARIES)
|
||||
set(TAGLIB_CFLAGS)
|
||||
|
||||
# MESSAGE( STATUS "PATHS: ${PATHS}")
|
||||
# if taglib-config has been found
|
||||
if(TAGLIBCONFIG_EXECUTABLE)
|
||||
|
||||
exec_program(${TAGLIBCONFIG_EXECUTABLE} ARGS --version RETURN_VALUE _return_VALUE OUTPUT_VARIABLE TAGLIB_VERSION)
|
||||
|
||||
if(TAGLIB_VERSION VERSION_LESS "${TAGLIB_MIN_VERSION}")
|
||||
message(STATUS "TagLib version not found: version searched :${TAGLIB_MIN_VERSION}, found ${TAGLIB_VERSION}")
|
||||
set(TAGLIB_FOUND FALSE)
|
||||
else(TAGLIB_VERSION VERSION_LESS "${TAGLIB_MIN_VERSION}")
|
||||
|
||||
exec_program(${TAGLIBCONFIG_EXECUTABLE} ARGS --libs RETURN_VALUE _return_VALUE OUTPUT_VARIABLE TAGLIB_LIBRARIES)
|
||||
|
||||
exec_program(${TAGLIBCONFIG_EXECUTABLE} ARGS --cflags RETURN_VALUE _return_VALUE OUTPUT_VARIABLE TAGLIB_CFLAGS)
|
||||
|
||||
if(TAGLIB_LIBRARIES AND TAGLIB_CFLAGS)
|
||||
set(TAGLIB_FOUND TRUE)
|
||||
# message(STATUS "Found taglib: ${TAGLIB_LIBRARIES}")
|
||||
endif(TAGLIB_LIBRARIES AND TAGLIB_CFLAGS)
|
||||
string(REGEX REPLACE " *-I" ";" TAGLIB_INCLUDES "${TAGLIB_CFLAGS}")
|
||||
endif(TAGLIB_VERSION VERSION_LESS "${TAGLIB_MIN_VERSION}")
|
||||
mark_as_advanced(TAGLIB_CFLAGS TAGLIB_LIBRARIES TAGLIB_INCLUDES)
|
||||
|
||||
else(TAGLIBCONFIG_EXECUTABLE)
|
||||
|
||||
include(FindLibraryWithDebug)
|
||||
include(FindPackageHandleStandardArgs)
|
||||
|
||||
find_path(TAGLIB_INCLUDES
|
||||
NAMES
|
||||
tag.h
|
||||
PATH_SUFFIXES taglib
|
||||
PATHS
|
||||
${INCLUDE_INSTALL_DIR}
|
||||
)
|
||||
|
||||
find_library_with_debug(TAGLIB_LIBRARIES
|
||||
WIN32_DEBUG_POSTFIX d
|
||||
NAMES tag
|
||||
PATHS
|
||||
${LIB_INSTALL_DIR}
|
||||
)
|
||||
|
||||
find_package_handle_standard_args(Taglib DEFAULT_MSG
|
||||
TAGLIB_INCLUDES TAGLIB_LIBRARIES)
|
||||
endif(TAGLIBCONFIG_EXECUTABLE)
|
||||
ENDIF()
|
||||
|
||||
if(TAGLIB_FOUND)
|
||||
if(NOT Taglib_FIND_QUIETLY AND TAGLIBCONFIG_EXECUTABLE)
|
||||
message(STATUS "Found TagLib: ${TAGLIB_LIBRARIES}")
|
||||
endif(NOT Taglib_FIND_QUIETLY AND TAGLIBCONFIG_EXECUTABLE)
|
||||
else(TAGLIB_FOUND)
|
||||
if(Taglib_FIND_REQUIRED)
|
||||
message(FATAL_ERROR "Could not find Taglib")
|
||||
endif(Taglib_FIND_REQUIRED)
|
||||
endif(TAGLIB_FOUND)
|
||||
@@ -0,0 +1,3 @@
|
||||
account required pam_unix.so
|
||||
auth required pam_unix.so
|
||||
password required pam_deny.so
|
||||
@@ -20,9 +20,16 @@ target_link_libraries(lmsauth PRIVATE
|
||||
|
||||
target_link_libraries(lmsauth PUBLIC
|
||||
pthread
|
||||
boost_system
|
||||
Boost::system
|
||||
wt
|
||||
)
|
||||
|
||||
if (PAM_FOUND)
|
||||
target_compile_options(lmsauth PRIVATE "-DLMS_SUPPORT_PAM")
|
||||
target_sources(lmsauth PRIVATE impl/pam/PAM.cpp)
|
||||
target_include_directories(lmsauth PRIVATE ${PAM_INCLUDE_DIR})
|
||||
target_link_libraries(lmsauth PRIVATE ${PAM_LIBRARIES})
|
||||
endif(PAM_FOUND)
|
||||
|
||||
install(TARGETS lmsauth DESTINATION lib)
|
||||
|
||||
|
||||
@@ -17,8 +17,6 @@
|
||||
* along with LMS. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
/* This file contains some classes in order to get info from file using the libavconv */
|
||||
|
||||
#include "AuthTokenService.hpp"
|
||||
|
||||
#include <Wt/Auth/HashFunction.h>
|
||||
|
||||
@@ -17,8 +17,6 @@
|
||||
* along with LMS. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
/* This file contains some classes in order to get info from file using the libavconv */
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "auth/IAuthTokenService.hpp"
|
||||
|
||||
@@ -17,8 +17,6 @@
|
||||
* along with LMS. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
/* This file contains some classes in order to get info from file using the libavconv */
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <shared_mutex>
|
||||
|
||||
@@ -17,8 +17,6 @@
|
||||
* along with LMS. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
/* This file contains some classes in order to get info from file using the libavconv */
|
||||
|
||||
#include "PasswordService.hpp"
|
||||
|
||||
#include <Wt/Auth/HashFunction.h>
|
||||
@@ -28,6 +26,9 @@
|
||||
#include "database/Session.hpp"
|
||||
#include "utils/Exception.hpp"
|
||||
#include "utils/Logger.hpp"
|
||||
#ifdef LMS_SUPPORT_PAM
|
||||
#include "pam/PAM.hpp"
|
||||
#endif
|
||||
|
||||
namespace Auth {
|
||||
|
||||
@@ -41,10 +42,29 @@ PasswordService::PasswordService(std::size_t maxThrottlerEntries)
|
||||
{
|
||||
}
|
||||
|
||||
bool
|
||||
PasswordService::isAuthModeSupported(Database::User::AuthMode authMode) const
|
||||
{
|
||||
switch (authMode)
|
||||
{
|
||||
case Database::User::AuthMode::Internal:
|
||||
return true;
|
||||
|
||||
case Database::User::AuthMode::PAM:
|
||||
#ifdef LMS_SUPPORT_PAM
|
||||
return true;
|
||||
#else
|
||||
return false;
|
||||
#endif
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
static
|
||||
bool
|
||||
checkUserPassword(Database::Session& session, const std::string& loginName, const std::string& password)
|
||||
{
|
||||
Database::User::AuthMode authMode;
|
||||
Database::User::PasswordHash passwordHash;
|
||||
{
|
||||
auto transaction {session.createSharedTransaction()};
|
||||
@@ -53,13 +73,29 @@ checkUserPassword(Database::Session& session, const std::string& loginName, cons
|
||||
if (!user)
|
||||
return false;
|
||||
|
||||
authMode = user->getAuthMode();
|
||||
passwordHash = user->getPasswordHash();
|
||||
}
|
||||
|
||||
const Wt::Auth::BCryptHashFunction hashFunc {6};
|
||||
return hashFunc.verify(password, passwordHash.salt, passwordHash.hash);
|
||||
}
|
||||
switch (authMode)
|
||||
{
|
||||
case Database::User::AuthMode::Internal:
|
||||
{
|
||||
LMS_LOG(AUTH, DEBUG) << "Checking internal password for user '" << loginName << "'";
|
||||
const Wt::Auth::BCryptHashFunction hashFunc {6}; // TODO parametrize this
|
||||
return hashFunc.verify(password, passwordHash.salt, passwordHash.hash);
|
||||
}
|
||||
|
||||
case Database::User::AuthMode::PAM:
|
||||
#ifdef LMS_SUPPORT_PAM
|
||||
return PAM::checkUserPassword(loginName, password);
|
||||
#else
|
||||
return false;
|
||||
#endif
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
PasswordService::PasswordCheckResult
|
||||
PasswordService::checkUserPassword(Database::Session& session, const boost::asio::ip::address& clientAddress, const std::string& loginName, const std::string& password)
|
||||
|
||||
@@ -46,14 +46,13 @@ namespace Auth {
|
||||
PasswordService(PasswordService&&) = delete;
|
||||
PasswordService& operator=(PasswordService&&) = delete;
|
||||
|
||||
private:
|
||||
|
||||
// Password services
|
||||
bool isAuthModeSupported(Database::User::AuthMode authMode) const;
|
||||
PasswordCheckResult checkUserPassword(Database::Session& session, const boost::asio::ip::address& clientAddress, const std::string& loginName, const std::string& password) override;
|
||||
Database::User::PasswordHash hashPassword(const std::string& password) const override;
|
||||
bool evaluatePasswordStrength(const std::string& loginName, const std::string& password) const override;
|
||||
|
||||
private:
|
||||
|
||||
std::shared_timed_mutex _mutex;
|
||||
LoginThrottler _loginThrottler;
|
||||
};
|
||||
|
||||
@@ -0,0 +1,183 @@
|
||||
/*
|
||||
* Copyright (C) 2020 Emeric Poupon
|
||||
*
|
||||
* This file is part of LMS.
|
||||
*
|
||||
* LMS is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* LMS is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with LMS. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#include "PAM.hpp"
|
||||
|
||||
#include <cstring>
|
||||
|
||||
#include "utils/Exception.hpp"
|
||||
#include "utils/Logger.hpp"
|
||||
|
||||
#include <security/pam_appl.h>
|
||||
|
||||
namespace Auth::PAM
|
||||
{
|
||||
|
||||
class PAMError
|
||||
{
|
||||
public:
|
||||
PAMError(std::string_view msg, pam_handle_t *pamh, int err)
|
||||
{
|
||||
_errorMsg = std::string {msg} + ": " + pam_strerror(pamh, err);
|
||||
}
|
||||
|
||||
std::string_view message() const { return _errorMsg; }
|
||||
|
||||
private:
|
||||
std::string _errorMsg;
|
||||
};
|
||||
|
||||
class PAMContext
|
||||
{
|
||||
public:
|
||||
PAMContext(std::string_view loginName)
|
||||
{
|
||||
int err {pam_start("lms", std::string {loginName}.c_str(), &_conv, &_pamh)};
|
||||
if (err != PAM_SUCCESS)
|
||||
throw PAMError {"start failed", _pamh, err};
|
||||
}
|
||||
|
||||
~PAMContext()
|
||||
{
|
||||
int err {pam_end(_pamh, 0)};
|
||||
if (err != PAM_SUCCESS)
|
||||
LMS_LOG(AUTH, ERROR) << "end failed: " << pam_strerror(_pamh, err);
|
||||
}
|
||||
|
||||
void authenticate(std::string_view password)
|
||||
{
|
||||
AuthenticateConvContext authContext {password};
|
||||
ScopedConvContextSetter scopedContext {*this, authContext};
|
||||
|
||||
int err {pam_authenticate(_pamh, 0)};
|
||||
if (err != PAM_SUCCESS)
|
||||
throw PAMError {"authenticate failed", _pamh, err};
|
||||
}
|
||||
|
||||
void validateAccount()
|
||||
{
|
||||
int err {pam_acct_mgmt(_pamh, PAM_SILENT)};
|
||||
if (err != PAM_SUCCESS)
|
||||
throw PAMError {"acct_mgmt failed", _pamh, err};
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
class ConvContext
|
||||
{
|
||||
public:
|
||||
virtual ~ConvContext() = default;
|
||||
};
|
||||
|
||||
class AuthenticateConvContext final : public ConvContext
|
||||
{
|
||||
public:
|
||||
AuthenticateConvContext(std::string_view password) : _password {password} {}
|
||||
|
||||
std::string_view getPassword() const { return _password; }
|
||||
|
||||
private:
|
||||
std::string_view _password;
|
||||
};
|
||||
|
||||
class ScopedConvContextSetter
|
||||
{
|
||||
public:
|
||||
ScopedConvContextSetter(PAMContext& pamContext, ConvContext& convContext)
|
||||
: _pamContext {pamContext}
|
||||
{
|
||||
_pamContext._convContext = &convContext;
|
||||
}
|
||||
|
||||
~ScopedConvContextSetter()
|
||||
{
|
||||
_pamContext._convContext = nullptr;
|
||||
}
|
||||
|
||||
ScopedConvContextSetter(const ScopedConvContextSetter&) = delete;
|
||||
ScopedConvContextSetter(ScopedConvContextSetter&&) = delete;
|
||||
ScopedConvContextSetter& operator=(const ScopedConvContextSetter&) = delete;
|
||||
ScopedConvContextSetter& operator=(ScopedConvContextSetter&&) = delete;
|
||||
|
||||
private:
|
||||
PAMContext& _pamContext;
|
||||
};
|
||||
|
||||
|
||||
static int conv(int msgCount, const pam_message** msgs, pam_response** resps, void* userData)
|
||||
{
|
||||
if (msgCount < 1)
|
||||
return PAM_CONV_ERR;
|
||||
if (!resps || !msgs || !userData)
|
||||
return PAM_CONV_ERR;
|
||||
|
||||
PAMContext& context {*static_cast<PAMContext*>(userData)};
|
||||
|
||||
AuthenticateConvContext* authenticateContext = dynamic_cast<AuthenticateConvContext*>(context._convContext);
|
||||
if (!authenticateContext)
|
||||
{
|
||||
LMS_LOG(AUTH, ERROR) << "Unexpected conv!";
|
||||
return PAM_CONV_ERR;
|
||||
}
|
||||
|
||||
// Only expect a PAM_PROMPT_ECHO_OFF msg
|
||||
if (msgCount != 1 || msgs[0]->msg_style != PAM_PROMPT_ECHO_OFF)
|
||||
{
|
||||
LMS_LOG(AUTH, ERROR) << "Unexpected conv message. Count = " << msgCount;
|
||||
return PAM_CONV_ERR;
|
||||
}
|
||||
|
||||
pam_response* response {static_cast<pam_response*>(malloc(sizeof(pam_response)))};
|
||||
if (!response)
|
||||
return PAM_CONV_ERR;
|
||||
|
||||
response->resp = strdup(std::string {authenticateContext->getPassword()}.c_str());
|
||||
|
||||
*resps = response;
|
||||
return PAM_SUCCESS;
|
||||
}
|
||||
|
||||
ConvContext* _convContext {};
|
||||
pam_conv _conv {&PAMContext::conv, this};
|
||||
pam_handle_t *_pamh {};
|
||||
|
||||
};
|
||||
|
||||
bool
|
||||
checkUserPassword(const std::string& loginName, const std::string& password)
|
||||
{
|
||||
try
|
||||
{
|
||||
LMS_LOG(AUTH, DEBUG) << "Checking PAM password for user '" << loginName << "'";
|
||||
PAMContext pamContext {loginName};
|
||||
|
||||
pamContext.authenticate(password);
|
||||
pamContext.validateAccount();
|
||||
|
||||
return true;
|
||||
}
|
||||
catch (const PAMError& error)
|
||||
{
|
||||
LMS_LOG(AUTH, ERROR) << "PAM error: " << error.message();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace Auth::PAM
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
/*
|
||||
* Copyright (C) 2020 Emeric Poupon
|
||||
*
|
||||
* This file is part of LMS.
|
||||
*
|
||||
* LMS is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* LMS is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with LMS. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#ifdef LMS_SUPPORT_PAM
|
||||
|
||||
#include <string>
|
||||
|
||||
namespace Auth::PAM
|
||||
{
|
||||
bool checkUserPassword(const std::string& loginName, const std::string& password);
|
||||
}
|
||||
|
||||
#endif // LMS_SUPPORT_PAM
|
||||
|
||||
@@ -48,6 +48,9 @@ namespace Auth {
|
||||
Mismatch,
|
||||
Throttled,
|
||||
};
|
||||
|
||||
virtual bool isAuthModeSupported(Database::User::AuthMode authMode) const = 0;
|
||||
|
||||
virtual PasswordCheckResult checkUserPassword(Database::Session& session, const boost::asio::ip::address& clientAddress, const std::string& loginName, const std::string& password) = 0;
|
||||
virtual Database::User::PasswordHash hashPassword(const std::string& password) const = 0;
|
||||
virtual bool evaluatePasswordStrength(const std::string& loginName, const std::string& password) const = 0;
|
||||
|
||||
@@ -6,21 +6,26 @@ add_library(lmsav SHARED
|
||||
impl/AvTypes.cpp
|
||||
)
|
||||
|
||||
# TODO make av libs private
|
||||
target_include_directories(lmsav INTERFACE
|
||||
include
|
||||
${AVCODEC_INCLUDE_DIR}
|
||||
${AVFORMAT_INCLUDE_DIR}
|
||||
${AVUTIL_INCLUDE_DIR}
|
||||
)
|
||||
|
||||
target_include_directories(lmsav PRIVATE
|
||||
include/
|
||||
)
|
||||
|
||||
# TODO make these private
|
||||
target_link_libraries(lmsav PUBLIC
|
||||
lmsutils
|
||||
avformat
|
||||
avutil
|
||||
std::filesystem
|
||||
wt
|
||||
${AVFORMAT_LIBRARY}
|
||||
${AVUTIL_LIBRARY}
|
||||
)
|
||||
|
||||
install(TARGETS lmsav DESTINATION lib)
|
||||
|
||||
@@ -496,12 +496,25 @@ std::chrono::milliseconds
|
||||
Release::getDuration() const
|
||||
{
|
||||
assert(self());
|
||||
assert(self()->id() != Wt::Dbo::dbo_traits<Artist>::invalidId() );
|
||||
assert(self()->id() != Wt::Dbo::dbo_traits<Artist>::invalidId());
|
||||
assert(session());
|
||||
|
||||
using milli = std::chrono::duration<int, std::milli>;
|
||||
|
||||
Wt::Dbo::Query<milli> query {session()->query<milli>("SELECT SUM(duration) FROM track t INNER JOIN release r ON t.release_id = r.id")
|
||||
Wt::Dbo::Query<milli> query {session()->query<milli>("SELECT COALESCE(SUM(duration), 0) FROM track t INNER JOIN release r ON t.release_id = r.id")
|
||||
.where("r.id = ?").bind(self()->id())};
|
||||
|
||||
return query.resultValue();
|
||||
}
|
||||
|
||||
Wt::WDateTime
|
||||
Release::getLastWritten() const
|
||||
{
|
||||
assert(self());
|
||||
assert(self()->id() != Wt::Dbo::dbo_traits<Artist>::invalidId());
|
||||
assert(session());
|
||||
|
||||
Wt::Dbo::Query<Wt::WDateTime> query {session()->query<Wt::WDateTime>("SELECT COALESCE(MAX(file_last_write), '1970-01-01T00:00:00') FROM track t INNER JOIN release r ON t.release_id = r.id")
|
||||
.where("r.id = ?").bind(self()->id())};
|
||||
|
||||
return query.resultValue();
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright (C) 2013 Emeric Poupon
|
||||
* Copyright (C) 2020 Emeric Poupon
|
||||
*
|
||||
* This file is part of LMS.
|
||||
*
|
||||
@@ -40,7 +40,7 @@
|
||||
|
||||
namespace Database {
|
||||
|
||||
#define LMS_DATABASE_VERSION 24
|
||||
#define LMS_DATABASE_VERSION 25
|
||||
|
||||
using Version = std::size_t;
|
||||
|
||||
@@ -267,6 +267,11 @@ CREATE TABLE "user_backup" (
|
||||
// Just increment the scan version of the settings to make the next scheduled scan rescan everything
|
||||
ScanSettings::get(*this).modify()->incScanVersion();
|
||||
}
|
||||
else if (version == 24)
|
||||
{
|
||||
// User's AuthMode
|
||||
_session.execute("ALTER TABLE user ADD auth_mode INTEGER NOT NULL DEFAULT(" + std::to_string(static_cast<int>(User::defaultAuthMode)) + ")");
|
||||
}
|
||||
else
|
||||
{
|
||||
LMS_LOG(DB, ERROR) << "Database version " << version << " cannot be handled using migration";
|
||||
|
||||
@@ -410,7 +410,7 @@ TrackList::getDuration() const
|
||||
|
||||
using milli = std::chrono::duration<int, std::milli>;
|
||||
|
||||
Wt::Dbo::Query<milli> query {session()->query<milli>("SELECT SUM(duration) FROM track t INNER JOIN tracklist_entry p_e ON t.id = p_e.track_id")
|
||||
Wt::Dbo::Query<milli> query {session()->query<milli>("SELECT COALESCE(SUM(duration), 0) FROM track t INNER JOIN tracklist_entry p_e ON t.id = p_e.track_id")
|
||||
.where("p_e.tracklist_id = ?").bind(self()->id())};
|
||||
|
||||
return query.resultValue();
|
||||
|
||||
@@ -70,10 +70,8 @@ AuthToken::getByValue(Session& session, const std::string& value)
|
||||
static const std::string playedListName {"__played_tracks__"};
|
||||
static const std::string queuedListName {"__queued_tracks__"};
|
||||
|
||||
User::User(const std::string& loginName, const PasswordHash& passwordHash)
|
||||
User::User(const std::string& loginName)
|
||||
: _loginName {loginName}
|
||||
, _passwordSalt {passwordHash.salt}
|
||||
, _passwordHash {passwordHash.hash}
|
||||
{
|
||||
}
|
||||
|
||||
@@ -96,11 +94,11 @@ User::getDemo(Session& session)
|
||||
}
|
||||
|
||||
User::pointer
|
||||
User::create(Session& session, const std::string& loginName, const PasswordHash& passwordHash)
|
||||
User::create(Session& session, const std::string& loginName)
|
||||
{
|
||||
session.checkUniqueLocked();
|
||||
|
||||
User::pointer user {session.getDboSession().add(std::make_unique<User>(loginName, passwordHash))};
|
||||
User::pointer user {session.getDboSession().add(std::make_unique<User>(loginName))};
|
||||
|
||||
TrackList::create(session, playedListName, TrackList::Type::Internal, false, user);
|
||||
TrackList::create(session, queuedListName, TrackList::Type::Internal, false, user);
|
||||
|
||||
@@ -90,6 +90,7 @@ class Release : public Wt::Dbo::Dbo<Release>
|
||||
std::optional<std::size_t> getTotalTrack() const;
|
||||
std::optional<std::size_t> getTotalDisc() const;
|
||||
std::chrono::milliseconds getDuration() const;
|
||||
Wt::WDateTime getLastWritten() const;
|
||||
|
||||
// Get the artists of this release
|
||||
std::vector<Wt::Dbo::ptr<Artist> > getArtists(TrackArtistLink::Type type = TrackArtistLink::Type::Artist) const;
|
||||
|
||||
@@ -100,6 +100,12 @@ class User : public Wt::Dbo::Dbo<User>
|
||||
DEMO = 2,
|
||||
};
|
||||
|
||||
enum class AuthMode
|
||||
{
|
||||
Internal = 0,
|
||||
PAM = 1,
|
||||
};
|
||||
|
||||
struct PasswordHash
|
||||
{
|
||||
std::string salt;
|
||||
@@ -137,13 +143,14 @@ class User : public Wt::Dbo::Dbo<User>
|
||||
static inline const Bitrate defaultSubsonicTranscodeBitrate {128000};
|
||||
static inline const UITheme defaultUITheme {UITheme::Dark};
|
||||
static inline const SubsonicArtistListMode defaultSubsonicArtistListMode {SubsonicArtistListMode::AllArtists};
|
||||
static inline const AuthMode defaultAuthMode {AuthMode::Internal};
|
||||
|
||||
|
||||
User() = default;
|
||||
User(const std::string& loginName, const PasswordHash& passwordHash);
|
||||
User(const std::string& loginName);
|
||||
|
||||
// utility
|
||||
static pointer create(Session& session, const std::string& loginName, const PasswordHash& passwordHash);
|
||||
static pointer create(Session& session, const std::string& loginName);
|
||||
|
||||
static pointer getById(Session& session, IdType id);
|
||||
static pointer getByLoginName(Session& session, const std::string& loginName);
|
||||
@@ -165,6 +172,7 @@ class User : public Wt::Dbo::Dbo<User>
|
||||
void setSubsonicTranscodeBitrate(Bitrate bitrate);
|
||||
void setCurPlayingTrackPos(std::size_t pos) { _curPlayingTrackPos = pos; }
|
||||
void setRadio(bool val) { _radio = val; }
|
||||
void setAuthMode(AuthMode mode) { _authMode = mode;}
|
||||
void setRepeatAll(bool val) { _repeatAll = val; }
|
||||
void setUITheme(UITheme uiTheme) { _uiTheme = uiTheme; }
|
||||
void clearAuthTokens();
|
||||
@@ -179,6 +187,7 @@ class User : public Wt::Dbo::Dbo<User>
|
||||
std::size_t getCurPlayingTrackPos() const { return _curPlayingTrackPos; }
|
||||
bool isRepeatAllSet() const { return _repeatAll; }
|
||||
bool isRadioSet() const { return _radio; }
|
||||
AuthMode getAuthMode() const { return _authMode; }
|
||||
UITheme getUITheme() const { return _uiTheme; }
|
||||
SubsonicArtistListMode getSubsonicArtistListMode() const { return _subsonicArtistListMode; }
|
||||
|
||||
@@ -218,6 +227,7 @@ class User : public Wt::Dbo::Dbo<User>
|
||||
Wt::Dbo::field(a, _curPlayingTrackPos, "cur_playing_track_pos");
|
||||
Wt::Dbo::field(a, _repeatAll, "repeat_all");
|
||||
Wt::Dbo::field(a, _radio, "radio");
|
||||
Wt::Dbo::field(a, _authMode, "auth_mode");
|
||||
Wt::Dbo::hasMany(a, _tracklists, Wt::Dbo::ManyToOne, "user");
|
||||
Wt::Dbo::hasMany(a, _starredArtists, Wt::Dbo::ManyToMany, "user_artist_starred", "", Wt::Dbo::OnDeleteCascade);
|
||||
Wt::Dbo::hasMany(a, _starredReleases, Wt::Dbo::ManyToMany, "user_release_starred", "", Wt::Dbo::OnDeleteCascade);
|
||||
@@ -246,6 +256,7 @@ class User : public Wt::Dbo::Dbo<User>
|
||||
int _curPlayingTrackPos {}; // Current track position in queue
|
||||
bool _repeatAll {};
|
||||
bool _radio {};
|
||||
AuthMode _authMode {defaultAuthMode};
|
||||
|
||||
Wt::Dbo::collection<Wt::Dbo::ptr<TrackList>> _tracklists;
|
||||
Wt::Dbo::collection<Wt::Dbo::ptr<Artist>> _starredArtists;
|
||||
|
||||
@@ -34,7 +34,7 @@ namespace API::Subsonic::Scan
|
||||
|
||||
const IMediaScanner::Status scanStatus {ServiceProvider<IMediaScanner>::get()->getStatus()};
|
||||
|
||||
statusResponse.setAttribute("scanning", scanStatus.currentState == IMediaScanner::State::InProgress ? "true" : "false");
|
||||
statusResponse.setAttribute("scanning", scanStatus.currentState == IMediaScanner::State::InProgress);
|
||||
if (scanStatus.currentState == IMediaScanner::State::InProgress && scanStatus.inProgressScanStats)
|
||||
statusResponse.setAttribute("count", scanStatus.inProgressScanStats->processedFiles);
|
||||
|
||||
|
||||
@@ -57,7 +57,6 @@ struct StreamParameters
|
||||
std::optional<Av::TranscodeParameters> transcodeParameters;
|
||||
};
|
||||
|
||||
|
||||
static
|
||||
StreamParameters
|
||||
getStreamParameters(RequestContext& context)
|
||||
@@ -110,7 +109,44 @@ getStreamParameters(RequestContext& context)
|
||||
}
|
||||
|
||||
void
|
||||
handle(RequestContext& context, const Wt::Http::Request& request, Wt::Http::Response& response)
|
||||
handleDownload(RequestContext& context, const Wt::Http::Request& request, Wt::Http::Response& response)
|
||||
{
|
||||
std::shared_ptr<IResourceHandler> resourceHandler;
|
||||
|
||||
Wt::Http::ResponseContinuation *continuation = request.continuation();
|
||||
if (!continuation)
|
||||
{
|
||||
// Mandatory params
|
||||
Id id {getMandatoryParameterAs<Id>(context.parameters, "id")};
|
||||
|
||||
std::filesystem::path trackPath;
|
||||
{
|
||||
auto transaction {context.dbSession.createSharedTransaction()};
|
||||
|
||||
auto track {Track::getById(context.dbSession, id.value)};
|
||||
if (!track)
|
||||
throw RequestedDataNotFoundError {};
|
||||
|
||||
trackPath = track->getPath();
|
||||
}
|
||||
|
||||
resourceHandler = createFileResourceHandler(trackPath);
|
||||
}
|
||||
else
|
||||
{
|
||||
resourceHandler = Wt::cpp17::any_cast<std::shared_ptr<IResourceHandler>>(continuation->data());
|
||||
}
|
||||
|
||||
resourceHandler->processRequest(request, response);
|
||||
if (!resourceHandler->isFinished())
|
||||
{
|
||||
Wt::Http::ResponseContinuation *continuation = response.createContinuation();
|
||||
continuation->setData(resourceHandler);
|
||||
}
|
||||
}
|
||||
|
||||
void
|
||||
handleStream(RequestContext& context, const Wt::Http::Request& request, Wt::Http::Response& response)
|
||||
{
|
||||
std::shared_ptr<IResourceHandler> resourceHandler;
|
||||
|
||||
|
||||
@@ -26,6 +26,7 @@
|
||||
|
||||
namespace API::Subsonic::Stream
|
||||
{
|
||||
void handle(RequestContext& context, const Wt::Http::Request& request, Wt::Http::Response& response);
|
||||
void handleDownload(RequestContext& context, const Wt::Http::Request& request, Wt::Http::Response& response);
|
||||
void handleStream(RequestContext& context, const Wt::Http::Request& request, Wt::Http::Response& response);
|
||||
}
|
||||
|
||||
|
||||
@@ -19,6 +19,7 @@
|
||||
#include "subsonic/SubsonicResource.hpp"
|
||||
|
||||
#include <atomic>
|
||||
#include <iomanip>
|
||||
#include <unordered_map>
|
||||
|
||||
#include <Wt/WLocalDateTime.h>
|
||||
@@ -50,8 +51,7 @@ using namespace Database;
|
||||
|
||||
static const std::string genreClusterName {"GENRE"};
|
||||
static const std::string reportedStarredDate {"2000-01-01T00:00:00"};
|
||||
static const std::string reportedCreatedBookmarkDate {"2000-01-01T00:00:00"};
|
||||
static const std::string reportedChangedBookmarkDate {"2000-01-01T00:00:00"};
|
||||
static const std::string reportedDummyDate {"2000-01-01T00:00:00"};
|
||||
|
||||
namespace API::Subsonic
|
||||
{
|
||||
@@ -287,7 +287,7 @@ trackToResponseNode(const Track::pointer& track, Session& dbSession, const User:
|
||||
Response::Node trackResponse;
|
||||
|
||||
trackResponse.setAttribute("id", IdToString({Id::Type::Track, track.id()}));
|
||||
trackResponse.setAttribute("isDir", "false");
|
||||
trackResponse.setAttribute("isDir", false);
|
||||
trackResponse.setAttribute("title", track->getName());
|
||||
if (track->getTrackNumber())
|
||||
trackResponse.setAttribute("track", *track->getTrackNumber());
|
||||
@@ -358,8 +358,8 @@ trackBookmarkToResponseNode(const TrackBookmark::pointer& trackBookmark)
|
||||
trackBookmarkNode.setAttribute("position", trackBookmark->getOffset().count());
|
||||
if (!trackBookmark->getComment().empty())
|
||||
trackBookmarkNode.setAttribute("comment", trackBookmark->getComment());
|
||||
trackBookmarkNode.setAttribute("created", reportedCreatedBookmarkDate);
|
||||
trackBookmarkNode.setAttribute("changed", reportedChangedBookmarkDate);
|
||||
trackBookmarkNode.setAttribute("created", reportedDummyDate);
|
||||
trackBookmarkNode.setAttribute("changed", reportedDummyDate);
|
||||
trackBookmarkNode.setAttribute("username", trackBookmark->getUser()->getLoginName());
|
||||
|
||||
return trackBookmarkNode;
|
||||
@@ -380,7 +380,13 @@ releaseToResponseNode(const Release::pointer& release, Session& dbSession, const
|
||||
else
|
||||
{
|
||||
albumNode.setAttribute("title", release->getName());
|
||||
albumNode.setAttribute("isDir", "true");
|
||||
albumNode.setAttribute("isDir", true);
|
||||
}
|
||||
|
||||
{
|
||||
std::time_t t {release->getLastWritten().toTime_t()};
|
||||
std::ostringstream oss; oss << std::put_time(std::gmtime(&t), "%FT%T");
|
||||
albumNode.setAttribute("created", oss.str());
|
||||
}
|
||||
|
||||
albumNode.setAttribute("id", IdToString({Id::Type::Release, release.id()}));
|
||||
@@ -471,18 +477,18 @@ userToResponseNode(const User::pointer& user)
|
||||
Response::Node userNode;
|
||||
|
||||
userNode.setAttribute("username", user->getLoginName());
|
||||
userNode.setAttribute("scrobblingEnabled", "false");
|
||||
userNode.setAttribute("adminRole", user->isAdmin() ? "true" : "false");
|
||||
userNode.setAttribute("settingsRole", "true");
|
||||
userNode.setAttribute("downloadRole", "false");
|
||||
userNode.setAttribute("uploadRole", "false");
|
||||
userNode.setAttribute("playlistRole", "true");
|
||||
userNode.setAttribute("coverArtRole", "false");
|
||||
userNode.setAttribute("commentRole", "false");
|
||||
userNode.setAttribute("podcastRole", "false");
|
||||
userNode.setAttribute("streamRole", "true");
|
||||
userNode.setAttribute("jukeboxRole", "false");
|
||||
userNode.setAttribute("shareRole", "false");
|
||||
userNode.setAttribute("scrobblingEnabled", false);
|
||||
userNode.setAttribute("adminRole", user->isAdmin());
|
||||
userNode.setAttribute("settingsRole", true);
|
||||
userNode.setAttribute("downloadRole", true);
|
||||
userNode.setAttribute("uploadRole", false);
|
||||
userNode.setAttribute("playlistRole", true);
|
||||
userNode.setAttribute("coverArtRole", false);
|
||||
userNode.setAttribute("commentRole", false);
|
||||
userNode.setAttribute("podcastRole", false);
|
||||
userNode.setAttribute("streamRole", true);
|
||||
userNode.setAttribute("jukeboxRole", false);
|
||||
userNode.setAttribute("shareRole", false);
|
||||
|
||||
Response::Node folder;
|
||||
folder.setValue("0");
|
||||
@@ -597,7 +603,9 @@ handleCreateUserRequest(RequestContext& context)
|
||||
if (User::getByLoginName(context.dbSession, username) != User::pointer{})
|
||||
throw UserAlreadyExistsGenericError {};
|
||||
|
||||
User::pointer user {User::create(context.dbSession, username, hash)};
|
||||
User::pointer user {User::create(context.dbSession, username)};
|
||||
user.modify()->setAuthMode(User::AuthMode::Internal);
|
||||
user.modify()->setPasswordHash(hash);
|
||||
|
||||
return Response::createOkResponse(context);
|
||||
}
|
||||
@@ -659,7 +667,7 @@ handleGetLicenseRequest(RequestContext& context)
|
||||
Response::Node& licenseNode {response.createNode("license")};
|
||||
licenseNode.setAttribute("licenseExpires", "2025-09-03T14:46:43");
|
||||
licenseNode.setAttribute("email", "foo@bar.com");
|
||||
licenseNode.setAttribute("valid", "true");
|
||||
licenseNode.setAttribute("valid", true);
|
||||
|
||||
return response;
|
||||
}
|
||||
@@ -715,9 +723,8 @@ handleGetAlbumListRequestCommon(const RequestContext& context, bool id3)
|
||||
}
|
||||
else if (type == "newest")
|
||||
{
|
||||
auto after {Wt::WLocalDateTime::currentServerDateTime().toUTC().addMonths(-6)};
|
||||
bool moreResults {};
|
||||
releases = Release::getLastWritten(context.dbSession, after, {}, Range {offset, size}, moreResults);
|
||||
releases = Release::getLastWritten(context.dbSession, std::nullopt, {}, Range {offset, size}, moreResults);
|
||||
}
|
||||
else if (type == "alphabeticalByName")
|
||||
{
|
||||
@@ -1210,8 +1217,8 @@ tracklistToResponseNode(const TrackList::pointer& tracklist, Session&)
|
||||
playlistNode.setAttribute("name", tracklist->getName());
|
||||
playlistNode.setAttribute("songCount", tracklist->getCount());
|
||||
playlistNode.setAttribute("duration", std::chrono::duration_cast<std::chrono::seconds>(tracklist->getDuration()).count());
|
||||
playlistNode.setAttribute("public", tracklist->isPublic() ? "true" : "false");
|
||||
playlistNode.setAttribute("created", "");
|
||||
playlistNode.setAttribute("public", tracklist->isPublic());
|
||||
playlistNode.setAttribute("created", reportedDummyDate);
|
||||
playlistNode.setAttribute("owner", tracklist->getUser()->getLoginName());
|
||||
|
||||
return playlistNode;
|
||||
@@ -1585,7 +1592,7 @@ handleUpdatePlaylistRequest(RequestContext& context)
|
||||
|
||||
std::vector<std::size_t> trackPositionsToRemove {getMultiParametersAs<std::size_t>(context.parameters, "songIndexToRemove")};
|
||||
|
||||
auto transaction {context.dbSession.createSharedTransaction()};
|
||||
auto transaction {context.dbSession.createUniqueTransaction()};
|
||||
|
||||
User::pointer user {User::getByLoginName(context.dbSession, context.userName)};
|
||||
if (!user)
|
||||
@@ -1805,8 +1812,7 @@ static std::unordered_map<std::string, RequestEntryPointInfo> requestEntryPoints
|
||||
{"deletePlaylist", {handleDeletePlaylistRequest, false}},
|
||||
|
||||
// Media retrieval
|
||||
{"download", {handleNotImplemented, false}},
|
||||
{"hls", {handleNotImplemented, false}},
|
||||
{"hls", {handleNotImplemented, false}},
|
||||
{"getCaptions", {handleNotImplemented, false}},
|
||||
{"getLyrics", {handleNotImplemented, false}},
|
||||
{"getAvatar", {handleNotImplemented, false}},
|
||||
@@ -1869,8 +1875,9 @@ using MediaRetrievalHandlerFunc = std::function<void(RequestContext&, const Wt::
|
||||
static std::unordered_map<std::string, MediaRetrievalHandlerFunc> mediaRetrievalHandlers
|
||||
{
|
||||
// Media retrieval
|
||||
{"download", Stream::handleDownload},
|
||||
{"stream", Stream::handleStream},
|
||||
{"getCoverArt", handleGetCoverArt},
|
||||
{"stream", Stream::handle},
|
||||
};
|
||||
|
||||
void
|
||||
|
||||
@@ -69,16 +69,10 @@ Response::Node::setAttribute(std::string_view key, std::string_view value)
|
||||
_attributes[std::string {key}] = std::string {value};
|
||||
}
|
||||
|
||||
void
|
||||
Response::Node::setAttribute(std::string_view key, long long value)
|
||||
{
|
||||
_attributes[std::string {key}] = value;
|
||||
}
|
||||
|
||||
void
|
||||
Response::Node::addChild(const std::string& key, Node node)
|
||||
{
|
||||
if (_value.valueless_by_exception())
|
||||
if (_value)
|
||||
throw LmsException {"Node already has a value"};
|
||||
|
||||
_children[key].emplace_back(std::move(node));
|
||||
@@ -87,7 +81,7 @@ Response::Node::addChild(const std::string& key, Node node)
|
||||
void
|
||||
Response::Node::addArrayChild(const std::string& key, Node node)
|
||||
{
|
||||
if (_value.valueless_by_exception())
|
||||
if (_value)
|
||||
throw LmsException {"Node already has a value"};
|
||||
|
||||
_childrenArrays[key].emplace_back(std::move(node));
|
||||
@@ -179,16 +173,22 @@ Response::writeXML(std::ostream& os)
|
||||
{
|
||||
if (std::holds_alternative<std::string>(itAttribute.second))
|
||||
res.put("<xmlattr>." + itAttribute.first, std::get<std::string>(itAttribute.second));
|
||||
else if (std::holds_alternative<bool>(itAttribute.second))
|
||||
res.put("<xmlattr>." + itAttribute.first, std::get<bool>(itAttribute.second));
|
||||
else if (std::holds_alternative<long long>(itAttribute.second))
|
||||
res.put("<xmlattr>." + itAttribute.first, std::get<long long>(itAttribute.second));
|
||||
}
|
||||
|
||||
if (node._value.valueless_by_exception())
|
||||
if (node._value)
|
||||
{
|
||||
if (std::holds_alternative<std::string>(node._value))
|
||||
res.put_value(std::get<std::string>(node._value));
|
||||
else if (std::holds_alternative<long long>(node._value))
|
||||
res.put_value(std::get<long long>(node._value));
|
||||
const auto& value {*node._value};
|
||||
|
||||
if (std::holds_alternative<std::string>(value))
|
||||
res.put_value(std::get<std::string>(value));
|
||||
else if (std::holds_alternative<bool>(value))
|
||||
res.put_value(std::get<bool>(value));
|
||||
else if (std::holds_alternative<long long>(value))
|
||||
res.put_value(std::get<long long>(value));
|
||||
}
|
||||
else
|
||||
{
|
||||
@@ -200,7 +200,7 @@ Response::writeXML(std::ostream& os)
|
||||
|
||||
for (auto itChildArrayNode : node._childrenArrays)
|
||||
{
|
||||
const std::vector<Response::Node>& childArrayNodes {itChildArrayNode .second};
|
||||
const std::vector<Response::Node>& childArrayNodes {itChildArrayNode.second};
|
||||
|
||||
for (const Response::Node& childNode : childArrayNodes )
|
||||
res.add_child(itChildArrayNode.first, nodeToPropertyTree(childNode));
|
||||
@@ -217,9 +217,11 @@ Response::writeXML(std::ostream& os)
|
||||
unsigned
|
||||
Response::getAPIMinorVersion(std::string_view clientName)
|
||||
{
|
||||
// Audinaut does not lower its client API version in plain text authentication mode
|
||||
// Some clients do not rely on version to enable the clear text password auth scheme
|
||||
if (clientName == "Audinaut")
|
||||
return 13;
|
||||
return 16;
|
||||
else if (clientName == "Sublime Music")
|
||||
return 16;
|
||||
else
|
||||
return 12;
|
||||
}
|
||||
@@ -233,20 +235,24 @@ Response::writeJSON(std::ostream& os)
|
||||
{
|
||||
Json::Object res;
|
||||
|
||||
for (auto itAttribute : node._attributes)
|
||||
auto valueToJsonValue {[](const Node::Value& value) -> Json::Value
|
||||
{
|
||||
if (std::holds_alternative<std::string>(itAttribute.second))
|
||||
res[itAttribute.first] = Json::Value {std::get<std::string>(itAttribute.second)};
|
||||
else if (std::holds_alternative<long long>(itAttribute.second))
|
||||
res[itAttribute.first] = Json::Value {std::get<long long>(itAttribute.second)};
|
||||
}
|
||||
if (std::holds_alternative<std::string>(value))
|
||||
return Json::Value {std::get<std::string>(value)};
|
||||
else if (std::holds_alternative<bool>(value))
|
||||
return Json::Value {std::get<bool>(value)};
|
||||
else if (std::holds_alternative<long long>(value))
|
||||
return Json::Value {std::get<long long>(value)};
|
||||
|
||||
if (node._value.valueless_by_exception())
|
||||
throw LmsException("Unexpected value type");
|
||||
}};
|
||||
|
||||
for (auto itAttribute : node._attributes)
|
||||
res[itAttribute.first] = valueToJsonValue(itAttribute.second);
|
||||
|
||||
if (node._value)
|
||||
{
|
||||
if (std::holds_alternative<std::string>(node._value))
|
||||
res["value"] = Json::Value {std::get<std::string>(node._value)};
|
||||
else if (std::holds_alternative<long long>(node._value))
|
||||
res["value"] = Json::Value {std::get<long long>(node._value)};
|
||||
res["value"] = valueToJsonValue(*node._value);
|
||||
}
|
||||
else
|
||||
{
|
||||
|
||||
@@ -19,6 +19,7 @@
|
||||
#pragma once
|
||||
|
||||
#include <map>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <variant>
|
||||
@@ -180,7 +181,15 @@ class Response
|
||||
{
|
||||
public:
|
||||
void setAttribute(std::string_view key, std::string_view value);
|
||||
void setAttribute(std::string_view key, long long value);
|
||||
|
||||
template <typename T, std::enable_if_t<std::is_arithmetic<T>::value>* = nullptr>
|
||||
void setAttribute(std::string_view key, T value)
|
||||
{
|
||||
if constexpr (std::is_same<bool, T>::value)
|
||||
_attributes[std::string {key}] = value;
|
||||
else
|
||||
_attributes[std::string {key}] = static_cast<long long>(value);
|
||||
}
|
||||
|
||||
// A Node has either a value or some children
|
||||
void setValue(std::string_view value);
|
||||
@@ -193,8 +202,9 @@ class Response
|
||||
|
||||
private:
|
||||
friend class Response;
|
||||
std::map<std::string, std::variant<std::string, long long>> _attributes;
|
||||
std::variant<std::string, long long> _value;
|
||||
using Value = std::variant<std::string, bool, long long>;
|
||||
std::map<std::string, Value> _attributes;
|
||||
std::optional<Value> _value;
|
||||
std::map<std::string, std::vector<Node>> _children;
|
||||
std::map<std::string, std::vector<Node>> _childrenArrays;
|
||||
};
|
||||
|
||||
@@ -25,7 +25,7 @@ target_link_libraries(lmsutils PRIVATE
|
||||
)
|
||||
|
||||
target_link_libraries(lmsutils PUBLIC
|
||||
boost_system
|
||||
Boost::system
|
||||
std::filesystem
|
||||
wt
|
||||
)
|
||||
|
||||
@@ -164,6 +164,7 @@ jsEscape(const std::string& str)
|
||||
{ '\r', "\\r" },
|
||||
{ '\t', "\\t" },
|
||||
{ '"', "\\\"" },
|
||||
{ '\'', "\\\'" },
|
||||
};
|
||||
|
||||
std::string escaped;
|
||||
|
||||
@@ -14,6 +14,7 @@ add_executable(lms
|
||||
ui/admin/InitWizardView.cpp
|
||||
ui/admin/UserView.cpp
|
||||
ui/admin/UsersView.cpp
|
||||
ui/common/AuthModeModel.cpp
|
||||
ui/common/Validators.cpp
|
||||
ui/explore/ArtistListHelpers.cpp
|
||||
ui/explore/ArtistView.cpp
|
||||
|
||||
@@ -19,6 +19,7 @@
|
||||
|
||||
#include "InitWizardView.hpp"
|
||||
|
||||
#include <Wt/WComboBox.h>
|
||||
#include <Wt/WFormModel.h>
|
||||
#include <Wt/WLineEdit.h>
|
||||
#include <Wt/WPushButton.h>
|
||||
@@ -29,6 +30,7 @@
|
||||
#include "utils/Service.hpp"
|
||||
|
||||
#include "common/Validators.hpp"
|
||||
#include "common/AuthModeModel.hpp"
|
||||
#include "LmsApplication.hpp"
|
||||
|
||||
namespace UserInterface {
|
||||
@@ -41,18 +43,23 @@ class InitWizardModel : public Wt::WFormModel
|
||||
static const Field AdminLoginField;
|
||||
static const Field PasswordField;
|
||||
static const Field PasswordConfirmField;
|
||||
static inline const Field AuthModeField{"auth-mode"};
|
||||
|
||||
InitWizardModel() : Wt::WFormModel()
|
||||
{
|
||||
addField(AdminLoginField);
|
||||
addField(AuthModeField);
|
||||
addField(PasswordField);
|
||||
addField(PasswordConfirmField);
|
||||
|
||||
setValidator(AuthModeField, createMandatoryValidator());
|
||||
setValidator(AdminLoginField, createNameValidator());
|
||||
setValidator(PasswordField, createMandatoryValidator());
|
||||
setValidator(PasswordConfirmField, createMandatoryValidator());
|
||||
}
|
||||
|
||||
std::shared_ptr<AuthModeModel> getAuthModeModel() const { return _authModeModel; }
|
||||
|
||||
void saveData()
|
||||
{
|
||||
const Database::User::PasswordHash passwordHash {ServiceProvider<::Auth::IPasswordService>::get()->hashPassword(valueText(PasswordField).toUTF8())};
|
||||
@@ -64,8 +71,54 @@ class InitWizardModel : public Wt::WFormModel
|
||||
if (!Database::User::getAll(LmsApp->getDbSession()).empty())
|
||||
throw LmsException("Admin user already created");
|
||||
|
||||
Database::User::pointer user {Database::User::create(LmsApp->getDbSession(), valueText(AdminLoginField).toUTF8(), passwordHash)};
|
||||
auto authModeRow {_authModeModel->getRowFromString(valueText(AuthModeField))};
|
||||
if (!authModeRow)
|
||||
throw LmsException {"Bad authentication mode"};
|
||||
|
||||
const Database::User::AuthMode authMode {_authModeModel->getValue(*authModeRow)};
|
||||
|
||||
Database::User::pointer user {Database::User::create(LmsApp->getDbSession(), valueText(AdminLoginField).toUTF8())};
|
||||
user.modify()->setType(Database::User::Type::ADMIN);
|
||||
user.modify()->setAuthMode(authMode);
|
||||
if (authMode == Database::User::AuthMode::Internal)
|
||||
user.modify()->setPasswordHash(passwordHash);
|
||||
}
|
||||
|
||||
void validatePassword(Wt::WString& error) const
|
||||
{
|
||||
auto authModeRow {_authModeModel->getRowFromString(valueText(AuthModeField))};
|
||||
if (!authModeRow)
|
||||
throw LmsException {"Bad authentication mode"};
|
||||
|
||||
const Database::User::AuthMode authMode {_authModeModel->getValue(*authModeRow)};
|
||||
if (authMode != Database::User::AuthMode::Internal)
|
||||
return;
|
||||
|
||||
if (!valueText(PasswordField).empty())
|
||||
{
|
||||
// Evaluate the strength of the password
|
||||
if (!ServiceProvider<::Auth::IPasswordService>::get()->evaluatePasswordStrength(valueText(AdminLoginField).toUTF8(), valueText(PasswordField).toUTF8()))
|
||||
error = Wt::WString::tr("Lms.password-too-weak");
|
||||
}
|
||||
else
|
||||
error = Wt::WString::tr("Lms.password-must-not-be-empty");
|
||||
}
|
||||
|
||||
void validatePasswordConfirm(Wt::WString& error) const
|
||||
{
|
||||
auto authModeRow {_authModeModel->getRowFromString(valueText(AuthModeField))};
|
||||
if (!authModeRow)
|
||||
throw LmsException {"Bad authentication mode"};
|
||||
|
||||
const Database::User::AuthMode authMode {_authModeModel->getValue(*authModeRow)};
|
||||
if (authMode != Database::User::AuthMode::Internal)
|
||||
return;
|
||||
|
||||
if (validation(PasswordField).state() == Wt::ValidationState::Valid)
|
||||
{
|
||||
if (valueText(PasswordField) != valueText(PasswordConfirmField))
|
||||
error = Wt::WString::tr("Lms.passwords-dont-match");
|
||||
}
|
||||
}
|
||||
|
||||
bool validateField(Field field)
|
||||
@@ -74,22 +127,11 @@ class InitWizardModel : public Wt::WFormModel
|
||||
|
||||
if (field == PasswordField)
|
||||
{
|
||||
if (!valueText(PasswordField).empty())
|
||||
{
|
||||
// Evaluate the strength of the password
|
||||
if (!ServiceProvider<::Auth::IPasswordService>::get()->evaluatePasswordStrength(valueText(AdminLoginField).toUTF8(), valueText(PasswordField).toUTF8()))
|
||||
error = Wt::WString::tr("Lms.password-too-weak");
|
||||
}
|
||||
else
|
||||
return Wt::WFormModel::validateField(field);
|
||||
validatePassword(error);
|
||||
}
|
||||
else if (field == PasswordConfirmField)
|
||||
{
|
||||
if (validation(PasswordField).state() == Wt::ValidationState::Valid)
|
||||
{
|
||||
if (valueText(PasswordField) != valueText(PasswordConfirmField))
|
||||
error = Wt::WString::tr("Lms.passwords-dont-match");
|
||||
}
|
||||
validatePasswordConfirm(error);
|
||||
}
|
||||
else
|
||||
{
|
||||
@@ -101,6 +143,7 @@ class InitWizardModel : public Wt::WFormModel
|
||||
return (validation(field).state() == Wt::ValidationState::Valid);
|
||||
}
|
||||
|
||||
std::shared_ptr<AuthModeModel> _authModeModel {createAuthModeModel()};
|
||||
};
|
||||
|
||||
const Wt::WFormModel::Field InitWizardModel::AdminLoginField = "admin-login";
|
||||
@@ -119,6 +162,20 @@ InitWizardView::InitWizardView()
|
||||
setFormWidget(InitWizardModel::AdminLoginField, std::move(adminLogin));
|
||||
}
|
||||
|
||||
// Auth mode
|
||||
auto authMode = std::make_unique<Wt::WComboBox>();
|
||||
authMode->setModel(model->getAuthModeModel());
|
||||
authMode->activated().connect([=](int row)
|
||||
{
|
||||
const Database::User::AuthMode authMode {model->getAuthModeModel()->getValue(row)};
|
||||
|
||||
model->setReadOnly(InitWizardModel::PasswordField, authMode != Database::User::AuthMode::Internal);
|
||||
model->setReadOnly(InitWizardModel::PasswordConfirmField, authMode != Database::User::AuthMode::Internal);
|
||||
updateModel(model.get());
|
||||
updateView(model.get());
|
||||
});
|
||||
setFormWidget(InitWizardModel::AuthModeField, std::move(authMode));
|
||||
|
||||
// Password
|
||||
{
|
||||
auto passwordEdit = std::make_unique<Wt::WLineEdit>();
|
||||
|
||||
@@ -35,6 +35,7 @@
|
||||
#include "utils/Service.hpp"
|
||||
#include "utils/String.hpp"
|
||||
|
||||
#include "common/AuthModeModel.hpp"
|
||||
#include "common/Validators.hpp"
|
||||
#include "common/ValueStringModel.hpp"
|
||||
#include "LmsApplication.hpp"
|
||||
@@ -51,6 +52,9 @@ class UserModel : public Wt::WFormModel
|
||||
static inline const Field LoginField {"login"};
|
||||
static inline const Field PasswordField {"password"};
|
||||
static inline const Field DemoField {"demo"};
|
||||
static inline const Field AuthModeField{"auth-mode"};
|
||||
|
||||
using AuthModeModel = ValueStringModel<User::AuthMode>;
|
||||
|
||||
UserModel(std::optional<Database::IdType> userId)
|
||||
: _userId {userId}
|
||||
@@ -61,16 +65,17 @@ class UserModel : public Wt::WFormModel
|
||||
setValidator(LoginField, createNameValidator());
|
||||
}
|
||||
|
||||
addField(AuthModeField);
|
||||
addField(PasswordField);
|
||||
addField(DemoField);
|
||||
|
||||
if (!_userId)
|
||||
setValidator(PasswordField, createMandatoryValidator());
|
||||
setValidator(AuthModeField, createMandatoryValidator());
|
||||
|
||||
// populate the model with initial data
|
||||
loadData();
|
||||
}
|
||||
|
||||
std::shared_ptr<AuthModeModel> getAuthModeModel() const { return _authModeModel; }
|
||||
|
||||
void saveData()
|
||||
{
|
||||
std::optional<Database::User::PasswordHash> passwordHash;
|
||||
@@ -84,8 +89,13 @@ class UserModel : public Wt::WFormModel
|
||||
// Update user
|
||||
Database::User::pointer user {Database::User::getById(LmsApp->getDbSession(), *_userId)};
|
||||
|
||||
// Account
|
||||
if (passwordHash)
|
||||
auto authModeRow {_authModeModel->getRowFromString(valueText(AuthModeField))};
|
||||
if (!authModeRow)
|
||||
throw LmsException {"Bad authentication mode"};
|
||||
|
||||
const Database::User::AuthMode authMode {_authModeModel->getValue(*authModeRow)};
|
||||
user.modify()->setAuthMode(authMode);
|
||||
if (authMode == Database::User::AuthMode::Internal && passwordHash)
|
||||
{
|
||||
user.modify()->setPasswordHash(*passwordHash);
|
||||
user.modify()->clearAuthTokens();
|
||||
@@ -94,15 +104,70 @@ class UserModel : public Wt::WFormModel
|
||||
else
|
||||
{
|
||||
// Create user
|
||||
Database::User::pointer user {Database::User::create(LmsApp->getDbSession(), valueText(LoginField).toUTF8(), *passwordHash)};
|
||||
Database::User::pointer user {Database::User::create(LmsApp->getDbSession(), valueText(LoginField).toUTF8())};
|
||||
|
||||
if (Wt::asNumber(value(DemoField)))
|
||||
user.modify()->setType(Database::User::Type::DEMO);
|
||||
|
||||
auto authModeRow {_authModeModel->getRowFromString(valueText(AuthModeField))};
|
||||
if (!authModeRow)
|
||||
throw LmsException {"Bad authentication mode"};
|
||||
|
||||
const Database::User::AuthMode authMode {_authModeModel->getValue(*authModeRow)};
|
||||
user.modify()->setAuthMode(authMode);
|
||||
if (authMode == Database::User::AuthMode::Internal)
|
||||
user.modify()->setPasswordHash(*passwordHash);
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
void validatePassword(Wt::WString& error) const
|
||||
{
|
||||
auto authModeRow {_authModeModel->getRowFromString(valueText(AuthModeField))};
|
||||
if (!authModeRow)
|
||||
throw LmsException {"Bad authentication mode"};
|
||||
|
||||
const Database::User::AuthMode authMode {_authModeModel->getValue(*authModeRow)};
|
||||
if (authMode != Database::User::AuthMode::Internal)
|
||||
return;
|
||||
|
||||
if (!valueText(PasswordField).empty())
|
||||
{
|
||||
if (Wt::asNumber(value(DemoField)))
|
||||
{
|
||||
// Demo account: password must be the same as the login name
|
||||
if (valueText(PasswordField) != getLoginName())
|
||||
error = Wt::WString::tr("Lms.Admin.User.demo-password-invalid");
|
||||
}
|
||||
else
|
||||
{
|
||||
// Evaluate the strength of the password for non demo accounts
|
||||
if (!ServiceProvider<::Auth::IPasswordService>::get()->evaluatePasswordStrength(getLoginName(), valueText(PasswordField).toUTF8()))
|
||||
error = Wt::WString::tr("Lms.password-too-weak");
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
auto transaction {LmsApp->getDbSession().createSharedTransaction()};
|
||||
|
||||
bool needPassword {true};
|
||||
|
||||
// Allow an empty password if and only if the user previously had one set
|
||||
if (_userId)
|
||||
{
|
||||
const Database::User::pointer user {Database::User::getById(LmsApp->getDbSession(), *_userId)};
|
||||
if (!user)
|
||||
throw UserNotFoundException {*_userId};
|
||||
|
||||
needPassword = user->getPasswordHash().hash.empty();
|
||||
}
|
||||
|
||||
if (needPassword)
|
||||
error = Wt::WString::tr("Lms.password-must-not-be-empty");
|
||||
}
|
||||
}
|
||||
|
||||
void loadData()
|
||||
{
|
||||
if (!_userId)
|
||||
@@ -115,6 +180,14 @@ class UserModel : public Wt::WFormModel
|
||||
throw UserNotFoundException {*_userId};
|
||||
else if (user == LmsApp->getUser())
|
||||
throw UserNotAllowedException {};
|
||||
|
||||
auto authModeRow {_authModeModel->getRowFromValue(user->getAuthMode())};
|
||||
if (authModeRow)
|
||||
{
|
||||
setValue(AuthModeField, _authModeModel->getString(*authModeRow));
|
||||
if (_authModeModel->getValue(*authModeRow) != User::AuthMode::Internal)
|
||||
setReadOnly(PasswordField, true);
|
||||
}
|
||||
}
|
||||
|
||||
std::string getLoginName() const
|
||||
@@ -144,21 +217,7 @@ class UserModel : public Wt::WFormModel
|
||||
}
|
||||
else if (field == PasswordField)
|
||||
{
|
||||
if (!valueText(PasswordField).empty())
|
||||
{
|
||||
if (Wt::asNumber(value(DemoField)))
|
||||
{
|
||||
// Demo account: password must be the same as the login name
|
||||
if (valueText(PasswordField) != getLoginName())
|
||||
error = Wt::WString::tr("Lms.Admin.User.demo-password-invalid");
|
||||
}
|
||||
else
|
||||
{
|
||||
// Evaluate the strength of the password for non demo accounts
|
||||
if (!ServiceProvider<::Auth::IPasswordService>::get()->evaluatePasswordStrength(getLoginName(), valueText(PasswordField).toUTF8()))
|
||||
error = Wt::WString::tr("Lms.password-too-weak");
|
||||
}
|
||||
}
|
||||
validatePassword(error);
|
||||
}
|
||||
else if (field == DemoField)
|
||||
{
|
||||
@@ -177,6 +236,7 @@ class UserModel : public Wt::WFormModel
|
||||
}
|
||||
|
||||
std::optional<Database::IdType> _userId;
|
||||
std::shared_ptr<AuthModeModel> _authModeModel {createAuthModeModel()};
|
||||
};
|
||||
|
||||
UserView::UserView()
|
||||
@@ -213,7 +273,6 @@ UserView::refreshView()
|
||||
|
||||
t->bindString("title", Wt::WString::tr("Lms.Admin.User.user-edit").arg(user->getLoginName()), Wt::TextFormat::Plain);
|
||||
t->setCondition("if-has-last-login", true);
|
||||
|
||||
t->bindString("last-login", user->getLastLogin().toString(), Wt::TextFormat::Plain);
|
||||
}
|
||||
else
|
||||
@@ -224,6 +283,19 @@ UserView::refreshView()
|
||||
t->bindString("title", Wt::WString::tr("Lms.Admin.User.user-create"));
|
||||
}
|
||||
|
||||
// Auth mode
|
||||
auto authMode = std::make_unique<Wt::WComboBox>();
|
||||
authMode->setModel(model->getAuthModeModel());
|
||||
authMode->activated().connect([=](int row)
|
||||
{
|
||||
const User::AuthMode authMode {model->getAuthModeModel()->getValue(row)};
|
||||
|
||||
model->setReadOnly(UserModel::PasswordField, authMode != User::AuthMode::Internal);
|
||||
t->updateModel(model.get());
|
||||
t->updateView(model.get());
|
||||
});
|
||||
t->setFormWidget(UserModel::AuthModeField, std::move(authMode));
|
||||
|
||||
// Password
|
||||
auto passwordEdit = std::make_unique<Wt::WLineEdit>();
|
||||
passwordEdit->setEchoMode(Wt::EchoMode::Password);
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
/*
|
||||
* Copyright (C) 2020 Emeric Poupon
|
||||
*
|
||||
* This file is part of LMS.
|
||||
*
|
||||
* LMS is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* LMS is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with LMS. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#include "AuthModeModel.hpp"
|
||||
|
||||
#include "auth/IPasswordService.hpp"
|
||||
#include "utils/Service.hpp"
|
||||
|
||||
namespace UserInterface
|
||||
{
|
||||
|
||||
std::unique_ptr<AuthModeModel>
|
||||
createAuthModeModel()
|
||||
{
|
||||
auto model {std::make_unique<AuthModeModel>()};
|
||||
|
||||
if (ServiceProvider<::Auth::IPasswordService>::get()->isAuthModeSupported(Database::User::AuthMode::Internal))
|
||||
model->add(Wt::WString::tr("Lms.Admin.User.auth-mode.internal"), Database::User::AuthMode::Internal);
|
||||
if (ServiceProvider<::Auth::IPasswordService>::get()->isAuthModeSupported(Database::User::AuthMode::PAM))
|
||||
model->add(Wt::WString::tr("Lms.Admin.User.auth-mode.pam"), Database::User::AuthMode::PAM);
|
||||
|
||||
return model;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
/*
|
||||
* Copyright (C) 2020 Emeric Poupon
|
||||
*
|
||||
* This file is part of LMS.
|
||||
*
|
||||
* LMS is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* LMS is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with LMS. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "database/User.hpp"
|
||||
#include "common/ValueStringModel.hpp"
|
||||
|
||||
namespace UserInterface
|
||||
{
|
||||
using AuthModeModel = ValueStringModel<Database::User::AuthMode>;
|
||||
|
||||
std::unique_ptr<AuthModeModel> createAuthModeModel();
|
||||
}
|
||||
|
||||
@@ -39,7 +39,7 @@ std::shared_ptr<Wt::WValidator>
|
||||
createMandatoryValidator()
|
||||
{
|
||||
auto v = std::make_shared<Wt::WValidator>();
|
||||
v->setMandatory(true);
|
||||
//sv->setMandatory(true);
|
||||
return v;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
|
||||
/*
|
||||
* Copyright (C) 2019 Emeric Poupon
|
||||
*
|
||||
|
||||
@@ -210,6 +210,8 @@ testSingleRelease(Session& session)
|
||||
releases = Release::getAll(session);
|
||||
CHECK(releases.size() == 1);
|
||||
CHECK(releases.front().id() == release.getId());
|
||||
|
||||
CHECK(release->getDuration() == std::chrono::seconds {0});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -708,9 +710,15 @@ testMultipleTracksMultipleClustersTopRelease(Session& session)
|
||||
ScopedRelease releaseB {session, "ReleaseB"};
|
||||
ScopedRelease releaseC {session, "ReleaseC"};
|
||||
|
||||
ScopedUser user {session, "MyUser", User::PasswordHash {}};
|
||||
ScopedUser user {session, "MyUser"};
|
||||
ScopedTrackList trackList {session, "TrackList", TrackList::Type::Playlist, false, user.lockAndGet()};
|
||||
|
||||
{
|
||||
auto transaction {session.createSharedTransaction()};
|
||||
|
||||
CHECK(trackList->getDuration() == std::chrono::seconds {0});
|
||||
}
|
||||
|
||||
{
|
||||
auto transaction {session.createUniqueTransaction()};
|
||||
|
||||
@@ -1221,7 +1229,7 @@ static
|
||||
void
|
||||
testSingleUser(Session& session)
|
||||
{
|
||||
ScopedUser user {session, "MyUser", User::PasswordHash {}};
|
||||
ScopedUser user {session, "MyUser"};
|
||||
|
||||
{
|
||||
auto transaction {session.createSharedTransaction()};
|
||||
@@ -1240,7 +1248,7 @@ void
|
||||
testSingleStarredArtist(Session& session)
|
||||
{
|
||||
ScopedArtist artist {session, "MyArtist"};
|
||||
ScopedUser user {session, "MyUser", User::PasswordHash {}};
|
||||
ScopedUser user {session, "MyUser"};
|
||||
|
||||
{
|
||||
auto transaction {session.createSharedTransaction()};
|
||||
@@ -1264,7 +1272,7 @@ void
|
||||
testSingleStarredRelease(Session& session)
|
||||
{
|
||||
ScopedRelease release {session, "MyRelease"};
|
||||
ScopedUser user {session, "MyUser", User::PasswordHash {}};
|
||||
ScopedUser user {session, "MyUser"};
|
||||
|
||||
{
|
||||
auto transaction {session.createUniqueTransaction()};
|
||||
@@ -1288,7 +1296,7 @@ void
|
||||
testSingleStarredTrack(Session& session)
|
||||
{
|
||||
ScopedTrack track {session, "MyTrack"};
|
||||
ScopedUser user {session, "MyUser", User::PasswordHash {}};
|
||||
ScopedUser user {session, "MyUser"};
|
||||
|
||||
{
|
||||
auto transaction {session.createUniqueTransaction()};
|
||||
@@ -1311,7 +1319,7 @@ static
|
||||
void
|
||||
testSingleTrackList(Session& session)
|
||||
{
|
||||
ScopedUser user {session, "MyUser", User::PasswordHash {}};
|
||||
ScopedUser user {session, "MyUser"};
|
||||
ScopedTrackList trackList {session, "MytrackList", TrackList::Type::Playlist, false, user.lockAndGet()};
|
||||
|
||||
{
|
||||
@@ -1328,7 +1336,7 @@ static
|
||||
void
|
||||
testSingleTrackListMultipleTrack(Session& session)
|
||||
{
|
||||
ScopedUser user {session, "MyUser", User::PasswordHash {}};
|
||||
ScopedUser user {session, "MyUser"};
|
||||
ScopedTrackList trackList {session, "MytrackList", TrackList::Type::Playlist, false, user.lockAndGet()};
|
||||
std::list<ScopedTrack> tracks;
|
||||
|
||||
@@ -1354,7 +1362,7 @@ static
|
||||
void
|
||||
testSingleTrackListMultipleTrackSingleCluster(Session& session)
|
||||
{
|
||||
ScopedUser user {session, "MyUser", User::PasswordHash {}};
|
||||
ScopedUser user {session, "MyUser"};
|
||||
ScopedTrackList trackList {session, "MyTrackList", TrackList::Type::Playlist, false, user.lockAndGet()};
|
||||
ScopedClusterType clusterType {session, "MyClusterType"};
|
||||
ScopedCluster cluster {session, clusterType.lockAndGet(), "MyCluster"};
|
||||
@@ -1388,7 +1396,7 @@ static
|
||||
void
|
||||
testSingleTrackListMultipleTrackMultiClusters(Session& session)
|
||||
{
|
||||
ScopedUser user {session, "MyUser", User::PasswordHash {}};
|
||||
ScopedUser user {session, "MyUser"};
|
||||
ScopedTrackList trackList {session, "MyTrackList", TrackList::Type::Playlist, false, user.lockAndGet()};
|
||||
ScopedClusterType clusterType {session, "MyClusterType"};
|
||||
ScopedCluster cluster1 {session, clusterType.lockAndGet(), "MyCluster1"};
|
||||
@@ -1443,7 +1451,7 @@ static
|
||||
void
|
||||
testSingleTrackListMultipleTrackMultiClustersRecentlyPlayed(Session& session)
|
||||
{
|
||||
ScopedUser user {session, "MyUser", User::PasswordHash {}};
|
||||
ScopedUser user {session, "MyUser"};
|
||||
ScopedTrackList trackList {session, "MyTrackList", TrackList::Type::Playlist, false, user.lockAndGet()};
|
||||
ScopedClusterType clusterType {session, "MyClusterType"};
|
||||
ScopedCluster cluster1 {session, clusterType.lockAndGet(), "MyCluster1"};
|
||||
@@ -1821,7 +1829,7 @@ void
|
||||
testSingleTrackSingleUserSingleBookmark(Session& session)
|
||||
{
|
||||
ScopedTrack track {session, "MyTrack"};
|
||||
ScopedUser user {session, "MyUser", User::PasswordHash {}};
|
||||
ScopedUser user {session, "MyUser"};
|
||||
ScopedTrackBookmark bookmark {session, user.lockAndGet(), track.lockAndGet()};
|
||||
|
||||
{
|
||||
|
||||
Reference in New Issue
Block a user