2018-03-08 09:41:39 +01:00
|
|
|
import Mastodon from 'mastodon-api'
|
|
|
|
|
2018-05-15 16:13:52 +02:00
|
|
|
const appName = 'Whalebird'
|
2018-05-19 09:41:44 +02:00
|
|
|
const appURL = 'https://whalebird.org'
|
2018-03-08 09:41:39 +01:00
|
|
|
const scope = 'read write follow'
|
|
|
|
|
|
|
|
export default class Authentication {
|
2018-04-01 14:43:23 +02:00
|
|
|
constructor (accountDB) {
|
|
|
|
this.db = accountDB
|
2018-03-08 16:24:18 +01:00
|
|
|
this.baseURL = ''
|
2018-03-10 16:48:40 +01:00
|
|
|
this.domain = ''
|
2018-03-08 09:41:39 +01:00
|
|
|
this.clientId = ''
|
|
|
|
this.clientSecret = ''
|
2018-03-10 16:48:40 +01:00
|
|
|
this.protocol = 'https'
|
2018-03-08 09:41:39 +01:00
|
|
|
}
|
|
|
|
|
2018-03-10 16:48:40 +01:00
|
|
|
setOtherInstance (domain) {
|
|
|
|
this.baseURL = `${this.protocol}://${domain}`
|
|
|
|
this.domain = domain
|
2018-03-08 16:24:18 +01:00
|
|
|
this.clientId = ''
|
|
|
|
this.clientSecret = ''
|
2018-03-08 16:33:43 +01:00
|
|
|
}
|
|
|
|
|
2018-04-01 14:58:57 +02:00
|
|
|
async getAuthorizationUrl (domain = 'mastodon.social') {
|
2018-03-10 16:48:40 +01:00
|
|
|
this.setOtherInstance(domain)
|
2018-05-19 09:41:44 +02:00
|
|
|
const res = await Mastodon.createOAuthApp(
|
|
|
|
this.baseURL + '/api/v1/apps',
|
|
|
|
appName,
|
|
|
|
scope,
|
|
|
|
'urn:ietf:wg:oauth:2.0:oob',
|
|
|
|
appURL
|
|
|
|
)
|
2018-04-01 14:58:57 +02:00
|
|
|
this.clientId = res.client_id
|
|
|
|
this.clientSecret = res.client_secret
|
2018-03-08 09:41:39 +01:00
|
|
|
|
2018-04-01 15:48:54 +02:00
|
|
|
const count = await this.db.countAuthorizedAccounts()
|
2018-04-01 14:58:57 +02:00
|
|
|
const json = {
|
|
|
|
baseURL: this.baseURL,
|
|
|
|
domain: this.domain,
|
|
|
|
clientId: this.clientId,
|
|
|
|
clientSecret: this.clientSecret,
|
|
|
|
accessToken: '',
|
|
|
|
username: '',
|
2018-04-01 15:48:54 +02:00
|
|
|
accountId: '',
|
2018-04-22 08:48:20 +02:00
|
|
|
avatar: '',
|
2018-04-01 15:48:54 +02:00
|
|
|
order: count + 1
|
2018-04-01 14:58:57 +02:00
|
|
|
}
|
|
|
|
await this.db.insertAccount(json)
|
|
|
|
const url = await Mastodon.getAuthorizationUrl(this.clientId, this.clientSecret, this.baseURL)
|
|
|
|
return url
|
2018-03-08 09:41:39 +01:00
|
|
|
}
|
|
|
|
|
2018-04-01 14:58:57 +02:00
|
|
|
async getAccessToken (code) {
|
|
|
|
const token = await Mastodon.getAccessToken(this.clientId, this.clientSecret, code, this.baseURL)
|
|
|
|
const search = {
|
|
|
|
baseURL: this.baseURL,
|
|
|
|
domain: this.domain,
|
|
|
|
clientId: this.clientId,
|
|
|
|
clientSecret: this.clientSecret
|
|
|
|
}
|
|
|
|
const rec = await this.db.searchAccount(search)
|
|
|
|
await this.db.updateAccount(rec._id, { accessToken: token })
|
|
|
|
return token
|
2018-03-08 09:41:39 +01:00
|
|
|
}
|
2018-03-08 10:00:33 +01:00
|
|
|
// TODO: Refresh access token when expired
|
2018-03-08 09:41:39 +01:00
|
|
|
}
|