Skip to content

Commit 0617964

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

File tree

3 files changed

+29
-4
lines changed

3 files changed

+29
-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

+21
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import KeychainAccess
44
import NetworkExtension
55
import SwiftUI
66

7+
@MainActor
78
class AppState: ObservableObject {
89
let appId = Bundle.main.bundleIdentifier!
910

@@ -94,6 +95,9 @@ class AppState: ObservableObject {
9495
)
9596
if hasSession {
9697
_sessionToken = Published(initialValue: keychainGet(for: Keys.sessionToken))
98+
if sessionToken == nil || sessionToken!.isEmpty == true {
99+
hasSession = false
100+
}
97101
}
98102
}
99103

@@ -104,6 +108,23 @@ class AppState: ObservableObject {
104108
reconfigure()
105109
}
106110

111+
public func handleTokenExpiry() async {
112+
if hasSession {
113+
let client = Client(url: baseAccessURL!, token: sessionToken!)
114+
do {
115+
_ = try await client.user("me")
116+
} catch let ClientError.api(apiErr) {
117+
// Expired token
118+
if apiErr.statusCode == 401 {
119+
clearSession()
120+
}
121+
} catch {
122+
// Some other failure, we'll show an error if they try and do something
123+
return
124+
}
125+
}
126+
}
127+
107128
public func clearSession() {
108129
hasSession = false
109130
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)