File size: 1,798 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import { get } from 'lodash';
import {
	LOGIN_AUTH_ACCOUNT_TYPE_REQUESTING,
	LOGIN_AUTH_ACCOUNT_TYPE_REQUEST_SUCCESS,
	LOGIN_AUTH_ACCOUNT_TYPE_REQUEST_FAILURE,
} from 'calypso/state/action-types';
import { recordTracksEventWithClientId as recordTracksEvent } from 'calypso/state/analytics/actions';
import { registerHandlers } from 'calypso/state/data-layer/handler-registry';
import { http } from 'calypso/state/data-layer/wpcom-http/actions';
import { noRetry } from 'calypso/state/data-layer/wpcom-http/pipeline/retry-on-failure/policies';
import { dispatchRequest } from 'calypso/state/data-layer/wpcom-http/utils';

export const getAuthAccountType = ( action ) =>
	http(
		{
			path: `/users/${ encodeURIComponent( action.usernameOrEmail ) }/auth-options`,
			method: 'GET',
			apiVersion: '1.1',
			retryPolicy: noRetry(),
		},
		action
	);

export const receiveSuccess = ( action, data ) => {
	const isPasswordless = get( data, 'passwordless' );

	return [
		{
			type: LOGIN_AUTH_ACCOUNT_TYPE_REQUEST_SUCCESS,
			data: {
				type: isPasswordless ? 'passwordless' : 'regular',
			},
		},
		recordTracksEvent( 'calypso_login_block_login_form_get_auth_type_success' ),
	];
};

export const receiveError = ( action, { error: code, message } ) => [
	{
		type: LOGIN_AUTH_ACCOUNT_TYPE_REQUEST_FAILURE,
		error: {
			code,
			message,
			field: 'usernameOrEmail',
		},
	},
	recordTracksEvent( 'calypso_login_block_login_form_get_auth_type_failure', {
		error_code: code,
		error_message: message,
	} ),
];

const getAuthAccountTypeRequest = dispatchRequest( {
	fetch: getAuthAccountType,
	onSuccess: receiveSuccess,
	onError: receiveError,
} );

registerHandlers( 'state/data-layer/wpcom/users/auth-options/index.js', {
	[ LOGIN_AUTH_ACCOUNT_TYPE_REQUESTING ]: [ getAuthAccountTypeRequest ],
} );