Skip to content
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

[NEW] Apple Login #24060

Merged
merged 9 commits into from
Jan 14, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
76 changes: 76 additions & 0 deletions app/apple/server/appleOauthRegisterService.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
import { KJUR } from 'jsrsasign';
ggazzo marked this conversation as resolved.
Show resolved Hide resolved
import { ServiceConfiguration } from 'meteor/service-configuration';

import { CustomOAuth } from '../../custom-oauth/server/custom_oauth_server';
import { settings, settingsRegistry } from '../../settings/server';

const config = {
serverURL: 'https://appleid.apple.com',
tokenPath: '/auth/token',
scope: 'name email',
mergeUsers: true,
accessTokenParam: 'access_token',
loginStyle: 'popup',
};

new CustomOAuth('apple', config);

settingsRegistry.addGroup('OAuth', function () {
this.section('Apple', function () {
this.add('Accounts_OAuth_Apple', false, { type: 'boolean', public: true });

this.add('Accounts_OAuth_Apple_id', '', { type: 'string', public: true });
this.add('Accounts_OAuth_Apple_secretKey', '', { type: 'string', multiline: true });

this.add('Accounts_OAuth_Apple_iss', '', { type: 'string' });
this.add('Accounts_OAuth_Apple_kid', '', { type: 'string' });
});
});

settings.watchMultiple(
[
'Accounts_OAuth_Apple',
'Accounts_OAuth_Apple_id',
'Accounts_OAuth_Apple_secretKey',
'Accounts_OAuth_Apple_iss',
'Accounts_OAuth_Apple_kid',
],
([enabled, clientId, serverSecret, iss, kid]) => {
if (!enabled) {
return ServiceConfiguration.configurations.remove({
service: 'apple',
});
}

const HEADER = {
kid,
alg: 'ES256',
};

const tokenPayload = {
iss,
iat: Math.floor(Date.now() / 1000),
exp: Math.floor(Date.now() / 1000) + 300,
aud: 'https://appleid.apple.com',
sub: clientId,
};

const secret = KJUR.jws.JWS.sign(null, HEADER, tokenPayload, serverSecret as string);

ServiceConfiguration.configurations.upsert(
{
service: 'apple',
},
{
$set: {
// We'll hide this button on Web Client
showButton: false,
secret,
enabled: settings.get('Accounts_OAuth_Apple'),
loginStyle: 'popup',
clientId,
},
},
);
},
);
31 changes: 1 addition & 30 deletions app/apple/server/startup.ts
Original file line number Diff line number Diff line change
@@ -1,30 +1 @@
import { ServiceConfiguration } from 'meteor/service-configuration';

import { settings, settingsRegistry } from '../../settings/server';

settingsRegistry.addGroup('OAuth', function () {
this.section('Apple', function () {
this.add('Accounts_OAuth_Apple', false, { type: 'boolean', public: true });
});
});

settings.watch('Accounts_OAuth_Apple', (enabled) => {
if (!enabled) {
return ServiceConfiguration.configurations.remove({
service: 'apple',
});
}

ServiceConfiguration.configurations.upsert(
{
service: 'apple',
},
{
$set: {
// We'll hide this button on Web Client
showButton: false,
enabled: settings.get('Accounts_OAuth_Apple'),
},
},
);
});
import './appleOauthRegisterService';
2 changes: 1 addition & 1 deletion app/apple/server/tokenHandler.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ const isValidAppleJWT = (identityToken, header) => {
}
};

