Files
keyboard/Shared/KBAuthManager.h
2025-10-31 16:06:54 +08:00

57 lines
2.2 KiB
Objective-C
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

//
// KBAuthManager.h
// 主 App 与键盘扩展共享使用
//
// 通过 Keychain Sharing 统一管理用户登录态access/refresh token
// 线程安全;在保存/清空时同时发送进程内通知与 Darwin 跨进程通知,
// 以便键盘扩展正运行在其他 App 时也能及时感知变更。
//
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
/// Darwin 跨进程通知名称:当令牌更新或清除时发送,用于提示 App/扩展刷新缓存。
extern NSString * const kKBDarwinAuthChanged;
/// 进程内通知NSNotificationCenter令牌更新或清除时发送。
extern NSNotificationName const KBAuthChangedNotification;
/// 简单的会话容器;可按需扩展字段。
@interface KBAuthSession : NSObject <NSSecureCoding>
@property (nonatomic, copy, nullable) NSString *accessToken;
@property (nonatomic, copy, nullable) NSString *refreshToken;
@property (nonatomic, strong, nullable) NSDate *expiryDate; // 可选:过期时间
@property (nonatomic, copy, nullable) NSString *userIdentifier; // 可选:如“用 Apple 登录”的 userIdentifier
@end
/// 基于“共享钥匙串”的鉴权管理器(使用 Keychain Sharing 访问组)。
@interface KBAuthManager : NSObject
+ (instancetype)shared;
/// 当前会话(内存缓存),在加载/保存/清除后更新。
@property (atomic, strong, readonly, nullable) KBAuthSession *current;
/// 是否已登录:存在 accessToken 且未明显过期(未设置过期时间则只要有 token 即视为已登录)。
- (BOOL)isLoggedIn;
/// 从钥匙串加载到内存;通常首次访问时会自动加载。
- (void)reloadFromKeychain;
/// 保存令牌到“共享钥匙串”并通知观察者。
- (BOOL)saveAccessToken:(NSString *)accessToken
refreshToken:(nullable NSString *)refreshToken
expiryDate:(nullable NSDate *)expiryDate
userIdentifier:(nullable NSString *)userIdentifier;
/// 从钥匙串与内存中清除令牌,并通知观察者。
- (void)signOut;
/// 便捷方法:若存在有效令牌,返回 `Authorization` 请求头;否则返回空字典。
- (NSDictionary<NSString *, NSString *> *)authorizationHeader;
@end
NS_ASSUME_NONNULL_END