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

96 lines
2.5 KiB
TypeScript
Raw Normal View History

import Mastodon, { OAuth } from 'megalodon'
import Account from './account'
import LocalAccount from '~/src/types/localAccount'
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 {
private db: Account
private baseURL: string
private domain: string
private clientId: string
private clientSecret: string
private protocol: 'http' | 'https'
constructor(accountDB: Account) {
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
}
setOtherInstance(domain: string) {
2018-03-10 16:48:40 +01:00
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'): Promise<string> {
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 order = await this.db
.lastAccount()
.then(account => account.order + 1)
.catch(err => {
console.log(err)
return 1
})
const local: LocalAccount = {
baseURL: this.baseURL,
domain: this.domain,
clientId: this.clientId,
clientSecret: this.clientSecret,
accessToken: '',
refreshToken: null,
username: '',
accountId: null,
avatar: '',
order: order
}
await this.db.insertAccount(local)
if (res.url === null) {
throw new AuthenticationURLError('Can not get url')
}
return res.url
2018-03-08 09:41:39 +01:00
}
async getAccessToken(code: string): Promise<string> {
const tokenData: OAuth.TokenData = 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 = tokenData.accessToken
const refreshToken = tokenData.refreshToken
const data = await this.db.fetchAccount(rec, accessToken)
await this.db.updateAccount(rec._id!, {
username: data.username,
accountId: data.id,
avatar: data.avatar,
accessToken: accessToken,
refreshToken: refreshToken
})
return accessToken
2018-03-08 09:41:39 +01:00
}
}
class AuthenticationURLError extends Error {}