UserObserver.php 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. <?php
  2. namespace App\Observers;
  3. use App\Jobs\AvatarPipeline\CreateAvatar;
  4. use App\Profile;
  5. use App\User;
  6. use App\UserSetting;
  7. use DB;
  8. class UserObserver
  9. {
  10. /**
  11. * Listen to the User created event.
  12. *
  13. * @param \App\User $user
  14. *
  15. * @return void
  16. */
  17. public function saved(User $user)
  18. {
  19. if($user->status == 'deleted') {
  20. return;
  21. }
  22. if (empty($user->profile)) {
  23. $profile = DB::transaction(function() use($user) {
  24. $profile = new Profile();
  25. $profile->user_id = $user->id;
  26. $profile->username = $user->username;
  27. $profile->name = $user->name;
  28. $pkiConfig = [
  29. 'digest_alg' => 'sha512',
  30. 'private_key_bits' => 2048,
  31. 'private_key_type' => OPENSSL_KEYTYPE_RSA,
  32. ];
  33. $pki = openssl_pkey_new($pkiConfig);
  34. openssl_pkey_export($pki, $pki_private);
  35. $pki_public = openssl_pkey_get_details($pki);
  36. $pki_public = $pki_public['key'];
  37. $profile->private_key = $pki_private;
  38. $profile->public_key = $pki_public;
  39. $profile->save();
  40. return $profile;
  41. });
  42. DB::transaction(function() use($user, $profile) {
  43. $user = User::findOrFail($user->id);
  44. $user->profile_id = $profile->id;
  45. $user->save();
  46. CreateAvatar::dispatch($profile);
  47. });
  48. }
  49. if (empty($user->settings)) {
  50. DB::transaction(function() use($user) {
  51. UserSetting::firstOrCreate([
  52. 'user_id' => $user->id
  53. ]);
  54. });
  55. }
  56. }
  57. }