2019-01-06 20:50:43 +00:00
using System ;
2016-11-18 09:28:39 +00:00
using System.Collections.Generic ;
using System.Globalization ;
using System.IO ;
using System.Linq ;
using Emby.Server.Implementations.Data ;
2019-01-13 19:22:24 +00:00
using MediaBrowser.Controller.Configuration ;
2016-11-18 09:28:39 +00:00
using MediaBrowser.Controller.Security ;
2019-01-13 19:22:24 +00:00
using MediaBrowser.Model.Devices ;
2016-11-18 09:28:39 +00:00
using MediaBrowser.Model.Querying ;
2019-01-13 19:22:24 +00:00
using Microsoft.Extensions.Logging ;
2016-11-18 09:28:39 +00:00
using SQLitePCL.pretty ;
namespace Emby.Server.Implementations.Security
{
public class AuthenticationRepository : BaseSqliteRepository , IAuthenticationRepository
{
2018-09-12 17:26:21 +00:00
private readonly IServerConfigurationManager _config ;
2016-11-18 09:28:39 +00:00
private readonly CultureInfo _usCulture = new CultureInfo ( "en-US" ) ;
2018-09-12 17:26:21 +00:00
public AuthenticationRepository ( ILogger logger , IServerConfigurationManager config )
2016-11-18 09:28:39 +00:00
: base ( logger )
{
2018-09-12 17:26:21 +00:00
_config = config ;
DbFilePath = Path . Combine ( config . ApplicationPaths . DataPath , "authentication.db" ) ;
2016-11-18 09:28:39 +00:00
}
public void Initialize ( )
{
using ( var connection = CreateConnection ( ) )
{
2016-11-29 19:12:37 +00:00
RunDefaultInitialization ( connection ) ;
2016-11-21 03:52:58 +00:00
2018-09-12 17:26:21 +00:00
var tableNewlyCreated = ! TableExists ( connection , "Tokens" ) ;
2016-11-18 09:28:39 +00:00
string [ ] queries = {
2018-09-12 17:26:21 +00:00
"create table if not exists Tokens (Id INTEGER PRIMARY KEY, AccessToken TEXT NOT NULL, DeviceId TEXT NOT NULL, AppName TEXT NOT NULL, AppVersion TEXT NOT NULL, DeviceName TEXT NOT NULL, UserId TEXT, UserName TEXT, IsActive BIT NOT NULL, DateCreated DATETIME NOT NULL, DateLastActivity DATETIME NOT NULL)" ,
"create table if not exists Devices (Id TEXT NOT NULL PRIMARY KEY, CustomName TEXT, Capabilities TEXT)" ,
"drop index if exists idx_AccessTokens" ,
"drop index if exists Tokens1" ,
"drop index if exists Tokens2" ,
"create index if not exists Tokens3 on Tokens (AccessToken, DateLastActivity)" ,
"create index if not exists Tokens4 on Tokens (Id, DateLastActivity)" ,
"create index if not exists Devices1 on Devices (Id)"
2016-11-18 09:28:39 +00:00
} ;
connection . RunQueries ( queries ) ;
2018-09-12 17:26:21 +00:00
TryMigrate ( connection , tableNewlyCreated ) ;
}
}
private void TryMigrate ( ManagedConnection connection , bool tableNewlyCreated )
{
try
{
if ( tableNewlyCreated & & TableExists ( connection , "AccessTokens" ) )
2016-11-18 09:28:39 +00:00
{
2018-09-12 17:26:21 +00:00
connection . RunInTransaction ( db = >
{
var existingColumnNames = GetColumnNames ( db , "AccessTokens" ) ;
AddColumn ( db , "AccessTokens" , "UserName" , "TEXT" , existingColumnNames ) ;
AddColumn ( db , "AccessTokens" , "DateLastActivity" , "DATETIME" , existingColumnNames ) ;
AddColumn ( db , "AccessTokens" , "AppVersion" , "TEXT" , existingColumnNames ) ;
2016-11-19 05:52:49 +00:00
2018-09-12 17:26:21 +00:00
} , TransactionMode ) ;
2016-11-28 19:26:48 +00:00
2018-09-12 17:26:21 +00:00
connection . RunQueries ( new [ ]
{
"update accesstokens set DateLastActivity=DateCreated where DateLastActivity is null" ,
"update accesstokens set DeviceName='Unknown' where DeviceName is null" ,
"update accesstokens set AppName='Unknown' where AppName is null" ,
"update accesstokens set AppVersion='1' where AppVersion is null" ,
"INSERT INTO Tokens (AccessToken, DeviceId, AppName, AppVersion, DeviceName, UserId, UserName, IsActive, DateCreated, DateLastActivity) SELECT AccessToken, DeviceId, AppName, AppVersion, DeviceName, UserId, UserName, IsActive, DateCreated, DateLastActivity FROM AccessTokens where deviceid not null and devicename not null and appname not null and isactive=1"
} ) ;
}
}
catch ( Exception ex )
{
2018-12-20 12:11:26 +00:00
Logger . LogError ( ex , "Error migrating authentication database" ) ;
2016-11-18 09:28:39 +00:00
}
}
2018-09-12 17:26:21 +00:00
public void Create ( AuthenticationInfo info )
2016-11-18 09:28:39 +00:00
{
2018-09-12 17:26:21 +00:00
if ( info = = null )
{
2019-01-06 20:50:43 +00:00
throw new ArgumentNullException ( nameof ( info ) ) ;
2018-09-12 17:26:21 +00:00
}
using ( WriteLock . Write ( ) )
{
using ( var connection = CreateConnection ( ) )
{
connection . RunInTransaction ( db = >
{
using ( var statement = db . PrepareStatement ( "insert into Tokens (AccessToken, DeviceId, AppName, AppVersion, DeviceName, UserId, UserName, IsActive, DateCreated, DateLastActivity) values (@AccessToken, @DeviceId, @AppName, @AppVersion, @DeviceName, @UserId, @UserName, @IsActive, @DateCreated, @DateLastActivity)" ) )
{
statement . TryBind ( "@AccessToken" , info . AccessToken ) ;
statement . TryBind ( "@DeviceId" , info . DeviceId ) ;
statement . TryBind ( "@AppName" , info . AppName ) ;
statement . TryBind ( "@AppVersion" , info . AppVersion ) ;
statement . TryBind ( "@DeviceName" , info . DeviceName ) ;
statement . TryBind ( "@UserId" , ( info . UserId . Equals ( Guid . Empty ) ? null : info . UserId . ToString ( "N" ) ) ) ;
statement . TryBind ( "@UserName" , info . UserName ) ;
statement . TryBind ( "@IsActive" , true ) ;
statement . TryBind ( "@DateCreated" , info . DateCreated . ToDateTimeParamValue ( ) ) ;
statement . TryBind ( "@DateLastActivity" , info . DateLastActivity . ToDateTimeParamValue ( ) ) ;
statement . MoveNext ( ) ;
}
2016-11-18 09:28:39 +00:00
2018-09-12 17:26:21 +00:00
} , TransactionMode ) ;
}
}
2016-11-18 09:28:39 +00:00
}
2018-09-12 17:26:21 +00:00
public void Update ( AuthenticationInfo info )
2016-11-18 09:28:39 +00:00
{
if ( info = = null )
{
2019-01-06 20:50:43 +00:00
throw new ArgumentNullException ( nameof ( info ) ) ;
2016-11-18 09:28:39 +00:00
}
2016-12-11 05:12:00 +00:00
using ( WriteLock . Write ( ) )
2016-11-18 09:28:39 +00:00
{
2016-12-11 05:12:00 +00:00
using ( var connection = CreateConnection ( ) )
2016-11-18 09:28:39 +00:00
{
connection . RunInTransaction ( db = >
{
2018-09-12 17:26:21 +00:00
using ( var statement = db . PrepareStatement ( "Update Tokens set AccessToken=@AccessToken, DeviceId=@DeviceId, AppName=@AppName, AppVersion=@AppVersion, DeviceName=@DeviceName, UserId=@UserId, UserName=@UserName, DateCreated=@DateCreated, DateLastActivity=@DateLastActivity where Id=@Id" ) )
2016-11-20 05:59:36 +00:00
{
2018-09-12 17:26:21 +00:00
statement . TryBind ( "@Id" , info . Id ) ;
2016-11-20 07:10:07 +00:00
statement . TryBind ( "@AccessToken" , info . AccessToken ) ;
2016-11-20 05:59:36 +00:00
2016-11-20 07:10:07 +00:00
statement . TryBind ( "@DeviceId" , info . DeviceId ) ;
statement . TryBind ( "@AppName" , info . AppName ) ;
statement . TryBind ( "@AppVersion" , info . AppVersion ) ;
statement . TryBind ( "@DeviceName" , info . DeviceName ) ;
2018-09-12 17:26:21 +00:00
statement . TryBind ( "@UserId" , ( info . UserId . Equals ( Guid . Empty ) ? null : info . UserId . ToString ( "N" ) ) ) ;
statement . TryBind ( "@UserName" , info . UserName ) ;
2016-11-20 07:10:07 +00:00
statement . TryBind ( "@DateCreated" , info . DateCreated . ToDateTimeParamValue ( ) ) ;
2018-09-12 17:26:21 +00:00
statement . TryBind ( "@DateLastActivity" , info . DateLastActivity . ToDateTimeParamValue ( ) ) ;
2016-11-20 05:59:36 +00:00
statement . MoveNext ( ) ;
}
2018-09-12 17:26:21 +00:00
} , TransactionMode ) ;
}
}
}
public void Delete ( AuthenticationInfo info )
{
if ( info = = null )
{
2019-01-06 20:50:43 +00:00
throw new ArgumentNullException ( nameof ( info ) ) ;
2018-09-12 17:26:21 +00:00
}
2016-11-28 19:26:48 +00:00
2018-09-12 17:26:21 +00:00
using ( WriteLock . Write ( ) )
{
using ( var connection = CreateConnection ( ) )
{
connection . RunInTransaction ( db = >
{
using ( var statement = db . PrepareStatement ( "Delete from Tokens where Id=@Id" ) )
{
statement . TryBind ( "@Id" , info . Id ) ;
statement . MoveNext ( ) ;
}
2016-11-28 19:26:48 +00:00
} , TransactionMode ) ;
2016-11-18 09:28:39 +00:00
}
}
}
2018-09-12 17:26:21 +00:00
private const string BaseSelectText = "select Tokens.Id, AccessToken, DeviceId, AppName, AppVersion, DeviceName, UserId, UserName, DateCreated, DateLastActivity, Devices.CustomName from Tokens left join Devices on Tokens.DeviceId=Devices.Id" ;
2016-11-18 09:28:39 +00:00
2019-01-06 20:50:43 +00:00
private static void BindAuthenticationQueryParams ( AuthenticationInfoQuery query , IStatement statement )
2016-11-20 05:59:36 +00:00
{
2018-09-12 17:26:21 +00:00
if ( ! string . IsNullOrEmpty ( query . AccessToken ) )
2016-11-20 05:59:36 +00:00
{
2016-11-20 07:10:07 +00:00
statement . TryBind ( "@AccessToken" , query . AccessToken ) ;
2016-11-20 05:59:36 +00:00
}
2018-09-12 17:26:21 +00:00
if ( ! query . UserId . Equals ( Guid . Empty ) )
2016-11-20 05:59:36 +00:00
{
2018-09-12 17:26:21 +00:00
statement . TryBind ( "@UserId" , query . UserId . ToString ( "N" ) ) ;
2016-11-20 05:59:36 +00:00
}
2018-09-12 17:26:21 +00:00
if ( ! string . IsNullOrEmpty ( query . DeviceId ) )
2016-11-20 05:59:36 +00:00
{
2016-11-20 07:10:07 +00:00
statement . TryBind ( "@DeviceId" , query . DeviceId ) ;
2016-11-20 05:59:36 +00:00
}
}
2016-11-18 09:28:39 +00:00
public QueryResult < AuthenticationInfo > Get ( AuthenticationInfoQuery query )
{
if ( query = = null )
{
2019-01-06 20:50:43 +00:00
throw new ArgumentNullException ( nameof ( query ) ) ;
2016-11-18 09:28:39 +00:00
}
2016-11-29 19:12:37 +00:00
var commandText = BaseSelectText ;
2016-11-18 09:28:39 +00:00
2016-11-29 19:12:37 +00:00
var whereClauses = new List < string > ( ) ;
2016-11-18 09:28:39 +00:00
2018-09-12 17:26:21 +00:00
if ( ! string . IsNullOrEmpty ( query . AccessToken ) )
2016-11-29 19:12:37 +00:00
{
whereClauses . Add ( "AccessToken=@AccessToken" ) ;
}
2016-11-18 09:28:39 +00:00
2018-09-12 17:26:21 +00:00
if ( ! string . IsNullOrEmpty ( query . DeviceId ) )
2016-11-29 19:12:37 +00:00
{
whereClauses . Add ( "DeviceId=@DeviceId" ) ;
}
2016-11-18 09:28:39 +00:00
2018-09-12 17:26:21 +00:00
if ( ! query . UserId . Equals ( Guid . Empty ) )
2016-11-29 19:12:37 +00:00
{
2018-09-12 17:26:21 +00:00
whereClauses . Add ( "UserId=@UserId" ) ;
2016-11-29 19:12:37 +00:00
}
2016-11-18 09:28:39 +00:00
2016-11-29 19:12:37 +00:00
if ( query . HasUser . HasValue )
{
if ( query . HasUser . Value )
{
whereClauses . Add ( "UserId not null" ) ;
}
else
{
whereClauses . Add ( "UserId is null" ) ;
}
}
2016-11-25 17:36:00 +00:00
2016-11-29 19:12:37 +00:00
var whereTextWithoutPaging = whereClauses . Count = = 0 ?
string . Empty :
2018-12-28 15:48:26 +00:00
" where " + string . Join ( " AND " , whereClauses . ToArray ( ) ) ;
2016-11-18 09:28:39 +00:00
2018-09-12 17:26:21 +00:00
commandText + = whereTextWithoutPaging ;
2016-11-18 09:28:39 +00:00
2018-09-12 17:26:21 +00:00
commandText + = " ORDER BY DateLastActivity desc" ;
2016-11-18 09:28:39 +00:00
2018-09-12 17:26:21 +00:00
if ( query . Limit . HasValue | | query . StartIndex . HasValue )
{
var offset = query . StartIndex ? ? 0 ;
2016-11-18 09:28:39 +00:00
2018-09-12 17:26:21 +00:00
if ( query . Limit . HasValue | | offset > 0 )
{
commandText + = " LIMIT " + ( query . Limit ? ? int . MaxValue ) . ToString ( CultureInfo . InvariantCulture ) ;
}
2016-11-18 09:28:39 +00:00
2018-09-12 17:26:21 +00:00
if ( offset > 0 )
{
commandText + = " OFFSET " + offset . ToString ( CultureInfo . InvariantCulture ) ;
}
2016-11-29 19:12:37 +00:00
}
2016-11-25 17:36:00 +00:00
2016-11-29 19:12:37 +00:00
var list = new List < AuthenticationInfo > ( ) ;
2016-11-18 09:28:39 +00:00
2016-12-11 05:12:00 +00:00
using ( WriteLock . Read ( ) )
2016-11-29 19:12:37 +00:00
{
2016-12-11 05:12:00 +00:00
using ( var connection = CreateConnection ( true ) )
2016-11-29 19:12:37 +00:00
{
2016-12-13 07:36:30 +00:00
return connection . RunInTransaction ( db = >
2016-11-20 05:59:36 +00:00
{
2016-12-13 07:36:30 +00:00
var result = new QueryResult < AuthenticationInfo > ( ) ;
2016-12-12 05:49:19 +00:00
var statementTexts = new List < string > ( ) ;
statementTexts . Add ( commandText ) ;
2018-09-12 17:26:21 +00:00
statementTexts . Add ( "select count (Id) from Tokens" + whereTextWithoutPaging ) ;
2016-11-20 05:59:36 +00:00
2016-12-13 08:45:04 +00:00
var statements = PrepareAllSafe ( db , statementTexts )
2016-12-12 05:49:19 +00:00
. ToList ( ) ;
2016-11-20 05:59:36 +00:00
2016-12-12 05:49:19 +00:00
using ( var statement = statements [ 0 ] )
2016-11-20 05:59:36 +00:00
{
2016-12-12 05:49:19 +00:00
BindAuthenticationQueryParams ( query , statement ) ;
2016-11-21 03:52:58 +00:00
2016-12-12 05:49:19 +00:00
foreach ( var row in statement . ExecuteQuery ( ) )
{
list . Add ( Get ( row ) ) ;
}
2016-11-21 03:52:58 +00:00
2016-12-12 05:49:19 +00:00
using ( var totalCountStatement = statements [ 1 ] )
2016-11-21 03:52:58 +00:00
{
2016-12-12 05:49:19 +00:00
BindAuthenticationQueryParams ( query , totalCountStatement ) ;
2016-12-12 08:53:25 +00:00
result . TotalRecordCount = totalCountStatement . ExecuteQuery ( )
2016-12-12 05:49:19 +00:00
. SelectScalarInt ( )
. First ( ) ;
}
2016-11-21 03:52:58 +00:00
}
2016-12-12 05:49:19 +00:00
2018-12-28 15:48:26 +00:00
result . Items = list . ToArray ( ) ;
2016-12-13 07:36:30 +00:00
return result ;
2016-12-12 05:49:19 +00:00
2016-12-13 07:36:30 +00:00
} , ReadTransactionMode ) ;
2016-11-20 05:59:36 +00:00
}
2016-11-18 09:28:39 +00:00
}
}
2019-01-06 20:50:43 +00:00
private static AuthenticationInfo Get ( IReadOnlyList < IResultSetValue > reader )
2016-11-18 09:28:39 +00:00
{
var info = new AuthenticationInfo
{
2018-09-12 17:26:21 +00:00
Id = reader [ 0 ] . ToInt64 ( ) ,
2016-11-18 09:28:39 +00:00
AccessToken = reader [ 1 ] . ToString ( )
} ;
if ( reader [ 2 ] . SQLiteType ! = SQLiteType . Null )
{
info . DeviceId = reader [ 2 ] . ToString ( ) ;
}
if ( reader [ 3 ] . SQLiteType ! = SQLiteType . Null )
{
info . AppName = reader [ 3 ] . ToString ( ) ;
}
if ( reader [ 4 ] . SQLiteType ! = SQLiteType . Null )
{
info . AppVersion = reader [ 4 ] . ToString ( ) ;
}
if ( reader [ 5 ] . SQLiteType ! = SQLiteType . Null )
{
info . DeviceName = reader [ 5 ] . ToString ( ) ;
}
if ( reader [ 6 ] . SQLiteType ! = SQLiteType . Null )
{
2018-09-12 17:26:21 +00:00
info . UserId = new Guid ( reader [ 6 ] . ToString ( ) ) ;
}
if ( reader [ 7 ] . SQLiteType ! = SQLiteType . Null )
{
info . UserName = reader [ 7 ] . ToString ( ) ;
2016-11-18 09:28:39 +00:00
}
info . DateCreated = reader [ 8 ] . ReadDateTime ( ) ;
if ( reader [ 9 ] . SQLiteType ! = SQLiteType . Null )
{
2018-09-12 17:26:21 +00:00
info . DateLastActivity = reader [ 9 ] . ReadDateTime ( ) ;
}
else
{
info . DateLastActivity = info . DateCreated ;
}
if ( reader [ 10 ] . SQLiteType ! = SQLiteType . Null )
{
info . DeviceName = reader [ 10 ] . ToString ( ) ;
2016-11-18 09:28:39 +00:00
}
return info ;
}
2018-09-12 17:26:21 +00:00
public DeviceOptions GetDeviceOptions ( string deviceId )
{
using ( WriteLock . Read ( ) )
{
using ( var connection = CreateConnection ( true ) )
{
return connection . RunInTransaction ( db = >
{
using ( var statement = PrepareStatementSafe ( db , "select CustomName from Devices where Id=@DeviceId" ) )
{
statement . TryBind ( "@DeviceId" , deviceId ) ;
var result = new DeviceOptions ( ) ;
foreach ( var row in statement . ExecuteQuery ( ) )
{
if ( row [ 0 ] . SQLiteType ! = SQLiteType . Null )
{
result . CustomName = row [ 0 ] . ToString ( ) ;
}
}
return result ;
}
} , ReadTransactionMode ) ;
}
}
}
public void UpdateDeviceOptions ( string deviceId , DeviceOptions options )
{
if ( options = = null )
{
2019-01-06 20:50:43 +00:00
throw new ArgumentNullException ( nameof ( options ) ) ;
2018-09-12 17:26:21 +00:00
}
using ( WriteLock . Write ( ) )
{
using ( var connection = CreateConnection ( ) )
{
connection . RunInTransaction ( db = >
{
using ( var statement = db . PrepareStatement ( "replace into devices (Id, CustomName, Capabilities) VALUES (@Id, @CustomName, (Select Capabilities from Devices where Id=@Id))" ) )
{
statement . TryBind ( "@Id" , deviceId ) ;
if ( string . IsNullOrWhiteSpace ( options . CustomName ) )
{
statement . TryBindNull ( "@CustomName" ) ;
}
else
{
statement . TryBind ( "@CustomName" , options . CustomName ) ;
}
statement . MoveNext ( ) ;
}
} , TransactionMode ) ;
}
}
}
2016-11-18 09:28:39 +00:00
}
}