User.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  1. <?php
  2. namespace App\Models;
  3. use Illuminate\Contracts\Auth\MustVerifyEmail;
  4. use Illuminate\Database\Eloquent\Factories\HasFactory;
  5. use Illuminate\Foundation\Auth\User as Authenticatable;
  6. use Illuminate\Notifications\Notifiable;
  7. use Laravel\Sanctum\HasApiTokens;
  8. use Illuminate\Support\Facades\Auth;
  9. use Illuminate\Support\Facades\Hash;
  10. use Illuminate\Support\Facades\DB;
  11. use App\Http\Traits\AgentTrait;
  12. use App\Models\DTO\SearchData;
  13. use App\Notifications\VerifyNotify;
  14. class User extends Authenticatable implements MustVerifyEmail
  15. {
  16. use HasApiTokens, HasFactory, Notifiable, AgentTrait;
  17. protected $table = 'users';
  18. protected $primaryKey = 'id';
  19. const CREATED_AT = 'created_at';
  20. const UPDATED_AT = 'updated_at';
  21. const DELETED_AT = 'deleted_at';
  22. /**
  23. * The attributes that are mass assignable.
  24. *
  25. * @var array<int, string>
  26. */
  27. protected $fillable = [
  28. 'user_group_id',
  29. 'user_grade_id',
  30. 'sid',
  31. 'email',
  32. 'name',
  33. 'nickname',
  34. 'password',
  35. 'today_message',
  36. 'group',
  37. 'grade',
  38. 'phone',
  39. 'birthday',
  40. 'gender',
  41. 'icon',
  42. 'thumb',
  43. 'receive_email',
  44. 'receive_sms',
  45. 'receive_note',
  46. 'register_ip',
  47. 'last_login_at',
  48. 'last_login_ip',
  49. 'is_open_profile',
  50. 'is_email_cert',
  51. 'is_auth_cert',
  52. 'is_adult_cert',
  53. 'is_denied',
  54. 'is_admin',
  55. 'is_withdraw',
  56. 'about_me',
  57. 'email_verified_at'
  58. ];
  59. /**
  60. * The attributes that should be hidden for serialization.
  61. *
  62. * @var array<int, string>
  63. */
  64. protected $hidden = [
  65. 'password',
  66. 'remember_token',
  67. ];
  68. /**
  69. * The attributes that should be cast.
  70. *
  71. * @var array<string, string>
  72. */
  73. protected $casts = [
  74. 'last_login_at' => 'datetime', // 마지막 로그인 일시
  75. 'email_verified_at' => 'datetime', // 이메일 인증일시
  76. 'auth_certified_at' => 'datetime', // 본인 인증일시
  77. 'password_updated_at' => 'datetime' // 비밀번호 변경일시
  78. ];
  79. /**
  80. * The attributes that should be mutated to dates.
  81. *
  82. * @var array
  83. */
  84. protected $dates = [
  85. 'last_login_at',
  86. 'created_at',
  87. 'updated_at',
  88. 'deleted_at',
  89. 'email_verified_at',
  90. 'auth_certified_at',
  91. 'password_updated_at'
  92. ];
  93. /**
  94. * 회원 비밀번호 조회
  95. */
  96. public function getAuthPassword()
  97. {
  98. return $this->password;
  99. }
  100. /**
  101. * 회원 정보 모두 조회
  102. */
  103. public function info()
  104. {
  105. return Auth::user();
  106. }
  107. /**
  108. * 회원 ID로 조회
  109. */
  110. public function findByUserID(string $sid): User
  111. {
  112. $query = $this->query();
  113. $query->where('sid', $sid);
  114. return $query->firstOrNew();
  115. }
  116. /**
  117. * 회원 Email로 조회
  118. */
  119. public function findByEmail(string $sid): User
  120. {
  121. $query = $this->query();
  122. $query->where('email', $sid);
  123. return $query->firstOrNew();
  124. }
  125. /**
  126. * 최고 관리자 조회
  127. */
  128. public function getMaster(): User
  129. {
  130. return $this->where('is_admin', 1)->findOrNew(config('master_key'));
  131. }
  132. /**
  133. * 운영자 조회
  134. */
  135. public function getAdmins()
  136. {
  137. return $this->where('is_admin', 1)->get();
  138. }
  139. /**
  140. * 회원 ID Unique 생성
  141. */
  142. public function getHashKey()
  143. {
  144. return md5(bin2hex($this->getKey()));
  145. }
  146. /**
  147. * 인증 이메일 반환
  148. */
  149. public function getEmailForPasswordReset(): string
  150. {
  151. return $this->email;
  152. }
  153. /**
  154. * 자동 로그인 토큰 이름
  155. */
  156. public function getRememberTokenName(): string
  157. {
  158. return 'remember_token';
  159. }
  160. /**
  161. * 자동 로그인 토큰 조회
  162. */
  163. public function getRememberToken(): ?string
  164. {
  165. return $this->remember_token;
  166. }
  167. /**
  168. * 인증받은 이메일 조회
  169. */
  170. public function getEmailForVerification(): string
  171. {
  172. return $this->email;
  173. }
  174. // /**
  175. // * 이메일 인증 알림 메시지 발신자 정보 지정
  176. // */
  177. // public function routeNotificationForMail($notification)
  178. // {
  179. // return [$this->email => $this->username];
  180. // }
  181. /**
  182. * 이메일 인증을 받았는지 확인
  183. */
  184. public function hasVerifiedEmail(): bool
  185. {
  186. return (config('use_register_email_auth') ? !is_null($this->email_verified_at) : true);
  187. }
  188. /**
  189. * 관리자 여부 확인
  190. */
  191. public function isAdministrator(): bool
  192. {
  193. return boolval($this->is_admin);
  194. }
  195. /**
  196. * 이메일 인증 완료 후 값 변경
  197. */
  198. public function markEmailAsVerified(): bool
  199. {
  200. return $this->forceFill([
  201. 'is_email_cert' => 1,
  202. 'email_verified_at' => $this->freshTimestamp()
  203. ])->save();
  204. }
  205. /**
  206. * 회원 조회
  207. */
  208. public function data(SearchData $params): object
  209. {
  210. $query = $this->query();
  211. $query->select(
  212. 'users.*'
  213. );
  214. if ($params->keyword) {
  215. switch ($params->field) {
  216. case 'users.id':
  217. case 'users.sid':
  218. $query->where($params->field, '=', $params->keyword);
  219. break;
  220. case 'users.name':
  221. case 'users.email':
  222. $query->where($params->field, 'LIKE', "%{$params->keyword}%");
  223. break;
  224. case 'users.created_at':
  225. case 'users.last_login_at':
  226. $query->whereDate($params->field, $params->keyword);
  227. break;
  228. }
  229. }
  230. if($params->receiveEmail) {
  231. $query->where('users.receive_email', 1);
  232. }
  233. if($params->receiveSms) {
  234. $query->where('users.receive_sms', 1);
  235. }
  236. if($params->receiveNote) {
  237. $query->where('users.receive_note',1);
  238. }
  239. if ($params->isAdmin) {
  240. $query->where('users.is_admin', '=', $params->isAdmin);
  241. }
  242. if ($params->isDenied) {
  243. $query->where('users.is_denied', '=', $params->isDenied);
  244. }
  245. if ($params->isWithdraw) {
  246. $query->where('users.is_withdraw', '=', $params->isWithdraw);
  247. }
  248. $query->orderByDesc('users.id');
  249. $list = $query->paginate($params->perPage, ['*'], 'page', $params->page);
  250. $total = $this->count();
  251. $rows = $list->count();
  252. return (object)[
  253. 'total' => $total,
  254. 'rows' => $rows,
  255. 'list' => $list
  256. ];
  257. }
  258. /**
  259. * 휴면회원 조회
  260. */
  261. public function dormantUsers(SearchData $params): object
  262. {
  263. $query = $this->query();
  264. $query->select(
  265. 'users.*'
  266. );
  267. if ($params->keyword) {
  268. switch ($params->field) {
  269. case 'users.id':
  270. case 'users.sid':
  271. $query->where($params->field, '=', $params->keyword);
  272. break;
  273. case 'users.name':
  274. case 'users.email':
  275. $query->where($params->field, 'LIKE', "%{$params->keyword}%");
  276. break;
  277. case 'users.created_at':
  278. case 'users.last_login_at':
  279. $query->whereDate($params->field, $params->keyword);
  280. break;
  281. }
  282. }
  283. $query->whereNotBetween('last_login_at', [
  284. now()->subYears(1)->format('Y-m-d 00:00:00'),
  285. now()->format('Y-m-d 23:59:59')
  286. ]);
  287. $query->orderByDesc('users.created_at');
  288. $list = $query->paginate($params->perPage, ['*'], 'page', $params->page);
  289. $total = $this->count();
  290. $rows = $list->count();
  291. return (object)[
  292. 'total' => $total,
  293. 'rows' => $rows,
  294. 'list' => $list
  295. ];
  296. }
  297. /**
  298. * 회원가입
  299. */
  300. public function register(array $data): mixed
  301. {
  302. return DB::transaction(function () use ($data)
  303. {
  304. $sid = current(explode('@', $data['email']));
  305. $ipAddress = request()->getClientIp();
  306. $userAgent = request()->headers->get('user-agent');
  307. $referer = request()->headers->get('referer');
  308. $device = $this->device($userAgent);
  309. $browser = $this->browser($userAgent);
  310. $platform = $this->platform($userAgent);
  311. $robot = $this->robot($userAgent);
  312. $language = $this->languages();
  313. $user = User::create([
  314. 'sid' => $sid,
  315. 'email' => $data['email'],
  316. 'name' => $data['nickname'],
  317. 'nickname' => $data['nickname'],
  318. 'password' => Hash::make($data['password']),
  319. 'register_ip' => $ipAddress,
  320. 'updated_at' => null
  321. ]);
  322. UserRegister::create([
  323. 'user_id' => $user->id,
  324. 'device' => $device,
  325. 'language' => $language,
  326. 'browser' => $browser,
  327. 'platform' => $platform,
  328. 'robot' => $robot,
  329. 'ip_address' => $ipAddress,
  330. 'user_agent' => $userAgent,
  331. 'referer' => $referer
  332. ]);
  333. return $user;
  334. });
  335. }
  336. /**
  337. * 회원 정보 수정
  338. */
  339. public function updater(int $uid, array $data): bool
  340. {
  341. return $this->find($uid)->update($data);
  342. }
  343. /**
  344. * 중복 이메일 확인
  345. */
  346. public function sendVerifyCodeToMail(): void
  347. {
  348. $this->notify(new VerifyNotify);
  349. }
  350. /**
  351. * 이메일 인증 정보 변경
  352. */
  353. public function generateEmailVerified(string $email): void
  354. {
  355. [$sid] = explode('@', $email);
  356. $this->sid = $sid;
  357. $this->email = $email;
  358. $this->email_verified_at = now();
  359. $this->is_email_cert = 1;
  360. $this->save();
  361. $this->sendVerifyCodeToMail();
  362. }
  363. /**
  364. * 회원 포인트(P)를 최신 상태로 변경
  365. */
  366. public function updateTotalPoint(int $userID): bool
  367. {
  368. $sql = "
  369. UPDATE users USR
  370. SET USR.point = (SELECT COALESCE(SUM(P.point), 0) FROM tb_point P WHERE P.user_id = USR.id)
  371. WHERE USR.id = ?;
  372. ";
  373. return DB::statement($sql, [$userID]);
  374. }
  375. }