添加登录功能
This commit is contained in:
commit
a3f61a29d0
120 files changed
+3974
No files matched your search
@@ -0,0 +1,34 @@
|
||||
import { GuestAccountStore, GuestError, GuestSession, TextStorage } from './GuestContracts';
|
||||
|
||||
/** 按产品和服务隔离身份,成功会话单独提交。 / Isolate identities by product/service and commit successful sessions separately. */
|
||||
export class GuestSessionStore implements GuestAccountStore {
|
||||
readonly identityKey: string;
|
||||
readonly sessionKey: string;
|
||||
constructor(private readonly storage: TextStorage, origin: string, product: string) {
|
||||
const scope = encodeURIComponent(`${origin.replace(/\/+$/, '')}|${product}`);
|
||||
this.identityKey = `fruit-pop.auth.identity.v1.${scope}`;
|
||||
this.sessionKey = `fruit-pop.auth.session.v1.${scope}`;
|
||||
}
|
||||
identity(create: () => string): string {
|
||||
try {
|
||||
const existing = this.storage.getItem(this.identityKey);
|
||||
const identity = existing ?? create();
|
||||
if (typeof identity !== 'string' || !/^[a-zA-Z0-9-]{16,128}$/.test(identity)) {
|
||||
throw new GuestError('identity', 'Unable to restore a secure guest identity.');
|
||||
}
|
||||
if (existing === null) this.writeVerified(this.identityKey, identity);
|
||||
return identity;
|
||||
} catch (error) { throw this.storageError(error); }
|
||||
}
|
||||
save(session: GuestSession): void {
|
||||
try { this.writeVerified(this.sessionKey, JSON.stringify(session)); }
|
||||
catch (error) { throw this.storageError(error); }
|
||||
}
|
||||
private writeVerified(key: string, text: string): void {
|
||||
this.storage.setItem(key, text);
|
||||
if (this.storage.getItem(key) !== text) throw new GuestError('storage', 'Unable to save guest data. Please retry.');
|
||||
}
|
||||
private storageError(error: unknown): GuestError {
|
||||
return error instanceof GuestError ? error : new GuestError('storage', 'Guest storage is unavailable. Please retry.');
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user