-
Notifications
You must be signed in to change notification settings - Fork 52
CLI: Implement auth status command
#2028
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
+166
−1
Merged
Changes from 13 commits
Commits
Show all changes
29 commits
Select commit
Hold shift + click to select a range
999b2a8
CLI: Implement `auth login` command
fredrikekelund 8650b02
Fix lint and tests
fredrikekelund fc661e0
Add tests, tweak command
fredrikekelund c8b228c
Consider expiration time
fredrikekelund 9fcc45f
Move logic around
fredrikekelund 36e6059
Unwrap
fredrikekelund a228ae9
Fix type error
fredrikekelund b838c0c
CLI: Implement `auth logout` command
fredrikekelund 4634320
CLI: Implement `auth status` command
fredrikekelund c1799fe
Address review comments
fredrikekelund 23aa26c
Reject unsupported platforms
fredrikekelund ed4f216
Merge branch 'f26d/cli-auth-login-command' into f26d/cli-auth-logout-…
fredrikekelund a68c998
Merge branch 'f26d/cli-auth-logout-command' into f26d/cli-auth-status…
fredrikekelund 49966e3
Merge branch 'trunk' into f26d/cli-auth-login-command
fredrikekelund e13fd34
Address review feedback
fredrikekelund c72a70d
Fix test
fredrikekelund edb407f
Merge branch 'f26d/cli-auth-login-command' into f26d/cli-auth-logout-…
fredrikekelund 6ba6a05
Fix
fredrikekelund 6946324
Merge branch 'f26d/cli-auth-logout-command' into f26d/cli-auth-status…
fredrikekelund 2908170
Merge branch 'trunk' into f26d/cli-auth-login-command
fredrikekelund fc816bf
docs: Update CLI documentation for auth login command
github-actions[bot] 5748109
Restore package-lock.json
fredrikekelund 7b1c743
Install inquirer dependency again
fredrikekelund d8feb6b
Tweak
fredrikekelund 20c7566
Merge branch 'f26d/cli-auth-login-command' into f26d/cli-auth-logout-…
fredrikekelund fdb06df
Merge branch 'f26d/cli-auth-logout-command' into f26d/cli-auth-status…
fredrikekelund 1cc1fe0
docs: Update CLI documentation for auth commands
github-actions[bot] 9df3824
Merge branch 'trunk' into f26d/cli-auth-status-command
fredrikekelund 3233720
docs: Add CLI documentation for auth status command
github-actions[bot] File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,96 @@ | ||
| import { password } from '@inquirer/prompts'; | ||
| import { __, sprintf } from '@wordpress/i18n'; | ||
| import { getAuthenticationUrl } from 'common/lib/oauth'; | ||
| import { AuthCommandLoggerAction as LoggerAction } from 'common/logger-actions'; | ||
| import { getUserInfo } from 'cli/lib/api'; | ||
| import { | ||
| getAuthToken, | ||
| lockAppdata, | ||
| readAppdata, | ||
| saveAppdata, | ||
| unlockAppdata, | ||
| } from 'cli/lib/appdata'; | ||
| import { openBrowser } from 'cli/lib/browser'; | ||
| import { getAppLocale } from 'cli/lib/i18n'; | ||
| import { Logger, LoggerError } from 'cli/logger'; | ||
| import { StudioArgv } from 'cli/types'; | ||
|
|
||
| const CLI_REDIRECT_URI = `https://developer.wordpress.com/copy-oauth-token`; | ||
|
|
||
| export async function runCommand(): Promise< void > { | ||
| const logger = new Logger< LoggerAction >(); | ||
|
|
||
| try { | ||
| await getAuthToken(); | ||
| logger.reportSuccess( __( 'Already authenticated with WordPress.com' ) ); | ||
| return; | ||
| } catch ( error ) { | ||
| // Assume the token is invalid and proceed with authentication | ||
| } | ||
|
|
||
| logger.reportStart( LoggerAction.LOGIN, __( 'Opening browser for authentication…' ) ); | ||
|
|
||
| const appLocale = await getAppLocale(); | ||
| const authUrl = getAuthenticationUrl( appLocale, CLI_REDIRECT_URI ); | ||
|
|
||
| try { | ||
| await openBrowser( authUrl ); | ||
| logger.reportSuccess( __( 'Browser opened successfully' ) ); | ||
| } catch ( error ) { | ||
| // If the browser fails to open, allow users to manually open the URL | ||
| const loggerError = new LoggerError( | ||
| sprintf( __( 'Failed to open browser. Please open the URL manually: %s' ), authUrl ), | ||
| error | ||
| ); | ||
| logger.reportError( loggerError ); | ||
| } | ||
|
|
||
| console.log( | ||
| __( 'Please complete authentication in your browser and paste the generated token here.' ) | ||
| ); | ||
| console.log( '' ); | ||
|
|
||
| try { | ||
| const accessToken = await password( { message: __( 'Authentication token:' ) } ); | ||
| const user = await getUserInfo( accessToken ); | ||
|
|
||
| logger.reportSuccess( __( 'Authentication completed successfully!' ) ); | ||
|
|
||
| try { | ||
| await lockAppdata(); | ||
| const userData = await readAppdata(); | ||
|
|
||
| const now = new Date(); | ||
| const twoWeeksInSeconds = 2 * 7 * 24 * 60 * 60; | ||
|
|
||
| userData.authToken = { | ||
| accessToken, | ||
| id: user.ID, | ||
| email: user.email, | ||
| displayName: user.display_name, | ||
| expiresIn: twoWeeksInSeconds, | ||
| expirationTime: now.getTime() + twoWeeksInSeconds * 1000, | ||
| }; | ||
|
|
||
| await saveAppdata( userData ); | ||
| } finally { | ||
| await unlockAppdata(); | ||
| } | ||
| } catch ( error ) { | ||
| if ( error instanceof LoggerError ) { | ||
| logger.reportError( error ); | ||
| } else { | ||
| logger.reportError( new LoggerError( __( 'Authentication failed' ), error ) ); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| export const registerCommand = ( yargs: StudioArgv ) => { | ||
| return yargs.command( { | ||
| command: 'login', | ||
| describe: __( 'Log in to WordPress.com' ), | ||
| handler: async () => { | ||
| await runCommand(); | ||
| }, | ||
| } ); | ||
| }; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,55 @@ | ||
| import { __ } from '@wordpress/i18n'; | ||
| import { AuthCommandLoggerAction as LoggerAction } from 'common/logger-actions'; | ||
| import { revokeAuthToken } from 'cli/lib/api'; | ||
| import { | ||
| readAppdata, | ||
| saveAppdata, | ||
| lockAppdata, | ||
| unlockAppdata, | ||
| getAuthToken, | ||
| } from 'cli/lib/appdata'; | ||
| import { Logger, LoggerError } from 'cli/logger'; | ||
| import { StudioArgv } from 'cli/types'; | ||
|
|
||
| export async function runCommand(): Promise< void > { | ||
| const logger = new Logger< LoggerAction >(); | ||
|
|
||
| logger.reportStart( LoggerAction.LOGOUT, __( 'Logging out…' ) ); | ||
| let token: Awaited< ReturnType< typeof getAuthToken > >; | ||
|
|
||
| try { | ||
| token = await getAuthToken(); | ||
| } catch ( error ) { | ||
| logger.reportSuccess( __( 'Already logged out' ) ); | ||
| return; | ||
| } | ||
|
|
||
| try { | ||
| await revokeAuthToken( token.accessToken ); | ||
|
|
||
| await lockAppdata(); | ||
| const userData = await readAppdata(); | ||
| delete userData.authToken; | ||
| await saveAppdata( userData ); | ||
|
|
||
| logger.reportSuccess( __( 'Successfully logged out' ) ); | ||
| } catch ( error ) { | ||
| if ( error instanceof LoggerError ) { | ||
| logger.reportError( error ); | ||
| } else { | ||
| logger.reportError( new LoggerError( __( 'Failed to log out' ), error ) ); | ||
| } | ||
| } finally { | ||
| await unlockAppdata(); | ||
| } | ||
| } | ||
|
|
||
| export const registerCommand = ( yargs: StudioArgv ) => { | ||
| return yargs.command( { | ||
| command: 'logout', | ||
| describe: __( 'Log out and clear WordPress.com authentication' ), | ||
| handler: async () => { | ||
| await runCommand(); | ||
| }, | ||
| } ); | ||
| }; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,43 @@ | ||
| import { __, sprintf } from '@wordpress/i18n'; | ||
| import { AuthCommandLoggerAction as LoggerAction } from 'common/logger-actions'; | ||
| import { getUserInfo } from 'cli/lib/api'; | ||
| import { getAuthToken } from 'cli/lib/appdata'; | ||
| import { Logger, LoggerError } from 'cli/logger'; | ||
| import { StudioArgv } from 'cli/types'; | ||
|
|
||
| export async function runCommand(): Promise< void > { | ||
| const logger = new Logger< LoggerAction >(); | ||
|
|
||
| logger.reportStart( LoggerAction.STATUS_CHECK, __( 'Checking authentication status…' ) ); | ||
| let token: Awaited< ReturnType< typeof getAuthToken > >; | ||
|
|
||
| try { | ||
| token = await getAuthToken(); | ||
| } catch ( error ) { | ||
| logger.reportError( new LoggerError( __( 'Authentication token is invalid or expired' ) ) ); | ||
| return; | ||
| } | ||
|
|
||
| try { | ||
| const userData = await getUserInfo( token.accessToken ); | ||
| logger.reportSuccess( | ||
| sprintf( __( 'Successfully authenticated with WordPress.com as `%s`' ), userData.username ) | ||
| ); | ||
| } catch ( error ) { | ||
| if ( error instanceof LoggerError ) { | ||
| logger.reportError( error ); | ||
| } else { | ||
| logger.reportError( new LoggerError( __( 'Failed to check authentication status' ), error ) ); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| export const registerCommand = ( yargs: StudioArgv ) => { | ||
| return yargs.command( { | ||
| command: 'status', | ||
| describe: __( 'Check authentication status' ), | ||
| handler: async () => { | ||
| await runCommand(); | ||
| }, | ||
| } ); | ||
| }; | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,185 @@ | ||
| import { password } from '@inquirer/prompts'; | ||
| import { getAuthenticationUrl } from 'common/lib/oauth'; | ||
| import { getUserInfo } from 'cli/lib/api'; | ||
| import { | ||
| getAuthToken, | ||
| lockAppdata, | ||
| readAppdata, | ||
| saveAppdata, | ||
| unlockAppdata, | ||
| } from 'cli/lib/appdata'; | ||
| import { openBrowser } from 'cli/lib/browser'; | ||
| import { getAppLocale } from 'cli/lib/i18n'; | ||
| import { Logger, LoggerError } from 'cli/logger'; | ||
|
|
||
| jest.mock( '@inquirer/prompts' ); | ||
| jest.mock( 'common/lib/oauth' ); | ||
| jest.mock( 'cli/lib/api' ); | ||
| jest.mock( 'cli/lib/appdata', () => ( { | ||
| ...jest.requireActual( 'cli/lib/appdata' ), | ||
| lockAppdata: jest.fn(), | ||
| readAppdata: jest.fn(), | ||
| saveAppdata: jest.fn(), | ||
| unlockAppdata: jest.fn(), | ||
| getAuthToken: jest.fn(), | ||
| } ) ); | ||
| jest.mock( 'cli/lib/browser' ); | ||
| jest.mock( 'cli/lib/i18n' ); | ||
| jest.mock( 'cli/logger' ); | ||
|
|
||
| describe( 'Auth Login Command', () => { | ||
| const mockAccessToken = 'mock-access-token-12345'; | ||
| const mockAuthUrl = 'https://public-api.wordpress.com/oauth2/authorize?client_id=123'; | ||
| const mockUserData = { | ||
| ID: 12345, | ||
| email: '[email protected]', | ||
| display_name: 'Test User', | ||
| }; | ||
| const mockAppdata = { | ||
| authToken: { | ||
| accessToken: 'existing-token', | ||
| id: 999, | ||
| email: '[email protected]', | ||
| displayName: 'Existing User', | ||
| expiresIn: 1209600, | ||
| expirationTime: Date.now() + 1209600000, | ||
| }, | ||
| }; | ||
|
|
||
| let mockLogger: { | ||
| reportStart: jest.Mock; | ||
| reportSuccess: jest.Mock; | ||
| reportError: jest.Mock; | ||
| reportKeyValuePair: jest.Mock; | ||
| }; | ||
|
|
||
| beforeEach( () => { | ||
| jest.clearAllMocks(); | ||
|
|
||
| mockLogger = { | ||
| reportStart: jest.fn(), | ||
| reportSuccess: jest.fn(), | ||
| reportError: jest.fn(), | ||
| reportKeyValuePair: jest.fn(), | ||
| }; | ||
|
|
||
| ( Logger as jest.Mock ).mockReturnValue( mockLogger ); | ||
| ( getAuthenticationUrl as jest.Mock ).mockReturnValue( mockAuthUrl ); | ||
| ( getAppLocale as jest.Mock ).mockResolvedValue( 'en' ); | ||
| ( getUserInfo as jest.Mock ).mockResolvedValue( mockUserData ); | ||
| ( openBrowser as jest.Mock ).mockResolvedValue( undefined ); | ||
| ( password as jest.Mock ).mockResolvedValue( mockAccessToken ); | ||
| ( readAppdata as jest.Mock ).mockResolvedValue( mockAppdata ); | ||
| ( getAuthToken as jest.Mock ).mockRejectedValue( new Error( 'Mock error' ) ); | ||
| ( lockAppdata as jest.Mock ).mockResolvedValue( undefined ); | ||
| ( unlockAppdata as jest.Mock ).mockResolvedValue( undefined ); | ||
| ( saveAppdata as jest.Mock ).mockResolvedValue( undefined ); | ||
| } ); | ||
|
|
||
| afterEach( () => { | ||
| jest.restoreAllMocks(); | ||
| } ); | ||
|
|
||
| it( 'should skip login if already authenticated', async () => { | ||
| ( getAuthToken as jest.Mock ).mockResolvedValue( mockAppdata.authToken ); | ||
|
|
||
| const { runCommand } = await import( '../login' ); | ||
| await runCommand(); | ||
|
|
||
| expect( openBrowser ).not.toHaveBeenCalled(); | ||
| expect( password ).not.toHaveBeenCalled(); | ||
| } ); | ||
|
|
||
| it( 'should complete the login process successfully', async () => { | ||
| const { runCommand } = await import( '../login' ); | ||
| await runCommand(); | ||
|
|
||
| expect( getAuthenticationUrl ).toHaveBeenCalledWith( | ||
| 'en', | ||
| 'https://developer.wordpress.com/copy-oauth-token' | ||
| ); | ||
| expect( openBrowser ).toHaveBeenCalledWith( mockAuthUrl ); | ||
| expect( password ).toHaveBeenCalledWith( { | ||
| message: 'Authentication token:', | ||
| } ); | ||
| expect( getUserInfo ).toHaveBeenCalledWith( mockAccessToken ); | ||
| expect( lockAppdata ).toHaveBeenCalled(); | ||
| expect( saveAppdata ).toHaveBeenCalledWith( { | ||
| authToken: { | ||
| accessToken: mockAccessToken, | ||
| id: mockUserData.ID, | ||
| email: mockUserData.email, | ||
| displayName: mockUserData.display_name, | ||
| expiresIn: expect.any( Number ), | ||
| expirationTime: expect.any( Number ), | ||
| }, | ||
| } ); | ||
| expect( unlockAppdata ).toHaveBeenCalled(); | ||
| } ); | ||
|
|
||
| it( 'should proceed with login if existing token is invalid', async () => { | ||
| const { runCommand } = await import( '../login' ); | ||
| await runCommand(); | ||
|
|
||
| expect( openBrowser ).toHaveBeenCalled(); | ||
| expect( password ).toHaveBeenCalled(); | ||
| } ); | ||
|
|
||
| it( 'should handle browser open failure', async () => { | ||
| const browserError = new LoggerError( 'Failed to open browser' ); | ||
| ( openBrowser as jest.Mock ).mockRejectedValue( browserError ); | ||
|
|
||
| const { runCommand } = await import( '../login' ); | ||
| await runCommand(); | ||
|
|
||
| expect( password ).toHaveBeenCalled(); | ||
| } ); | ||
|
|
||
| it( 'should handle API error when fetching user info', async () => { | ||
| const apiError = new LoggerError( 'Failed to fetch user info' ); | ||
| ( getUserInfo as jest.Mock ).mockRejectedValue( apiError ); | ||
|
|
||
| const { runCommand } = await import( '../login' ); | ||
| await runCommand(); | ||
|
|
||
| expect( mockLogger.reportError ).toHaveBeenCalled(); | ||
| expect( mockLogger.reportError ).toHaveBeenCalledWith( expect.any( LoggerError ) ); | ||
| expect( getUserInfo ).toHaveBeenCalled(); | ||
| } ); | ||
|
|
||
| it( 'should unlock appdata even if save fails', async () => { | ||
| const saveError = new Error( 'Failed to save' ); | ||
| ( saveAppdata as jest.Mock ).mockRejectedValue( saveError ); | ||
|
|
||
| const { runCommand } = await import( '../login' ); | ||
| await runCommand(); | ||
|
|
||
| expect( mockLogger.reportError ).toHaveBeenCalled(); | ||
| expect( mockLogger.reportError ).toHaveBeenCalledWith( expect.any( LoggerError ) ); | ||
| expect( lockAppdata ).toHaveBeenCalled(); | ||
| expect( unlockAppdata ).toHaveBeenCalled(); | ||
| } ); | ||
|
|
||
| it( 'should handle lock appdata failure', async () => { | ||
| const lockError = new Error( 'Failed to lock' ); | ||
| ( lockAppdata as jest.Mock ).mockRejectedValue( lockError ); | ||
|
|
||
| const { runCommand } = await import( '../login' ); | ||
| await runCommand(); | ||
|
|
||
| expect( mockLogger.reportError ).toHaveBeenCalled(); | ||
| expect( mockLogger.reportError ).toHaveBeenCalledWith( expect.any( LoggerError ) ); | ||
| } ); | ||
|
|
||
| it( 'should use provided locale', async () => { | ||
| ( getAppLocale as jest.Mock ).mockResolvedValue( 'fr' ); | ||
|
|
||
| const { runCommand } = await import( '../login' ); | ||
| await runCommand(); | ||
|
|
||
| expect( getAuthenticationUrl ).toHaveBeenCalledWith( | ||
| 'fr', | ||
| 'https://developer.wordpress.com/copy-oauth-token' | ||
| ); | ||
| } ); | ||
| } ); |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Code Style - The type annotation
Awaited< ReturnType< typeof getAuthToken > >is correct but creates an unused variable declaration sincetokenis reassigned in the try block. Consider simplifying:This would eliminate the uninitialized variable and flatten the nesting slightly. However, the current approach with two separate try-catch blocks does make the error handling more explicit, so this is a minor style preference.