Skip to content

Commit 15066a3

Browse files
committed
chore: sign user out on launch if token expired
1 parent b7ccbca commit 15066a3

File tree

3 files changed

+30
-4
lines changed

3 files changed

+30
-4
lines changed

Coder Desktop/Coder Desktop/Coder_DesktopApp.swift

+4
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,10 @@ class AppDelegate: NSObject, NSApplicationDelegate {
5656
state.reconfigure()
5757
}
5858
}
59+
// Sign out if token is expired
60+
Task { @MainActor in
61+
await state.handleTokenExpiry()
62+
}
5963
}
6064

6165
// This function MUST eventually call `NSApp.reply(toApplicationShouldTerminate: true)`

Coder Desktop/Coder Desktop/State.swift

+22
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,9 @@ import Foundation
33
import KeychainAccess
44
import NetworkExtension
55
import SwiftUI
6+
import CoderSDK
67

8+
@MainActor
79
class AppState: ObservableObject {
810
let appId = Bundle.main.bundleIdentifier!
911

@@ -94,6 +96,9 @@ class AppState: ObservableObject {
9496
)
9597
if hasSession {
9698
_sessionToken = Published(initialValue: keychainGet(for: Keys.sessionToken))
99+
if sessionToken == nil || sessionToken!.isEmpty == true {
100+
hasSession = false
101+
}
97102
}
98103
}
99104

@@ -104,6 +109,23 @@ class AppState: ObservableObject {
104109
reconfigure()
105110
}
106111

112+
public func handleTokenExpiry() async {
113+
if hasSession {
114+
let client = Client(url: self.baseAccessURL!, token: self.sessionToken!)
115+
do {
116+
_ = try await client.user("me")
117+
} catch let ClientError.api(apiErr) {
118+
// Expired token
119+
if apiErr.statusCode == 401 {
120+
clearSession()
121+
}
122+
} catch {
123+
// Some other failure, we'll show an error if they try and do something
124+
return
125+
}
126+
}
127+
}
128+
107129
public func clearSession() {
108130
hasSession = false
109131
sessionToken = nil

Coder Desktop/CoderSDK/Client.swift

+4-4
Original file line numberDiff line numberDiff line change
@@ -104,10 +104,10 @@ public struct Client {
104104
}
105105

106106
public struct APIError: Decodable, Sendable {
107-
let response: Response
108-
let statusCode: Int
109-
let method: String
110-
let url: URL
107+
public let response: Response
108+
public let statusCode: Int
109+
public let method: String
110+
public let url: URL
111111

112112
var description: String {
113113
var components = ["\(method) \(url.absoluteString)\nUnexpected status code \(statusCode):\n\(response.message)"]

0 commit comments

Comments
 (0)