refs #859 Check credentials and update token when launch application

This commit is contained in:
AkiraFukushima 2019-05-22 22:52:40 +09:00
parent b547e09b93
commit e76d72dc79
2 changed files with 152 additions and 138 deletions

View File

@ -1,28 +1,29 @@
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 {
private db: Datastore
constructor (db: Datastore) {
constructor(db: Datastore) {
this.db = db
}
async initialize () {
async initialize() {
await this.cleanup()
await this.reorder()
await this.updateUnique()
}
updateUnique (): Promise<{}> {
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({})
})
@ -33,12 +34,14 @@ export default class Account {
/**
* Reorder accounts, because sometimes the order of accounts is duplicated.
*/
async reorder () {
async reorder() {
const accounts = await this.listAllAccounts()
await Promise.all(accounts.map(async (account, index) => {
const update = await this.updateAccount(account._id!, Object.assign(account, { order: index + 1 }))
return update
}))
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
}
@ -46,21 +49,23 @@ export default class Account {
/**
* Check order of all accounts, and fix if order is negative value or over the length.
*/
async cleanup () {
async cleanup() {
const accounts = await this.listAccounts()
if (accounts.length < 1) {
return accounts.length
}
if (accounts[0].order < 1 || accounts[accounts.length - 1].order > accounts.length) {
await Promise.all(accounts.map(async (element, index) => {
const update = await this.updateAccount(element._id!, Object.assign(element, { order: index + 1 }))
return update
}))
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
}
insertAccount (localAccount: LocalAccount): Promise<LocalAccount> {
insertAccount(localAccount: LocalAccount): Promise<LocalAccount> {
return new Promise((resolve, reject) => {
this.db.insert<LocalAccount>(localAccount, (err, doc) => {
if (err) return reject(err)
@ -73,36 +78,42 @@ export default class Account {
/**
* List up all accounts either authenticated or not authenticated.
*/
listAllAccounts (order = 1): Promise<Array<LocalAccount>> {
listAllAccounts(order = 1): Promise<Array<LocalAccount>> {
return new Promise((resolve, reject) => {
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)
})
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)
})
})
}
/**
* List up authenticated accounts.
*/
listAccounts (): Promise<Array<LocalAccount>> {
listAccounts(): Promise<Array<LocalAccount>> {
return new Promise((resolve, reject) => {
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)
})
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)
})
})
}
// Get the last account.
async lastAccount (): Promise<LocalAccount> {
async lastAccount(): Promise<LocalAccount> {
const accounts = await this.listAllAccounts(-1)
return accounts[0]
}
getAccount (id: string): Promise<LocalAccount> {
getAccount(id: string): Promise<LocalAccount> {
return new Promise((resolve, reject) => {
this.db.findOne<LocalAccount>(
{
@ -117,28 +128,29 @@ export default class Account {
})
}
searchAccount (obj: any): Promise<LocalAccount> {
searchAccount(obj: any): Promise<LocalAccount> {
return new Promise((resolve, reject) => {
this.db.findOne<LocalAccount>(
obj,
(err, doc) => {
if (err) return reject(err)
if (isEmpty(doc)) return reject(new EmptyRecordError('empty'))
resolve(doc)
})
})
}
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.findOne<LocalAccount>(obj, (err, doc) => {
if (err) return reject(err)
resolve(docs)
if (isEmpty(doc)) return reject(new EmptyRecordError('empty'))
resolve(doc)
})
})
}
updateAccount (id: string, obj: any): Promise<LocalAccount> {
searchAccounts(obj: any, order = 1): Promise<Array<LocalAccount>> {
return new Promise((resolve, reject) => {
this.db
.find<LocalAccount>(obj)
.sort({ order: order })
.exec((err, docs) => {
if (err) return reject(err)
resolve(docs)
})
})
}
updateAccount(id: string, obj: any): Promise<LocalAccount> {
return new Promise((resolve, reject) => {
this.db.update(
{
@ -156,13 +168,14 @@ export default class Account {
if (err) return reject(err)
if (isEmpty(doc)) return reject(new EmptyRecordError('empty'))
resolve(doc)
})
}
)
}
)
})
}
removeAccount (id: string): Promise<number> {
removeAccount(id: string): Promise<number> {
return new Promise((resolve, reject) => {
this.db.remove(
{
@ -177,26 +190,21 @@ export default class Account {
})
}
removeAll (): Promise<number> {
removeAll(): Promise<number> {
return new Promise((resolve, reject) => {
this.db.remove(
{},
{ multi: true },
(err, numRemoved) => {
if (err) return reject(err)
resolve(numRemoved)
}
)
this.db.remove({}, { multi: true }, (err, numRemoved) => {
if (err) return reject(err)
resolve(numRemoved)
})
})
}
async forwardAccount (ac: LocalAccount): Promise<LocalAccount | {}> {
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) => {
console.log(err)
return []
})
const accounts = await this.searchAccounts({ order: { $lt: ac.order } }, -1).catch(err => {
console.log(err)
return []
})
if (accounts.length < 1) {
return Promise.resolve({})
}
@ -206,36 +214,35 @@ 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 | {}> {
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) => {
console.log(err)
return []
})
const accounts = await this.searchAccounts({ order: { $gt: ac.order } }, 1).catch(err => {
console.log(err)
return []
})
if (accounts.length < 1) {
return Promise.resolve({})
}
@ -245,63 +252,82 @@ 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
}
async refreshAccounts (): Promise<Array<LocalAccount>> {
async refreshAccounts(): Promise<Array<LocalAccount>> {
const accounts = await this.listAccounts()
if (accounts.length < 1) {
return accounts
}
const results = await Promise.all(accounts.map(async (account) => {
const refresh = await this.refresh(account)
return refresh
}))
const results = await Promise.all(
accounts.map(async account => {
const refresh = await this.refresh(account)
return refresh
})
)
return results
}
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 = {
username: res.data.username,
accountId: res.data.id,
avatar: res.data.avatar
}
return this.updateAccount(account._id!, json)
})
/**
* 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> {
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'
)
async fetchAccount(account: LocalAccount, accessToken: string): Promise<RemoteAccount> {
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 {}

View File

@ -56,7 +56,7 @@ export default class Authentication {
clientId: this.clientId,
clientSecret: this.clientSecret,
accessToken: '',
refreshToken: '',
refreshToken: null,
username: '',
accountId: null,
avatar: '',
@ -90,20 +90,6 @@ export default class Authentication {
})
return accessToken
}
async updateAccessToken(id: string): Promise<string> {
const account = await this.db.getAccount(id)
if (!account.refreshToken) {
throw new RefreshTokenDoesNotExist()
}
const data: OAuth.TokenData = await Mastodon.refreshToken(account.clientId, account.clientSecret, account.refreshToken, account.baseURL)
await this.db.updateAccount(id, {
accessToken: data.access_token,
refreshToken: data.refresh_token
})
return data.access_token
}
}
class AuthenticationURLError extends Error {}
class RefreshTokenDoesNotExist extends Error {}