Allow for undefined email and displayName

OAuth2 allows the user to only consent to a subset of the scopes
requested. Previously, the Generic Oauth2 implementation assumes that
the `username`, `email` and `displayName` attributes are supplied, and
may crash if they are not defined.

This commit allows for `email` and `displayName` to not be defined,
either through the user refusing consent or the OAuth2 configuration
not asking for them in the first place (by not setting
`userProfile*Attr`).

If `email` is not provided, the `emails` property is simply left empty.
If `displayName` is not provided, it is left undefined, and CodiMD uses
the `username` whenever the `displayName` is expected.

This does not deal with the case where `username` is not provided. Since
usernames are not unique in CodiMD, it is possible to deal with this by
setting a dummy username. This can be added in a future commit if
desired.

Fixes #406

Signed-off-by: Dexter Chua <dalcde@yahoo.com.hk>
This commit is contained in:
Dexter Chua 2020-06-17 21:09:47 +08:00 committed by Dexter Chua
parent 389bbc46f7
commit e45327df5d

View file

@ -1,6 +1,7 @@
import { InternalOAuthError, Strategy as OAuth2Strategy } from 'passport-oauth2'
import { config } from '../../../config'
import { PassportProfile, ProviderEnum } from '../utils'
import { logger } from '../../../logger'
function extractProfileAttribute (data, path: string): string {
// can handle stuff like `attrs[0].name`
@ -15,14 +16,33 @@ function extractProfileAttribute (data, path: string): string {
function parseProfile (data): Partial<PassportProfile> {
const username = extractProfileAttribute(data, config.oauth2.userProfileUsernameAttr)
const displayName = extractProfileAttribute(data, config.oauth2.userProfileDisplayNameAttr)
const email = extractProfileAttribute(data, config.oauth2.userProfileEmailAttr)
let displayName: string | undefined
try {
// This may fail if the config.oauth2.userProfileDisplayNameAttr is undefined,
// or it is foo.bar and data["foo"] is undefined.
displayName = extractProfileAttribute(data, config.oauth2.userProfileDisplayNameAttr)
} catch (e) {
displayName = undefined
logger.debug('\'id_token[%s]\' is undefined. Setting \'displayName\' to \'undefined\'.\n%s', config.oauth2.userProfileDisplayNameAttr, e.message)
}
const emails: string[] = []
try {
const email = extractProfileAttribute(data, config.oauth2.userProfileEmailAttr)
if (email !== undefined) {
emails.push(email)
} else {
logger.debug('\'id_token[%s]\' is undefined. Setting \'emails\' to [].', config.oauth2.userProfileEmailAttr)
}
} catch (e) {
logger.debug('\'id_token[%s]\' is undefined. Setting \'emails\' to [].\n%s', config.oauth2.userProfileEmailAttr, e.message)
}
return {
id: username,
username: username,
displayName: displayName,
emails: [email]
emails: emails
}
}