Implemented the first attempt at authentication in the LoginView view.

This commit is contained in:
Javier Cicchelli 2022-12-11 21:33:33 +01:00
parent 0a8b18719a
commit 342658e3f7

View File

@ -6,6 +6,11 @@
// Copyright © 2022 Röck+Cöde. All rights reserved. // Copyright © 2022 Röck+Cöde. All rights reserved.
// //
import APIService
import DataModels
import DependencyInjection
import Dependencies
import KeychainStorage
import SwiftUI import SwiftUI
public struct LoginView: View { public struct LoginView: View {
@ -43,6 +48,14 @@ public struct LoginView: View {
fileprivate extension LoginView { fileprivate extension LoginView {
struct LoginContainer: View { struct LoginContainer: View {
// MARK: Dependencies
@Dependency(\.apiService) private var apiService
// MARK: Storages
@KeychainStorage(key: .KeychainStorage.account) private var account: Account?
// MARK: States // MARK: States
@State private var isAuthenticating: Bool = false @State private var isAuthenticating: Bool = false
@ -68,11 +81,11 @@ fileprivate extension LoginView {
password: $password, password: $password,
errorMessage: $errorMessage errorMessage: $errorMessage
) { ) {
// TODO: login with the username and password. isAuthenticating = true
} }
Button { Button {
// TODO: login with the username and password. isAuthenticating = true
} label: { } label: {
Label { Label {
Text( Text(
@ -95,6 +108,9 @@ fileprivate extension LoginView {
.buttonBorderShape(.roundedRectangle(radius: 8)) .buttonBorderShape(.roundedRectangle(radius: 8))
.controlSize(.large) .controlSize(.large)
.disabled(isLoginDisabled) .disabled(isLoginDisabled)
.task(id: isAuthenticating) {
await authenticate()
}
} }
} }
} }
@ -103,9 +119,37 @@ fileprivate extension LoginView {
// MARK: - Helpers // MARK: - Helpers
private extension LoginView.LoginContainer { private extension LoginView.LoginContainer {
// MARK: Computed
var isLoginDisabled: Bool { var isLoginDisabled: Bool {
username.isEmpty || password.isEmpty 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 // MARK: - Previews