text changes to registration mail content
[namibia] / module / User / src / User / Service / Profile.php
1 <?php
2 namespace User\Service;
3 ini_set('memory_limit', '512M');
4
5
6 /**
7  * Authentication functionality.
8  * @author andre.fourie
9  *
10  */
11 class Profile extends \User\DataBin\Profile
12 {
13
14
15         /**
16          * Login functionality for mobile devices.
17          * @param \Workspace\Utility\ServiceInputParams $contract
18          * @return array
19          */
20         public function deviceLogin(\Workspace\Utility\ServiceInputParams $contract)
21         {
22                 \Utility\Registry::clearAuthData();
23                 $em = \Utility\Registry::getEntityManager();
24                 $user = $em->getRepository('\User\Entity\Profile')
25                         ->findOneBy(array('email' => $contract->data->Login['email']));
26                 if (is_null($user)
27                         || $user->archived
28                         || !$user->passwordValid($contract->data->Login['pin']))
29                 {
30                         return $contract->deviceError('Authentication Failure.', 'Could not authenticate user.');
31                 }
32                 $authData = $user->toArray(array('company', 'permissions'));
33                 if ($authData['company']['jobState'] != 'Active')
34                 {
35                         return $contract->deviceError('Authentication Failure.', 'Dealership suspended, no authentication allowed.');
36                 }
37                 if ($authData['jobState'] != 'Active')
38                 {
39                         return $contract->deviceError('Authentication Failure.', 'User account suspended, no authentication allowed.');
40                 }
41                 $user->lastLogin = new \DateTime("now");
42                 $user->ipAddress = $_SERVER['REMOTE_ADDR'];
43                 $log = new \User\Entity\AuthenticationLog();
44                 $log->profile = $user;
45                 $log->ipAddress = $_SERVER['REMOTE_ADDR'];
46                 $em->persist($log);
47                 $em->flush();
48                 \Utility\Registry::setAuthData($authData);
49                 return $contract->deviceSuccess('Authenticated.', \Utility\Registry::getAuthData());
50         }
51
52         /**
53          * Pin reset functionality for mobile devices.
54          * @param \Workspace\Utility\ServiceInputParams $contract
55          * @return array
56          */
57         public function deviceResetPin(\Workspace\Utility\ServiceInputParams $contract)
58         {
59                 \Utility\Registry::clearAuthData();
60                 $em = \Utility\Registry::getEntityManager();
61                 $user = isset($contract->data->Login['email']) && !empty($contract->data->Login['email'])
62                         ? $em->getRepository('\User\Entity\Profile')
63                                 ->findOneBy(array('email' => $contract->data->Login['email']))
64                         : $em->getRepository('\User\Entity\Profile')
65                                 ->findOneBy(array('mobile' => $contract->data->Login['mobile']));
66                 if (is_null($user)
67                         || $user->archived)
68                 {
69                         return $contract->deviceError('Reset Pin Failure.', 'Could not locate user.');
70                 }
71
72                 $pin = mt_rand(1000, 9999);
73                 $user->password = $pin;
74                 $em->flush();
75                 \Utility\Debug::errorLog('PinReset: ' . $user->email, $pin);
76
77                 // Send notifications.
78                 $this->sendPinResetNotification(null, $user, $pin);
79
80                 return $contract->deviceSuccess('Pin Reset.', array());
81         }
82
83         /**
84          * Contract to reset users pin.
85          * @param object|null $jobRecord
86          * @param array $input
87          * @return \Workspace\Contract\UseOnce
88          */
89         public function contractForgotPassword($jobRecord, array $input = array())
90         {
91                 $options = new \Workspace\UseCase\Options();
92                 $requirement = new \Workspace\UseCase\Requirement();
93                 $requirement->addOptionalInput(array(
94                                 'Reset' => array(
95                                                 'email'  => 'String250',
96                                                 'mobile' => 'String20'
97                                 )
98                 ));
99                 return new \Workspace\Contract\UseOnce($options, $requirement);
100         }
101
102         /**
103          * Reset pin for user.
104          * @param object|null $jobRecord
105          * @param \Workspace\Utility\ServiceInputParams $contract
106          * @return array
107          */
108         public function executeForgotPassword($jobRecord, \Workspace\Utility\ServiceInputParams $contract)
109         {
110                 \Utility\Registry::clearAuthData();
111                 $em = \Utility\Registry::getEntityManager();
112                 $searchBy = array();
113                 isset($contract->data->Reset['email'])
114                         && !empty($contract->data->Reset['email'])
115                         && $searchBy['email'] = $contract->data->Reset['email'];
116                 isset($contract->data->Reset['mobile'])
117                         && !empty($contract->data->Reset['mobile'])
118                         && $searchBy['mobile'] = $contract->data->Reset['mobile'];
119                 $user = $em->getRepository('\User\Entity\Profile')
120                         ->findOneBy($searchBy);
121                 if (is_null($user)
122                         || $user->archived)
123                 {
124                         return $contract->error('Reset Failure.', 'Could not reset pin.');
125                 }
126
127
128                 $pin = mt_rand(1000, 9999);
129                 $user->password = $pin;
130                 $em->flush();
131                 \Utility\Debug::errorLog('PinReset: ' . $user->email, $pin);
132
133                 $this->sendPinResetNotification(null, $user, $pin);
134
135                 return $contract->success('Pin Reset.', array());
136         }
137
138         /**
139          * Contract to login a user.
140          * @param object|null $jobRecord
141          * @param array $input
142          * @return \Workspace\Contract\UseOnce
143          */
144         public function contractLogin($jobRecord, array $input = array())
145         {
146                 \Utility\Registry::clearAuthData();
147                 $options = new \Workspace\UseCase\Options();
148                 $requirement = new \Workspace\UseCase\Requirement();
149                 $requirement->addRequiredInput(array(
150                                 'Login' => array(
151                                                 'email' => 'Email',
152                                                 'pin'   => 'String50'
153                                 )
154                 ));
155                 return new \Workspace\Contract\UseOnce($options, $requirement);
156         }
157
158         /**
159          * Login a user.
160          * @param object|null $jobRecord
161          * @param \Workspace\Utility\ServiceInputParams $contract
162          * @return array
163          */
164         public function executeLogin($jobRecord, \Workspace\Utility\ServiceInputParams $contract)
165         {
166                 \Utility\Registry::clearAuthData();
167                 \Utility\Registry::clearSessionData();
168                 $em = \Utility\Registry::getEntityManager();
169                 $user = $em->getRepository('\User\Entity\Profile')
170                         ->findOneBy(array('email' => $contract->data->Login['email']));
171                 if (is_null($user)
172                         || $user->archived
173                         || !$user->passwordValid($contract->data->Login['pin']))
174                 {
175                         return $contract->error('Authentication Failure.', 'Could not authenticate user.');
176                 }
177                 $authData = $user->toArray(array(
178                                 'company', 'tradeCenter', 'group', 'groupDivision', 'permissions',
179                                 'city', 'region', 'contact', 'manager'
180                 ));
181                 $auctionOpenDays = array();
182                 if ($authData['company']
183                         && isset($authData['company']['group'])
184                         && is_array($authData['company']['group'])
185                         && !empty($authData['company']['group']))
186                 {
187                         $openDays = $this->em->createQuery(
188                                         "SELECT openDayGroup, openDay "
189                                         . "FROM \\Auction\\Entity\\OpenDayGroup openDayGroup "
190                                         . "JOIN openDayGroup.openDay openDay "
191                                         . "WHERE IDENTITY(openDayGroup.companyGroup) = :groupId "
192                                         . "AND openDay.openDate >= :minDate"
193                                 )
194                                 ->setParameter('groupId', $authData['company']['group']['id'])
195                                 ->setParameter('minDate', new \DateTime('now'))
196                                 ->getArrayResult();
197                         foreach ($openDays as $openDay)
198                         {
199                                 $date = $openDay['openDay']['openDate']->format('Y-m-d');
200                                 $auctionOpenDays[$date] = $date;
201                         }
202                 }
203                 $authData['auctionOpenDays'] = $auctionOpenDays;
204                 if ($authData['company']['jobState'] != 'Active')
205                 {
206                         return $contract->error('Authentication Failure.', 'Dealership suspended, no authentication allowed.');
207                 }
208                 if ($authData['jobState'] != 'Active')
209                 {
210                         return $contract->error('Authentication Failure.', 'User account suspended, no authentication allowed.');
211                 }
212                 $user->lastLogin = new \DateTime("now");
213                 $user->ipAddress = $_SERVER['REMOTE_ADDR'];
214                 $log = new \User\Entity\AuthenticationLog();
215                 $log->profile = $user;
216                 $log->ipAddress = $_SERVER['REMOTE_ADDR'];
217                 $em->persist($log);
218                 $em->flush();
219                 $authData['config'] = $em
220                         ->getRepository('Config\Entity\Config')
221                         ->find(1)
222                         ->toArray();
223                 \Utility\Registry::setAuthData($authData);
224                 switch (\Utility\Registry::getUserType())
225                 {
226                         case 'Group User':
227                                 if (!$authData['permissions']['suDivisionFull'])
228                                 {
229                                         \Utility\Registry::setAuthSudo(
230                                                         'Division',
231                                                         $authData['company']['groupDivision']['name'],
232                                                         $authData['company']['groupDivision']['id']
233                                         );
234                                 }
235                                 break;
236                         case 'Dealer Principle':
237                                 break;
238                 }
239                 $authData['servertime'] = time();
240                 return $contract->success('Authenticated.', $authData);
241         }
242
243         public function contractLogout($jobRecord, array $input = array())
244         {
245                 \Utility\Registry::clearAuthData();
246                 $options = new \Workspace\UseCase\Options();
247                 $requirement = new \Workspace\UseCase\Requirement();
248                 $requirement->addRequiredInput(array());
249                 return new \Workspace\Contract\UseOnce($options, $requirement);
250         }
251
252         /**
253          * Login a user.
254          * @param object|null $jobRecord
255          * @param \Workspace\Utility\ServiceInputParams $contract
256          * @return array
257          */
258         public function executeLogout($jobRecord, \Workspace\Utility\ServiceInputParams $contract)
259         {
260                 \Utility\Registry::clearAuthData();
261                 \Utility\Registry::clearSessionData();
262                 return $contract->success('Logged out.', array());
263         }
264
265         /**
266          * Contract to login a user.
267          * @param object|null $jobRecord
268          * @param array $input
269          * @return \Workspace\Contract\UseOnce
270          */
271         public function contractActiveAccount($jobRecord, array $input = array())
272         {
273                 if (!\Utility\Registry::isAuthenticated())
274                 {
275                         throw new \Exception('Not Authenticated.');
276                 }
277
278                 $options = new \Workspace\UseCase\Options();
279                 $requirement = new \Workspace\UseCase\Requirement();
280                 $requirement->addRequiredInput(array());
281                 $contract = new \Workspace\Contract\UseOnce($options, $requirement);
282                 $authData = \Utility\Registry::getAuthData();
283                 if (isset($authData['pin']))
284                 {
285                         unset($authData['pin']);
286                 }
287                 if (isset($authData['password']))
288                 {
289                         unset($authData['password']);
290                 }
291                 if (isset($authData['salt']))
292                 {
293                         unset($authData['salt']);
294                 }
295                 $authData['servertime'] = time();
296                 return $contract->setData(
297                                 $authData
298                                 );
299         }
300
301         public function executeActiveAccount($jobRecord, \Workspace\Utility\ServiceInputParams $contract)
302         {
303                 return $contract->success('DevNull.', array());
304         }
305
306         /**
307          * ExecuteAfter: Update.
308          * Send welcome notification with new pin for user just registered/created on system.
309          * @param array $meta
310          * @param object|null $jobRecord
311          * @param object|null $record
312          * @param \Workspace\Utility\ServiceInputParams $contract
313          * @return array
314          */
315         public function updateAuthSession($meta, $jobRecord, $record, \Workspace\Utility\ServiceInputParams $contract)
316         {
317                 #-> Do we need to update session data?
318                 if (\Utility\Registry::getAuthParam('id') == $record->id)
319                 {
320                         $authData = $record->toArray(array(
321                                         'company', 'group', 'groupDivision', 'permissions',
322                                         'city', 'region', 'contact', 'manager'
323                         ));
324                         \Utility\Registry::setAuthData($authData);
325                 }
326         }
327
328         /**
329          * ExecuteAfter: Create.
330          * Send welcome notification with new pin for user just registered/created on system.
331          * @param array $meta
332          * @param object|null $jobRecord
333          * @param object|null $record
334          * @param \Workspace\Utility\ServiceInputParams $contract
335          * @return array
336          */
337         public function sendWelcomeNotification($meta, $jobRecord, $record, \Workspace\Utility\ServiceInputParams $contract)
338         {
339                 #-> Pin generated by \User\Entity\Profile::fromArray()
340                 $pin = \Utility\Registry::checkOnce('NewUser.Pin');
341                 $record = !is_null($record)
342                         ? $record->toArray()
343                         : $jobRecord->toArray();
344
345                 //echo '<pre>' . print_r($record, true) . '</pre>';
346
347                 $authData = \Utility\Registry::getAuthData();
348
349                 //echo '<pre>' . print_r($authData, true) . '</pre>';
350
351
352                 $fromCompanyId  = !is_null($authData) && isset($authData['company']['id']) ? $authData['company']['id'] : null;
353                 $fromProfileId  = !is_null($authData) && isset($authData['id']) ? $authData['id'] : null;
354
355                 $toCompanyId    = isset($record['company']['id']) ? $record['company']['id'] : null;
356                 $toProfileId    = isset($record['id']) ? $record['id'] : null;
357                 $email                  = isset($record['email']) ? $record['email'] : null;
358                 $mobile                 = null;
359                 $subject                = null;
360                 $templateName   = 'new-profile-recipient';
361
362                 $params = array();
363                 $params['firstName']    = $record['firstName'];
364                 $params['familyName']   = $record['familyName'];
365                 $params['email']            = $record['email'];
366                 $params['pin']          = $pin;
367
368                 #-> Send welcome notification.
369                 $oNotify = new \Utility\Comms\Notification();
370                 $oNotify->sendFromTemplate(
371                                 $fromCompanyId, $fromProfileId,
372                                 $toCompanyId, $toProfileId,
373                                 $email, $mobile,
374                                 $subject,
375                                 $templateName,
376                                 $params
377                                 );
378         }
379
380         public function sendPinResetNotification($jobRecord, $record, $pin)
381         {
382                 $record = !is_null($record)
383                         ? $record->toArray(array('company'))
384                         : $jobRecord->toArray(array('company'));
385
386                 $authData = \Utility\Registry::getAuthData();
387
388                 $fromCompanyId  = isset($authData['company']['id']) ? $authData['company']['id'] : null;
389                 $fromProfileId  = isset($authData['id']) ? $authData['id'] : null;
390
391                 $toCompanyId    = isset($record['company']['id']) ? $record['company']['id'] : null;
392                 $toProfileId    = isset($record['id']) ? $record['id'] : null;
393                 $email                  = isset($record['email']) ? $record['email'] : null;
394                 $mobile                 = isset($record['mobile']) ? $record['mobile'] : null;
395                 $subject                = null;
396                 $templateName   = 'forgot-pin';
397
398                 $params = array();
399                 $params['firstName']    = $record['firstName'];
400                 $params['familyName']   = $record['familyName'];
401                 $params['email']                = $record['email'];
402                 $params['pin']                  = $pin;
403
404                 #-> Send welcome notification.
405                 $oNotify = new \Utility\Comms\Notification();
406                 $oNotify->sendFromTemplate(
407                                 $fromCompanyId, $fromProfileId,
408                                 $toCompanyId, $toProfileId,
409                                 $email, $mobile,
410                                 $subject,
411                                 $templateName,
412                                 $params
413                 );
414                 \Utility\Debug::errorLog("sendPinResetNotification","sms:".$mobile." email:".$email);
415         }
416
417         /**
418          * Contract to set sudo filter.
419          * @param object|null $jobRecord
420          * @param array $input
421          * @return \Workspace\Contract\UseOnce
422          */
423         public function contractSetSu($jobRecord, array $input = array())
424         {
425                 $options = new \Workspace\UseCase\Options();
426                 $requirement = new \Workspace\UseCase\Requirement();
427                 $requirement->addOptionalInput(array(
428                                 'Sudo' => array(
429                                                 'Group'    => 'Integer',
430                                                 'Division' => 'Integer',
431                                                 'Company'  => 'Integer'
432                                 )
433                 ));
434                 return new \Workspace\Contract\Recurring($options, $requirement);
435         }
436
437         /**
438          * Set sudo filter.
439          * @param object|null $jobRecord
440          * @param \Workspace\Utility\ServiceInputParams $contract
441          * @return array
442          */
443         public function executeSetSu($jobRecord, \Workspace\Utility\ServiceInputParams $contract)
444         {
445                 if (isset($contract->data->Sudo['Group']))
446                 {
447                         $id = 0 == $contract->data->Sudo['Group']
448                                 ? false
449                                 : $contract->data->Sudo['Group'];
450                         $name = '';
451                         if ($id)
452                         {
453                                 $item = $this->em->getRepository('\Company\Entity\Group')
454                                         ->find($id);
455                                 if (!is_null($item))
456                                 {
457                                         $name = $item->name;
458                                 }
459                         }
460                         \Utility\Registry::setAuthSudo('Group', $name, $id);
461                         \Utility\Registry::setAuthSudo('Division', '', false);
462                         \Utility\Registry::setAuthSudo('Company', '', false);
463                 }
464                 if (isset($contract->data->Sudo['Division']))
465                 {
466                         $id = 0 == $contract->data->Sudo['Division']
467                                 ? false
468                                 : $contract->data->Sudo['Division'];
469                         $name = '';
470                         if ($id)
471                         {
472                                 $item = $this->em->getRepository('\Company\Entity\GroupDivision')
473                                         ->find($id);
474                                 if (!is_null($item))
475                                 {
476                                         $name = $item->name;
477                                 }
478                         }
479                         \Utility\Registry::setAuthSudo('Division', $name, $id);
480                         \Utility\Registry::setAuthSudo('Company', '', false);
481                 }
482                 if (isset($contract->data->Sudo['Company']))
483                 {
484                         $id = 0 == $contract->data->Sudo['Company']
485                                 ? false
486                                 : $contract->data->Sudo['Company'];
487                         $name = '';
488                         if ($id)
489                         {
490                                 $item = $this->em->getRepository('\Company\Entity\Company')
491                                         ->find($id);
492                                 if (!is_null($item))
493                                 {
494                                         $name = $item->name;
495                                 }
496                         }
497                         \Utility\Registry::setAuthSudo('Company', $name, $id);
498                 }
499                 return $contract->success('Filter set.', array());
500         }
501
502 }