Skip to content
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
107 changes: 107 additions & 0 deletions central/api/email_oauth.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
"""Connect a mailbox in one click on a V2 site, for any OAuth mail provider in PROVIDERS.

Central holds Frappe Cloud's app for each provider; a site reaches `start` and `relay_token` through its Pilot.
"""

from urllib.parse import urlencode

import frappe
from frappe import _

from central.api.pilot import pilot_credential_auth
from central.iam import can
from central.integrations.email_oauth.email_oauth import (
CALLBACK_PATH,
claim_code,
exchange_token,
forget_sign_in,
get_sign_in,
mark_login_sent,
remember_code_owner,
start_sign_in,
)

LOGIN_PATH = "/dashboard/login"


# nosemgrep: guest-whitelisted-method -- pilot_credential_auth verifies the caller below.
@frappe.whitelist(allow_guest=True, methods=["POST"])
@pilot_credential_auth
def start(provider: str, state: str, code_challenge: str, return_url: str) -> dict:
"""Called by a site through its Pilot: remember where to send the browser back, return the provider's sign-in link."""
credential = frappe.local.pilot_credential
return start_sign_in(provider, state, code_challenge, return_url, credential.team, credential.server)


# nosemgrep: guest-whitelisted-method -- the provider sends the browser here; the code only goes to the site's team.
@frappe.whitelist(allow_guest=True, methods=["GET"])
def callback(
state: str | None = None,
code: str | None = None,
error: str | None = None,
error_description: str | None = None,
) -> None:
"""Every provider sends the browser here. Single use: the note is deleted on the first read."""
note = get_sign_in(state)
if not note:
frappe.respond_as_web_page(
_("Link expired"),
_("This sign-in has expired or was already used. Please start again from your site."),
http_status_code=400,
primary_action=None,
)
return
# a logged-out browser signs in to Central once, then comes back here with the same code (D3)
if code and not error and frappe.session.user == "Guest" and not note.get("login_sent"):
mark_login_sent(state, note)
back = add_query_params(CALLBACK_PATH, state=state, code=code)
redirect(add_query_params(LOGIN_PATH, **{"redirect-to": back}))
return
forget_sign_in(state)
redirect(
add_query_params(note["return_url"], state=state, **site_params(note, code, error, error_description))
)


def site_params(note: dict, code: str | None, error: str | None, error_description: str | None) -> dict:
if error or not code:
return {"error": error or "invalid_request", "error_description": error_description}
# the code goes only to the site's team, so a stranger's site never gets it (consent phishing)
if can(frappe.session.user, note["team"], "server:view", server=note["server"]):
remember_code_owner(code, note["team"], note["server"])
return {"code": code}
return {"error": "not_team_member"}


def redirect(location: str) -> None:
frappe.local.response.type = "redirect"
frappe.local.response.location = location


def add_query_params(url: str, **params: str | None) -> str:
return f"{url}{'&' if '?' in url else '?'}{urlencode({k: v for k, v in params.items() if v})}"


# nosemgrep: guest-whitelisted-method -- pilot_credential_auth verifies the caller below.
@frappe.whitelist(allow_guest=True, methods=["POST"])
@pilot_credential_auth
def relay_token(
provider: str,
grant_type: str,
code: str | None = None,
code_verifier: str | None = None,
refresh_token: str | None = None,
scope: str | None = None,
) -> dict:
"""Called by a site through its Pilot: swap a code or refresh token at the provider using Frappe Cloud's app secret."""
if grant_type == "authorization_code": # initial exchange of the authorization code for a token
credential = frappe.local.pilot_credential
claim_code(code, credential.team, credential.server)
return exchange_token(
provider,
grant_type,
code=code,
code_verifier=code_verifier,
refresh_token=refresh_token,
scope=scope,
)
Empty file.
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
// Copyright (c) 2026, frappe and contributors
// For license information, please see license.txt

// frappe.ui.form.on("Email OAuth Provider", {
// refresh(frm) {

