1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

164

165

166

167

168

169

170

171

172

173

174

175

176

177

178

179

180

181

182

183

184

185

186

187

188

189

190

191

192

193

194

195

196

197

198

199

200

201

202

203

204

205

206

207

208

209

210

211

212

213

214

215

216

217

218

219

220

221

222

223

224

225

226

227

228

229

230

231

232

233

234

235

236

237

238

239

240

241

242

243

244

245

246

247

248

249

250

251

252

253

254

255

256

257

258

259

260

261

262

263

264

265

266

267

268

269

270

271

272

273

274

275

276

277

278

279

280

281

282

283

284

285

286

287

288

289

290

291

292

293

294

295

296

297

298

299

300

301

302

303

304

305

306

307

308

309

310

311

312

313

314

315

316

317

318

319

320

321

322

323

324

325

326

327

328

329

330

331

332

333

334

335

336

337

338

339

340

341

342

343

344

345

346

347

348

349

350

351

352

353

354

355

356

357

358

359

360

361

362

363

364

365

366

367

368

369

370

371

372

373

374

375

376

377

378

379

380

381

382

383

384

385

386

387

388

389

390

391

392

393

394

395

396

397

398

399

400

401

402

403

404

405

406

407

408

409

410

411

412

413

414

415

416

417

418

419

420

421

422

423

424

425

426

427

428

429

430

431

432

433

434

435

436

437

438

439

440

441

442

443

444

445

446

447

448

449

450

451

452

453

454

455

456

457

458

459

460

461

462

463

464

465

466

467

468

469

470

471

472

473

474

475

476

477

478

479

480

481

482

483

484

485

486

# Copyright 2013 The Distro Tracker Developers 

# See the COPYRIGHT file at the top-level directory of this distribution and 

# at https://deb.li/DTAuthors 

# 

# This file is part of Distro Tracker. It is subject to the license terms 

# in the LICENSE file found in the top-level directory of this 

# distribution and at https://deb.li/DTLicense. No part of Distro Tracker, 

# including this file, may be copied, modified, propagated, or distributed 

# except according to the terms contained in the LICENSE file. 

"""Django views for django_email_accounts.""" 

 

from django.conf import settings 

from django.contrib import messages 

from django.contrib.auth import authenticate, login, logout 

from django.contrib.auth.decorators import login_required 

from django.contrib.auth.forms import PasswordChangeForm 

from django.core.exceptions import PermissionDenied 

from django.core.mail import send_mail 

from django.http import Http404 

from django.shortcuts import get_object_or_404, redirect, render 

from django.template.loader import render_to_string 

from django.urls import reverse_lazy 

from django.utils.decorators import method_decorator 

from django.utils.http import is_safe_url, urlencode 

from django.views.generic import TemplateView 

from django.views.generic.base import View 

from django.views.generic.edit import CreateView, FormView, UpdateView 

 

from django_email_accounts import run_hook 

from django_email_accounts.forms import ( 

AddEmailToAccountForm, 

AuthenticationForm, 

ChangePersonalInfoForm, 

ForgotPasswordForm, 

ResetPasswordForm, 

UserCreationForm 

) 

from django_email_accounts.models import ( 

AddEmailConfirmation, 

MergeAccountConfirmation, 

ResetPasswordConfirmation, 

User, 

UserEmail, 

UserRegistrationConfirmation 

) 

 

 

class LoginView(FormView): 

form_class = AuthenticationForm 

success_url = reverse_lazy('accounts-profile') 

template_name = 'accounts/login.html' 

redirect_parameter = 'next' 

 

def get(self, request, *args, **kwargs): 

""" 

Handles GET requests and instantiates a blank version of the form 

when a user is not authenticated. 

 

Override default FormView behavior to redirect to profile 

if user is already authenticated. 

""" 

if self.request.user.is_authenticated: 

return redirect(self.success_url) 

else: 

return super().get(request, *args, **kwargs) 

 

def form_valid(self, form): 

redirect_url = self.request.GET.get( 

self.redirect_parameter, self.success_url) 

70 ↛ 74line 70 didn't jump to line 74, because the condition on line 70 was never true if not is_safe_url( 

redirect_url, 

allowed_hosts=set(self.request.get_host()) 

): 

redirect_url = self.success_url 

 

login(self.request, form.get_user()) 

 

return redirect(redirect_url) 

 

 

