From 4e09ee3eb255160c88a378375d69123a3e000497 Mon Sep 17 00:00:00 2001 From: Igor Scheller Date: Thu, 11 Oct 2018 01:26:34 +0200 Subject: [PATCH] Replaced more user related stuff (Contains some buggy stuff too...) --- .../controller/shift_entries_controller.php | 6 +- includes/controller/shifts_controller.php | 9 +- .../controller/user_angeltypes_controller.php | 9 +- includes/controller/users_controller.php | 44 ++- includes/model/Message_model.php | 1 - includes/model/ShiftEntry_model.php | 5 +- includes/model/User_model.php | 348 +++--------------- includes/pages/admin_active.php | 116 +++--- includes/pages/admin_arrive.php | 58 ++- includes/pages/admin_free.php | 42 +-- includes/pages/guest_login.php | 2 +- includes/pages/user_atom.php | 6 +- includes/pages/user_ical.php | 9 +- includes/pages/user_messages.php | 11 +- includes/pages/user_settings.php | 91 ++--- includes/sys_auth.php | 65 ++-- includes/view/AngelTypes_view.php | 22 +- includes/view/ShiftEntry_view.php | 4 +- includes/view/UserAngelTypes_view.php | 8 +- includes/view/User_view.php | 108 +++--- src/Helpers/Authenticator.php | 51 ++- src/Models/User/Contact.php | 6 +- src/Models/User/PasswordReset.php | 4 +- src/Models/User/Settings.php | 8 +- src/Models/User/State.php | 10 +- src/Models/User/User.php | 14 +- .../AuthenticatorServiceProviderTest.php | 3 + tests/Unit/Helpers/AuthenticatorTest.php | 49 ++- .../Helpers/Stub/UserModelImplementation.php | 17 + 29 files changed, 470 insertions(+), 656 deletions(-) diff --git a/includes/controller/shift_entries_controller.php b/includes/controller/shift_entries_controller.php index 2876991a..bbf2e5b0 100644 --- a/includes/controller/shift_entries_controller.php +++ b/includes/controller/shift_entries_controller.php @@ -111,10 +111,10 @@ function shift_entry_create_controller_admin($shift, $angeltype) redirect(shift_link($shift)); } - $users = Users(); + $users = User::all(); $users_select = []; foreach ($users as $u) { - $users_select[$u['UID']] = $u['Nick']; + $users_select[$u->id] = $u->name; } $angeltypes_select = []; @@ -185,7 +185,7 @@ function shift_entry_create_controller_supporter($shift, $angeltype) $users = Users_by_angeltype($angeltype); $users_select = []; foreach ($users as $u) { - $users_select[$u['UID']] = $u['Nick']; + $users_select[$u->id] = $u->name; } $room = Room($shift['RID']); diff --git a/includes/controller/shifts_controller.php b/includes/controller/shifts_controller.php index b56440e5..07e81957 100644 --- a/includes/controller/shifts_controller.php +++ b/includes/controller/shifts_controller.php @@ -353,20 +353,17 @@ function shift_next_controller() */ function shifts_json_export_controller() { - global $user; $request = request(); if (!$request->has('key') || !preg_match('/^[\da-f]{32}$/', $request->input('key'))) { engelsystem_error('Missing key.'); } - $key = $request->input('key'); - - $user = User_by_api_key($key); - if (empty($user)) { + $user = auth()->apiUser('key'); + if (!$user) { engelsystem_error('Key invalid.'); } - if (!in_array('shifts_json_export', privileges_for_user($user['UID']))) { + if (!in_array('shifts_json_export', privileges_for_user($user->id))) { engelsystem_error('No privilege for shifts_json_export.'); } diff --git a/includes/controller/user_angeltypes_controller.php b/includes/controller/user_angeltypes_controller.php index a38adfec..6080d08b 100644 --- a/includes/controller/user_angeltypes_controller.php +++ b/includes/controller/user_angeltypes_controller.php @@ -362,16 +362,17 @@ function user_angeltype_add_controller() */ function user_angeltype_join_controller($angeltype) { - global $user, $privileges; + global $privileges; + $user = auth()->user(); - $user_angeltype = UserAngelType_by_User_and_AngelType($user['UID'], $angeltype); + $user_angeltype = UserAngelType_by_User_and_AngelType($user->id, $angeltype); if (!empty($user_angeltype)) { error(sprintf(__('You are already a %s.'), $angeltype['name'])); redirect(page_link_to('angeltypes')); } if (request()->has('confirmed')) { - $user_angeltype_id = UserAngelType_create($user['UID'], $angeltype); + $user_angeltype_id = UserAngelType_create($user->id, $angeltype); $success_message = sprintf(__('You joined %s.'), $angeltype['name']); engelsystem_log(sprintf( @@ -382,7 +383,7 @@ function user_angeltype_join_controller($angeltype) success($success_message); if (in_array('admin_user_angeltypes', $privileges)) { - UserAngelType_confirm($user_angeltype_id, $user['UID']); + UserAngelType_confirm($user_angeltype_id, $user->id); engelsystem_log(sprintf( 'User %s confirmed as %s.', User_Nick_render($user), diff --git a/includes/controller/users_controller.php b/includes/controller/users_controller.php index 3c05f596..61b19231 100644 --- a/includes/controller/users_controller.php +++ b/includes/controller/users_controller.php @@ -2,6 +2,7 @@ use Engelsystem\Database\DB; use Engelsystem\Models\User\PasswordReset; +use Engelsystem\Models\User\State; use Engelsystem\Models\User\User; use Engelsystem\ShiftCalendarRenderer; use Engelsystem\ShiftsFilter; @@ -79,7 +80,7 @@ function user_delete_controller() } if ($valid) { - User_delete($user_source->id); + $user_source->delete(); mail_user_delete($user_source); success(__('User deleted.')); @@ -268,13 +269,28 @@ function users_list_controller() } $order_by = 'Nick'; - if ($request->has('OrderBy') && in_array($request->input('OrderBy'), User_sortable_columns())) { + if ($request->has('OrderBy') && in_array($request->input('OrderBy'), [ + 'Nick', + 'Name', + 'Vorname', + 'DECT', + 'email', + 'Size', + 'Gekommen', + 'Aktiv', + 'force_active', + 'Tshirt', + 'lastLogIn' + ])) { $order_by = $request->input('OrderBy'); } - $users = Users($order_by); - foreach ($users as &$user) { - $user['freeloads'] = count(ShiftEntries_freeloaded_by_user($user['UID'])); + /** @var User[] $users */ + $users = User::query() + ->orderBy($order_by) + ->get(); + foreach ($users as $user) { + $user->setAttribute('freeloads', count(ShiftEntries_freeloaded_by_user($user->id))); } return [ @@ -282,12 +298,12 @@ function users_list_controller() Users_view( $users, $order_by, - User_arrived_count(), - User_active_count(), - User_force_active_count(), + State::whereArrived(true)->count(), + State::whereActive(true)->count(), + State::whereForceActive(true)->count(), ShiftEntries_freeloaded_count(), - User_tshirts_count(), - User_got_voucher_count() + State::whereGotShirt(true)->count(), + State::query()->sum('got_voucher') ) ]; } @@ -300,7 +316,7 @@ function users_list_controller() function user_password_recovery_set_new_controller() { $request = request(); - $passwordReset = PasswordReset::whereToken($request->input('token')); + $passwordReset = PasswordReset::whereToken($request->input('token'))->first(); if (!$passwordReset) { error(__('Token is not correct.')); redirect(page_link_to('login')); @@ -344,11 +360,13 @@ function user_password_recovery_start_controller() if ($request->has('submit')) { $valid = true; + $user_source = null; if ($request->has('email') && strlen(strip_request_item('email')) > 0) { $email = strip_request_item('email'); if (check_email($email)) { - $user_source = User_by_email($email); - if (empty($user_source)) { + /** @var User $user_source */ + $user_source = User::whereEmail($email)->first(); + if (!$user_source) { $valid = false; error(__('E-mail address is not correct.')); } diff --git a/includes/model/Message_model.php b/includes/model/Message_model.php index 4f8a3972..89beeb07 100644 --- a/includes/model/Message_model.php +++ b/includes/model/Message_model.php @@ -27,7 +27,6 @@ function Message($message_id) /** * TODO: use validation functions, return new message id - * TODO: global $user can't be used in model! * send message * * @param int $receiver_user_id User ID of Receiver diff --git a/includes/model/ShiftEntry_model.php b/includes/model/ShiftEntry_model.php index c8ca5ef4..593e40b2 100644 --- a/includes/model/ShiftEntry_model.php +++ b/includes/model/ShiftEntry_model.php @@ -77,7 +77,6 @@ function ShiftEntry_create($shift_entry) { $user = User::find($shift_entry['UID']); $shift = Shift($shift_entry['SID']); - mail_shift_assign($user, $shift); $result = DB::insert(' INSERT INTO `ShiftEntry` ( `SID`, @@ -104,6 +103,7 @@ function ShiftEntry_create($shift_entry) . ' from ' . date('Y-m-d H:i', $shift['start']) . ' to ' . date('Y-m-d H:i', $shift['end']) ); + mail_shift_assign($user, $shift); return $result; } @@ -151,7 +151,6 @@ function ShiftEntry($shift_entry_id) */ function ShiftEntry_delete($shiftEntry) { - mail_shift_removed(User::find($shiftEntry['UID']), Shift($shiftEntry['SID'])); DB::delete('DELETE FROM `ShiftEntry` WHERE `id` = ?', [$shiftEntry['id']]); $signout_user = User::find($shiftEntry['UID']); @@ -167,6 +166,8 @@ function ShiftEntry_delete($shiftEntry) . ' to ' . date('Y-m-d H:i', $shift['end']) . ' as ' . $angeltype['name'] ); + + mail_shift_removed(User::find($shiftEntry['UID']), Shift($shiftEntry['SID'])); } /** diff --git a/includes/model/User_model.php b/includes/model/User_model.php index 298ac18d..6192fa20 100644 --- a/includes/model/User_model.php +++ b/includes/model/User_model.php @@ -2,23 +2,15 @@ use Carbon\Carbon; use Engelsystem\Database\DB; +use Engelsystem\Models\User\PasswordReset; use Engelsystem\Models\User\User; use Engelsystem\ValidationResult; +use Illuminate\Database\Query\JoinClause; /** * User model */ -/** - * Delete a user - * - * @param int $user_id - */ -function User_delete($user_id) -{ - DB::delete('DELETE FROM `User` WHERE `UID`=?', [$user_id]); -} - /** * Returns the tshirt score (number of hours counted for tshirt). * Accounts only ended shifts. @@ -29,14 +21,14 @@ function User_delete($user_id) function User_tshirt_score($userId) { $shift_sum_formula = User_get_shifts_sum_query(); - $result_shifts = DB::selectOne(' - SELECT ROUND((' . $shift_sum_formula . ') / 3600, 2) AS `tshirt_score` - FROM `User` LEFT JOIN `ShiftEntry` ON `User`.`UID` = `ShiftEntry`.`UID` + $result_shifts = DB::selectOne(sprintf(' + SELECT ROUND((%s) / 3600, 2) AS `tshirt_score` + FROM `users` LEFT JOIN `ShiftEntry` ON `users`.`id` = `ShiftEntry`.`UID` LEFT JOIN `Shifts` ON `ShiftEntry`.`SID` = `Shifts`.`SID` - WHERE `User`.`UID` = ? + WHERE `users`.`id` = ? AND `Shifts`.`end` < ? - GROUP BY `User`.`UID` - ', [ + GROUP BY `users`.`id` + ', $shift_sum_formula), [ $userId, time() ]); @@ -46,9 +38,9 @@ function User_tshirt_score($userId) $result_worklog = DB::selectOne(' SELECT SUM(`work_hours`) AS `tshirt_score` - FROM `User` - LEFT JOIN `UserWorkLog` ON `User`.`UID` = `UserWorkLog`.`user_id` - WHERE `User`.`UID` = ? + FROM `users` + LEFT JOIN `UserWorkLog` ON `users`.`id` = `UserWorkLog`.`user_id` + WHERE `users`.`id` = ? AND `UserWorkLog`.`work_timestamp` < ? ', [ $userId, @@ -61,181 +53,6 @@ function User_tshirt_score($userId) return $result_shifts['tshirt_score'] + $result_worklog['tshirt_score']; } -/** - * Update user. - * - * @param array $user - */ -function User_update($user) -{ - DB::update(' - UPDATE `User` SET - `Nick`=?, - `Name`=?, - `Vorname`=?, - `Alter`=?, - `Telefon`=?, - `DECT`=?, - `Handy`=?, - `email`=?, - `email_shiftinfo`=?, - `email_by_human_allowed`=?, - `jabber`=?, - `Size`=?, - `Gekommen`=?, - `Aktiv`=?, - `force_active`=?, - `Tshirt`=?, - `color`=?, - `Sprache`=?, - `Hometown`=?, - `got_voucher`=?, - `arrival_date`=?, - `planned_arrival_date`=?, - `planned_departure_date`=? - WHERE `UID`=? - ', - [ - $user['Nick'], - $user['Name'], - $user['Vorname'], - $user['Alter'], - $user['Telefon'], - $user['DECT'], - $user['Handy'], - $user['email'], - (int)$user['email_shiftinfo'], - (int)$user['email_by_human_allowed'], - $user['jabber'], - $user['Size'], - $user['Gekommen'], - $user['Aktiv'], - (int)$user['force_active'], - $user['Tshirt'], - $user['color'], - $user['Sprache'], - $user['Hometown'], - $user['got_voucher'], - $user['arrival_date'], - $user['planned_arrival_date'], - $user['planned_departure_date'], - $user['UID'], - ] - ); -} - -/** - * Counts all forced active users. - * - * @return int - */ -function User_force_active_count() -{ - $result = DB::selectOne('SELECT COUNT(*) FROM `User` WHERE `force_active` = 1'); - - if (empty($result)) { - return 0; - } - - return (int)array_shift($result); -} - -/** - * @return int - */ -function User_active_count() -{ - $result = DB::selectOne('SELECT COUNT(*) FROM `User` WHERE `Aktiv` = 1'); - - if (empty($result)) { - return 0; - } - - return (int)array_shift($result); -} - -/** - * @return int - */ -function User_got_voucher_count() -{ - $result = DB::selectOne('SELECT SUM(`got_voucher`) FROM `User`'); - - if (empty($result)) { - return 0; - } - - return (int)array_shift($result); -} - -/** - * @return int - */ -function User_arrived_count() -{ - $result = DB::selectOne('SELECT COUNT(*) FROM `User` WHERE `Gekommen` = 1'); - - if (empty($result)) { - return 0; - } - - return (int)array_shift($result); -} - -/** - * @return int - */ -function User_tshirts_count() -{ - $result = DB::selectOne('SELECT COUNT(*) FROM `User` WHERE `Tshirt` = 1'); - - if (empty($result)) { - return 0; - } - - return (int)array_shift($result); -} - -/** - * Returns all column names for sorting in an array. - * - * @return array - */ -function User_sortable_columns() -{ - return [ - 'Nick', - 'Name', - 'Vorname', - 'Alter', - 'DECT', - 'email', - 'Size', - 'Gekommen', - 'Aktiv', - 'force_active', - 'Tshirt', - 'lastLogIn' - ]; -} - -/** - * Get all users, ordered by Nick by default or by given param. - * - * @param string $order_by - * @return array - */ -function Users($order_by = 'Nick') -{ - return DB::select(sprintf(' - SELECT * - FROM `User` - ORDER BY `%s` ASC - ', - trim(DB::getPdo()->quote($order_by), '\'') - )); -} - /** * Returns true if user is freeloader * @@ -251,60 +68,43 @@ function User_is_freeloader($user) * Returns all users that are not member of given angeltype. * * @param array $angeltype Angeltype - * @return array[] + * @return User[] */ function Users_by_angeltype_inverted($angeltype) { - return DB::select(' - SELECT `User`.* - FROM `User` - LEFT JOIN `UserAngelTypes` - ON (`User`.`UID`=`UserAngelTypes`.`user_id` AND `angeltype_id`=?) - WHERE `UserAngelTypes`.`id` IS NULL - ORDER BY `Nick` - ', - [ - $angeltype['id'] - ] - ); + return User::query() + ->leftJoin('UserAngelTypes', 'users.id', '=', 'UserAngelTypes.user_id') + ->leftJoin('UserAngelTypes', function ($query) use ($angeltype) { + /** @var JoinClause $query */ + $query + ->on('users.id', '=', 'UserAngelTypes.user_id') + ->on('UserAngelTypes.angeltype_id', '=', $angeltype['id']); + }) + ->whereNull('UserAngelTypes.id') + ->orderBy('users.name') + ->get('users.*'); } /** * Returns all members of given angeltype. * * @param array $angeltype - * @return array[] + * @return User[] */ function Users_by_angeltype($angeltype) { - return DB::select(' - SELECT - `User`.*, - `UserAngelTypes`.`id` AS `user_angeltype_id`, - `UserAngelTypes`.`confirm_user_id`, - `UserAngelTypes`.`supporter`, - (`UserDriverLicenses`.`user_id` IS NOT NULL) AS `wants_to_drive`, - `UserDriverLicenses`.* - FROM `User` - JOIN `UserAngelTypes` ON `User`.`UID`=`UserAngelTypes`.`user_id` - LEFT JOIN `UserDriverLicenses` ON `User`.`UID`=`UserDriverLicenses`.`user_id` - WHERE `UserAngelTypes`.`angeltype_id`=? - ORDER BY `Nick` - ', - [ - $angeltype['id'] - ] - ); -} - -/** - * Returns User id array - * - * @return array[] - */ -function User_ids() -{ - return DB::select('SELECT `UID` FROM `User`'); + return User::query() + ->join('UserAngelTypes', 'users.id', '=', 'UserAngelTypes.user_id') + ->leftJoin('UserDriverLicenses', 'users.id', '=', 'UserDriverLicenses.user_id') + ->where('UserAngelTypes.angeltype_id', '=', $angeltype['id']) + ->get([ + 'users.*', + '`UserAngelTypes`.`id` AS `user_angeltype_id`', + '`UserAngelTypes`.`confirm_user_id`', + '`UserAngelTypes`.`supporter`', + '(`UserDriverLicenses`.`user_id` IS NOT NULL) AS `wants_to_drive`', + '`UserDriverLicenses`.*', + ]); } /** @@ -331,22 +131,6 @@ function User_validate_mail($mail) return new ValidationResult(check_email($mail), $mail); } -/** - * Validate user jabber address - * - * @param string $jabber Jabber-ID to validate - * @return ValidationResult - */ -function User_validate_jabber($jabber) -{ - $jabber = strip_item($jabber); - if ($jabber == '') { - // Empty is ok - return new ValidationResult(true, ''); - } - return new ValidationResult(check_email($jabber), $jabber); -} - /** * Validate the planned arrival date * @@ -417,45 +201,6 @@ function User_validate_planned_departure_date($planned_arrival_date, $planned_de return new ValidationResult(true, $planned_departure_date); } -/** - * Returns User by api_key. - * - * @param string $api_key User api key - * @return array|null Matching user, null if not found - */ -function User_by_api_key($api_key) -{ - $user = DB::selectOne('SELECT * FROM `User` WHERE `api_key`=? LIMIT 1', [$api_key]); - - return empty($user) ? null : $user; -} - -/** - * Returns User by email. - * - * @param string $email - * @return array|null Matching user, null when not found - */ -function User_by_email($email) -{ - $user = DB::selectOne('SELECT * FROM `User` WHERE `email`=? LIMIT 1', [$email]); - - return empty($user) ? null : $user; -} - -/** - * Returns User by password token. - * - * @param string $token - * @return array|null Matching user, null when not found - */ -function User_by_password_recovery_token($token) -{ - $user = DB::selectOne('SELECT * FROM `User` WHERE `password_recovery_token`=? LIMIT 1', [$token]); - - return empty($user) ? null : $user; -} - /** * Generates a new api key for given user. * @@ -475,27 +220,18 @@ function User_reset_api_key($user, $log = true) /** * Generates a new password recovery token for given user. * - * @param array $user + * @param User $user * @return string */ -function User_generate_password_recovery_token(&$user) +function User_generate_password_recovery_token($user) { - $user['password_recovery_token'] = md5($user['Nick'] . time() . rand()); - DB::update(' - UPDATE `User` - SET `password_recovery_token`=? - WHERE `UID`=? - LIMIT 1 - ', - [ - $user['password_recovery_token'], - $user['UID'], - ] - ); + $reset = PasswordReset::findOrNew($user->id); + $reset->token = md5($user->name . time() . rand()); + $reset->save(); engelsystem_log('Password recovery for ' . User_Nick_render($user) . ' started.'); - return $user['password_recovery_token']; + return $reset->token; } /** diff --git a/includes/pages/admin_active.php b/includes/pages/admin_active.php index 33c7459d..8d9f35bd 100644 --- a/includes/pages/admin_active.php +++ b/includes/pages/admin_active.php @@ -1,6 +1,6 @@ count(); $count = $forced_count; $limit = ''; $set_active = ''; @@ -54,21 +54,26 @@ function admin_active() $limit = ' LIMIT ' . $count; } if ($request->has('ack')) { - DB::update('UPDATE `User` SET `Aktiv` = 0 WHERE `Tshirt` = 0'); - $users = DB::select(sprintf(' + State::query() + ->where('got_shirt', '=', false) + ->update(['active' => false]); + + /** @var User[] $users */ + $users = User::query()->raw(sprintf(' SELECT - `User`.*, + `users`.*, COUNT(`ShiftEntry`.`id`) AS `shift_count`, (%s + ( - SELECT COALESCE(SUM(`work_hours`) * 3600, 0) FROM `UserWorkLog` WHERE `user_id`=`User`.`UID` + SELECT COALESCE(SUM(`work_hours`) * 3600, 0) FROM `UserWorkLog` WHERE `user_id`=`users`.`id` AND `work_timestamp` < %s )) AS `shift_length` - FROM `User` - LEFT JOIN `ShiftEntry` ON `User`.`UID` = `ShiftEntry`.`UID` + FROM `users` + LEFT JOIN `ShiftEntry` ON `users`.`id` = `ShiftEntry`.`UID` LEFT JOIN `Shifts` ON `ShiftEntry`.`SID` = `Shifts`.`SID` - WHERE `User`.`Gekommen` = 1 - AND `User`.`force_active`=0 - GROUP BY `User`.`UID` + LEFT JOIN `users_state` ON `users`.`id` = `users_state`.`user_id` + WHERE `users_state`.`arrived` = 1 + AND `users_state`.`force_active` = 0 + GROUP BY `users`.`id` ORDER BY `force_active` DESC, `shift_length` DESC %s ', @@ -78,10 +83,12 @@ function admin_active() )); $user_nicks = []; foreach ($users as $usr) { - DB::update('UPDATE `User` SET `Aktiv` = 1 WHERE `UID`=?', [$usr['UID']]); + $usr->state->active = true; + $usr->state->save(); $user_nicks[] = User_Nick_render($usr); } - DB::update('UPDATE `User` SET `Aktiv`=1 WHERE `force_active`=TRUE'); + + State::whereForceActive(true)->update(['active' => 'true']); engelsystem_log('These angels are active now: ' . join(', ', $user_nicks)); $limit = ''; @@ -103,7 +110,8 @@ function admin_active() $user_id = $request->input('active'); $user_source = User::find($user_id); if ($user_source) { - DB::update('UPDATE `User` SET `Aktiv`=1 WHERE `UID`=? LIMIT 1', [$user_id]); + $user_source->state->active = true; + $user_source->state->save(); engelsystem_log('User ' . User_Nick_render($user_source) . ' is active now.'); $msg = success(__('Angel has been marked as active.'), true); } else { @@ -113,7 +121,8 @@ function admin_active() $user_id = $request->input('not_active'); $user_source = User::find($user_id); if (!$user_source) { - DB::update('UPDATE `User` SET `Aktiv`=0 WHERE `UID`=? LIMIT 1', [$user_id]); + $user_source->state->active = false; + $user_source->state->save(); engelsystem_log('User ' . User_Nick_render($user_source) . ' is NOT active now.'); $msg = success(__('Angel has been marked as not active.'), true); } else { @@ -123,7 +132,8 @@ function admin_active() $user_id = $request->input('tshirt'); $user_source = User::find($user_id); if (!$user_source) { - DB::update('UPDATE `User` SET `Tshirt`=1 WHERE `UID`=? LIMIT 1', [$user_id]); + $user_source->state->got_shirt = true; + $user_source->state->save(); engelsystem_log('User ' . User_Nick_render($user_source) . ' has tshirt now.'); $msg = success(__('Angel has got a t-shirt.'), true); } else { @@ -133,7 +143,8 @@ function admin_active() $user_id = $request->input('not_tshirt'); $user_source = User::find($user_id); if (!$user_source) { - DB::update('UPDATE `User` SET `Tshirt`=0 WHERE `UID`=? LIMIT 1', [$user_id]); + $user_source->state->got_shirt = false; + $user_source->state->save(); engelsystem_log('User ' . User_Nick_render($user_source) . ' has NO tshirt.'); $msg = success(__('Angel has got no t-shirt.'), true); } else { @@ -141,20 +152,22 @@ function admin_active() } } - $users = DB::select(sprintf(' + $users = User::query()->raw(sprintf(' SELECT - `User`.*, + `users`.*, COUNT(`ShiftEntry`.`id`) AS `shift_count`, (%s + ( - SELECT COALESCE(SUM(`work_hours`) * 3600, 0) FROM `UserWorkLog` WHERE `user_id`=`User`.`UID` + SELECT COALESCE(SUM(`work_hours`) * 3600, 0) FROM `UserWorkLog` WHERE `user_id`=`users`.`id` AND `work_timestamp` < %s )) AS `shift_length` - FROM `User` LEFT JOIN `ShiftEntry` ON `User`.`UID` = `ShiftEntry`.`UID` + FROM `users` + LEFT JOIN `users_state` ON `users`.`id` = `users_state`.`user_id` + LEFT JOIN `ShiftEntry` ON `users`.`id` = `ShiftEntry`.`UID` LEFT JOIN `Shifts` ON `ShiftEntry`.`SID` = `Shifts`.`SID` ' . ($show_all_shifts ? '' : 'AND (`Shifts`.`end` < ' . time() . " OR `Shifts`.`end` IS NULL)") . ' - WHERE `User`.`Gekommen` = 1 - GROUP BY `User`.`UID` - ORDER BY `force_active` DESC, `shift_length` DESC + WHERE `users_state`.`arrived` = 1 + GROUP BY `users`.`id` + ORDER BY `users_state`.`force_active` DESC, `shift_length` DESC %s ', $shift_sum_formula, @@ -167,11 +180,11 @@ function admin_active() } else { $tokens = explode(' ', $search); } - foreach ($users as &$usr) { + foreach ($users as $usr) { if (count($tokens) > 0) { $match = false; foreach ($tokens as $t) { - if (stristr($usr['Nick'], trim($t))) { + if (stristr($usr->name, trim($t))) { $match = true; break; } @@ -180,18 +193,20 @@ function admin_active() continue; } } - $usr['nick'] = User_Nick_render($usr); - $usr['shirt_size'] = $tshirt_sizes[$usr['Size']]; - $usr['work_time'] = round($usr['shift_length'] / 60) + + $userData = []; + $userData['nick'] = User_Nick_render($usr); + $userData['shirt_size'] = $tshirt_sizes[$usr->personalData->shirt_size]; + $userData['work_time'] = round($usr['shift_length'] / 60) . ' min (' . sprintf('%.2f', $usr['shift_length'] / 3600) . ' h)'; - $usr['active'] = glyph_bool($usr['Aktiv'] == 1); - $usr['force_active'] = glyph_bool($usr['force_active'] == 1); - $usr['tshirt'] = glyph_bool($usr['Tshirt'] == 1); + $userData['active'] = glyph_bool($usr->state->active == 1); + $userData['force_active'] = glyph_bool($usr->state->force_active == 1); + $userData['tshirt'] = glyph_bool($usr->state->got_shirt == 1); $actions = []; - if ($usr['Aktiv'] == 0) { + if (!$usr->state->active) { $parameters = [ - 'active' => $usr['UID'], + 'active' => $usr->id, 'search' => $search, ]; if ($show_all_shifts) { @@ -201,9 +216,9 @@ function admin_active() . __('set active') . ''; } - if ($usr['Aktiv'] == 1) { + if ($usr->state->active) { $parametersRemove = [ - 'not_active' => $usr['UID'], + 'not_active' => $usr->id, 'search' => $search, ]; if ($show_all_shifts) { @@ -213,9 +228,9 @@ function admin_active() . __('remove active') . ''; } - if ($usr['Tshirt'] == 0) { + if (!$usr->state->got_shirt) { $parametersShirt = [ - 'tshirt' => $usr['UID'], + 'tshirt' => $usr->id, 'search' => $search, ]; if ($show_all_shifts) { @@ -225,9 +240,9 @@ function admin_active() . __('got t-shirt') . ''; } - if ($usr['Tshirt'] == 1) { + if ($usr->state->got_shirt) { $parameters = [ - 'not_tshirt' => $usr['UID'], + 'not_tshirt' => $usr->id, 'search' => $search, ]; if ($show_all_shifts) { @@ -238,30 +253,27 @@ function admin_active() . ''; } - $usr['actions'] = join(' ', $actions); + $userData['actions'] = join(' ', $actions); - $matched_users[] = $usr; + $matched_users[] = $userData; } $shirt_statistics = []; foreach (array_keys($tshirt_sizes) as $size) { - $gc = DB::selectOne( - 'SELECT count(*) FROM `User` WHERE `Size`=? AND `Tshirt`=1', - [$size] - ); - $gc = array_shift($gc); - + $gc = State::query() + ->leftJoin('users_settings', 'users_state.user_id', '=', 'users_settings.user_id') + ->where('users_state.got_shirt', '=', true) + ->where('users_personal_data.shirt_size', '=', $size) + ->count(); $shirt_statistics[] = [ 'size' => $size, - 'given' => (int)$gc + 'given' => $gc ]; } - $shirtCount = User_tshirts_count(); - $shirt_statistics[] = [ 'size' => '' . __('Sum') . '', - 'given' => '' . $shirtCount . '' + 'given' => '' . State::whereGotShirt(true)->count() . '' ]; return page_with_title(admin_active_title(), [ diff --git a/includes/pages/admin_arrive.php b/includes/pages/admin_arrive.php index 62d74290..f06c2c55 100644 --- a/includes/pages/admin_arrive.php +++ b/includes/pages/admin_arrive.php @@ -1,6 +1,5 @@ input('reset'); $user_source = User::find($user_id); if ($user_source) { - DB::update(' - UPDATE `User` - SET `Gekommen`=0, `arrival_date` = NULL - WHERE `UID`=? - LIMIT 1 - ', [$user_id]); + $user_source->state->arrived = false; + $user_source->state->save(); + $user_source->personalData->arrival_date = null; + $user_source->personalData->save(); + engelsystem_log('User set to not arrived: ' . User_Nick_render($user_source)); success(__('Reset done. Angel has not arrived.')); redirect(user_link($user_source->id)); @@ -45,12 +43,11 @@ function admin_arrive() $user_id = $request->input('arrived'); $user_source = User::find($user_id); if ($user_source) { - DB::update(' - UPDATE `User` - SET `Gekommen`=1, `arrival_date`=? - WHERE `UID`=? - LIMIT 1 - ', [time(), $user_id]); + $user_source->state->arrived = true; + $user_source->state->save(); + $user_source->personalData->arrival_date = new Carbon\Carbon(); + $user_source->personalData->save(); + engelsystem_log('User set has arrived: ' . User_Nick_render($user_source)); success(__('Angel has been marked as arrived.')); redirect(user_link($user_source->id)); @@ -59,7 +56,8 @@ function admin_arrive() } } - $users = DB::select('SELECT * FROM `User` ORDER BY `Nick`'); + /** @var User[] $users */ + $users = User::query()->orderBy('name')->get(); $arrival_count_at_day = []; $planned_arrival_count_at_day = []; $planned_departure_count_at_day = []; @@ -72,7 +70,7 @@ function admin_arrive() foreach ($users as $usr) { if (count($tokens) > 0) { $match = false; - $index = join(' ', $usr); + $index = join(' ', $usr->toArray()); foreach ($tokens as $t) { if (stristr($index, trim($t))) { $match = true; @@ -84,43 +82,43 @@ function admin_arrive() } } - $usr['nick'] = User_Nick_render($usr); - if (!is_null($usr['planned_departure_date'])) { - $usr['rendered_planned_departure_date'] = date('Y-m-d', $usr['planned_departure_date']); + $usr->name = User_Nick_render($usr); + if ($usr->personalData->planned_departure_date) { + $usr['rendered_planned_departure_date'] = $usr->personalData->planned_departure_date->format('Y-m-d'); } else { $usr['rendered_planned_departure_date'] = '-'; } - $usr['rendered_planned_arrival_date'] = date('Y-m-d', $usr['planned_arrival_date']); - $usr['rendered_arrival_date'] = $usr['arrival_date'] > 0 ? date('Y-m-d', $usr['arrival_date']) : '-'; - $usr['arrived'] = $usr['Gekommen'] == 1 ? __('yes') : ''; - $usr['actions'] = $usr['Gekommen'] == 1 + $usr['rendered_planned_arrival_date'] = $usr->personalData->planned_arrival_date->format('Y-m-d'); + $usr['rendered_arrival_date'] = $usr->personalData->arrival_date ? $usr->personalData->arrival_date->format('Y-m-d') : '-'; + $usr['arrived'] = $usr->state->arrived ? __('yes') : ''; + $usr['actions'] = $usr->state->arrived == 1 ? '' . __('reset') . '' : '' . __('arrived') . ''; - if ($usr['arrival_date'] > 0) { - $day = date('Y-m-d', $usr['arrival_date']); + if ($usr->personalData->arrival_date) { + $day = $usr->personalData->arrival_date->format('Y-m-d'); if (!isset($arrival_count_at_day[$day])) { $arrival_count_at_day[$day] = 0; } $arrival_count_at_day[$day]++; } - if (!is_null($usr['planned_arrival_date'])) { - $day = date('Y-m-d', $usr['planned_arrival_date']); + if ($usr->personalData->planned_arrival_date) { + $day = $usr->personalData->planned_arrival_date->format('Y-m-d'); if (!isset($planned_arrival_count_at_day[$day])) { $planned_arrival_count_at_day[$day] = 0; } $planned_arrival_count_at_day[$day]++; } - if (!is_null($usr['planned_departure_date']) && $usr['Gekommen'] == 1) { - $day = date('Y-m-d', $usr['planned_departure_date']); + if ($usr->personalData->planned_departure_date && $usr->state->arrived) { + $day = $usr->personalData->planned_departure_date->format('Y-m-d'); if (!isset($planned_departure_count_at_day[$day])) { $planned_departure_count_at_day[$day] = 0; } diff --git a/includes/pages/admin_free.php b/includes/pages/admin_free.php index d1d102c7..9b1f581b 100644 --- a/includes/pages/admin_free.php +++ b/includes/pages/admin_free.php @@ -1,6 +1,7 @@ quote($angelType) - . ' AND `UserAngelTypes`.`user_id` = `User`.`UID`'; + . ' AND `UserAngelTypes`.`user_id` = `users`.`id`'; if ($request->has('confirmed_only')) { $angelTypeSearch .= ' AND `UserAngelTypes`.`confirm_user_id`'; } @@ -43,26 +44,25 @@ function admin_free() $angel_types[$angel_type['id']] = $angel_type['name']; } - $users = DB::select(' - SELECT `User`.* - FROM `User` - ' . $angelTypeSearch . ' - LEFT JOIN `ShiftEntry` ON `User`.`UID` = `ShiftEntry`.`UID` + /** @var User[] $users */ + $users = User::query()->raw(sprintf(' + SELECT `users`.* + FROM `users` + %s + LEFT JOIN `ShiftEntry` ON `users`.`id` = `ShiftEntry`.`UID` + LEFT JOIN `users_state` ON `users`.`id` = `users_state`.`user_id` LEFT JOIN `Shifts` ON ( `ShiftEntry`.`SID` = `Shifts`.`SID` - AND `Shifts`.`start` < ? - AND `Shifts`.`end` > ? + AND `Shifts`.`start` < %u + AND `Shifts`.`end` > %u ) - WHERE `User`.`Gekommen` = 1 + WHERE `users_state`.`arrived` = 1 AND `Shifts`.`SID` IS NULL - GROUP BY `User`.`UID` - ORDER BY `Nick` - ', - [ - time(), - time(), - ] + GROUP BY `users`.`id` + ORDER BY `users` + ', $angelTypeSearch, time(), time() + ) ); $free_users_table = []; @@ -74,7 +74,7 @@ function admin_free() foreach ($users as $usr) { if (count($tokens) > 0) { $match = false; - $index = join('', $usr); + $index = join('', $usr->toArray()); foreach ($tokens as $t) { if (stristr($index, trim($t))) { $match = true; @@ -89,12 +89,11 @@ function admin_free() $free_users_table[] = [ 'name' => User_Nick_render($usr), 'shift_state' => User_shift_state_render($usr), - 'dect' => $usr['DECT'], - 'jabber' => $usr['jabber'], - 'email' => $usr['email_by_human_allowed'] ? $usr['email'] : glyph('eye-close'), + 'dect' => $usr->contact->dect, + 'email' => $usr->settings->email_human ? ($usr->contact->email ? $usr->contact->email : $usr->email) : glyph('eye-close'), 'actions' => in_array('admin_user', $privileges) - ? button(page_link_to('admin_user', ['id' => $usr['UID']]), __('edit'), 'btn-xs') + ? button(page_link_to('admin_user', ['id' => $usr->id]), __('edit'), 'btn-xs') : '' ]; } @@ -119,7 +118,6 @@ function admin_free() 'name' => __('Nick'), 'shift_state' => '', 'dect' => __('DECT'), - 'jabber' => __('Jabber'), 'email' => __('E-Mail'), 'actions' => '' ], $free_users_table) diff --git a/includes/pages/guest_login.php b/includes/pages/guest_login.php index 32532c6f..bc919acf 100644 --- a/includes/pages/guest_login.php +++ b/includes/pages/guest_login.php @@ -431,7 +431,7 @@ function guest_login() if ($request->has('submit')) { if ($request->has('nick') && strlen(User_validate_Nick($request->input('nick'))) > 0) { $nick = User_validate_Nick($request->input('nick')); - $login_user = User::whereName($nick); + $login_user = User::whereName($nick)->first(); if ($login_user) { if ($request->has('password')) { if (!verify_password($request->postData('password'), $login_user->password, $login_user->id)) { diff --git a/includes/pages/user_atom.php b/includes/pages/user_atom.php index f6a67a15..6aafb74f 100644 --- a/includes/pages/user_atom.php +++ b/includes/pages/user_atom.php @@ -7,19 +7,17 @@ use Engelsystem\Database\DB; */ function user_atom() { - global $user; $request = request(); if (!$request->has('key') || !preg_match('/^[\da-f]{32}$/', $request->input('key'))) { engelsystem_error('Missing key.'); } - $key = $request->input('key'); - $user = User_by_api_key($key); + $user = auth()->apiUser('key'); if (empty($user)) { engelsystem_error('Key invalid.'); } - if (!in_array('atom', privileges_for_user($user['UID']))) { + if (!in_array('atom', privileges_for_user($user->id))) { engelsystem_error('No privilege for atom.'); } diff --git a/includes/pages/user_ical.php b/includes/pages/user_ical.php index f7ed64dd..8a80d681 100644 --- a/includes/pages/user_ical.php +++ b/includes/pages/user_ical.php @@ -5,20 +5,17 @@ */ function user_ical() { - global $user; $request = request(); if (!$request->has('key') || !preg_match('/^[\da-f]{32}$/', $request->input('key'))) { engelsystem_error('Missing key.'); } - $key = $request->input('key'); - $user = User_by_api_key($key); - if (empty($user)) { + $user = auth()->apiUser('key'); + if (!$user) { engelsystem_error('Key invalid.'); } - - if (!in_array('ical', privileges_for_user($user['UID']))) { + if (!in_array('ical', privileges_for_user($user->id))) { engelsystem_error('No privilege for ical.'); } diff --git a/includes/pages/user_messages.php b/includes/pages/user_messages.php index 4431133e..9b587343 100644 --- a/includes/pages/user_messages.php +++ b/includes/pages/user_messages.php @@ -39,17 +39,18 @@ function user_messages() $request = request(); if (!$request->has('action')) { - $users = DB::select( - 'SELECT `UID`, `Nick` FROM `User` WHERE NOT `UID`=? ORDER BY `Nick`', - [$user->id] - ); + /** @var User[] $users */ + $users = User::query() + ->whereKeyNot($user->id) + ->orderBy('name') + ->get(['id', 'name']); $to_select_data = [ '' => __('Select recipient...') ]; foreach ($users as $u) { - $to_select_data[$u['UID']] = $u['Nick']; + $to_select_data[$u->id] = $u->name; } $to_select = html_select_key('to', 'to', $to_select_data, ''); diff --git a/includes/pages/user_settings.php b/includes/pages/user_settings.php index cf8d2f0b..fbcd8baf 100644 --- a/includes/pages/user_settings.php +++ b/includes/pages/user_settings.php @@ -1,7 +1,7 @@ has('mail')) { $result = User_validate_mail($request->input('mail')); - $user_source['email'] = $result->getValue(); + $user_source->email = $result->getValue(); if (!$result->isValid()) { $valid = false; error(__('E-mail address is not correct.')); @@ -36,20 +36,11 @@ function user_settings_main($user_source, $enable_tshirt_size, $tshirt_sizes) error(__('Please enter your e-mail.')); } - $user_source['email_shiftinfo'] = $request->has('email_shiftinfo'); - $user_source['email_by_human_allowed'] = $request->has('email_by_human_allowed'); - - if ($request->has('jabber')) { - $result = User_validate_jabber($request->input('jabber')); - $user_source['jabber'] = $result->getValue(); - if (!$result->isValid()) { - $valid = false; - error(__('Please check your jabber account information.')); - } - } + $user_source->settings->email_shiftinfo = $request->has('email_shiftinfo'); + $user_source->settings->email_human = $request->has('email_by_human_allowed'); if ($request->has('tshirt_size') && isset($tshirt_sizes[$request->input('tshirt_size')])) { - $user_source['Size'] = $request->input('tshirt_size'); + $user_source->personalData->shirt_size = $request->input('tshirt_size'); } elseif ($enable_tshirt_size) { $valid = false; } @@ -57,7 +48,7 @@ function user_settings_main($user_source, $enable_tshirt_size, $tshirt_sizes) if ($request->has('planned_arrival_date')) { $tmp = parse_date('Y-m-d H:i', $request->input('planned_arrival_date') . ' 00:00'); $result = User_validate_planned_arrival_date($tmp); - $user_source['planned_arrival_date'] = $result->getValue(); + $user_source->personalData->planned_arrival_date = Carbon::createFromTimestamp($result->getValue()); if (!$result->isValid()) { $valid = false; error(__('Please enter your planned date of arrival. It should be after the buildup start date and before teardown end date.')); @@ -66,8 +57,8 @@ function user_settings_main($user_source, $enable_tshirt_size, $tshirt_sizes) if ($request->has('planned_departure_date')) { $tmp = parse_date('Y-m-d H:i', $request->input('planned_departure_date') . ' 00:00'); - $result = User_validate_planned_departure_date($user_source['planned_arrival_date'], $tmp); - $user_source['planned_departure_date'] = $result->getValue(); + $result = User_validate_planned_departure_date($user_source->personalData->arrival_date->getTimestamp(), $tmp); + $user_source->personalData->planned_departure_date = Carbon::createFromTimestamp($result->getValue()); if (!$result->isValid()) { $valid = false; error(__('Please enter your planned date of departure. It should be after your planned arrival date and after buildup start date and before teardown end date.')); @@ -75,21 +66,21 @@ function user_settings_main($user_source, $enable_tshirt_size, $tshirt_sizes) } // Trivia - $user_source['Name'] = strip_request_item('lastname', $user_source['Name']); - $user_source['Vorname'] = strip_request_item('prename', $user_source['Vorname']); - $user_source['Alter'] = strip_request_item('age', $user_source['Alter']); - $user_source['Telefon'] = strip_request_item('tel', $user_source['Telefon']); + $user_source->name = strip_request_item('lastname', $user_source['Name']); + $user_source->personalData->first_name = strip_request_item('prename', $user_source['Vorname']); if (strlen(strip_request_item('dect')) <= 5) { - $user_source['DECT'] = strip_request_item('dect', $user_source['DECT']); + $user_source->contact->dect = strip_request_item('dect', $user_source['DECT']); } else { $valid = false; error(__('For dect numbers are only 5 digits allowed.')); } - $user_source['Handy'] = strip_request_item('mobile', $user_source['Handy']); - $user_source['Hometown'] = strip_request_item('hometown', $user_source['Hometown']); + $user_source->contact->mobile = strip_request_item('mobile', $user_source['Handy']); if ($valid) { - User_update($user_source); + $user_source->save(); + $user_source->contact->save(); + $user_source->personalData->save(); + $user_source->settings->save(); success(__('Settings saved.')); redirect(page_link_to('user_settings')); @@ -101,14 +92,14 @@ function user_settings_main($user_source, $enable_tshirt_size, $tshirt_sizes) /** * Change user password. * - * @param array $user_source The user + * @param User $user_source The user */ function user_settings_password($user_source) { $request = request(); if ( !$request->has('password') - || !verify_password($request->postData('password'), $user_source['Passwort'], $user_source['UID']) + || !verify_password($request->postData('password'), $user_source->password, $user_source->id) ) { error(__('-> not OK. Please try again.')); } elseif (strlen($request->postData('new_password')) < config('min_password_length')) { @@ -116,7 +107,7 @@ function user_settings_password($user_source) } elseif ($request->postData('new_password') != $request->postData('new_password2')) { error(__('Your passwords don\'t match.')); } else { - set_password($user_source['UID'], $request->postData('new_password')); + set_password($user_source->id, $request->postData('new_password')); success(__('Password saved.')); } redirect(page_link_to('user_settings')); @@ -125,9 +116,9 @@ function user_settings_password($user_source) /** * Change user theme * - * @param array $user_source The user + * @param User $user_source The user * @param array $themes List of available themes - * @return array + * @return User */ function user_settings_theme($user_source, $themes) { @@ -135,22 +126,13 @@ function user_settings_theme($user_source, $themes) $request = request(); if ($request->has('theme') && isset($themes[$request->input('theme')])) { - $user_source['color'] = $request->input('theme'); + $user_source->settings->theme = $request->input('theme'); } else { $valid = false; } if ($valid) { - DB::update(' - UPDATE `User` - SET `color`=? - WHERE `UID`=? - ', - [ - $user_source['color'], - $user_source['UID'], - ] - ); + $user_source->settings->save(); success(__('Theme changed.')); redirect(page_link_to('user_settings')); @@ -162,9 +144,9 @@ function user_settings_theme($user_source, $themes) /** * Change use locale * - * @param array $user_source The user + * @param User $user_source The user * @param array $locales List of available locales - * @return array + * @return User */ function user_settings_locale($user_source, $locales) { @@ -173,23 +155,14 @@ function user_settings_locale($user_source, $locales) $session = session(); if ($request->has('language') && isset($locales[$request->input('language')])) { - $user_source['Sprache'] = $request->input('language'); + $user_source->settings->language = $request->input('language'); } else { $valid = false; } if ($valid) { - DB::update(' - UPDATE `User` - SET `Sprache`=? - WHERE `UID`=? - ', - [ - $user_source['Sprache'], - $user_source['UID'], - ] - ); - $session->set('locale', $user_source['Sprache']); + $user_source->settings->save(); + $session->set('locale', $user_source->settings->language); success('Language changed.'); redirect(page_link_to('user_settings')); @@ -205,7 +178,6 @@ function user_settings_locale($user_source, $locales) */ function user_settings() { - global $user; $request = request(); $config = config(); $themes = config('available_themes'); @@ -227,8 +199,7 @@ function user_settings() $teardown_end_date = $teardown->getTimestamp(); } - $user_source = $user; - + $user_source = auth()->user(); if ($request->has('submit')) { $user_source = user_settings_main($user_source, $enable_tshirt_size, $tshirt_sizes); } elseif ($request->has('submit_password')) { diff --git a/includes/sys_auth.php b/includes/sys_auth.php index 91edca77..5d2fa8be 100644 --- a/includes/sys_auth.php +++ b/includes/sys_auth.php @@ -1,31 +1,25 @@ has('uid')) { - $user = DB::selectOne('SELECT * FROM `User` WHERE `UID`=? LIMIT 1', [$session->get('uid')]); - if (!empty($user)) { - // User ist eingeloggt, Datensatz zur Verfügung stellen und Timestamp updaten - DB::update(' - UPDATE `User` - SET `lastLogIn` = ? - WHERE `UID` = ? - LIMIT 1 - ', [ - time(), - $session->get('uid'), - ]); - $privileges = privileges_for_user($user['UID']); + $user = auth()->user(); + + if ($user) { + $user->last_login_at = new Carbon(); + $user->save(); + + $privileges = privileges_for_user($user->id); return; } @@ -60,18 +54,9 @@ function generate_salt($length = 16) */ function set_password($uid, $password) { - DB::update(' - UPDATE `User` - SET `Passwort` = ?, - `password_recovery_token`=NULL - WHERE `UID` = ? - LIMIT 1 - ', - [ - crypt($password, config('crypt_alg') . '$' . generate_salt(16) . '$'), - $uid - ] - ); + $user = User::find($uid); + $user->password = crypt($password, config('crypt_alg') . '$' . generate_salt(16) . '$'); + $user->save(); } /** @@ -103,19 +88,11 @@ function verify_password($password, $salt, $uid = null) // let's update it! // we duplicate the query from the above set_password() function to have the extra safety of checking // the old hash - DB::update(' - UPDATE `User` - SET `Passwort` = ? - WHERE `UID` = ? - AND `Passwort` = ? - LIMIT 1 - ', - [ - crypt($password, $crypt_alg . '$' . generate_salt() . '$'), - $uid, - $salt, - ] - ); + $user = User::find($uid); + if ($user->password == $salt) { + $user->password = crypt($password, $crypt_alg . '$' . generate_salt() . '$'); + $user->save(); + } } return $correct; } @@ -129,11 +106,11 @@ function privileges_for_user($user_id) $privileges = []; $user_privileges = DB::select(' SELECT `Privileges`.`name` - FROM `User` - JOIN `UserGroups` ON (`User`.`UID` = `UserGroups`.`uid`) + FROM `users` + JOIN `UserGroups` ON (`users`.`id` = `UserGroups`.`uid`) JOIN `GroupPrivileges` ON (`UserGroups`.`group_id` = `GroupPrivileges`.`group_id`) JOIN `Privileges` ON (`GroupPrivileges`.`privilege_id` = `Privileges`.`id`) - WHERE `User`.`UID`=? + WHERE `users`.`id`=? ', [$user_id]); foreach ($user_privileges as $user_privilege) { $privileges[] = $user_privilege['name']; diff --git a/includes/view/AngelTypes_view.php b/includes/view/AngelTypes_view.php index be79cbb9..3ce063ab 100644 --- a/includes/view/AngelTypes_view.php +++ b/includes/view/AngelTypes_view.php @@ -190,10 +190,10 @@ function AngelType_view_buttons($angeltype, $user_angeltype, $admin_angeltypes, /** * Renders and sorts the members of an angeltype into supporters, members and unconfirmed members. * - * @param array $angeltype - * @param array $members - * @param bool $admin_user_angeltypes - * @param bool $admin_angeltypes + * @param array $angeltype + * @param User[] $members + * @param bool $admin_user_angeltypes + * @param bool $admin_angeltypes * @return array [supporters, members, unconfirmed members] */ function AngelType_view_members($angeltype, $members, $admin_user_angeltypes, $admin_angeltypes) @@ -202,7 +202,7 @@ function AngelType_view_members($angeltype, $members, $admin_user_angeltypes, $a $members_confirmed = []; $members_unconfirmed = []; foreach ($members as $member) { - $member['Nick'] = User_Nick_render($member); + $member->name = User_Nick_render($member); if ($angeltype['requires_driver_license']) { $member['wants_to_drive'] = glyph_bool($member['wants_to_drive']); $member['has_car'] = glyph_bool($member['has_car']); @@ -317,7 +317,7 @@ function AngelType_view_table_headers($angeltype, $supporter, $admin_angeltypes) * Render an angeltype page containing the member lists. * * @param array $angeltype - * @param array[] $members + * @param User[] $members * @param array $user_angeltype * @param bool $admin_user_angeltypes * @param bool $admin_angeltypes @@ -380,11 +380,11 @@ function AngelType_view_shifts($angeltype, $shiftsFilterRenderer, $shiftCalendar } /** - * @param array $angeltype - * @param array $members - * @param bool $admin_user_angeltypes - * @param bool $admin_angeltypes - * @param bool $supporter + * @param array $angeltype + * @param User[] $members + * @param bool $admin_user_angeltypes + * @param bool $admin_angeltypes + * @param bool $supporter * @return string HTML */ function AngelType_view_info( diff --git a/includes/view/ShiftEntry_view.php b/includes/view/ShiftEntry_view.php index 51f02cce..9b528256 100644 --- a/includes/view/ShiftEntry_view.php +++ b/includes/view/ShiftEntry_view.php @@ -76,7 +76,7 @@ function ShiftEntry_delete_title() * @param array $room * @param array $angeltype * @param array $angeltypes_select - * @param array $signup_user + * @param User $signup_user * @param array $users_select * @return string */ @@ -90,7 +90,7 @@ function ShiftEntry_create_view_admin($shift, $room, $angeltype, $angeltypes_sel info(__('Do you want to sign up the following user for this shift?'), true), form([ form_select('angeltype_id', __('Angeltype'), $angeltypes_select, $angeltype['id']), - form_select('user_id', __('User'), $users_select, $signup_user['UID']), + form_select('user_id', __('User'), $users_select, $signup_user->id), form_submit('submit', glyph('ok') . __('Save')) ]) ]); diff --git a/includes/view/UserAngelTypes_view.php b/includes/view/UserAngelTypes_view.php index 0702a2b3..78bf6fe9 100644 --- a/includes/view/UserAngelTypes_view.php +++ b/includes/view/UserAngelTypes_view.php @@ -147,7 +147,7 @@ function UserAngelType_delete_view($user_angeltype, $user, $angeltype) /** * @param array $angeltype - * @param array[] $users_source + * @param User[] $users_source * @param int $user_id * @return string */ @@ -155,7 +155,7 @@ function UserAngelType_add_view($angeltype, $users_source, $user_id) { $users = []; foreach ($users_source as $user_source) { - $users[$user_source['UID']] = User_Nick_render($user_source); + $users[$user_source->id] = User_Nick_render($user_source); } return page_with_title(__('Add user to angeltype'), [ @@ -176,7 +176,7 @@ function UserAngelType_add_view($angeltype, $users_source, $user_id) } /** - * @param array $user + * @param User $user * @param array $angeltype * @return string */ @@ -194,7 +194,7 @@ function UserAngelType_join_view($user, $angeltype) button( page_link_to( 'user_angeltypes', - ['action' => 'add', 'angeltype_id' => $angeltype['id'], 'user_id' => $user['UID'], 'confirmed' => 1] + ['action' => 'add', 'angeltype_id' => $angeltype['id'], 'user_id' => $user->id, 'confirmed' => 1] ), glyph('ok') . __('save'), 'btn-primary' diff --git a/includes/view/User_view.php b/includes/view/User_view.php index 1c1aa30a..bcf9aff7 100644 --- a/includes/view/User_view.php +++ b/includes/view/User_view.php @@ -6,7 +6,7 @@ use Engelsystem\Models\User\User; /** * Renders user settings page * - * @param array $user_source The user + * @param User $user_source The user * @param array $locales Available languages * @param array $themes Available themes * @param int $buildup_start_date Unix timestamp @@ -24,6 +24,7 @@ function User_settings_view( $enable_tshirt_size, $tshirt_sizes ) { + $personalData = $user_source->personalData; return page_with_title(settings_title(), [ msg(), div('row', [ @@ -31,48 +32,44 @@ function User_settings_view( form([ form_info('', __('Here you can change your user details.')), form_info(entry_required() . ' = ' . __('Entry required!')), - form_text('nick', __('Nick'), $user_source['Nick'], true), - form_text('lastname', __('Last name'), $user_source['Name']), - form_text('prename', __('First name'), $user_source['Vorname']), + form_text('nick', __('Nick'), $user_source->name, true), + form_text('lastname', __('Last name'), $user_source->personalData->last_name), + form_text('prename', __('First name'), $user_source->personalData->first_name), form_date( 'planned_arrival_date', __('Planned date of arrival') . ' ' . entry_required(), - $user_source['planned_arrival_date'], + $personalData->arrival_date ? $personalData->arrival_date->getTimestamp() : '', $buildup_start_date, $teardown_end_date ), form_date( 'planned_departure_date', __('Planned date of departure'), - $user_source['planned_departure_date'], + $personalData->planned_departure_date ? $personalData->planned_departure_date->getTimestamp() : '', $buildup_start_date, $teardown_end_date ), - form_text('age', __('Age'), $user_source['Alter']), - form_text('tel', __('Phone'), $user_source['Telefon']), - form_text('dect', __('DECT'), $user_source['DECT']), - form_text('mobile', __('Mobile'), $user_source['Handy']), - form_text('mail', __('E-Mail') . ' ' . entry_required(), $user_source['email']), + form_text('dect', __('DECT'), $user_source->contact->dect), + form_text('mobile', __('Mobile'), $user_source->contact->mobile), + form_text('mail', __('E-Mail') . ' ' . entry_required(), $user_source->contact->email), form_checkbox( 'email_shiftinfo', __( 'The %s is allowed to send me an email (e.g. when my shifts change)', [config('app_name')] ), - $user_source['email_shiftinfo'] + $user_source->settings->email_shiftinfo ), form_checkbox( 'email_by_human_allowed', __('Humans are allowed to send me an email (e.g. for ticket vouchers)'), - $user_source['email_by_human_allowed'] + $user_source->settings->email_human ), - form_text('jabber', __('Jabber'), $user_source['jabber']), - form_text('hometown', __('Hometown'), $user_source['Hometown']), $enable_tshirt_size ? form_select( 'tshirt_size', __('Shirt size'), $tshirt_sizes, - $user_source['Size'], + $user_source->personalData->shirt_size, __('Please select...') ) : '', form_info('', __('Please visit the angeltypes page to manage your angeltypes.')), @@ -89,12 +86,12 @@ function User_settings_view( ]), form([ form_info(__('Here you can choose your color settings:')), - form_select('theme', __('Color settings:'), $themes, $user_source['color']), + form_select('theme', __('Color settings:'), $themes, $user_source->settings->theme), form_submit('submit_theme', __('Save')) ]), form([ form_info(__('Here you can choose your language:')), - form_select('language', __('Language:'), $locales, $user_source['Sprache']), + form_select('language', __('Language:'), $locales, $user_source->settings->language), form_submit('submit_language', __('Save')) ]) ]) @@ -194,14 +191,14 @@ function User_edit_vouchers_view($user) } /** - * @param array[] $users - * @param string $order_by - * @param int $arrived_count - * @param int $active_count - * @param int $force_active_count - * @param int $freeloads_count - * @param int $tshirts_count - * @param int $voucher_count + * @param User[] $users + * @param string $order_by + * @param int $arrived_count + * @param int $active_count + * @param int $force_active_count + * @param int $freeloads_count + * @param int $tshirts_count + * @param int $voucher_count * @return string */ function Users_view( @@ -214,18 +211,28 @@ function Users_view( $tshirts_count, $voucher_count ) { - foreach ($users as &$user) { - $user['Nick'] = User_Nick_render($user); - $user['Gekommen'] = glyph_bool($user['Gekommen']); - $user['Aktiv'] = glyph_bool($user['Aktiv']); - $user['force_active'] = glyph_bool($user['force_active']); - $user['Tshirt'] = glyph_bool($user['Tshirt']); - $user['lastLogIn'] = date(__('m/d/Y h:i a'), $user['lastLogIn']); - $user['actions'] = table_buttons([ - button_glyph(page_link_to('admin_user', ['id' => $user['UID']]), 'edit', 'btn-xs') + + $usersList = []; + foreach ($users as $user) { + $u = []; + $u['Nick'] = User_Nick_render($user); + $u['Vorname'] = $user->personalData->first_name; + $u['Name'] = $user->personalData->last_name; + $u['DECT'] = $user->contact->dect; + $u['Gekommen'] = glyph_bool($user->state->arrived); + $u['got_voucher'] = glyph_bool($user->state->got_voucher); + $u['freeloads'] = $user->getAttribute('freeloads'); + $u['Aktiv'] = glyph_bool($user->state->active); + $u['force_active'] = glyph_bool($user->state->force_active); + $u['Tshirt'] = glyph_bool($user->state->got_shirt); + $u['Size'] = $user->personalData->shirt_size; + $u['lastLogIn'] = $user->last_login_at ? $user->last_login_at->format(__('m/d/Y h:i a')) : ''; + $u['actions'] = table_buttons([ + button_glyph(page_link_to('admin_user', ['id' => $user->id]), 'edit', 'btn-xs') ]); + $usersList[] = $u; } - $users[] = [ + $usersList[] = [ 'Nick' => '' . __('Sum') . '', 'Gekommen' => $arrived_count, 'got_voucher' => $voucher_count, @@ -233,7 +240,7 @@ function Users_view( 'force_active' => $force_active_count, 'freeloads' => $freeloads_count, 'Tshirt' => $tshirts_count, - 'actions' => '' . count($users) . '' + 'actions' => '' . count($usersList) . '' ]; return page_with_title(__('All users'), [ @@ -255,7 +262,7 @@ function Users_view( 'Size' => Users_table_header_link('Size', __('Size'), $order_by), 'lastLogIn' => Users_table_header_link('lastLogIn', __('Last login'), $order_by), 'actions' => '' - ], $users) + ], $usersList) ]); } @@ -281,19 +288,18 @@ function Users_table_header_link($column, $label, $order_by) function User_shift_state_render($user) { if ($user instanceof User) { - $userModel = $user; - $user = [ - 'Gekommen' => $userModel->state->arrived, - 'UID' => $user->id, - ]; + $id = $user->id; + $arrived = $user->state->arrived; + } else { + $arrived = $user['Gekommen']; + $id = $user['UID']; } - if (!$user['Gekommen']) { + if (!$arrived) { return ''; } - $upcoming_shifts = ShiftEntries_upcoming_for_user($user['UID']); - + $upcoming_shifts = ShiftEntries_upcoming_for_user($id); if (empty($upcoming_shifts)) { return '' . __('Free') . ''; } @@ -424,7 +430,7 @@ function User_view_myshift($shift, $user_source, $its_me) * @param int $tshirt_score * @param bool $tshirt_admin * @param array[] $user_worklogs - * @param $admin_user_worklog_privilege + * @param bool $admin_user_worklog_privilege * @return array */ function User_view_myshifts( @@ -437,19 +443,19 @@ function User_view_myshifts( $admin_user_worklog_privilege ) { $myshifts_table = []; - $timesum = 0; + $timeSum = 0; foreach ($shifts as $shift) { $myshifts_table[$shift['start']] = User_view_myshift($shift, $user_source, $its_me); if (!$shift['freeloaded']) { - $timesum += ($shift['end'] - $shift['start']); + $timeSum += ($shift['end'] - $shift['start']); } } if ($its_me || $admin_user_worklog_privilege) { foreach ($user_worklogs as $worklog) { $myshifts_table[$worklog['work_timestamp']] = User_view_worklog($worklog, $admin_user_worklog_privilege); - $timesum += $worklog['work_hours'] * 3600; + $timeSum += $worklog['work_hours'] * 3600; } } @@ -457,7 +463,7 @@ function User_view_myshifts( ksort($myshifts_table); $myshifts_table[] = [ 'date' => '' . __('Sum:') . '', - 'duration' => '' . sprintf('%.2f', round($timesum / 3600, 2)) . ' h', + 'duration' => '' . sprintf('%.2f', round($timeSum / 3600, 2)) . ' h', 'room' => '', 'shift_info' => '', 'comment' => '', diff --git a/src/Helpers/Authenticator.php b/src/Helpers/Authenticator.php index eee7b965..3061fbc1 100644 --- a/src/Helpers/Authenticator.php +++ b/src/Helpers/Authenticator.php @@ -2,33 +2,40 @@ namespace Engelsystem\Helpers; -use Engelsystem\Models\BaseModel; use Engelsystem\Models\User\User; use Engelsystem\Models\User\User as UserRepository; +use Psr\Http\Message\ServerRequestInterface; use Symfony\Component\HttpFoundation\Session\Session; class Authenticator { - /** @var UserRepository */ + /** @var User */ protected $user = null; + /** @var ServerRequestInterface */ + protected $request; + /** @var Session */ protected $session; - /** @var BaseModel */ + /** @var UserRepository */ protected $userRepository; /** - * @param Session $session - * @param UserRepository $userRepository + * @param ServerRequestInterface $request + * @param Session $session + * @param UserRepository $userRepository */ - public function __construct(Session $session, UserRepository $userRepository) + public function __construct(ServerRequestInterface $request, Session $session, UserRepository $userRepository) { + $this->request = $request; $this->session = $session; $this->userRepository = $userRepository; } /** + * Load the user from session + * * @return User|null */ public function user() @@ -51,6 +58,36 @@ class Authenticator $this->user = $user; - return $user; + return $this->user; + } + + /** + * Get the user by his api key + * + * @param string $parameter + * @return User|null + */ + public function apiUser($parameter = 'api_key') + { + if ($this->user) { + return $this->user; + } + + $params = $this->request->getQueryParams(); + if (!isset($params[$parameter])) { + return null; + } + + $user = $this + ->userRepository + ->whereApiKey($params[$parameter]) + ->first(); + if (!$user) { + return $this->user(); + } + + $this->user = $user; + + return $this->user; } } diff --git a/src/Models/User/Contact.php b/src/Models/User/Contact.php index 8adf9df7..23bc528c 100644 --- a/src/Models/User/Contact.php +++ b/src/Models/User/Contact.php @@ -7,9 +7,9 @@ namespace Engelsystem\Models\User; * @property string $email * @property string $mobile * - * @method static \Illuminate\Database\Query\Builder|\Engelsystem\Models\User\Contact whereDect($value) - * @method static \Illuminate\Database\Query\Builder|\Engelsystem\Models\User\Contact whereEmail($value) - * @method static \Illuminate\Database\Query\Builder|\Engelsystem\Models\User\Contact whereMobile($value) + * @method static \Illuminate\Database\Query\Builder|\Engelsystem\Models\User\Contact[] whereDect($value) + * @method static \Illuminate\Database\Query\Builder|\Engelsystem\Models\User\Contact[] whereEmail($value) + * @method static \Illuminate\Database\Query\Builder|\Engelsystem\Models\User\Contact[] whereMobile($value) */ class Contact extends HasUserModel { diff --git a/src/Models/User/PasswordReset.php b/src/Models/User/PasswordReset.php index b65258c5..cd722aba 100644 --- a/src/Models/User/PasswordReset.php +++ b/src/Models/User/PasswordReset.php @@ -6,8 +6,8 @@ namespace Engelsystem\Models\User; * @property string $token * @property \Carbon\Carbon $created_at * - * @method static \Illuminate\Database\Query\Builder|\Engelsystem\Models\User\PasswordReset whereToken($value) - * @method static \Illuminate\Database\Query\Builder|\Engelsystem\Models\User\PasswordReset whereCreatedAt($value) + * @method static \Illuminate\Database\Query\Builder|\Engelsystem\Models\User\PasswordReset[] whereToken($value) + * @method static \Illuminate\Database\Query\Builder|\Engelsystem\Models\User\PasswordReset[] whereCreatedAt($value) */ class PasswordReset extends HasUserModel { diff --git a/src/Models/User/Settings.php b/src/Models/User/Settings.php index 8f86e123..d062f902 100644 --- a/src/Models/User/Settings.php +++ b/src/Models/User/Settings.php @@ -8,10 +8,10 @@ namespace Engelsystem\Models\User; * @property bool $email_human * @property bool $email_shiftinfo * - * @method static \Illuminate\Database\Query\Builder|\Engelsystem\Models\User\Settings whereLanguage($value) - * @method static \Illuminate\Database\Query\Builder|\Engelsystem\Models\User\Settings whereTheme($value) - * @method static \Illuminate\Database\Query\Builder|\Engelsystem\Models\User\Settings whereEmailHuman($value) - * @method static \Illuminate\Database\Query\Builder|\Engelsystem\Models\User\Settings whereEmailShiftinfo($value) + * @method static \Illuminate\Database\Query\Builder|\Engelsystem\Models\User\Settings[] whereLanguage($value) + * @method static \Illuminate\Database\Query\Builder|\Engelsystem\Models\User\Settings[] whereTheme($value) + * @method static \Illuminate\Database\Query\Builder|\Engelsystem\Models\User\Settings[] whereEmailHuman($value) + * @method static \Illuminate\Database\Query\Builder|\Engelsystem\Models\User\Settings[] whereEmailShiftinfo($value) */ class Settings extends HasUserModel { diff --git a/src/Models/User/State.php b/src/Models/User/State.php index 6a1876ed..5651736d 100644 --- a/src/Models/User/State.php +++ b/src/Models/User/State.php @@ -9,11 +9,11 @@ namespace Engelsystem\Models\User; * @property bool $got_shirt * @property int $got_voucher * - * @method static \Illuminate\Database\Query\Builder|\Engelsystem\Models\User\State whereArrived($value) - * @method static \Illuminate\Database\Query\Builder|\Engelsystem\Models\User\State whereActive($value) - * @method static \Illuminate\Database\Query\Builder|\Engelsystem\Models\User\State whereForceActive($value) - * @method static \Illuminate\Database\Query\Builder|\Engelsystem\Models\User\State whereGotShirt($value) - * @method static \Illuminate\Database\Query\Builder|\Engelsystem\Models\User\State whereGotVoucher($value) + * @method static \Illuminate\Database\Query\Builder|\Engelsystem\Models\User\State[] whereArrived($value) + * @method static \Illuminate\Database\Query\Builder|\Engelsystem\Models\User\State[] whereActive($value) + * @method static \Illuminate\Database\Query\Builder|\Engelsystem\Models\User\State[] whereForceActive($value) + * @method static \Illuminate\Database\Query\Builder|\Engelsystem\Models\User\State[] whereGotShirt($value) + * @method static \Illuminate\Database\Query\Builder|\Engelsystem\Models\User\State[] whereGotVoucher($value) */ class State extends HasUserModel { diff --git a/src/Models/User/User.php b/src/Models/User/User.php index d2a5129d..bc4ad015 100644 --- a/src/Models/User/User.php +++ b/src/Models/User/User.php @@ -21,13 +21,13 @@ use Illuminate\Database\Eloquent\Relations\HasOne; * @property-read \Illuminate\Database\Query\Builder|\Engelsystem\Models\User\State $state * * @method static \Illuminate\Database\Query\Builder|\Engelsystem\Models\User\User whereId($value) - * @method static \Illuminate\Database\Query\Builder|\Engelsystem\Models\User\User whereName($value) - * @method static \Illuminate\Database\Query\Builder|\Engelsystem\Models\User\User whereEmail($value) - * @method static \Illuminate\Database\Query\Builder|\Engelsystem\Models\User\User wherePassword($value) - * @method static \Illuminate\Database\Query\Builder|\Engelsystem\Models\User\User whereApiKey($value) - * @method static \Illuminate\Database\Query\Builder|\Engelsystem\Models\User\User whereLastLoginAt($value) - * @method static \Illuminate\Database\Query\Builder|\Engelsystem\Models\User\User whereCreatedAt($value) - * @method static \Illuminate\Database\Query\Builder|\Engelsystem\Models\User\User whereUpdatedAt($value) + * @method static \Illuminate\Database\Query\Builder|\Engelsystem\Models\User\User[] whereName($value) + * @method static \Illuminate\Database\Query\Builder|\Engelsystem\Models\User\User[] whereEmail($value) + * @method static \Illuminate\Database\Query\Builder|\Engelsystem\Models\User\User[] wherePassword($value) + * @method static \Illuminate\Database\Query\Builder|\Engelsystem\Models\User\User[] whereApiKey($value) + * @method static \Illuminate\Database\Query\Builder|\Engelsystem\Models\User\User[] whereLastLoginAt($value) + * @method static \Illuminate\Database\Query\Builder|\Engelsystem\Models\User\User[] whereCreatedAt($value) + * @method static \Illuminate\Database\Query\Builder|\Engelsystem\Models\User\User[] whereUpdatedAt($value) */ class User extends BaseModel { diff --git a/tests/Unit/Helpers/AuthenticatorServiceProviderTest.php b/tests/Unit/Helpers/AuthenticatorServiceProviderTest.php index f7819da2..f42e9dff 100644 --- a/tests/Unit/Helpers/AuthenticatorServiceProviderTest.php +++ b/tests/Unit/Helpers/AuthenticatorServiceProviderTest.php @@ -5,7 +5,9 @@ namespace Engelsystem\Test\Unit\Helpers; use Engelsystem\Application; use Engelsystem\Helpers\Authenticator; use Engelsystem\Helpers\AuthenticatorServiceProvider; +use Engelsystem\Http\Request; use Engelsystem\Test\Unit\ServiceProviderTest; +use Psr\Http\Message\ServerRequestInterface; class AuthenticatorServiceProviderTest extends ServiceProviderTest { @@ -15,6 +17,7 @@ class AuthenticatorServiceProviderTest extends ServiceProviderTest public function testRegister() { $app = new Application(); + $app->bind(ServerRequestInterface::class, Request::class); $serviceProvider = new AuthenticatorServiceProvider($app); $serviceProvider->register(); diff --git a/tests/Unit/Helpers/AuthenticatorTest.php b/tests/Unit/Helpers/AuthenticatorTest.php index 085887c4..2c03b968 100644 --- a/tests/Unit/Helpers/AuthenticatorTest.php +++ b/tests/Unit/Helpers/AuthenticatorTest.php @@ -7,6 +7,7 @@ use Engelsystem\Models\User\User; use Engelsystem\Test\Unit\Helpers\Stub\UserModelImplementation; use Engelsystem\Test\Unit\ServiceProviderTest; use PHPUnit\Framework\MockObject\MockObject; +use Psr\Http\Message\ServerRequestInterface; use Symfony\Component\HttpFoundation\Session\Session; class AuthenticatorTest extends ServiceProviderTest @@ -17,6 +18,8 @@ class AuthenticatorTest extends ServiceProviderTest */ public function testUser() { + /** @var ServerRequestInterface|MockObject $request */ + $request = $this->getMockForAbstractClass(ServerRequestInterface::class); /** @var Session|MockObject $session */ $session = $this->createMock(Session::class); /** @var UserModelImplementation|MockObject $userRepository */ @@ -33,7 +36,7 @@ class AuthenticatorTest extends ServiceProviderTest 1337 ); - $auth = new Authenticator($session, $userRepository); + $auth = new Authenticator($request, $session, $userRepository); // Not in session $this->assertEquals(null, $auth->user()); @@ -52,4 +55,48 @@ class AuthenticatorTest extends ServiceProviderTest UserModelImplementation::$user = null; $this->assertEquals($user, $auth->user()); } + + /** + * @covers \Engelsystem\Helpers\Authenticator::apiUser + */ + public function testApiUser() + { + /** @var ServerRequestInterface|MockObject $request */ + $request = $this->getMockForAbstractClass(ServerRequestInterface::class); + /** @var Session|MockObject $session */ + $session = $this->createMock(Session::class); + /** @var UserModelImplementation|MockObject $userRepository */ + $userRepository = new UserModelImplementation(); + /** @var User|MockObject $user */ + $user = $this->createMock(User::class); + + $request->expects($this->exactly(3)) + ->method('getQueryParams') + ->with() + ->willReturnOnConsecutiveCalls( + [], + ['api_key' => 'iMaNot3xiSt1nGAp1Key!'], + ['foo_key' => 'SomeSecretApiKey'] + ); + + /** @var Authenticator|MockObject $auth */ + $auth = new Authenticator($request, $session, $userRepository); + + // No key + $this->assertEquals(null, $auth->apiUser()); + + // Unknown user + UserModelImplementation::$apiKey = 'iMaNot3xiSt1nGAp1Key!'; + $this->assertEquals(null, $auth->apiUser()); + + // User found + UserModelImplementation::$apiKey = 'SomeSecretApiKey'; + UserModelImplementation::$user = $user; + $this->assertEquals($user, $auth->apiUser('foo_key')); + + // User cached + UserModelImplementation::$apiKey = null; + UserModelImplementation::$user = null; + $this->assertEquals($user, $auth->apiUser()); + } } diff --git a/tests/Unit/Helpers/Stub/UserModelImplementation.php b/tests/Unit/Helpers/Stub/UserModelImplementation.php index 934aaeb2..1b14a17e 100644 --- a/tests/Unit/Helpers/Stub/UserModelImplementation.php +++ b/tests/Unit/Helpers/Stub/UserModelImplementation.php @@ -3,6 +3,7 @@ namespace Engelsystem\Test\Unit\Helpers\Stub; use Engelsystem\Models\User\User; +use Illuminate\Database\Eloquent\Collection; use InvalidArgumentException; class UserModelImplementation extends User @@ -13,6 +14,9 @@ class UserModelImplementation extends User /** @var int */ public static $id = null; + /** @var int */ + public static $apiKey = null; + /** * @param mixed $id * @param array $columns @@ -26,4 +30,17 @@ class UserModelImplementation extends User return self::$user; } + + /** + * @param string $apiKey + * @return User[]|Collection|\Illuminate\Database\Query\Builder + */ + public static function whereApiKey($apiKey) + { + if ($apiKey != static::$apiKey) { + throw new InvalidArgumentException('Wrong api key searched'); + } + + return new Collection([self::$user]); + } }