File size: 2,486 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
import page from '@automattic/calypso-router';
import { getLocaleFromPath, removeLocaleFromPath } from '@automattic/i18n-utils';
import debugModule from 'debug';
import { useTranslate } from 'i18n-calypso';
import store from 'store';
import DocumentHead from 'calypso/components/data/document-head';
import { navigate } from 'calypso/lib/navigate';
import InviteAccept from 'calypso/my-sites/invites/invite-accept';
import { getRedirectAfterAccept } from 'calypso/my-sites/invites/utils';
import { setUserEmailVerified } from 'calypso/state/current-user/actions';
import { getCurrentUserEmail, isUserLoggedIn } from 'calypso/state/current-user/selectors';
import { acceptInvite as acceptInviteAction } from 'calypso/state/invites/actions';

/**
 * Module variables
 */
const debug = debugModule( 'calypso:invite-accept:controller' );

export function redirectWithoutLocaleifLoggedIn( context, next ) {
	if ( isUserLoggedIn( context.store.getState() ) && getLocaleFromPath( context.path ) ) {
		return page.redirect( removeLocaleFromPath( context.path ) );
	}

	next();
}

export function acceptInvite( context, next ) {
	const acceptedInvite = store.get( 'invite_accepted' );
	if ( acceptedInvite ) {
		debug( 'invite_accepted is set in localStorage' );
		if ( getCurrentUserEmail( context.store.getState() ) === acceptedInvite.sentTo ) {
			debug( 'Setting email_verified in user object' );
			context.store.dispatch( setUserEmailVerified( true ) );
		}
		store.remove( 'invite_accepted' );
		const emailVerificationSecret = context.query.email_verification_secret;

		context.store
			.dispatch( acceptInviteAction( acceptedInvite, emailVerificationSecret ) )
			.then( () => {
				const redirect = getRedirectAfterAccept( acceptedInvite );
				debug( 'Accepted invite and redirecting to:  ' + redirect );
				navigate( redirect );
			} )
			.catch( ( error ) => {
				debug( 'Accept invite error: ' + JSON.stringify( error ) );
				page( window.location.href );
			} );
		return;
	}

	const AcceptInviteTitle = () => {
		const translate = useTranslate();

		return <DocumentHead title={ translate( 'Accept Invite', { textOnly: true } ) } />;
	};

	context.primary = (
		<>
			<AcceptInviteTitle />
			<InviteAccept
				siteId={ context.params.site_id }
				inviteKey={ context.params.invitation_key }
				activationKey={ context.params.activation_key }
				authKey={ context.params.auth_key }
				locale={ context.params.locale }
				path={ context.path }
			/>
		</>
	);
	next();
}