oauth2.authorize {
	# for non-oauth2 handled domains you will see and should ignore
	# ERRROR: "Config item "realm[...].oauth2.discovery" does not exist"
	if (&Realm && &User-Password && "%{config:realm[%{Realm}].oauth2.discovery}") {
		oauth2_perl
		if (updated && "%{config:realm[%{Realm}].oauth2.cache_password}" =~ /^(yes)?$/i) {
			update control {
				&Cache-Read-Only = yes
			}
			oauth2_cache
			# outsource the authentication to PAP if we have valid cached credentials
			if (ok && "%{request:OAuth2-Password-Last-Modified}" == "%{control:OAuth2-Password-Last-Modified}") {
				update control {
					Auth-Type -= "oauth2"
				}
			}
		}
	} else {
		noop
	}
}

oauth2.authenticate {
	oauth2_perl
}

oauth2.post-auth {
	if ("%{config:realm[%{Realm}].oauth2.cache_password}" =~ /^(yes)?$/i) {
		if (&control:Auth-Type == "oauth2") {
			update request {
				&Tmp-String-0 = "%{randstr:32.}"
			}
			update control {
				&Password-With-Header = "{ssha512}%{sha512:%{&User-Password}%{&Tmp-String-0}}%{hex:&Tmp-String-0}"
			}
		}
		if (&control:OAuth2-Password-Last-Modified) {
			oauth2_cache
		}
	}
}