class LogoutView(View): 

success_url = '/' 

redirect_parameter = 'next' 

 

def get(self, request): 

user = request.user 

logout(request) 

 

next_url = request.GET.get(self.redirect_parameter, self.success_url) 

if not is_safe_url( 

next_url, 

allowed_hosts=set(self.request.get_host()) 

): 

next_url = self.success_url 

 

redirect_url = run_hook('post-logout-redirect', request, user, next_url) 

if redirect_url: 

return redirect(redirect_url) 

else: 

return redirect(next_url if next_url else '/') 

 

 

class RegisterUser(CreateView): 

""" 

Provides a view that displays a registration form on a GET request and 

registers the user on a POST. 

 

``template_name`` and ``success_url`` properties can be overridden when 

instantiating the view in order to customize the page displayed on a GET 

request and the URL to which the user should be redirected after a 

successful POST, respectively. 

 

Additionally, by overriding the ``confirmation_email_template`` and 

``confirmation_email_subject`` it is possible to customize the subject and 

content of a confirmation email sent to the user being registered. 

 

Instead of providing a ``confirmation_email_template`` you may also override 

the :meth:`get_confirmation_email_content` to provide a custom rendered 

text content. 

 

The sender of the email can be changed by modifying the 

``confirmation_email_from_address`` setting. 

""" 

template_name = 'accounts/register.html' 

model = User 

success_url = reverse_lazy('accounts-register-success') 

 

confirmation_email_template = 'accounts/registration-confirmation-email.txt' 

confirmation_email_subject = 'Registration Confirmation' 

confirmation_email_from_address = settings.DEFAULT_FROM_EMAIL 

 

def get_confirmation_email_content(self, confirmation): 

return render_to_string(self.confirmation_email_template, { 

'confirmation': confirmation, 

}) 

 

def get_form_class(self): 

return UserCreationForm 

 

def form_valid(self, form): 

response = super(RegisterUser, self).form_valid(form) 

self.send_confirmation_mail(form.instance) 

 

return response 

 

def send_confirmation_mail(self, user): 

""" 

Sends a confirmation email to the user. The user is inactive until the 

email is confirmed by clicking a URL found in the email. 

""" 

confirmation = UserRegistrationConfirmation.objects.create_confirmation( 

user=user) 

 

send_mail( 

self.confirmation_email_subject, 

self.get_confirmation_email_content(confirmation), 

from_email=self.confirmation_email_from_address, 

recipient_list=[user.main_email]) 

 

 

class LoginRequiredMixin(object): 

""" 

A view mixin which makes sure that the user is logged in before accessing 

the view. 

""" 

@method_decorator(login_required) 

def dispatch(self, *args, **kwargs): 

return super(LoginRequiredMixin, self).dispatch(*args, **kwargs) 

 

 

class MessageMixin(object): 

""" 

A View mixin which adds a success info message to the list of messages 

managed by the :mod:`django.contrib.message` framework in case a form has 

been successfully processed. 

 

The message which is added is retrieved by calling the :meth:`get_message` 

method. Alternatively, a :attr:`message` attribute can be set if no 

calculations are necessary. 

""" 

def form_valid(self, *args, **kwargs): 

message = self.get_message() 

if message: 

messages.info(self.request, message) 

return super(MessageMixin, self).form_valid(*args, **kwargs) 

 

def get_message(self): 

if self.message: 

return self.message 

 

 

class SetPasswordMixin(object): 

def form_valid(self, form): 

user = self.confirmation.user 

user.is_active = True 

password = form.cleaned_data['password1'] 

user.set_password(password) 

user.save() 

 

# The confirmation key is no longer needed 

self.confirmation.delete() 

 

# Log the user in 

user = authenticate(username=user.main_email, password=password) 

login(self.request, user) 

 

return super(SetPasswordMixin, self).form_valid(form) 

 

def get_confirmation_instance(self, confirmation_key): 

self.confirmation = get_object_or_404( 

self.confirmation_class, 

confirmation_key=confirmation_key) 

return self.confirmation 

 

def post(self, request, confirmation_key): 

self.get_confirmation_instance(confirmation_key) 

return super(SetPasswordMixin, self).post(request, confirmation_key) 

 

def get(self, request, confirmation_key): 

self.get_confirmation_instance(confirmation_key) 

return super(SetPasswordMixin, self).get(request, confirmation_key) 

 

 

