1
1
const superagent = require ( 'superagent' )
2
2
3
3
class Auth {
4
- constructor ( authUrl , supabaseKey , options = { } ) {
4
+ constructor ( authUrl , supabaseKey , options = { autoRefreshToken : true } ) {
5
5
this . authUrl = authUrl
6
6
this . accessToken = null
7
7
this . refreshToken = null
8
8
this . supabaseKey = supabaseKey
9
9
this . currentUser = null
10
+ this . autoRefreshToken = options . autoRefreshToken
10
11
11
12
this . signup = async ( email , password ) => {
12
13
const { body } = await superagent
@@ -18,13 +19,32 @@ class Auth {
18
19
}
19
20
20
21
this . login = async ( email , password ) => {
22
+
21
23
const response = await superagent
22
- . post ( `${ authUrl } /token?grant_type=password&username=${ email } &password=${ password } ` )
24
+ . post ( `${ authUrl } /token?grant_type=password` , { email, password } )
25
+ . set ( 'accept' , 'json' )
26
+ . set ( 'apikey' , this . supabaseKey )
27
+
28
+ if ( response . status === 200 ) {
29
+ this . accessToken = response . body [ 'access_token' ]
30
+ this . refreshToken = response . body [ 'refresh_token' ]
31
+ if ( this . autoRefreshToken && tokenExirySeconds )
32
+ setTimeout ( this . refreshToken , tokenExirySeconds - 60 )
33
+ }
34
+ return response
35
+ }
36
+
37
+ this . refreshToken = async ( ) => {
38
+ const response = await superagent
39
+ . post ( `${ authUrl } /token?grant_type=refresh_token` , { refresh_token : this . refreshToken } )
23
40
. set ( 'apikey' , this . supabaseKey )
24
41
25
42
if ( response . status === 200 ) {
26
43
this . accessToken = response . body [ 'access_token' ]
27
44
this . refreshToken = response . body [ 'refresh_token' ]
45
+ let tokenExirySeconds = response . body [ 'expires_in' ]
46
+ if ( this . autoRefreshToken && tokenExirySeconds )
47
+ setTimeout ( this . refreshToken , tokenExirySeconds - 60 )
28
48
}
29
49
return response
30
50
}
@@ -39,6 +59,14 @@ class Auth {
39
59
this . accessToken = null
40
60
}
41
61
62
+ // this.setRefreshTokenExpiry = (refreshTokenExpirySeconds) => {
63
+ // let bufferSeconds = 60
64
+ // let t = new Date() // current time
65
+ // this.refreshTokenExpiry = t.setSeconds(
66
+ // t.getSeconds() + (refreshTokenExpirySeconds - bufferSeconds)
67
+ // )
68
+ // }
69
+
42
70
this . user = async ( ) => {
43
71
if ( this . currentUser ) return this . currentUser
44
72
0 commit comments