-
Notifications
You must be signed in to change notification settings - Fork 7
/
auth.ts
50 lines (45 loc) · 1.54 KB
/
auth.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import { AxiosInstance, AxiosResponse } from 'axios';
import { SiweMessage } from 'siwe';
import { cacheConfigs } from '../../config';
import { SignerService } from '../signer';
import { AuthTokens, SiweOptions } from './cache-client.types';
/**
* Provides authentication methods to ssi-hub
*
* @todo Move here authentication parts of `CacheClient`
* @todo Make this class top-level module in order to use in application
*/
export class SsiAuth {
private readonly config: SiweOptions;
constructor(
private signerService: SignerService,
private http: AxiosInstance
) {
this.config = cacheConfigs()[this.signerService.chainId].auth;
}
/**
* Signs in to ssi-hub. Authentication method configurations are looked for in `cacheConfigs`
*
* @returns authentication tokens
*/
async signIn(): Promise<AxiosResponse<AuthTokens>> {
const {
data: { nonce },
} = await this.http.post<{ nonce: string }>('/login/siwe/initiate');
const siweMessage = new SiweMessage({
statement: `I accept the Terms of Service: ${this.config.domain}`,
nonce,
domain: new URL(this.config.domain).host,
address: this.signerService.address,
uri: `${cacheConfigs()[this.signerService.chainId].url}login/siwe/verify`,
version: '1',
chainId: this.signerService.chainId,
});
const message = siweMessage.prepareMessage();
const signature = await this.signerService.signer.signMessage(message);
return this.http.post<AuthTokens>('/login/siwe/verify', {
message,
signature,
});
}
}