class RegistrationConfirmation(SetPasswordMixin, MessageMixin, FormView): 

form_class = ResetPasswordForm 

template_name = 'accounts/registration-confirmation.html' 

success_url = reverse_lazy('accounts-profile') 

message = 'You have successfully registered' 

confirmation_class = UserRegistrationConfirmation 

 

 

class ResetPasswordView(SetPasswordMixin, MessageMixin, FormView): 

form_class = ResetPasswordForm 

template_name = 'accounts/registration-reset-password.html' 

success_url = reverse_lazy('accounts-profile') 

message = 'You have successfully reset your password' 

confirmation_class = ResetPasswordConfirmation 

 

 

class ForgotPasswordView(FormView): 

form_class = ForgotPasswordForm 

success_url = reverse_lazy('accounts-password-reset-success') 

template_name = 'accounts/forgot-password.html' 

 

confirmation_email_template = \ 

'accounts/password-reset-confirmation-email.txt' 

confirmation_email_subject = 'Password Reset Confirmation' 

confirmation_email_from_address = settings.DEFAULT_FROM_EMAIL 

 

def get_confirmation_email_content(self, confirmation): 

return render_to_string(self.confirmation_email_template, { 

'confirmation': confirmation, 

}) 

 

def form_valid(self, form): 

# Create a ResetPasswordConfirmation instance 

email = form.cleaned_data['email'] 

user = User.objects.get(emails__email=email) 

confirmation = \ 

ResetPasswordConfirmation.objects.create_confirmation(user=user) 

 

# Send a confirmation email 

send_mail( 

self.confirmation_email_subject, 

self.get_confirmation_email_content(confirmation), 

from_email=self.confirmation_email_from_address, 

recipient_list=[email]) 

 

return super(ForgotPasswordView, self).form_valid(form) 

 

 

class ChangePersonalInfoView(LoginRequiredMixin, MessageMixin, UpdateView): 

template_name = 'accounts/change-personal-info.html' 

form_class = ChangePersonalInfoForm 

model = User 

success_url = reverse_lazy('accounts-profile-modify') 

message = 'Successfully changed your information' 

 

def get_object(self, queryset=None): 

return self.request.user 

 

 

class PasswordChangeView(LoginRequiredMixin, MessageMixin, FormView): 

template_name = 'accounts/password-update.html' 

form_class = PasswordChangeForm 

success_url = reverse_lazy('accounts-profile-password-change') 

message = 'Successfully updated your password' 

 

def get_form_kwargs(self): 

kwargs = super(PasswordChangeView, self).get_form_kwargs() 

kwargs['user'] = self.request.user 

return kwargs 

 

def form_valid(self, form, *args, **kwargs): 

form.save() 

return super(PasswordChangeView, self).form_valid(form, *args, **kwargs) 

 

 

class AccountProfile(LoginRequiredMixin, View): 

template_name = 'accounts/profile.html' 

 

def get(self, request): 

return render(request, self.template_name, { 

'user': request.user, 

}) 

 

 

class ManageAccountEmailsView(LoginRequiredMixin, MessageMixin, FormView): 

""" 

Render a page letting users add or remove emails to their accounts. 

 

Apart from the ``success_url``, a ``merge_accounts_url`` can be provided, 

if the name of the view is to differ from ``accounts-merge-confirmation`` 

""" 

form_class = AddEmailToAccountForm 

template_name = 'accounts/profile-manage-emails.html' 

success_url = reverse_lazy('accounts-manage-emails') 

merge_accounts_url = reverse_lazy('accounts-merge-confirmation') 

 

confirmation_email_template = 'accounts/add-email-confirmation-email.txt' 

confirmation_email_subject = 'Add Email To Account' 

confirmation_email_from_address = settings.DEFAULT_FROM_EMAIL 

 

def get_confirmation_email_content(self, confirmation): 

return render_to_string(self.confirmation_email_template, { 

'confirmation': confirmation, 

}) 

 

def form_valid(self, form): 

email = form.cleaned_data['email'] 

user_email, _ = UserEmail.objects.get_or_create( 

email__iexact=email, 

defaults={'email': email} 

) 

if not user_email.user: 

# The email is not associated with an account yet. 

# Ask for confirmation to add it to this account. 

confirmation = AddEmailConfirmation.objects.create_confirmation( 

user=self.request.user, 

email=user_email) 

