class OAuth2FrontendController(RedditController): def check_for_bearer_token(self): pass def pre(self): RedditController.pre(self) require_https() def _check_redirect_uri(self, client, redirect_uri): if not redirect_uri or not client or redirect_uri != client.redirect_uri: abort(ForbiddenError(errors.OAUTH2_INVALID_REDIRECT_URI)) def _error_response(self, state, redirect_uri, as_fragment=False): """Return an error redirect, but only if client_id and redirect_uri are valid.""" resp = {"state": state} if (errors.OAUTH2_INVALID_CLIENT, "client_id") in c.errors: resp["error"] = "unauthorized_client" elif (errors.OAUTH2_ACCESS_DENIED, "authorize") in c.errors: resp["error"] = "access_denied" elif (errors.BAD_HASH, None) in c.errors: resp["error"] = "access_denied" elif (errors.INVALID_OPTION, "response_type") in c.errors: resp["error"] = "unsupported_response_type" elif (errors.OAUTH2_INVALID_SCOPE, "scope") in c.errors: resp["error"] = "invalid_scope" else: resp["error"] = "invalid_request" final_redirect = _update_redirect_uri(redirect_uri, resp, as_fragment) return self.redirect(final_redirect, code=302) @validate(VUser(), response_type=VOneOf("response_type", ("code", "token")), client=VOAuth2ClientID(), redirect_uri=VRequired("redirect_uri", errors.OAUTH2_INVALID_REDIRECT_URI), scope=VOAuth2Scope(), state=VRequired("state", errors.NO_TEXT), duration=VOneOf("duration", ("temporary", "permanent"), default="temporary")) def GET_authorize(self, response_type, client, redirect_uri, scope, state, duration): """ First step in [OAuth 2.0](http://oauth.net/2/) authentication. End users will be prompted for their credentials (username/password) and asked if they wish to authorize the application identified by the **client_id** parameter with the permissions specified by the **scope** parameter. They are then redirected to the endpoint on the client application's side specified by **redirect_uri**. If the user granted permission to the application, the response will contain a **code** parameter with a temporary authorization code which can be exchanged for an access token at [/api/v1/access_token](#api_method_access_token). **redirect_uri** must match the URI configured for the client in the [app preferences](/prefs/apps). If **client_id** or **redirect_uri** is not valid, or if the call does not take place over SSL, a 403 error will be returned. For all other errors, a redirect to **redirect_uri** will be returned, with a **error** parameter indicating why the request failed. """ # Check redirect URI first; it will ensure client exists self._check_redirect_uri(client, redirect_uri) if response_type == "token" and client.is_confidential(): # Prevent "confidential" clients from distributing tokens # in a non-confidential manner c.errors.add((errors.OAUTH2_INVALID_CLIENT, "client_id")) if response_type == "token" and duration != "temporary": # implicit grant -> No refresh tokens allowed c.errors.add((errors.INVALID_OPTION, "duration")) if not c.errors: return OAuth2AuthorizationPage(client, redirect_uri, scope, state, duration, response_type).render() else: return self._error_response(state, redirect_uri, as_fragment=(response_type == "token")) @validate(VUser(), VModhash(fatal=False), client=VOAuth2ClientID(), redirect_uri=VRequired("redirect_uri", errors.OAUTH2_INVALID_REDIRECT_URI), scope=VOAuth2Scope(), state=VRequired("state", errors.NO_TEXT), duration=VOneOf("duration", ("temporary", "permanent"), default="temporary"), authorize=VRequired("authorize", errors.OAUTH2_ACCESS_DENIED), response_type=VOneOf("response_type", ("code", "token"), default="code")) def POST_authorize(self, authorize, client, redirect_uri, scope, state, duration, response_type): """Endpoint for OAuth2 authorization.""" if response_type == "token" and client.is_confidential(): # Prevent "confidential" clients from distributing tokens # in a non-confidential manner c.errors.add((errors.OAUTH2_INVALID_CLIENT, "client_id")) if response_type == "token" and duration != "temporary": # implicit grant -> No refresh tokens allowed c.errors.add((errors.INVALID_OPTION, "duration")) self._check_redirect_uri(client, redirect_uri) if c.errors: return self._error_response(state, redirect_uri, as_fragment=(response_type == "token")) if response_type == "code": code = OAuth2AuthorizationCode._new(client._id, redirect_uri, c.user._id36, scope, duration == "permanent") resp = {"code": code._id, "state": state} final_redirect = _update_redirect_uri(redirect_uri, resp) elif response_type == "token": token = OAuth2AccessToken._new(client._id, c.user._id36, scope) token_data = OAuth2AccessController._make_token_dict(token) token_data["state"] = state final_redirect = _update_redirect_uri(redirect_uri, token_data, as_fragment=True) return self.redirect(final_redirect, code=302)
class OAuth2FrontendController(RedditController): def check_for_bearer_token(self): pass def pre(self): RedditController.pre(self) require_https() def _abort_oauth_error(self, error): g.stats.simple_event('oauth2.errors.%s' % error) abort(BadRequestError(error)) def _check_redirect_uri(self, client, redirect_uri): if (errors.OAUTH2_INVALID_CLIENT, 'client_id') in c.errors: self._abort_oauth_error(errors.OAUTH2_INVALID_CLIENT) if not redirect_uri or redirect_uri != client.redirect_uri: self._abort_oauth_error(errors.OAUTH2_INVALID_REDIRECT_URI) def _check_response_type_and_scope(self, response_type, scope): if (errors.INVALID_OPTION, 'response_type') in c.errors: self._abort_oauth_error(errors.OAUTH2_INVALID_RESPONSE_TYPE) if (errors.OAUTH2_INVALID_SCOPE, 'scope') in c.errors: self._abort_oauth_error(errors.OAUTH2_INVALID_SCOPE) def _check_client_type_and_duration(self, response_type, client, duration): if response_type == "token" and client.is_confidential(): # Prevent "confidential" clients from distributing tokens # in a non-confidential manner self._abort_oauth_error(errors.OAUTH2_CONFIDENTIAL_TOKEN) if response_type == "token" and duration != "temporary": # implicit grant -> No refresh tokens allowed self._abort_oauth_error(errors.OAUTH2_NO_REFRESH_TOKENS_ALLOWED) def _error_response(self, state, redirect_uri, as_fragment=False): """Return an error redirect.""" resp = {"state": state} if (errors.OAUTH2_ACCESS_DENIED, "authorize") in c.errors: resp["error"] = "access_denied" elif (errors.INVALID_MODHASH, None) in c.errors: resp["error"] = "access_denied" else: resp["error"] = "invalid_request" final_redirect = _update_redirect_uri(redirect_uri, resp, as_fragment) return self.redirect(final_redirect, code=302) def _check_employee_grants(self, client, scope): if not c.user.employee or not client or not scope: return if client._id in g.employee_approved_clients: return if client._id in g.mobile_auth_allowed_clients: return # The identity scope doesn't leak much, and we don't mind if employees # prove their identity to some external service if scope.scopes == {"identity"}: return error_page = RedditError( title=_('this app has not been approved for use with employee accounts'), message="", ) request.environ["usable_error_content"] = error_page.render() self.abort403() @validate(VUser(), response_type = VOneOf("response_type", ("code", "token")), client = VOAuth2ClientID(), redirect_uri = VRequired("redirect_uri", errors.OAUTH2_INVALID_REDIRECT_URI), scope = VOAuth2Scope(), state = VRequired("state", errors.NO_TEXT), duration = VOneOf("duration", ("temporary", "permanent"), default="temporary")) def GET_authorize(self, response_type, client, redirect_uri, scope, state, duration): """ First step in [OAuth 2.0](http://oauth.net/2/) authentication. End users will be prompted for their credentials (username/password) and asked if they wish to authorize the application identified by the **client_id** parameter with the permissions specified by the **scope** parameter. They are then redirected to the endpoint on the client application's side specified by **redirect_uri**. If the user granted permission to the application, the response will contain a **code** parameter with a temporary authorization code which can be exchanged for an access token at [/api/v1/access_token](#api_method_access_token). **redirect_uri** must match the URI configured for the client in the [app preferences](/prefs/apps). All errors will show a 400 error page along with some information on what option was wrong. """ self._check_employee_grants(client, scope) # Check redirect URI first; it will ensure client exists self._check_redirect_uri(client, redirect_uri) self._check_response_type_and_scope(response_type, scope) self._check_client_type_and_duration(response_type, client, duration) if not c.errors: return OAuth2AuthorizationPage(client, redirect_uri, scope, state, duration, response_type).render() else: self._abort_oauth_error(errors.INVALID_OPTION) @validate(VUser(), VModhash(fatal=False), client = VOAuth2ClientID(), redirect_uri = VRequired("redirect_uri", errors.OAUTH2_INVALID_REDIRECT_URI), scope = VOAuth2Scope(), state = VRequired("state", errors.NO_TEXT), duration = VOneOf("duration", ("temporary", "permanent"), default="temporary"), authorize = VRequired("authorize", errors.OAUTH2_ACCESS_DENIED), response_type = VOneOf("response_type", ("code", "token"), default="code")) def POST_authorize(self, authorize, client, redirect_uri, scope, state, duration, response_type): """Endpoint for OAuth2 authorization.""" self._check_employee_grants(client, scope) self._check_redirect_uri(client, redirect_uri) self._check_response_type_and_scope(response_type, scope) self._check_client_type_and_duration(response_type, client, duration) if c.errors: return self._error_response(state, redirect_uri, as_fragment=(response_type == "token")) if response_type == "code": code = OAuth2AuthorizationCode._new(client._id, redirect_uri, c.user._id36, scope, duration == "permanent") resp = {"code": code._id, "state": state} final_redirect = _update_redirect_uri(redirect_uri, resp) g.stats.simple_event('oauth2.POST_authorize.authorization_code_create') elif response_type == "token": device_id = get_device_id(client) token = OAuth2AccessToken._new( client_id=client._id, user_id=c.user._id36, scope=scope, device_id=device_id, ) resp = OAuth2AccessController._make_new_token_response(token) resp["state"] = state final_redirect = _update_redirect_uri(redirect_uri, resp, as_fragment=True) g.stats.simple_event('oauth2.POST_authorize.access_token_create') # If this is the first time the user is logging in with an official # mobile app, gild them if (g.live_config.get('mobile_gild_first_login') and not c.user.has_used_mobile_app and client._id in g.mobile_auth_gild_clients): buyer = Account.system_user() admintools.adjust_gold_expiration( c.user, days=g.mobile_auth_gild_time) create_gift_gold( buyer._id, c.user._id, g.mobile_auth_gild_time, datetime.now(g.tz), signed=True, note='first_mobile_auth') subject = 'Let there be gold! Reddit just sent you Reddit gold!' message = ( "Thank you for using the Reddit mobile app! As a thank you " "for logging in during launch week, you've been gifted %s of " "Reddit Gold.\n\n" "Reddit Gold is Reddit's premium membership program, which " "grants you: \n" "An ads-free experience in Reddit's mobile apps, and\n" "Extra site features on desktop\n\n" "Discuss and get help on the features and perks at " "r/goldbenefits." ) % g.mobile_auth_gild_message message += '\n\n' + strings.gold_benefits_msg send_system_message(c.user, subject, message, add_to_sent=False) c.user.has_used_mobile_app = True c.user._commit() return self.redirect(final_redirect, code=302)