@taizo-pro/github-discussions-cli
Version:
A powerful command-line tool for interacting with GitHub Discussions without opening a browser
91 lines • 2.95 kB
JavaScript
import { promises as fs } from 'fs';
import { join } from 'path';
import { homedir } from 'os';
import { ErrorType } from './types.js';
export class FileAuthManager {
configDir;
tokenFile;
constructor() {
this.configDir = join(homedir(), '.github-discussions');
this.tokenFile = join(this.configDir, 'token');
}
async getToken() {
try {
const token = await fs.readFile(this.tokenFile, 'utf8');
return token.trim() || null;
}
catch (error) {
if (error.code === 'ENOENT') {
return null;
}
throw this.createError(ErrorType.CONFIGURATION_ERROR, 'Failed to read token file', error);
}
}
async setToken(token) {
try {
await this.ensureConfigDir();
await fs.writeFile(this.tokenFile, token, { mode: 0o600 });
}
catch (error) {
throw this.createError(ErrorType.CONFIGURATION_ERROR, 'Failed to save token', error);
}
}
async validateToken(token) {
try {
const response = await fetch('https://api.github.com/user', {
headers: {
Authorization: `token ${token}`,
'User-Agent': 'github-discussions-cli',
},
});
if (response.status === 200) {
const data = await response.json();
return !!data.login;
}
return false;
}
catch (error) {
throw this.createError(ErrorType.NETWORK_ERROR, 'Failed to validate token', error);
}
}
async clearToken() {
try {
await fs.unlink(this.tokenFile);
}
catch (error) {
if (error.code !== 'ENOENT') {
throw this.createError(ErrorType.CONFIGURATION_ERROR, 'Failed to clear token', error);
}
}
}
async ensureConfigDir() {
try {
await fs.mkdir(this.configDir, { recursive: true, mode: 0o700 });
}
catch (error) {
throw this.createError(ErrorType.CONFIGURATION_ERROR, 'Failed to create config directory', error);
}
}
createError(type, message, originalError) {
return {
type,
message,
details: originalError,
suggestions: this.getSuggestions(type),
};
}
getSuggestions(type) {
switch (type) {
case ErrorType.CONFIGURATION_ERROR:
return [
'Check file permissions in ~/.github-discussions/',
'Ensure you have write access to your home directory',
];
case ErrorType.NETWORK_ERROR:
return ['Check your internet connection', 'Try again later'];
default:
return [];
}
}
}
//# sourceMappingURL=auth-manager.js.map