token support, api fixes and security, dark mode

This commit is contained in:
Joey Kimsey
2024-12-07 01:58:27 -05:00
parent b93d0259e4
commit 485d85cb0a
26 changed files with 934 additions and 85 deletions

View File

@ -43,7 +43,6 @@ class User extends DatabaseModel {
[ 'name', 'varchar', '20' ],
[ 'confirmationCode', 'varchar', '80' ],
[ 'prefs', 'text', '' ],
[ 'auth_token', 'text', '' ],
];
public $permissionMatrix = [
'uploadImages' => [
@ -694,33 +693,45 @@ class User extends DatabaseModel {
return $this->data;
}
public function findByToken( $token ) {
$data = self::$db->get( $this->tableName, [ 'auth_token', '=', $token ] );
if ( ! $data->count() ) {
public function authorize( $username, $password ) {
if ( !isset( self::$log ) ) {
self::$log = new Log;
}
if ( !$this->get( $username ) ) {
self::$log->login( 0, "API: User not found: $username" );
return false;
}
return $data->first();
}
public function addAccessToken( $id, $length = 64 ) {
if ( ! Check::id( $id ) ) {
// login attempts protection.
$timeLimit = ( time() - 3600 );
$limit = Config::getValue( 'main/loginLimit' );
$user = $this->data();
if ( $limit > 0 ) {
$limitCheck = self::$db->get(
'logs',
[
'source', '=', 'login',
'AND',
'userID', '=', $user->ID,
'AND',
'time', '>=', $timeLimit,
'AND',
'action', '!=', 'pass',
]
);
if ( $limitCheck->count() >= $limit ) {
self::$log->login( $user->ID, 'API: Too many failed attempts.' );
return false;
}
}
if ( !Check::password( $password ) ) {
self::$log->login( $user->ID, 'API: Invalid Password.' );
return false;
}
$fields = [ 'auth_token' => $this->generateRandomString( $length ) ];
if ( !self::$db->update( $this->tableName, $id, $fields ) ) {
Debug::error( "User: $id not updated." );
if ( !Hash::check( $password, $user->password ) ) {
self::$log->login( $user->ID, 'API: Wrong Password.' );
return false;
}
return true;
}
private function generateRandomString( $length = 10 ) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen( $characters );
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[random_int(0, $charactersLength - 1)];
}
return $randomString;
self::$log->login( $this->data()->ID, 'API: pass' );
return $user;
}
}