-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
LoginToutViewController.swift
647 lines (533 loc) · 21 KB
/
LoginToutViewController.swift
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
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
import AuthenticationServices
import FBSDKLoginKit
import Foundation
import KsApi
import Library
import MessageUI
import Prelude
import ReactiveSwift
import UIKit
public final class LoginToutViewController: UIViewController, MFMailComposeViewControllerDelegate,
ProcessingViewPresenting {
// MARK: - Properties
@available(iOS 13.0, *)
private lazy var appleLoginButton: ASAuthorizationAppleIDButton = {
ASAuthorizationAppleIDButton(type: .continue, style: .black)
}()
private lazy var backgroundImageView: UIImageView = { UIImageView(frame: .zero) }()
private lazy var bringCreativeProjectsToLifeLabel = { UILabel(frame: .zero) }()
private lazy var contextLabel = { UILabel(frame: .zero) }()
private lazy var emailLoginStackView = { UIStackView(frame: .zero) }()
private lazy var fbLoginButton = { UIButton(type: .custom)
|> \.translatesAutoresizingMaskIntoConstraints .~ false
}()
private lazy var fbLoginManager: LoginManager = {
let manager = LoginManager()
manager.defaultAudience = .friends
return manager
}()
private lazy var fbLoginStackView = { UIStackView(frame: .zero) }()
private lazy var getNotifiedLabel = { UILabel(frame: .zero) }()
private let helpViewModel = HelpViewModel()
private lazy var loginButton = { UIButton(type: .custom)
|> \.translatesAutoresizingMaskIntoConstraints .~ false
}()
private lazy var loginContextStackView = { UIStackView() }()
private lazy var logoImageView = { UIImageView(frame: .zero) }()
internal var processingView: ProcessingView? = ProcessingView(frame: .zero)
private lazy var rootStackView = { UIStackView() }()
private lazy var scrollView = {
UIScrollView(frame: .zero)
|> \.alwaysBounceVertical .~ true
}()
private lazy var separatorView: UIView = { UIView(frame: .zero) }()
private var sessionStartedObserver: Any?
private lazy var signupButton = { UIButton(type: .custom)
|> \.translatesAutoresizingMaskIntoConstraints .~ false
}()
private let viewModel: LoginToutViewModelType = LoginToutViewModel()
// MARK: - Configuration
public static func configuredWith(
loginIntent intent: LoginIntent,
project: Project? = nil,
reward: Reward? = nil
) -> LoginToutViewController {
let vc = LoginToutViewController.instantiate()
vc.viewModel.inputs.configureWith(intent, project: project, reward: reward)
vc.helpViewModel.inputs.configureWith(helpContext: .loginTout)
vc.helpViewModel.inputs.canSendEmail(MFMailComposeViewController.canSendMail())
return vc
}
// MARK: - Lifecycle
public override func viewDidLoad() {
super.viewDidLoad()
self.configureViews()
self.setupConstraints()
self.configureTargets()
self.fbLoginManager.logOut()
self.sessionStartedObserver = NotificationCenter.default
.addObserver(forName: .ksr_sessionStarted, object: nil, queue: nil) { [weak self] _ in
self?.viewModel.inputs.userSessionStarted()
}
if self.presentingViewController != nil {
self.navigationItem.leftBarButtonItem = .close(self, selector: #selector(self.closeButtonPressed))
}
_ = self.navigationItem
|> \.rightBarButtonItem .~ .help(self, selector: #selector(self.helpButtonPressed))
}
public override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.viewModel.inputs.view(isPresented: self.presentingViewController != nil)
self.viewModel.inputs.viewWillAppear()
}
deinit {
self.sessionStartedObserver.doIfSome(NotificationCenter.default.removeObserver)
}
// MARK: - Styles
public override func bindStyles() {
super.bindStyles()
_ = self.backgroundImageView
|> backgroundImageViewStyle
if #available(iOS 13.0, *) {
_ = self.appleLoginButton
|> roundedStyle(cornerRadius: Styles.grid(2))
}
_ = self.bringCreativeProjectsToLifeLabel
|> baseLabelStyle
|> UILabel.lens.font .~ .ksr_title2()
|> UILabel.lens.text %~ { _ in Strings.Bring_creative_projects_to_life() }
_ = self.contextLabel
|> baseLabelStyle
|> UILabel.lens.font %~ { _ in
self.bringCreativeProjectsToLifeLabel.isHidden ? UIFont.ksr_title2() : UIFont.ksr_subhead()
}
_ = self.fbLoginButton
|> facebookButtonStyle
|> UIButton.lens.title(for: .normal) %~ { _ in Strings.Continue_with_Facebook() }
_ = self.getNotifiedLabel
|> baseLabelStyle
|> UILabel.lens.font %~~ { _, label in
label.traitCollection.isRegularRegular ? UIFont.ksr_subhead() : UIFont.ksr_caption2()
}
|> UILabel.lens.text %~ { _ in Strings.Get_notified_when_your_friends_back_and_launch_projects() }
_ = self.loginButton
|> greyButtonStyle
|> UIButton.lens.title(for: .normal) %~ { _ in
Strings.login_tout_back_intent_traditional_login_button()
}
_ = self.loginContextStackView
|> UIStackView.lens.spacing .~ Styles.gridHalf(1)
|> UIStackView.lens.layoutMargins %~~ { _, stack in
stack.traitCollection.isRegularRegular
? .init(topBottom: Styles.grid(10), leftRight: 0)
: .init(top: Styles.grid(10), left: 0, bottom: Styles.grid(5), right: 0)
}
|> UIStackView.lens.isLayoutMarginsRelativeArrangement .~ true
_ = self.logoImageView
|> logoImageViewStyle
_ = self.rootStackView
|> baseStackViewStyle
|> loginRootStackViewStyle
|> UIStackView.lens.spacing .~ Styles.grid(5)
_ = self.separatorView
|> separatorViewStyle
_ = self.signupButton
|> signupWithEmailButtonStyle
_ = [self.loginContextStackView, self.fbLoginStackView, self.emailLoginStackView]
||> baseStackViewStyle
}
// MARK: - View Model
public override func bindViewModel() {
self.viewModel.outputs.startLogin
.observeForControllerAction()
.observeValues { [weak self] _ in
self?.pushLoginViewController()
}
self.viewModel.outputs.startSignup
.observeForControllerAction()
.observeValues { [weak self] _ in
self?.pushSignupViewController()
}
self.viewModel.outputs.logIntoEnvironmentWithApple
.observeValues { [weak self] accessTokenEnv in
AppEnvironment.login(accessTokenEnv)
self?.viewModel.inputs.environmentLoggedIn()
}
self.viewModel.outputs.logIntoEnvironmentWithFacebook
.observeValues { [weak self] accessTokenEnv in
guard let strongSelf = self else { return }
AppEnvironment.login(accessTokenEnv)
/** FIXME: Not releasing this yet - re-test functionality as it failed regression testing on release-5.6.1 (see confluence regression testing document)
guard featureFacebookLoginDeprecationEnabled(),
let needsPassword = accessTokenEnv.user.needsPassword,
needsPassword else {
strongSelf.pushSetYourPasswordViewController()
return
}
*/
strongSelf.viewModel.inputs.environmentLoggedIn()
}
self.viewModel.outputs.postNotification
.observeForUI()
.observeValues {
NotificationCenter.default.post($0.0)
NotificationCenter.default.post($0.1)
}
self.viewModel.outputs.startFacebookConfirmation
.observeForControllerAction()
.observeValues { [weak self] user, token in
self?.pushFacebookConfirmationController(facebookUser: user, facebookToken: token)
}
self.viewModel.outputs.startTwoFactorChallenge
.observeForControllerAction()
.observeValues { [weak self] token in
self?.pushTwoFactorViewController(facebookAccessToken: token)
}
self.viewModel.outputs.attemptFacebookLogin
.observeValues { [weak self] _ in self?.attemptFacebookLogin()
}
self.viewModel.outputs.showFacebookErrorAlert
.observeForControllerAction()
.observeValues { [weak self] error in
guard let strongSelf = self else { return }
if featureFacebookLoginDeprecationEnabled() {
strongSelf.present(
UIAlertController.facebookDeprecationNewPasswordOptionAlert(
loginHandler: { [weak self] _ in
self?.pushLoginViewController()
},
setNewPasswordHandler: { [weak self] _ in
self?.pushFacebookResetPasswordViewController()
}
),
animated: true,
completion: nil
)
return
}
strongSelf.present(
UIAlertController.alertController(forError: error),
animated: true,
completion: nil
)
}
self.viewModel.outputs.dismissViewController
.observeForControllerAction()
.observeValues { [weak self] in
self?.dismiss(animated: true)
}
self.helpViewModel.outputs.showHelpSheet
.observeForControllerAction()
.observeValues { [weak self] in
self?.showHelpSheet(helpTypes: $0)
}
self.helpViewModel.outputs.showMailCompose
.observeForControllerAction()
.observeValues { [weak self] in
guard let strongSelf = self else { return }
let controller = MFMailComposeViewController.support()
controller.mailComposeDelegate = strongSelf
strongSelf.present(controller, animated: true, completion: nil)
}
self.helpViewModel.outputs.showNoEmailError
.observeForControllerAction()
.observeValues { [weak self] alert in
self?.present(alert, animated: true, completion: nil)
}
self.helpViewModel.outputs.showWebHelp
.observeForControllerAction()
.observeValues { [weak self] helpType in
self?.goToHelpType(helpType)
}
self.contextLabel.rac.text = self.viewModel.outputs.logInContextText
self.bringCreativeProjectsToLifeLabel.rac.hidden = self.viewModel.outputs.headlineLabelHidden
self.viewModel.outputs.headlineLabelHidden
.observeForUI()
.observeValues { [weak self] isHidden in
_ = self?.contextLabel
?|> UILabel.lens.font .~ (isHidden ? UIFont.ksr_title2() : UIFont.ksr_subhead())
}
self.viewModel.outputs.attemptAppleLogin
.observeForUI()
.observeValues { [weak self] in
if #available(iOS 13, *) {
self?.attemptAppleLogin()
}
}
self.viewModel.outputs.showAppleErrorAlert
.observeForControllerAction()
.observeValues { [weak self] message in
self?.present(UIAlertController.genericError(message), animated: true)
}
self.viewModel.outputs.isLoading
.observeForUI()
.observeValues { [weak self] isLoading in
if isLoading {
self?.showProcessingView()
} else {
self?.hideProcessingView()
}
}
}
// MARK: - Functions
private func configureViews() {
_ = (self.backgroundImageView, self.view)
|> ksr_addSubviewToParent()
|> ksr_constrainViewToEdgesInParent()
_ = (self.scrollView, self.view)
|> ksr_addSubviewToParent()
|> ksr_constrainViewToEdgesInParent()
_ = (self.rootStackView, self.scrollView)
|> ksr_addSubviewToParent()
|> ksr_constrainViewToEdgesInParent()
_ = ([
self.loginContextStackView, self.fbLoginStackView, self.separatorView, self.emailLoginStackView
], self.rootStackView)
|> ksr_addArrangedSubviewsToStackView()
let spacer = UIView()
_ = ([
self.logoImageView, spacer, self.bringCreativeProjectsToLifeLabel, self.contextLabel
], self.loginContextStackView)
|> ksr_addArrangedSubviewsToStackView()
if #available(iOS 13.0, *) {
_ = ([self.appleLoginButton, self.fbLoginButton, self.getNotifiedLabel], self.fbLoginStackView)
|> ksr_addArrangedSubviewsToStackView()
} else {
_ = ([self.fbLoginButton, self.getNotifiedLabel], self.fbLoginStackView)
|> ksr_addArrangedSubviewsToStackView()
}
_ = ([self.signupButton, self.loginButton], self.emailLoginStackView)
|> ksr_addArrangedSubviewsToStackView()
}
private func setupConstraints() {
NSLayoutConstraint.activate([
self.separatorView.heightAnchor.constraint(equalToConstant: 1),
self.rootStackView.widthAnchor.constraint(equalTo: self.view.widthAnchor),
self.fbLoginButton.heightAnchor.constraint(greaterThanOrEqualToConstant: Styles.minTouchSize.height),
self.loginButton.heightAnchor.constraint(greaterThanOrEqualToConstant: Styles.minTouchSize.height),
self.signupButton.heightAnchor.constraint(greaterThanOrEqualToConstant: Styles.minTouchSize.height)
])
if #available(iOS 13.0, *) {
NSLayoutConstraint.activate([
self.appleLoginButton.heightAnchor
.constraint(greaterThanOrEqualToConstant: Styles.minTouchSize.height)
])
}
}
private func configureTargets() {
if #available(iOS 13.0, *) {
self.appleLoginButton.addTarget(
self, action: #selector(self.appleLoginButtonPressed(_:)),
for: .touchUpInside
)
}
self.fbLoginButton.addTarget(
self, action: #selector(self.facebookLoginButtonPressed(_:)),
for: .touchUpInside
)
self.loginButton.addTarget(self, action: #selector(self.loginButtonPressed(_:)), for: .touchUpInside)
self.signupButton.addTarget(self, action: #selector(self.signupButtonPressed), for: .touchUpInside)
}
@available(iOS 13, *)
private func attemptAppleLogin() {
let appleIDRequest = ASAuthorizationAppleIDProvider().createRequest()
|> \.requestedScopes .~ [.fullName, .email]
let authorizationController = ASAuthorizationController(authorizationRequests: [appleIDRequest])
|> \.delegate .~ self
?|> \.presentationContextProvider .~ self
authorizationController?.performRequests()
}
fileprivate func goToHelpType(_ helpType: HelpType) {
let vc = HelpWebViewController.configuredWith(helpType: helpType)
self.navigationController?.pushViewController(vc, animated: true)
self.navigationItem.backBarButtonItem = UIBarButtonItem.back(nil, selector: nil)
}
fileprivate func pushLoginViewController() {
self.navigationController?.pushViewController(LoginViewController.instantiate(), animated: true)
self.navigationItem.backBarButtonItem = UIBarButtonItem.back(nil, selector: nil)
}
fileprivate func pushTwoFactorViewController(facebookAccessToken token: String) {
let vc = TwoFactorViewController.configuredWith(facebookAccessToken: token)
self.navigationController?.pushViewController(vc, animated: true)
self.navigationItem.backBarButtonItem = UIBarButtonItem.back(nil, selector: nil)
}
fileprivate func pushFacebookConfirmationController(
facebookUser user: ErrorEnvelope.FacebookUser?,
facebookToken token: String
) {
let vc = FacebookConfirmationViewController
.configuredWith(facebookUserEmail: user?.email ?? "", facebookAccessToken: token)
self.navigationController?.pushViewController(vc, animated: true)
self.navigationItem.backBarButtonItem = UIBarButtonItem.back(nil, selector: nil)
}
fileprivate func pushSignupViewController() {
self.navigationController?.pushViewController(SignupViewController.instantiate(), animated: true)
self.navigationItem.backBarButtonItem = UIBarButtonItem.back(nil, selector: nil)
}
private func pushFacebookResetPasswordViewController() {
let vc = FacebookResetPasswordViewController.instantiate()
self.navigationController?.pushViewController(vc, animated: true)
self.navigationItem
.backBarButtonItem = UIBarButtonItem(title: "Log in", style: .plain, target: nil, action: nil)
}
private func pushSetYourPasswordViewController() {
let vc = SetYourPasswordViewController.instantiate()
vc.delegate = self
self.navigationController?.pushViewController(vc, animated: true)
self.navigationItem
.backBarButtonItem = UIBarButtonItem(title: "Log in", style: .plain, target: nil, action: nil)
}
fileprivate func showHelpSheet(helpTypes: [HelpType]) {
let helpSheet = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
helpTypes.forEach { helpType in
helpSheet.addAction(
UIAlertAction(title: helpType.title, style: .default) { [weak helpVM = self.helpViewModel] _ in
helpVM?.inputs.helpTypeButtonTapped(helpType)
}
)
}
helpSheet.addAction(
UIAlertAction(
title: Strings.login_tout_help_sheet_cancel(),
style: .cancel,
handler: nil
)
)
// iPad provision
helpSheet.popoverPresentationController?.barButtonItem = self.navigationItem.rightBarButtonItem
self.present(helpSheet, animated: true, completion: nil)
}
// MARK: - Facebook Login
fileprivate func attemptFacebookLogin() {
self.fbLoginManager.logIn(
permissions: ["public_profile", "email", "user_friends"], from: nil
) { result, error in
if let error = error {
self.viewModel.inputs.facebookLoginFail(error: error)
} else if let result = result, !result.isCancelled {
self.viewModel.inputs.facebookLoginSuccess(result: result)
}
}
}
// MARK: - Accessors
@objc public func mailComposeController(
_: MFMailComposeViewController,
didFinishWith result: MFMailComposeResult,
error _: Error?
) {
self.helpViewModel.inputs.mailComposeCompletion(result: result)
self.dismiss(animated: true, completion: nil)
}
@objc private func appleLoginButtonPressed(_: UIButton) {
self.viewModel.inputs.appleLoginButtonPressed()
}
@objc private func closeButtonPressed() {
self.dismiss(animated: true, completion: nil)
}
@objc private func helpButtonPressed() {
self.helpViewModel.inputs.showHelpSheetButtonTapped()
}
@objc private func loginButtonPressed(_: UIButton) {
self.viewModel.inputs.loginButtonPressed()
}
@objc private func facebookLoginButtonPressed(_: UIButton) {
self.viewModel.inputs.facebookLoginButtonPressed()
}
@objc private func signupButtonPressed() {
self.viewModel.inputs.signupButtonPressed()
}
}
extension LoginToutViewController: TabBarControllerScrollable {
func scrollToTop() {
guard let scrollView = self.view.subviews
.first(where: { view in view is UIScrollView })
.flatMap({ view in view as? UIScrollView })
else { return }
scrollView.scrollToTop()
}
}
// MARK: - Styles
private let backgroundImageViewStyle: ImageViewStyle = { imageView in
imageView
|> \.contentMode .~ .scaleToFill
|> \.image .~ image(named: "signup-background")
}
private let baseStackViewStyle: StackViewStyle = { stackView in
stackView
|> \.distribution .~ .fill
|> \.alignment .~ .fill
|> \.axis .~ .vertical
|> \.spacing .~ Styles.grid(2)
}
private let baseLabelStyle: LabelStyle = { label in
label
|> \.textAlignment .~ NSTextAlignment.center
|> \.lineBreakMode .~ NSLineBreakMode.byWordWrapping
|> \.numberOfLines .~ 0
}
private let logoImageViewStyle: ImageViewStyle = { imageView in
imageView
|> \.image .~ image(named: "kickstarter-logo")?.withRenderingMode(.alwaysTemplate)
|> \.tintColor .~ .ksr_create_500
|> \.contentMode .~ .scaleAspectFit
|> \.translatesAutoresizingMaskIntoConstraints .~ false
|> \.accessibilityLabel %~ { _ in Strings.general_accessibility_kickstarter() }
}
private let separatorViewStyle: ViewStyle = { view in
view
|> \.backgroundColor .~ .ksr_support_300
|> \.translatesAutoresizingMaskIntoConstraints .~ false
}
// MARK: - ASAuthorizationControllerDelegate
@available(iOS 13, *)
extension LoginToutViewController: ASAuthorizationControllerDelegate {
public func authorizationController(
controller _: ASAuthorizationController,
didCompleteWithAuthorization authorization: ASAuthorization
) {
guard let credential = authorization.credential as? ASAuthorizationAppleIDCredential,
let authToken = credential.authorizationCode else {
return
}
let fullName = credential.fullName
let token = String(data: authToken, encoding: .utf8)
let data = (
appId: AppEnvironment.current.apiService.appId,
firstName: fullName?.givenName,
lastName: fullName?.familyName,
token: token
) as? SignInWithAppleData
self.viewModel.inputs.appleAuthorizationDidSucceed(with: data)
}
public func authorizationController(
controller _: ASAuthorizationController,
didCompleteWithError error: Error
) {
if let error = error as? ASAuthorizationError {
let authError: AuthServicesError
switch error.errorCode {
case ASAuthorizationError.canceled.rawValue:
authError = .canceled
default:
authError = .other(error)
}
self.viewModel.inputs.appleAuthorizationDidFail(with: authError)
}
}
}
// MARK: SetYourPasswordViewControllerDelegate
extension LoginToutViewController: SetYourPasswordViewControllerDelegate {
func setPasswordCompleteAndLogUserIn() {
self.viewModel.inputs.environmentLoggedIn()
}
}
// MARK: - ASAuthorizationControllerPresentationContextProviding
@available(iOS 13.0, *)
extension LoginToutViewController: ASAuthorizationControllerPresentationContextProviding {
public func presentationAnchor(for _: ASAuthorizationController) -> ASPresentationAnchor {
guard let window = self.view.window else {
return ASPresentationAnchor()
}
return window
}
}