Whalebird-desktop-client-ma.../src/main/auth.js

67 lines
1.7 KiB
JavaScript
Raw Normal View History

import Mastodon from 'megalodon'
2018-03-08 09:41:39 +01:00
const appName = 'Whalebird'
const appURL = 'https://whalebird.org'
2018-03-08 09:41:39 +01:00
const scope = 'read write follow'
export default class Authentication {
constructor (accountDB) {
this.db = accountDB
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
this.clientId = ''
this.clientSecret = ''
2018-03-08 16:33:43 +01:00
}
async getAuthorizationUrl (domain = 'mastodon.social') {
2018-03-10 16:48:40 +01:00
this.setOtherInstance(domain)
const res = await Mastodon.registerApp(
appName, {
scopes: scope,
website: appURL
},
this.baseURL
)
this.clientId = res.clientId
this.clientSecret = res.clientSecret
2018-03-08 09:41:39 +01:00
const count = await this.db.countAuthorizedAccounts()
const json = {
baseURL: this.baseURL,
domain: this.domain,
clientId: this.clientId,
clientSecret: this.clientSecret,
accessToken: '',
username: '',
accountId: '',
avatar: '',
order: count + 1
}
await this.db.insertAccount(json)
return res.url
2018-03-08 09:41:39 +01:00
}
async getAccessToken (code) {
const token = await Mastodon.fetchAccessToken(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)
const accessToken = token.access_token
await this.db.updateAccount(rec._id, { accessToken: accessToken })
return accessToken
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
}