self.message = ( 

'Before the email is associated with this account, ' 

'you must follow the confirmation link sent to the address' 

) 

# Send a confirmation email 

send_mail( 

self.confirmation_email_subject, 

self.get_confirmation_email_content(confirmation), 

from_email=self.confirmation_email_from_address, 

recipient_list=[email]) 

elif user_email.user == self.request.user: 

self.message = 'This email is already associated with your account.' 

else: 

# Offer the user to merge the two accounts 

return redirect(self.merge_accounts_url + '?' + urlencode({ 

'email': email, 

})) 

 

return super(ManageAccountEmailsView, self).form_valid(form) 

 

 

class AccountMergeConfirmView(LoginRequiredMixin, View): 

template_name = 'accounts/account-merge-confirm.html' 

success_url = reverse_lazy('accounts-merge-confirmed') 

 

confirmation_email_template = \ 

'accounts/merge-accounts-confirmation-email.txt' 

confirmation_email_subject = 'Merge Accounts' 

confirmation_email_from_address = settings.DEFAULT_FROM_EMAIL 

 

def get_confirmation_email_content(self, confirmation): 

return render_to_string(self.confirmation_email_template, { 

'confirmation': confirmation, 

}) 

 

def get_user_email(self, query_dict): 

if 'email' not in query_dict: 

raise Http404 

email = query_dict['email'] 

user_email = get_object_or_404(UserEmail, email__iexact=email) 

return user_email 

 

def get(self, request): 

self.request = request 

user_email = self.get_user_email(self.request.GET) 

 

return render(request, self.template_name, { 

'user_email': user_email, 

}) 

 

def post(self, request): 

self.request = request 

 

user_email = self.get_user_email(self.request.POST) 

if not user_email.user or user_email.user == self.request.user: 

pass 

 

# Send a confirmation mail 

confirmation = MergeAccountConfirmation.objects.create_confirmation( 

initial_user=self.request.user, 

merge_with=user_email.user) 

send_mail( 

self.confirmation_email_subject, 

self.get_confirmation_email_content(confirmation), 

from_email=self.confirmation_email_from_address, 

recipient_list=[user_email.email]) 

 

return redirect(self.success_url + '?' + urlencode({ 

'email': user_email.email, 

})) 

 

 

class AccountMergeFinalize(View): 

template_name = 'accounts/account-merge-finalize.html' 

success_url = reverse_lazy('accounts-merge-finalized') 

 

def get(self, request, confirmation_key): 

confirmation = get_object_or_404( 

MergeAccountConfirmation, 

confirmation_key=confirmation_key) 

 

return render(request, self.template_name, { 

'confirmation': confirmation, 

}) 

 

def post(self, request, confirmation_key): 

confirmation = get_object_or_404( 

MergeAccountConfirmation, 

confirmation_key=confirmation_key) 

 

initial_user = confirmation.initial_user 

merge_with = confirmation.merge_with 

 

# Move emails 

for email in merge_with.emails.all(): 

initial_user.emails.add(email) 

 

# Run a post merge hook 

run_hook('post-merge', initial_user, merge_with) 

 

confirmation.delete() 

 

if request.user == confirmation.merge_with: 

logout(request) 

 

# The account is now obsolete and should be removed 

merge_with.delete() 

 

return redirect(self.success_url) 

 

 

class AccountMergeConfirmedView(TemplateView): 

template_name = 'accounts/accounts-merge-confirmed.html' 

 

def get_context_data(self, **kwargs): 

if 'email' not in self.request.GET: 

raise Http404 

email = self.request.GET['email'] 

user_email = get_object_or_404(UserEmail, email__iexact=email) 

context = super(AccountMergeConfirmedView, 

self).get_context_data(**kwargs) 

context['email'] = user_email 

 

return context 

 

 

class ConfirmAddAccountEmail(View): 

template_name = 'accounts/new-email-added.html' 

 

def get(self, request, confirmation_key): 

confirmation = get_object_or_404( 

AddEmailConfirmation, 

confirmation_key=confirmation_key) 

user = confirmation.user 

user_email = confirmation.email 

confirmation.delete() 

# If the email has become associated with a different user in the mean 

# time, abort the operation. 

if user_email.user and user_email.user != user: 

raise PermissionDenied 

user_email.user = user 

user_email.save() 

 

return render(request, self.template_name, { 

'new_email': user_email, 

})