1 | const baseURL = "https://auth.oneidtech.com/auth";
|
2 |
|
3 | class OneID {
|
4 | private static _apiKey: string;
|
5 |
|
6 | static start({ apiKey }: { apiKey: string }) {
|
7 | if (!apiKey) {
|
8 | throw new Error("apiKey is required");
|
9 | }
|
10 | this._apiKey = apiKey;
|
11 | }
|
12 |
|
13 | static get apiKey() {
|
14 | if (!this._apiKey) {
|
15 | throw new Error("apiKey is not set, please call start() first");
|
16 | }
|
17 | return this._apiKey;
|
18 | }
|
19 | }
|
20 |
|
21 | export const start = OneID.start.bind(OneID);
|
22 |
|
23 | export function handleAuth(): Promise<{ token: string; user: User }> {
|
24 | let width = 760;
|
25 | let height = 760;
|
26 | const y = window.top.outerHeight / 2 + window.top.screenY - height / 2;
|
27 | const x = window.top.outerWidth / 2 + window.top.screenX - width / 2;
|
28 | const w = window.open(
|
29 | `${baseURL}?type=login&callback=${window.location.origin}&api_key=${OneID.apiKey}`,
|
30 | "auth",
|
31 | `width=${width},height=${height},scrollbars=no,status=no,toolbar=no,menubar=no,location=no,resizable=no,dependent=no,dialog=no,top=${y}, left=${x}`
|
32 | );
|
33 | w?.focus();
|
34 |
|
35 | return new Promise((resolve, reject) => {
|
36 | const anotherInterval = setInterval(() => {
|
37 | try {
|
38 | let searchParams = new URLSearchParams(w?.location?.search);
|
39 | if (searchParams.get("token") && searchParams.get("user")) {
|
40 | let token = searchParams.get("token")!;
|
41 | let userString = searchParams.get("user")!;
|
42 | const user = JSON.parse(userString);
|
43 | clearInterval(anotherInterval);
|
44 | resolve({
|
45 | token,
|
46 | user,
|
47 | });
|
48 | w?.close();
|
49 | }
|
50 | } catch (e) {
|
51 |
|
52 |
|
53 | }
|
54 | }, 300);
|
55 |
|
56 | const interval = setInterval(() => {
|
57 | if (w?.closed) {
|
58 | clearInterval(anotherInterval);
|
59 | clearInterval(interval);
|
60 | return reject("window closed");
|
61 | }
|
62 | });
|
63 | });
|
64 | }
|
65 |
|
66 | export interface User {
|
67 | _id: string;
|
68 | username: string;
|
69 | oneId: string;
|
70 | email: string;
|
71 | isVerified: boolean;
|
72 | fullName?: string;
|
73 | gender?: string;
|
74 | dob?: string;
|
75 | phone?: string;
|
76 | maritalStatus?: string;
|
77 | primaryAddress?: string;
|
78 | secondaryAddress?: string;
|
79 | country?: string;
|
80 | postalCode?: string;
|
81 | [key: string]: any;
|
82 | }
|