// },
// });
122 changes: 122 additions & 0 deletions central/central/doctype/email_oauth_provider/email_oauth_provider.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
{
"actions": [],
"allow_bulk_edit": 1,
"autoname": "field:provider",
"creation": "2026-10-20 14:50:38.036333",
"doctype": "DocType",
"editable_grid": 1,
"engine": "InnoDB",
"field_order": [
"enabled",
"provider",
"client_id",
"client_secret",
"column_break_app",
"endpoints_section",
"authorize_url",
"token_url",
"sign_in_section",
"scopes",
"query_parameters"
],
"fields": [
{
"description": "The key sites sign in with, e.g. microsoft",
"fieldname": "provider",
"fieldtype": "Data",
"in_list_view": 1,
"label": "Provider",
"reqd": 1,
"set_only_once": 1,
"unique": 1
},
{
"default": "0",
"fieldname": "enabled",
"fieldtype": "Check",
"in_list_view": 1,
"label": "Enabled"
Comment thread
RitvikSardana marked this conversation as resolved.
Resolved
},
{
"fieldname": "column_break_app",
"fieldtype": "Column Break"
},
{
"fieldname": "client_id",
"fieldtype": "Data",
"label": "Client ID"
},
{
"fieldname": "client_secret",
"fieldtype": "Password",
"label": "Client Secret"
},
{
"fieldname": "endpoints_section",
"fieldtype": "Section Break",
"label": "Endpoints"
},
{
"fieldname": "authorize_url",
"fieldtype": "Data",
"in_list_view": 1,
"label": "Authorize URL",
"options": "URL",
"reqd": 1
},
{
"fieldname": "token_url",
"fieldtype": "Data",
"in_list_view": 1,
"label": "Token URL",
"options": "URL",
"reqd": 1
},
{
"fieldname": "sign_in_section",
"fieldtype": "Section Break",
"label": "Sign-in"
},
{
"fieldname": "scopes",
"fieldtype": "Table",
"label": "Scopes",
"options": "OAuth Scope"
},
{
"description": "Added to the sign-in link",
"fieldname": "query_parameters",
"fieldtype": "Table",
"label": "Query Parameters",
"options": "Query Parameters"
}
],
"grid_page_length": 50,
"links": [],
"modified": "2026-10-21 00:44:49.250559",
"modified_by": "Administrator",
"module": "Central",
"name": "Email OAuth Provider",
"naming_rule": "By fieldname",
"owner": "Administrator",
"permissions": [
{
"create": 1,
"delete": 1,
"email": 1,
"export": 1,
"print": 1,
"read": 1,
"report": 1,
"role": "System Manager",
"share": 1,
"write": 1
}
],
"row_format": "Dynamic",
"rows_threshold_for_grid_search": 20,
"sort_field": "creation",
"sort_order": "DESC",
"states": [],
"track_changes": 1
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
# Copyright (c) 2026, frappe and contributors
# For license information, please see license.txt

import frappe
from frappe import _
from frappe.model.document import Document


class EmailOAuthProvider(Document):
# begin: auto-generated types
# This code is auto-generated. Do not modify anything in this block.

from typing import TYPE_CHECKING

if TYPE_CHECKING:
from frappe.integrations.doctype.oauth_scope.oauth_scope import OAuthScope
from frappe.integrations.doctype.query_parameters.query_parameters import QueryParameters
from frappe.types import DF

authorize_url: DF.Data
client_id: DF.Data | None
client_secret: DF.Password | None
enabled: DF.Check
provider: DF.Data
query_parameters: DF.Table[QueryParameters]
scopes: DF.Table[OAuthScope]
token_url: DF.Data
# end: auto-generated types

def validate(self):
for field in ("authorize_url", "token_url"):
if not self.get(field).startswith("https://"):
frappe.throw(
_("{0} must start with https://").format(_(self.meta.get_label(field))),
title=_("Invalid URL"),
)
if self.enabled and not (
self.client_id and self.get_password("client_secret", raise_exception=False)
):
frappe.throw(
_("Add the Client ID and Client Secret before enabling {0}").format(self.provider),
title=_("Missing credentials"),
)

def get_scopes(self) -> list[str]:
return [row.scope for row in self.scopes]

def get_query_params(self) -> dict[str, str]:
return {row.key: row.value for row in self.query_parameters}
17 changes: 16 additions & 1 deletion central/central/sidebar/central/central.json
Original file line number Diff line number Diff line change
Expand Up @@ -666,9 +666,24 @@
"open_in_new_tab": 1,
"show_arrow": 0,
"type": "Link"
},
{
"added": 0,
"child": 1,
"collapsible": 1,
"hidden": 0,
"indent": 0,
"is_default_module": 0,
"keep_closed": 0,
"label": "Email OAuth Provider",
"link_to": "Email OAuth Provider",
"link_type": "DocType",
"open_in_new_tab": 1,
"show_arrow": 0,
"type": "Link"
}
],
"modified": "2026-10-11 10:00:00.000000",
"modified": "2026-10-20 10:00:00.000000",
"modified_by": "Administrator",
"module": "Central",
"name": "Central",
Expand Down
3 changes: 3 additions & 0 deletions central/hooks.py
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,7 @@
"central.billing.platform.constraints.ensure_constraints",
"central.billing.settings.ensure_welcome_credit_amounts",
"central.billing.gateways.setup.ensure_gateway_records",
"central.integrations.email_oauth.setup.ensure_email_oauth_providers",
"central.billing.navigation.ensure_workspace_sidebars",
]

Expand Down Expand Up @@ -255,6 +256,7 @@
"central.billing.settings.ensure_snapshot_settings",
"central.billing.platform.constraints.ensure_constraints",
"central.billing.gateways.setup.ensure_gateway_records",
"central.integrations.email_oauth.setup.ensure_email_oauth_providers",
"central.billing.navigation.ensure_workspace_sidebars",
]

Expand All @@ -269,6 +271,7 @@
"central.billing.platform.constraints.ensure_constraints",
"central.billing.settings.ensure_welcome_credit_amounts",
"central.billing.gateways.setup.ensure_gateway_records",
"central.integrations.email_oauth.setup.ensure_email_oauth_providers",
"central.billing.navigation.ensure_workspace_sidebars",
]

Expand Down
Empty file.
Loading
Loading