LoginUserService   A
last analyzed

Complexity

Total Complexity 33

Size/Duplication

Total Lines 329
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 33
eloc 185
dl 0
loc 329
rs 9.76
c 0
b 0
f 0

16 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 2 1
A GetCurrentUser() 0 12 2
A GetUserFromHeaderToken() 0 15 3
A SearchCommissioners() 0 13 2
A GetAll() 0 14 2
A GetCommissioner() 0 13 2
A SetAuthenticationObjectValuesOnLogin() 0 11 1
A _CreateForgottenPasswordLink() 0 5 1
A DeleteUser() 0 22 4
A ResetPassword() 0 23 2
A CurrentUserIsAdmin() 0 4 1
A BeginForgottenPasswordProcess() 0 40 2
B UpdateUserProfile() 0 67 6
A CreateUnverifiedNewUser() 0 41 2
A _CreateEmailVerificationLink() 0 5 1
A VerifyUser() 0 7 1
1
<?php
2
3
namespace PhpDraft\Domain\Services;
4
5
use \Silex\Application;
6
use Symfony\Component\HttpFoundation\Request;
7
use Symfony\Component\Security\Core\Util\StringUtils;
8
use PhpDraft\Domain\Entities\LoginUser;
9
use PhpDraft\Domain\Models\PhpDraftResponse;
10
use PhpDraft\Domain\Models\MailMessage;
11
12
class LoginUserService {
13
  private $app;
14
15
  public function __construct(Application $app) {
16
    $this->app = $app;
17
  }
18
19
  public function GetCurrentUser() {
20
    $token = $this->app['security.token_storage']->getToken();
21
22
    if ($token == null) {
23
      //In public actions, this isn't an exception - we're just not logged in.
24
      return null;
25
      //throw new \Exception("Username not found.");
26
    }
27
28
    $usr = $token->getUser();
29
30
    return $this->app['phpdraft.LoginUserRepository']->Load($usr->getUsername());
31
  }
32
33
  //This is a hack to make accessing logged in user info from anonymous routes possible:
34
  public function GetUserFromHeaderToken(Request $request) {
35
    $request_token = $request->headers->get(AUTH_KEY_HEADER, '');
0 ignored issues
show
Bug introduced by
The constant PhpDraft\Domain\Services\AUTH_KEY_HEADER was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
36
37
    if (empty($request_token)) {
38
      return null;
39
    }
40
41
    try {
42
      $decoded = $this->app['security.jwt.encoder']->decode($request_token);
43
44
      $email = $decoded->name;
45
46
      return $this->app['phpdraft.LoginUserRepository']->Load($email);
47
    } catch (\Exception $ex) {
48
      return null;
49
    }
50
  }
51
52
  public function SetAuthenticationObjectValuesOnLogin(PhpDraftResponse $response, $user) {
53
    $now = new \DateTime("now", new \DateTimeZone('GMT'));
54
    $interval = new \DateInterval('P0Y0M0DT0H0M' . AUTH_SECONDS . 'S');
0 ignored issues
show
Bug introduced by
The constant PhpDraft\Domain\Services\AUTH_SECONDS was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
55
    $authTimeout = $now->add($interval);
56
57
    $response->name = $user->getName();
0 ignored issues
show
Bug introduced by
The property name does not seem to exist on PhpDraft\Domain\Models\PhpDraftResponse.
Loading history...
58
    $response->is_admin = $user->isAdmin();
0 ignored issues
show
Bug introduced by
The property is_admin does not seem to exist on PhpDraft\Domain\Models\PhpDraftResponse.
Loading history...
59
    $response->token = $this->app['security.jwt.encoder']->encode(['name' => $user->getUsername()]);
0 ignored issues
show
Bug introduced by
The property token does not seem to exist on PhpDraft\Domain\Models\PhpDraftResponse.
Loading history...
60
    $response->auth_timeout = $authTimeout->format('Y-m-d H:i:s');
0 ignored issues
show
Bug introduced by
The property auth_timeout does not seem to exist on PhpDraft\Domain\Models\PhpDraftResponse.
Loading history...
61
62
    return $response;
63
  }
64
65
  public function SearchCommissioners($searchTerm) {
66
    $response = new PhpDraftResponse();
67
68
    try {
69
      $response->commissioners = $this->app['phpdraft.LoginUserRepository']->SearchCommissioners($searchTerm);
0 ignored issues
show
Bug introduced by
The property commissioners does not seem to exist on PhpDraft\Domain\Models\PhpDraftResponse.
Loading history...
70
      $response->success = true;
71
    } catch (\Exception $ex) {
72
      $message = $ex->getMessage();
73
      $response->success = false;
74
      $response->errors[] = $message;
75
    }
76
77
    return $response;
78
  }
79
80
  public function GetCommissioner($commish_id) {
81
    $response = new PhpDraftResponse();
82
83
    try {
84
      $response->commissioner = $this->app['phpdraft.LoginUserRepository']->LoadPublicById($commish_id);
0 ignored issues
show
Bug introduced by
The property commissioner does not seem to exist on PhpDraft\Domain\Models\PhpDraftResponse.
Loading history...
85
      $response->success = true;
86
    } catch (\Exception $ex) {
87
      $message = $ex->getMessage();
88
      $response->success = false;
89
      $response->errors[] = $message;
90
    }
91
92
    return $response;
93
  }
94
95
  public function GetAll() {
96
    $response = new PhpDraftResponse();
97
98
    try {
99
      $response->users = $this->app['phpdraft.LoginUserRepository']->LoadAll();
0 ignored issues
show
Bug introduced by
The property users does not seem to exist on PhpDraft\Domain\Models\PhpDraftResponse.
Loading history...
100
      $response->roles = $this->app['phpdraft.LoginUserRepository']->GetRoles();
0 ignored issues
show
Bug introduced by
The property roles does not seem to exist on PhpDraft\Domain\Models\PhpDraftResponse.
Loading history...
101
      $response->success = true;
102
    } catch (\Exception $e) {
103
      $message = $e->getMessage();
104
      $response->success = false;
105
      $response->errors[] = $message;
106
    }
107
108
    return $response;
109
  }
110
111
  public function CreateUnverifiedNewUser(LoginUser $user) {
112
    $user->enabled = false;
113
114
    $user->verificationKey = $this->app['phpdraft.SaltService']->GenerateSaltForUrl();
115
    $user->salt = $this->app['phpdraft.SaltService']->GenerateSalt();
116
    $user->password = $this->app['security.encoder.digest']->encodePassword($user->password, $user->salt);
117
    $user->roles = array('ROLE_COMMISH');
118
119
    $response = new PhpDraftResponse();
120
121
    try {
122
      $user = $this->app['phpdraft.LoginUserRepository']->Create($user);
123
124
      $message = new MailMessage();
125
126
      $message->to_addresses = array(
127
        $user->email => $user->name
128
      );
129
130
      $verifyLink = $this->_CreateEmailVerificationLink($user);
131
      $emailParameters = array(
132
        'imageBaseUrl' => sprintf("%s/images/email", APP_BASE_URL),
0 ignored issues
show
Bug introduced by
The constant PhpDraft\Domain\Services\APP_BASE_URL was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
133
        'verifyLink' => $verifyLink,
134
      );
135
136
      $message->subject = "HootDraft: Verify your email address";
137
      $message->is_html = true;
138
      $message->body = $this->app['phpdraft.TemplateRenderService']->RenderTemplate('VerifyEmail.html', $emailParameters);
139
      $message->altBody = "Hey pal, we need you to verify your email address. Click this link to do so: $verifyLink";
140
141
      $this->app['phpdraft.EmailService']->SendMail($message);
142
143
      $response->success = true;
144
    } catch (\Exception $e) {
145
      //$this->app['db']->rollback();
146
147
      $response->success = false;
148
      $response->errors = array("Unable to create new user or send verification email.");
149
    }
150
151
    return $response;
152
  }
153
154
  public function VerifyUser(LoginUser $user) {
155
    $user->enabled = true;
156
    $user->verificationKey = null;
157
158
    $user = $this->app['phpdraft.LoginUserRepository']->Update($user);
0 ignored issues
show
Unused Code introduced by
The assignment to $user is dead and can be removed.
Loading history...
159
160
    return new PhpDraftResponse(true);
161
  }
162
163
  public function BeginForgottenPasswordProcess(LoginUser $user) {
164
    $user->verificationKey = $this->app['phpdraft.SaltService']->GenerateSaltForUrl();
165
166
    $response = new PhpDraftResponse();
167
168
    try {
169
      $this->app['db']->beginTransaction();
170
171
      $user = $this->app['phpdraft.LoginUserRepository']->Update($user);
172
173
      $message = new MailMessage();
174
175
      $message->to_addresses = array(
176
        $user->email => $user->name
177
      );
178
179
      $resetLink = $this->_CreateForgottenPasswordLink($user);
180
      $emailParameters = array(
181
        'imageBaseUrl' => sprintf("%s/images/email", APP_BASE_URL),
0 ignored issues
show
Bug introduced by
The constant PhpDraft\Domain\Services\APP_BASE_URL was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
182
        'resetLink' => $resetLink,
183
      );
184
185
      $message->subject = "HootDraft: Reset Password Request";
186
      $message->is_html = true;
187
      $message->body = $this->app['phpdraft.TemplateRenderService']->RenderTemplate('ResetPassword.html', $emailParameters);
188
      $message->altBody = "Hello, looks like you've requested to reset your password. To do so, click this link: $resetLink";
189
190
      $this->app['phpdraft.EmailService']->SendMail($message);
191
192
      $response->success = true;
193
194
      $this->app['db']->commit();
195
    } catch (\Exception $e) {
196
      $this->app['db']->rollback();
197
198
      $response->success = false;
199
      $response->errors = array($e->getMessage());
200
    }
201
202
    return $response;
203
  }
204
205
  public function ResetPassword(LoginUser $user) {
206
    $user->verificationKey = null;
207
    $user->salt = $this->app['phpdraft.SaltService']->GenerateSalt();
208
    $user->password = $this->app['security.encoder.digest']->encodePassword($user->password, $user->salt);
209
210
    $response = new PhpDraftResponse();
211
212
    try {
213
      $this->app['db']->beginTransaction();
214
215
      $user = $this->app['phpdraft.LoginUserRepository']->Update($user);
0 ignored issues
show
Unused Code introduced by
The assignment to $user is dead and can be removed.
Loading history...
216
217
      $response->success = true;
218
219
      $this->app['db']->commit();
220
    } catch (\Exception $e) {
221
      $this->app['db']->rollback();
222
223
      $response->success = false;
224
      $response->errors = array($e->getMessage());
225
    }
226
227
    return $response;
228
  }
229
230
  public function UpdateUserProfile(Request $request) {
231
    $email = strtolower($request->get('_email'));
232
    $name = $request->get('_name');
233
    $newPassword = $request->get('_newPassword');
234
    $sendEmail = false;
235
    $invalidateLogin = false;
236
237
    $user = $this->app['phpdraft.LoginUserService']->GetCurrentUser();
238
239
    $user->name = $name;
240
241
    //Update user email, invalidate login
242
    if (!empty($email) && !StringUtils::equals($email, $user->email)) {
243
      $user->email = $email;
244
      $user->enabled = 0;
245
      $invalidateLogin = true;
246
      $user->verificationKey = $this->app['phpdraft.SaltService']->GenerateSalt();
247
      $sendEmail = true;
248
    }
249
250
    if (!empty($newPassword)) {
251
      $invalidateLogin = true;
252
      $user->salt = $this->app['phpdraft.SaltService']->GenerateSalt();
253
      $user->password = $this->app['security.encoder.digest']->encodePassword($newPassword, $user->salt);
254
    }
255
256
    $response = new PhpDraftResponse();
257
258
    try {
259
      $this->app['db']->beginTransaction();
260
261
      $user = $this->app['phpdraft.LoginUserRepository']->Update($user);
262
263
      if ($sendEmail) {
264
        $message = new MailMessage();
265
266
        $message->to_addresses = array(
267
          $user->email => $user->name
268
        );
269
270
        $verifyLink = $this->_CreateEmailVerificationLink($user);
271
        $emailParameters = array(
272
          'imageBaseUrl' => sprintf("%s/images/email", APP_BASE_URL),
0 ignored issues
show
Bug introduced by
The constant PhpDraft\Domain\Services\APP_BASE_URL was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
273
          'verifyLink' => $verifyLink,
274
        );
275
276
        $message->subject = "HootDraft: Verify your email address";
277
        $message->is_html = true;
278
        $message->body = $this->app['phpdraft.TemplateRenderService']->RenderTemplate('ReverifyEmail.html', $emailParameters);
279
        $message->altBody = "Hi, and welcome to Hoot Draft! Before we get started, can you click this link to verify that you are who you say you are? Thanks pal! $verifyLink";
280
281
        $this->app['phpdraft.EmailService']->SendMail($message);
282
      }
283
284
      $response->success = true;
285
      $response->invalidateLogin = $invalidateLogin;
0 ignored issues
show
Bug introduced by
The property invalidateLogin does not seem to exist on PhpDraft\Domain\Models\PhpDraftResponse.
Loading history...
286
      $response->sendEmail = $sendEmail;
0 ignored issues
show
Bug introduced by
The property sendEmail does not seem to exist on PhpDraft\Domain\Models\PhpDraftResponse.
Loading history...
287
288
      $this->app['db']->commit();
289
    } catch (\Exception $e) {
290
      $this->app['db']->rollback();
291
292
      $response->success = false;
293
      $response->errors = array($e->getMessage());
294
    }
295
296
    return $response;
297
  }
298
299
  public function DeleteUser(LoginUser $user) {
300
    $response = new PhpDraftResponse();
301
302
    try {
303
      //Find all drafts this user owns
304
      $drafts = $this->app['phpdraft.DraftRepository']->GetAllDraftsByCommish($user->id);
305
      foreach ($drafts as $draft) {
306
        $response = $this->app['phpdraft.DraftService']->DeleteDraft($draft);
307
        if (!$response->success) {
308
          throw new \Exception("Unable to recursively delete draft or one of its children.");
309
        }
310
      }
311
      $this->app['phpdraft.LoginUserRepository']->Delete($user);
312
313
      $response->success = true;
314
    } catch (\Exception $e) {
315
      $message = $e->getMessage();
316
      $response->success = false;
317
      $response->errors[] = $message;
318
    }
319
320
    return $response;
321
  }
322
323
  public function CurrentUserIsAdmin(LoginUser $user) {
324
    $roles = explode(',', $user->roles);
325
326
    return in_array('ROLE_ADMIN', $roles);
327
  }
328
329
  private function _CreateEmailVerificationLink(LoginUser $user) {
330
    $encodedEmail = urlencode($user->email);
331
    $encodedToken = urlencode($user->verificationKey);
332
333
    return sprintf("%s/verify/%s/%s", APP_BASE_URL, $encodedEmail, $encodedToken);
0 ignored issues
show
Bug introduced by
The constant PhpDraft\Domain\Services\APP_BASE_URL was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
334
  }
335
336
  private function _CreateForgottenPasswordLink(LoginUser $user) {
337
    $encodedEmail = urlencode($user->email);
338
    $encodedToken = urlencode($user->verificationKey);
339
340
    return sprintf("%s/resetPassword/%s/%s", APP_BASE_URL, $encodedEmail, $encodedToken);
0 ignored issues
show
Bug introduced by
The constant PhpDraft\Domain\Services\APP_BASE_URL was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
341
  }
342
}
343