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

84 lines
2.3 KiB
JavaScript
Raw Normal View History

2018-03-08 09:41:39 +01:00
import Mastodon from 'mastodon-api'
import log from 'electron-log'
2018-03-08 09:41:39 +01:00
const appName = 'whalebird'
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
}
2018-03-10 16:48:40 +01:00
getAuthorizationUrl (domain = 'mastodon.social') {
this.setOtherInstance(domain)
return new Promise((resolve, reject) => {
Mastodon.createOAuthApp(this.baseURL + '/api/v1/apps', appName, scope)
.catch(err => log.error(err))
.then((res) => {
this.clientId = res.client_id
this.clientSecret = res.client_secret
2018-03-08 09:41:39 +01:00
// TODO: Save order number
const json = {
baseURL: this.baseURL,
domain: this.domain,
clientId: this.clientId,
clientSecret: this.clientSecret,
accessToken: '',
username: '',
accountId: ''
}
this.db.insertAccount(json)
.then((doc) => {
Mastodon.getAuthorizationUrl(this.clientId, this.clientSecret, this.baseURL)
.then((url) => {
resolve(url)
})
.catch((err) => {
reject(err)
})
})
.catch((err) => {
reject(err)
})
2018-03-08 10:00:33 +01:00
})
})
2018-03-08 09:41:39 +01:00
}
getAccessToken (code) {
2018-03-08 10:00:33 +01:00
return new Promise((resolve, reject) => {
Mastodon.getAccessToken(this.clientId, this.clientSecret, code, this.baseURL)
.catch(err => reject(err))
.then((token) => {
const search = {
baseURL: this.baseURL,
2018-03-10 16:48:40 +01:00
domain: this.domain,
clientId: this.clientId,
clientSecret: this.clientSecret
}
this.db.searchAccount(search)
.then((rec) => {
this.db.updateAccount(rec._id, { accessToken: token })
.then((doc) => {
resolve(token)
})
.catch(err => reject(err))
})
2018-03-08 10:00:33 +01:00
})
})
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
}