refs #174 Refactor auth.js to use async/await

This commit is contained in:
AkiraFukushima 2018-04-01 21:58:57 +09:00
parent 23623f6b99
commit 018cc91db1

View File

@ -1,5 +1,4 @@
import Mastodon from 'mastodon-api' import Mastodon from 'mastodon-api'
import log from 'electron-log'
const appName = 'whalebird' const appName = 'whalebird'
const scope = 'read write follow' const scope = 'read write follow'
@ -21,63 +20,38 @@ export default class Authentication {
this.clientSecret = '' this.clientSecret = ''
} }
getAuthorizationUrl (domain = 'mastodon.social') { async getAuthorizationUrl (domain = 'mastodon.social') {
this.setOtherInstance(domain) this.setOtherInstance(domain)
return new Promise((resolve, reject) => { const res = await Mastodon.createOAuthApp(this.baseURL + '/api/v1/apps', appName, scope)
Mastodon.createOAuthApp(this.baseURL + '/api/v1/apps', appName, scope) this.clientId = res.client_id
.catch(err => log.error(err)) this.clientSecret = res.client_secret
.then((res) => {
this.clientId = res.client_id
this.clientSecret = res.client_secret
// TODO: Save order number // TODO: Save order number
const json = { const json = {
baseURL: this.baseURL, baseURL: this.baseURL,
domain: this.domain, domain: this.domain,
clientId: this.clientId, clientId: this.clientId,
clientSecret: this.clientSecret, clientSecret: this.clientSecret,
accessToken: '', accessToken: '',
username: '', username: '',
accountId: '' accountId: ''
} }
this.db.insertAccount(json) await this.db.insertAccount(json)
.then((doc) => { const url = await Mastodon.getAuthorizationUrl(this.clientId, this.clientSecret, this.baseURL)
Mastodon.getAuthorizationUrl(this.clientId, this.clientSecret, this.baseURL) return url
.then((url) => {
resolve(url)
})
.catch((err) => {
reject(err)
})
})
.catch((err) => {
reject(err)
})
})
})
} }
getAccessToken (code) { async getAccessToken (code) {
return new Promise((resolve, reject) => { const token = await Mastodon.getAccessToken(this.clientId, this.clientSecret, code, this.baseURL)
Mastodon.getAccessToken(this.clientId, this.clientSecret, code, this.baseURL) const search = {
.catch(err => reject(err)) baseURL: this.baseURL,
.then((token) => { domain: this.domain,
const search = { clientId: this.clientId,
baseURL: this.baseURL, clientSecret: this.clientSecret
domain: this.domain, }
clientId: this.clientId, const rec = await this.db.searchAccount(search)
clientSecret: this.clientSecret await this.db.updateAccount(rec._id, { accessToken: token })
} return token
this.db.searchAccount(search)
.then((rec) => {
this.db.updateAccount(rec._id, { accessToken: token })
.then((doc) => {
resolve(token)
})
.catch(err => reject(err))
})
})
})
} }
// TODO: Refresh access token when expired // TODO: Refresh access token when expired
} }