File size: 2,099 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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
import { filterUserObject, getLogoutUrl, rawCurrentUserFetch } from 'calypso/lib/user/shared-utils';
import {
	clearStore,
	disablePersistence,
	getStoredUserId,
	setStoredUserId,
} from 'calypso/lib/user/store';
import {
	CURRENT_USER_FETCH,
	CURRENT_USER_RECEIVE,
	CURRENT_USER_SET_EMAIL_VERIFIED,
	CURRENT_USER_SET_JETPACK_PARTNER_TYPE,
} from 'calypso/state/action-types';
import { getCurrentUser } from 'calypso/state/current-user/selectors';

/**
 * Returns an action object that sets the current user object on the store
 * @param  {Object} user user object
 * @returns {Object}        Action object
 */
export function setCurrentUser( user ) {
	return {
		type: CURRENT_USER_RECEIVE,
		user,
	};
}

let fetchingUser = null;

export function fetchCurrentUser( { retry = false } = {} ) {
	return ( dispatch ) => {
		if ( fetchingUser ) {
			return fetchingUser;
		}

		dispatch( {
			type: CURRENT_USER_FETCH,
		} );

		fetchingUser = rawCurrentUserFetch( { retry } )
			.then( async ( user ) => {
				const userData = filterUserObject( user );

				const storedUserId = getStoredUserId();
				if ( storedUserId != null && storedUserId !== userData.ID ) {
					await clearStore();
				}

				setStoredUserId( userData.ID );
				dispatch( setCurrentUser( userData ) );
			} )
			.catch( () => {
				// @TODO: Improve error handling
			} )
			.finally( () => {
				fetchingUser = null;
			} );

		return fetchingUser;
	};
}

export function redirectToLogout( postLogoutRedirectUrl ) {
	return async ( dispatch, getState ) => {
		const userData = getCurrentUser( getState() );
		const logoutUrl = getLogoutUrl( userData, postLogoutRedirectUrl );

		// Clear any data stored locally within the user data module or localStorage
		disablePersistence();
		await clearStore();

		window.location.href = logoutUrl;
	};
}

export function setUserEmailVerified( verified ) {
	return {
		type: CURRENT_USER_SET_EMAIL_VERIFIED,
		verified,
	};
}

export function setUserJetpackPartnerType( partnerType ) {
	return {
		type: CURRENT_USER_SET_JETPACK_PARTNER_TYPE,
		jetpack_partner_type: partnerType,
	};
}