thedesk/src/main/Auth.ts

89 lines
2.7 KiB
TypeScript
Raw Normal View History

2019-04-25 21:26:25 +09:00
import { ipcMain, Event, shell, app } from "electron"
import Mastodon, { Status, Response } from "megalodon"
2019-04-25 21:26:25 +09:00
import { join } from "path"
import Datastore from "nedb"
import Window from "./Window"
2019-04-25 00:52:40 +09:00
export default class Auth {
public static ready() {
2019-04-25 01:04:26 +09:00
let clientId: string
let clientSecret: string
2019-04-25 00:52:40 +09:00
ipcMain.on("new-account-setup", async (event: Event, instance: string) => {
const SCOPES: string = "read write follow"
let url: string | null
Mastodon.registerApp(
"TheDesk",
{
scopes: SCOPES
},
2019-04-25 01:04:26 +09:00
"https://" + instance
)
.then(appData => {
clientId = appData.clientId
clientSecret = appData.clientSecret
url = appData.url
if (url) {
shell.openExternal(
url,
{
activate: false
},
err => {
if (err) console.log(err)
}
)
} else {
2019-04-25 21:26:25 +09:00
Window.windowMap.get("main")!.webContents.send(`error`, {
id: "ERROR_GET_AUTHURL",
message: "Failed to get auth URL to login."
})
}
2019-04-25 01:04:26 +09:00
})
.catch((err: Error) =>
2019-04-25 21:26:25 +09:00
Window.windowMap.get("main")!.webContents.send(`error`, {
id: "ERROR_CONNECTION",
message: "Connection error",
meta: err
})
)
2019-04-25 01:04:26 +09:00
})
ipcMain.on(
"new-account-auth",
async (event: Event, code: string, instance: string) => {
let url: string = "https://" + instance
Mastodon.fetchAccessToken(clientId, clientSecret, code, url)
.then((tokenData: Partial<{ accessToken: string }>) => {
if (tokenData.accessToken) {
const client = new Mastodon(
tokenData.accessToken,
url + "/api/v1"
)
client
.get<[Status]>("/accounts/verify_credentials")
.then((resp: Response<[Status]>) => {
console.log(resp.data)
2019-04-25 21:26:25 +09:00
var db = new Datastore({
filename: join(app.getPath("userData"), "account.db")
})
db.loadDatabase()
})
} else {
2019-04-25 21:26:25 +09:00
Window.windowMap.get("main")!.webContents.send(`error`, {
id: "ERROR_GET_TOKEN",
message: "Failed to get access token."
})
}
})
2019-04-25 21:26:25 +09:00
.catch((err: Error) =>
Window.windowMap.get("main")!.webContents.send(`error`, {
id: "ERROR_CONNECTION",
message: "Connection error",
meta: err
})
)
}
)
2019-04-25 00:52:40 +09:00
}
}