From 342658e3f761c707cf5108b884390d10efd34de8 Mon Sep 17 00:00:00 2001 From: Javier Cicchelli Date: Sun, 11 Dec 2022 21:33:33 +0100 Subject: [PATCH] Implemented the first attempt at authentication in the LoginView view. --- .../Sources/Login/UI/Views/LoginView.swift | 48 ++++++++++++++++++- 1 file changed, 46 insertions(+), 2 deletions(-) diff --git a/Modules/Sources/Login/UI/Views/LoginView.swift b/Modules/Sources/Login/UI/Views/LoginView.swift index 392073b..89e8e0e 100644 --- a/Modules/Sources/Login/UI/Views/LoginView.swift +++ b/Modules/Sources/Login/UI/Views/LoginView.swift @@ -6,6 +6,11 @@ // Copyright © 2022 Röck+Cöde. All rights reserved. // +import APIService +import DataModels +import DependencyInjection +import Dependencies +import KeychainStorage import SwiftUI public struct LoginView: View { @@ -43,6 +48,14 @@ public struct LoginView: View { fileprivate extension LoginView { struct LoginContainer: View { + // MARK: Dependencies + + @Dependency(\.apiService) private var apiService + + // MARK: Storages + + @KeychainStorage(key: .KeychainStorage.account) private var account: Account? + // MARK: States @State private var isAuthenticating: Bool = false @@ -68,11 +81,11 @@ fileprivate extension LoginView { password: $password, errorMessage: $errorMessage ) { - // TODO: login with the username and password. + isAuthenticating = true } Button { - // TODO: login with the username and password. + isAuthenticating = true } label: { Label { Text( @@ -95,6 +108,9 @@ fileprivate extension LoginView { .buttonBorderShape(.roundedRectangle(radius: 8)) .controlSize(.large) .disabled(isLoginDisabled) + .task(id: isAuthenticating) { + await authenticate() + } } } } @@ -103,9 +119,37 @@ fileprivate extension LoginView { // MARK: - Helpers private extension LoginView.LoginContainer { + + // MARK: Computed + var isLoginDisabled: Bool { username.isEmpty || password.isEmpty } + + // MARK: Functions + + func authenticate() async { + guard isAuthenticating else { return } + + do { + _ = try await apiService.getUser(credentials: .init( + username: username, + password: password + )) + + account = .init( + username: username, + password: password + ) + } catch APIClientError.authenticationFailed { + errorMessage = .init(localized: "login.error.authentication_failed.text") + isAuthenticating = false + } catch { + errorMessage = .init(localized: "login.error.unknown.text") + isAuthenticating = false + } + } + } // MARK: - Previews