import { createSession, logout as apiLogout } from '../ao-lib/api.js' import { aoEnv, setAoEnv } from '../ao-lib/settings.js' import { askQuestionText } from './welcome.js' // Returns true if there is a session cookie for ao-cli saved in the AO .env file (=ready to make session requests) export function isLoggedIn() { const username = aoEnv('AO_CLI_SESSION_USERNAME') const memberId = aoEnv('AO_CLI_SESSION_MEMBERID') const sessionId = aoEnv('AO_CLI_SESSION_ID') const sessionToken = aoEnv('AO_CLI_SESSION_TOKEN') return username && memberId && sessionId && sessionToken } // Interactive prompt to log in. Performs the login request. export async function loginPrompt() { const username = await askQuestionText('Username:') const password = await askQuestionText('Password:', { type: 'password' }) await login(username, password) } export async function login(username, password) { try { console.log('Attempting login as', username, 'with password', '*'.repeat(password.length)) const response = await createSession(username, password) if(response) { setAoEnv('AO_CLI_SESSION_USERNAME', username) setAoEnv('AO_CLI_SESSION_MEMBERID', response.memberId) // might not need to save this actually setAoEnv('AO_CLI_SESSION_ID', response.session) setAoEnv('AO_CLI_SESSION_TOKEN', response.token) console.log('Logged in as', username + '.', 'memberId:', response.memberId) return true } else { console.log('Login failed. Response:', response) return false } } catch(err) { if(err.status === 401) { console.log("No account on the AO server matched the username and password you entered. (401 Unauthorized)") } else { console.log(err) } return false } } export async function logout() { try { console.log('Logging out...') const response = await apiLogout() setAoEnv('AO_CLI_SESSION_USERNAME', null) setAoEnv('AO_CLI_SESSION_MEMBERID', null) setAoEnv('AO_CLI_SESSION_ID', null) setAoEnv('AO_CLI_SESSION_TOKEN', null) if(response.statusCode === 200) { console.log('Logged out') } else { console.log('Server rejected logout. Forgetting session anyway. Response:', response) return false } } catch(err) { console.log(err) } return true }