Merge pull request #925 from h3poteto/iss-859
refs #859 Update access token using refresh token when expire the token
This commit is contained in:
commit
4ecec106e7
|
@ -1,6 +1,7 @@
|
|||
import { isEmpty } from 'lodash'
|
||||
import Mastodon, { Account as RemoteAccount } from 'megalodon'
|
||||
import Datastore from 'nedb'
|
||||
import log from 'electron-log'
|
||||
import LocalAccount from '~/src/types/localAccount'
|
||||
|
||||
export default class Account {
|
||||
|
@ -19,10 +20,10 @@ export default class Account {
|
|||
updateUnique(): Promise<{}> {
|
||||
return new Promise((resolve, reject) => {
|
||||
// At first, remove old index.
|
||||
this.db.removeIndex('order', (err) => {
|
||||
this.db.removeIndex('order', err => {
|
||||
if (err) reject(err)
|
||||
// Add unique index.
|
||||
this.db.ensureIndex({ fieldName: 'order', unique: true, sparse: true }, (err) => {
|
||||
this.db.ensureIndex({ fieldName: 'order', unique: true, sparse: true }, err => {
|
||||
if (err) reject(err)
|
||||
resolve({})
|
||||
})
|
||||
|
@ -35,10 +36,12 @@ export default class Account {
|
|||
*/
|
||||
async reorder() {
|
||||
const accounts = await this.listAllAccounts()
|
||||
await Promise.all(accounts.map(async (account, index) => {
|
||||
await Promise.all(
|
||||
accounts.map(async (account, index) => {
|
||||
const update = await this.updateAccount(account._id!, Object.assign(account, { order: index + 1 }))
|
||||
return update
|
||||
}))
|
||||
})
|
||||
)
|
||||
const ordered = await this.listAllAccounts()
|
||||
return ordered
|
||||
}
|
||||
|
@ -52,10 +55,12 @@ export default class Account {
|
|||
return accounts.length
|
||||
}
|
||||
if (accounts[0].order < 1 || accounts[accounts.length - 1].order > accounts.length) {
|
||||
await Promise.all(accounts.map(async (element, index) => {
|
||||
await Promise.all(
|
||||
accounts.map(async (element, index) => {
|
||||
const update = await this.updateAccount(element._id!, Object.assign(element, { order: index + 1 }))
|
||||
return update
|
||||
}))
|
||||
})
|
||||
)
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
@ -75,7 +80,10 @@ export default class Account {
|
|||
*/
|
||||
listAllAccounts(order = 1): Promise<Array<LocalAccount>> {
|
||||
return new Promise((resolve, reject) => {
|
||||
this.db.find<LocalAccount>({}).sort({ order: order }).exec((err, docs) => {
|
||||
this.db
|
||||
.find<LocalAccount>({})
|
||||
.sort({ order: order })
|
||||
.exec((err, docs) => {
|
||||
if (err) return reject(err)
|
||||
if (isEmpty(docs)) return reject(new EmptyRecordError('empty'))
|
||||
resolve(docs)
|
||||
|
@ -88,7 +96,10 @@ export default class Account {
|
|||
*/
|
||||
listAccounts(): Promise<Array<LocalAccount>> {
|
||||
return new Promise((resolve, reject) => {
|
||||
this.db.find<LocalAccount>({ accessToken: { $ne: '' } }).sort({ order: 1 }).exec((err, docs) => {
|
||||
this.db
|
||||
.find<LocalAccount>({ accessToken: { $ne: '' } })
|
||||
.sort({ order: 1 })
|
||||
.exec((err, docs) => {
|
||||
if (err) return reject(err)
|
||||
if (isEmpty(docs)) return reject(new EmptyRecordError('empty'))
|
||||
resolve(docs)
|
||||
|
@ -119,9 +130,7 @@ export default class Account {
|
|||
|
||||
searchAccount(obj: any): Promise<LocalAccount> {
|
||||
return new Promise((resolve, reject) => {
|
||||
this.db.findOne<LocalAccount>(
|
||||
obj,
|
||||
(err, doc) => {
|
||||
this.db.findOne<LocalAccount>(obj, (err, doc) => {
|
||||
if (err) return reject(err)
|
||||
if (isEmpty(doc)) return reject(new EmptyRecordError('empty'))
|
||||
resolve(doc)
|
||||
|
@ -131,7 +140,10 @@ export default class Account {
|
|||
|
||||
searchAccounts(obj: any, order = 1): Promise<Array<LocalAccount>> {
|
||||
return new Promise((resolve, reject) => {
|
||||
this.db.find<LocalAccount>(obj).sort({ order: order }).exec((err, docs) => {
|
||||
this.db
|
||||
.find<LocalAccount>(obj)
|
||||
.sort({ order: order })
|
||||
.exec((err, docs) => {
|
||||
if (err) return reject(err)
|
||||
resolve(docs)
|
||||
})
|
||||
|
@ -156,7 +168,8 @@ export default class Account {
|
|||
if (err) return reject(err)
|
||||
if (isEmpty(doc)) return reject(new EmptyRecordError('empty'))
|
||||
resolve(doc)
|
||||
})
|
||||
}
|
||||
)
|
||||
}
|
||||
)
|
||||
})
|
||||
|
@ -179,21 +192,16 @@ export default class Account {
|
|||
|
||||
removeAll(): Promise<number> {
|
||||
return new Promise((resolve, reject) => {
|
||||
this.db.remove(
|
||||
{},
|
||||
{ multi: true },
|
||||
(err, numRemoved) => {
|
||||
this.db.remove({}, { multi: true }, (err, numRemoved) => {
|
||||
if (err) return reject(err)
|
||||
resolve(numRemoved)
|
||||
}
|
||||
)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
async forwardAccount(ac: LocalAccount): Promise<LocalAccount | {}> {
|
||||
// Find account which is the previous of the target account.
|
||||
const accounts = await this.searchAccounts({ order: { $lt: ac.order } }, -1)
|
||||
.catch((err) => {
|
||||
const accounts = await this.searchAccounts({ order: { $lt: ac.order } }, -1).catch(err => {
|
||||
console.log(err)
|
||||
return []
|
||||
})
|
||||
|
@ -206,33 +214,32 @@ export default class Account {
|
|||
|
||||
// At first, we need to update the previous account with dummy order.
|
||||
// Because this column is uniqued, so can not update with same order.
|
||||
await this.updateAccount(previousAccount._id!, Object.assign(
|
||||
previousAccount,
|
||||
{
|
||||
await this.updateAccount(
|
||||
previousAccount._id!,
|
||||
Object.assign(previousAccount, {
|
||||
order: -1
|
||||
}
|
||||
))
|
||||
})
|
||||
)
|
||||
// Change order of the target account.
|
||||
const updated = await this.updateAccount(ac._id!, Object.assign(
|
||||
ac,
|
||||
{
|
||||
const updated = await this.updateAccount(
|
||||
ac._id!,
|
||||
Object.assign(ac, {
|
||||
order: previousOrder
|
||||
}
|
||||
))
|
||||
})
|
||||
)
|
||||
// Update the previous account with right order.
|
||||
await this.updateAccount(previousAccount._id!, Object.assign(
|
||||
previousAccount,
|
||||
{
|
||||
await this.updateAccount(
|
||||
previousAccount._id!,
|
||||
Object.assign(previousAccount, {
|
||||
order: targetOrder
|
||||
}
|
||||
))
|
||||
})
|
||||
)
|
||||
return updated
|
||||
}
|
||||
|
||||
async backwardAccount(ac: LocalAccount): Promise<LocalAccount | {}> {
|
||||
// Find account which is the next of the target account.
|
||||
const accounts = await this.searchAccounts({ order: { $gt: ac.order } }, 1)
|
||||
.catch((err) => {
|
||||
const accounts = await this.searchAccounts({ order: { $gt: ac.order } }, 1).catch(err => {
|
||||
console.log(err)
|
||||
return []
|
||||
})
|
||||
|
@ -245,26 +252,26 @@ export default class Account {
|
|||
|
||||
// At first, we need to update the next account with dummy order.
|
||||
// Because this colum is uniqued, so can not update with same order.
|
||||
await this.updateAccount(nextAccount._id!, Object.assign(
|
||||
nextAccount,
|
||||
{
|
||||
await this.updateAccount(
|
||||
nextAccount._id!,
|
||||
Object.assign(nextAccount, {
|
||||
order: -1
|
||||
}
|
||||
))
|
||||
})
|
||||
)
|
||||
// Change order of the target account/
|
||||
const updated = await this.updateAccount(ac._id!, Object.assign(
|
||||
ac,
|
||||
{
|
||||
const updated = await this.updateAccount(
|
||||
ac._id!,
|
||||
Object.assign(ac, {
|
||||
order: nextOrder
|
||||
}
|
||||
))
|
||||
})
|
||||
)
|
||||
// Update the next account with right order.
|
||||
await this.updateAccount(nextAccount._id!, Object.assign(
|
||||
nextAccount,
|
||||
{
|
||||
await this.updateAccount(
|
||||
nextAccount._id!,
|
||||
Object.assign(nextAccount, {
|
||||
order: targetOrder
|
||||
}
|
||||
))
|
||||
})
|
||||
)
|
||||
return updated
|
||||
}
|
||||
|
||||
|
@ -273,35 +280,54 @@ export default class Account {
|
|||
if (accounts.length < 1) {
|
||||
return accounts
|
||||
}
|
||||
const results = await Promise.all(accounts.map(async (account) => {
|
||||
const results = await Promise.all(
|
||||
accounts.map(async account => {
|
||||
const refresh = await this.refresh(account)
|
||||
return refresh
|
||||
}))
|
||||
})
|
||||
)
|
||||
return results
|
||||
}
|
||||
|
||||
/**
|
||||
* refresh: Refresh an account which is already saved at local
|
||||
* @param {LocalAccount} account is an local account
|
||||
* @return {LocalAccount} updated account
|
||||
*/
|
||||
async refresh(account: LocalAccount): Promise<LocalAccount> {
|
||||
const client = new Mastodon(
|
||||
account.accessToken!,
|
||||
account.baseURL + '/api/v1'
|
||||
)
|
||||
return client.get<RemoteAccount>('/accounts/verify_credentials')
|
||||
.then(res => {
|
||||
const json = {
|
||||
let client = new Mastodon(account.accessToken!, account.baseURL + '/api/v1')
|
||||
let json = {}
|
||||
try {
|
||||
const res = await client.get<RemoteAccount>('/accounts/verify_credentials')
|
||||
json = {
|
||||
username: res.data.username,
|
||||
accountId: res.data.id,
|
||||
avatar: res.data.avatar
|
||||
}
|
||||
} catch (err) {
|
||||
log.error(err)
|
||||
log.info('Get new access token using refresh token...')
|
||||
// If failed to fetch account, get new access token usign refresh token.
|
||||
if (!account.refreshToken) {
|
||||
throw new RefreshTokenDoesNotExist()
|
||||
}
|
||||
const token = await Mastodon.refreshToken(account.clientId, account.clientSecret, account.refreshToken, account.baseURL)
|
||||
client = new Mastodon(token.access_token, account.baseURL + '/api/v1')
|
||||
const res = await client.get<RemoteAccount>('/accounts/verify_credentials')
|
||||
json = {
|
||||
username: res.data.username,
|
||||
accountId: res.data.id,
|
||||
avatar: res.data.avatar,
|
||||
accessToken: token.accessToken,
|
||||
refreshToken: token.refreshToken
|
||||
}
|
||||
}
|
||||
return this.updateAccount(account._id!, json)
|
||||
})
|
||||
}
|
||||
|
||||
// Confirm the access token, and check duplicate
|
||||
async fetchAccount(account: LocalAccount, accessToken: string): Promise<RemoteAccount> {
|
||||
const client = new Mastodon(
|
||||
accessToken,
|
||||
account.baseURL + '/api/v1'
|
||||
)
|
||||
const client = new Mastodon(accessToken, account.baseURL + '/api/v1')
|
||||
const res = await client.get<RemoteAccount>('/accounts/verify_credentials')
|
||||
const query = {
|
||||
baseURL: account.baseURL,
|
||||
|
@ -318,3 +344,5 @@ export default class Account {
|
|||
class EmptyRecordError extends Error {}
|
||||
|
||||
class DuplicateRecordError extends Error {}
|
||||
|
||||
class RefreshTokenDoesNotExist extends Error {}
|
||||
|
|
|
@ -1,4 +1,4 @@
|
|||
import Mastodon from 'megalodon'
|
||||
import Mastodon, { OAuth } from 'megalodon'
|
||||
import Account from './account'
|
||||
import LocalAccount from '~/src/types/localAccount'
|
||||
|
||||
|
@ -33,7 +33,8 @@ export default class Authentication {
|
|||
async getAuthorizationUrl(domain = 'mastodon.social'): Promise<string> {
|
||||
this.setOtherInstance(domain)
|
||||
const res = await Mastodon.registerApp(
|
||||
appName, {
|
||||
appName,
|
||||
{
|
||||
scopes: scope,
|
||||
website: appURL
|
||||
},
|
||||
|
@ -42,9 +43,10 @@ export default class Authentication {
|
|||
this.clientId = res.clientId
|
||||
this.clientSecret = res.clientSecret
|
||||
|
||||
const order = await this.db.lastAccount()
|
||||
const order = await this.db
|
||||
.lastAccount()
|
||||
.then(account => account.order + 1)
|
||||
.catch((err) => {
|
||||
.catch(err => {
|
||||
console.log(err)
|
||||
return 1
|
||||
})
|
||||
|
@ -54,7 +56,7 @@ export default class Authentication {
|
|||
clientId: this.clientId,
|
||||
clientSecret: this.clientSecret,
|
||||
accessToken: '',
|
||||
refreshToken: '',
|
||||
refreshToken: null,
|
||||
username: '',
|
||||
accountId: null,
|
||||
avatar: '',
|
||||
|
@ -68,7 +70,7 @@ export default class Authentication {
|
|||
}
|
||||
|
||||
async getAccessToken(code: string): Promise<string> {
|
||||
const tokenData = await Mastodon.fetchAccessToken(this.clientId, this.clientSecret, code, this.baseURL)
|
||||
const tokenData: OAuth.TokenData = await Mastodon.fetchAccessToken(this.clientId, this.clientSecret, code, this.baseURL)
|
||||
const search = {
|
||||
baseURL: this.baseURL,
|
||||
domain: this.domain,
|
||||
|
@ -88,7 +90,6 @@ export default class Authentication {
|
|||
})
|
||||
return accessToken
|
||||
}
|
||||
// TODO: Refresh access token when expired
|
||||
}
|
||||
|
||||
class AuthenticationURLError extends Error {}
|
||||
|
|
Loading…
Reference in New Issue