2026-05-01 21:27:39 +08:00
|
|
|
import Foundation
|
|
|
|
|
import XuqmSDK
|
|
|
|
|
|
|
|
|
|
@MainActor
|
|
|
|
|
final class AuthViewModel: ObservableObject {
|
|
|
|
|
@Published var state: LoginState = .idle
|
|
|
|
|
@Published var currentUserId: String = ""
|
|
|
|
|
@Published var currentNickname: String = ""
|
|
|
|
|
|
2026-05-02 11:29:50 +08:00
|
|
|
private struct DemoLoginResponse: Decodable, Sendable {
|
|
|
|
|
let imToken: String
|
|
|
|
|
let profile: DemoProfile
|
|
|
|
|
struct DemoProfile: Decodable, Sendable {
|
|
|
|
|
let userId: String
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-05-01 21:27:39 +08:00
|
|
|
func login(userId: String, password: String) {
|
|
|
|
|
guard !userId.isEmpty, !password.isEmpty else {
|
|
|
|
|
state = .error("请输入用户 ID 和密码")
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
state = .loading
|
|
|
|
|
Task {
|
|
|
|
|
do {
|
2026-05-02 11:29:50 +08:00
|
|
|
let config = XuqmSDK.shared.requireConfig()
|
|
|
|
|
let res: DemoLoginResponse = try await ApiClient.shared.request(
|
|
|
|
|
path: "/api/demo/auth/login",
|
|
|
|
|
method: "POST",
|
2026-05-07 19:39:48 +08:00
|
|
|
queryItems: [URLQueryItem(name: "appKey", value: config.appKey)],
|
|
|
|
|
body: ["appKey": config.appKey, "userId": userId, "password": password]
|
2026-05-02 11:29:50 +08:00
|
|
|
)
|
|
|
|
|
await XuqmSDK.shared.login(userId: res.profile.userId, userSig: res.imToken)
|
|
|
|
|
currentUserId = res.profile.userId
|
|
|
|
|
currentNickname = res.profile.userId
|
2026-05-01 21:27:39 +08:00
|
|
|
state = .success
|
|
|
|
|
} catch {
|
|
|
|
|
state = .error(error.localizedDescription)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func logout() {
|
2026-05-02 11:29:50 +08:00
|
|
|
Task { await XuqmSDK.shared.logout() }
|
2026-05-01 21:27:39 +08:00
|
|
|
currentUserId = ""
|
|
|
|
|
currentNickname = ""
|
|
|
|
|
state = .idle
|
|
|
|
|
}
|
|
|
|
|
}
|