export const handleIdentityToken = ({ identityToken, fullName, email }) => {
export const handleIdentityToken = ({ identityToken, fullName = {}, email }) => {
check(identityToken, String);
check(fullName, Match.Maybe(Object));
check(email, Match.Maybe(String));
Expand Down
4 changes: 2 additions & 2 deletions app/cors/server/cors.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ WebApp.rawConnectHandlers.use(function (req, res, next) {
]
.filter(Boolean)
.join(' ');

const external = [settings.get('Accounts_OAuth_Apple') && 'https://appleid.cdn-apple.com'].filter(Boolean).join(' ');
res.setHeader(
'Content-Security-Policy',
[
Expand All @@ -45,7 +45,7 @@ WebApp.rawConnectHandlers.use(function (req, res, next) {
'frame-src *',
'img-src * data: blob:',
'media-src * data:',
`script-src 'self' 'unsafe-eval' ${inlineHashes} ${cdn_prefixes}`,
`script-src 'self' 'unsafe-eval' ${inlineHashes} ${cdn_prefixes} ${external}`,
`style-src 'self' 'unsafe-inline' ${cdn_prefixes}`,
].join('; '),
);
Expand Down
23 changes: 16 additions & 7 deletions app/ui-login/client/login/services.html
Original file line number Diff line number Diff line change
@@ -1,9 +1,18 @@
<template name='loginServices'>
<template name="loginServices">
{{#if loginService.length}}
<div class="oauth-login buttons-group">
{{#each loginService}}
<button type="button" class="rc-button rc-button--secondary external-login {{service.service}}" title="{{displayName}}" style="{{#if service.buttonColor}}background-color:{{service.buttonColor}};{{/if}}{{#if service.buttonLabelColor}}color:{{service.buttonLabelColor}};{{/if}}"><i class="icon-{{icon}} service-icon"></i><i class="icon-spin animate-spin loading-icon hidden"></i><span>{{service.buttonLabelText}}</span></button>
{{/each}}
</div>
{{/if}}
<div class="oauth-login buttons-group">
{{#each loginService}}
<button
type="button"
class="rc-button rc-button--secondary external-login {{service.service}}"
title="{{displayName}}"
style="{{#if service.buttonColor}}background-color:{{service.buttonColor}};{{/if}}{{#if service.buttonLabelColor}}color:{{service.buttonLabelColor}};{{/if}}"
>
<i class="icon-{{icon}} service-icon"></i
><i class="icon-spin animate-spin loading-icon hidden"></i
><span>{{service.buttonLabelText}}</span>
</button>
{{/each}}
</div>
{{/if}} {{> AppleOauthButton}}
</template>
4 changes: 2 additions & 2 deletions client/lib/utils/createAnchor.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
export const createAnchor = (id: string): HTMLDivElement => {
export const createAnchor = (id: string, target = document.body): HTMLDivElement => {
const div = document.createElement('div');
div.id = id;
document.body.appendChild(div);
target.appendChild(div);
return div;
};
4 changes: 4 additions & 0 deletions client/templates.ts
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,10 @@ createTemplateForComponent('SortList', () => import('./components/SortList'));

createTemplateForComponent('CreateRoomList', () => import('./sidebar/header/actions/CreateRoomList'));

createTemplateForComponent('AppleOauthButton', () => import('./views/login/AppleOauth/AppleOauthButton'), {
renderContainerView: () => HTML.DIV({ style: 'display: flex; justify-content: center;' }),
});

createTemplateForComponent('UserDropdown', () => import('./sidebar/header/UserDropdown'));

createTemplateForComponent('sidebarFooter', () => import('./sidebar/footer'));
93 changes: 93 additions & 0 deletions client/views/login/AppleOauth/AppleOauthButton.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
import { Accounts } from 'meteor/accounts-base';
import React, { FC, useCallback, useEffect, useLayoutEffect, useRef } from 'react';

import { useAbsoluteUrl } from '../../../contexts/ServerContext';
import { useSetting } from '../../../contexts/SettingsContext';

export const AppleOauthButton: FC = () => {
const enabled = useSetting('Accounts_OAuth_Apple');
const absoluteUrl = useAbsoluteUrl();
const appleClientID = useSetting('Accounts_OAuth_Apple_id');

const redirectURI = absoluteUrl('_oauth/apple');

useEffect(() => {
const success = (data: any): void => {
const { authorization, user } = data.detail;

Accounts.callLoginMethod({
methodArguments: [
{
serviceName: 'apple',
identityToken: authorization.id_token,
...(user && {
fullName: {
givenName: user.name.firstName,
familyName: user.name.lastName,
},
email: user.email,
}),
},
],
userCallback: console.log,
});
};

const error = (error: any): void => {
// handle error.
console.error(error);
};
document.addEventListener('AppleIDSignInOnSuccess', success);
// Listen for authorization failures
document.addEventListener('AppleIDSignInOnFailure', error);

return (): void => {
document.removeEventListener('AppleIDSignInOnSuccess', success);
document.removeEventListener('AppleIDSignInOnFailure', error);
};
}, []);

const scriptLoadedHandler = useCallback(() => {
if (!enabled) {
return;
}
(window as any).AppleID.auth.init({
clientId: appleClientID,
scope: 'name email',
redirectURI,
usePopup: true,
});
}, [enabled, appleClientID, redirectURI]);

const ref = useRef<HTMLScriptElement>();

useEffect(() => {
if ((window as any).AppleID) {
scriptLoadedHandler();
return;
}
if (!ref.current) {
return;
}
ref.current.onload = scriptLoadedHandler;
}, [scriptLoadedHandler]);

useLayoutEffect(() => {
const script = document.createElement('script');
script.src = 'https://appleid.cdn-apple.com/appleauth/static/jsapi/appleid/1/en_US/appleid.auth.js';
script.async = true;
ref.current = script;
document.body.appendChild(script);
return (): void => {
document.body.removeChild(script);
};
}, []);

if (!enabled) {
return null;
}

return <div id='appleid-signin' data-height='40px'></div>;
};

export default AppleOauthButton;
2 changes: 1 addition & 1 deletion definition/rest/v1/settings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ export type OauthCustomConfiguration = {
identityPath: unknown;
authorizePath: unknown;
scope: unknown;
loginStyle: unknown;
loginStyle: 'popup' | 'redirect';
tokenSentVia: unknown;
identityTokenSentVia: unknown;
keyField: unknown;
Expand Down
6 changes: 6 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,7 @@
"@types/imap": "^0.8.35",
"@types/jsdom": "^16.2.12",
"@types/jsdom-global": "^3.0.2",
"@types/jsrsasign": "^9.0.1",
"@types/ldapjs": "^2.2.1",
"@types/less": "^3.0.2",
"@types/lodash.get": "^4.4.6",
Expand Down
2 changes: 1 addition & 1 deletion server/configuration/accounts_meld.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { Users } from '../../app/models';
const orig_updateOrCreateUserFromExternalService = Accounts.updateOrCreateUserFromExternalService;

Accounts.updateOrCreateUserFromExternalService = function (serviceName, serviceData = {}, ...args /* , options*/) {
const services = ['facebook', 'github', 'gitlab', 'google', 'meteor-developer', 'linkedin', 'twitter'];
const services = ['facebook', 'github', 'gitlab', 'google', 'meteor-developer', 'linkedin', 'twitter', 'apple'];

if (services.includes(serviceName) === false && serviceData._OAuthCustom !== true) {
return orig_updateOrCreateUserFromExternalService.apply(this, [serviceName, serviceData, ...args]);
Expand Down