-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathauth.js
116 lines (100 loc) · 3.37 KB
/
auth.js
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
import { Clerk } from '@clerk/clerk-js'
import { createApp, defineAsyncComponent } from 'vue'
export class AuthService {
constructor(args) {
this.authMode = ['clerk', 'basic', 'none'].includes(args.authMode) ? args.authMode : 'none'
this.copilotBackend = args.copilotBackend
this.clerkPublicKey = args.clerkPublicKey
}
async signIn(password = null) {
if (this.authMode === 'clerk') {
return this.clerkSignIn()
}
if (this.authMode === 'basic') {
if (sessionStorage.getItem('copilot_auth_token')) {
return { authenticated: true, token: sessionStorage.getItem('copilot_auth_token') }
}
if (password) {
return this.basicSignIn(password)
}
return this.basicSignIn()
}
return {}
}
async clerkSignIn() {
const clerk = new Clerk(this.clerkPublicKey)
await clerk.load()
if (!clerk.user) {
clerk.openSignIn({
appearance: {
socialButtonsVariant: "iconButton",
elements: {
card: {
boxShadow: 'none',
},
modalCloseButton: {
display: 'none'
},
footerAction: {
display: 'none'
},
}
},
})
await new Promise(resolve => {
clerk.addListener(({ user }) => {
if (user) resolve()
})
})
}
return clerk.user
}
async fetchBasicAuth(password) {
if (!password) {
throw new Error('Password required')
}
const response = await fetch(`${this.copilotBackend}/auth`, {
method: 'POST',
// credentials: 'include',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${password}`
},
body: JSON.stringify({
messages: [{
"role": "user",
"content": "Authenticate"
}]
})
})
const token = await response.text()
if (response.status !== 200 || !token) {
throw new Error('Authentication failed')
}
sessionStorage.setItem('copilot_auth_token', token)
return { authenticated: true, token: token}
}
async basicSignIn() {
sessionStorage.removeItem('copilot_auth_token')
return new Promise((resolve, reject) => {
const modalContainer = document.createElement('div')
document.body.appendChild(modalContainer)
const BasicAuthWindow = defineAsyncComponent(() =>
import('../components/BasicAuthWindow.vue')
)
const authApp = createApp(BasicAuthWindow, {
'onSubmit': async (password) => {
try {
const user = await this.fetchBasicAuth(password)
authApp.unmount()
document.body.removeChild(modalContainer)
resolve(user)
} catch (error) {
throw error
}
}
})
authApp.mount(modalContainer)
})
}
}