Upstream version 9.38.198.0
[platform/framework/web/crosswalk.git] / src / chrome / browser / extensions / api / identity / web_auth_flow.cc
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "chrome/browser/extensions/api/identity/web_auth_flow.h"
6
7 #include "apps/app_window.h"
8 #include "base/base64.h"
9 #include "base/debug/trace_event.h"
10 #include "base/location.h"
11 #include "base/message_loop/message_loop.h"
12 #include "base/strings/string_util.h"
13 #include "base/strings/utf_string_conversions.h"
14 #include "chrome/browser/extensions/component_loader.h"
15 #include "chrome/browser/extensions/extension_service.h"
16 #include "chrome/browser/profiles/profile.h"
17 #include "chrome/common/extensions/api/identity_private.h"
18 #include "chrome/common/extensions/extension_constants.h"
19 #include "content/public/browser/navigation_details.h"
20 #include "content/public/browser/navigation_entry.h"
21 #include "content/public/browser/notification_details.h"
22 #include "content/public/browser/notification_service.h"
23 #include "content/public/browser/notification_source.h"
24 #include "content/public/browser/notification_types.h"
25 #include "content/public/browser/render_frame_host.h"
26 #include "content/public/browser/resource_request_details.h"
27 #include "content/public/browser/web_contents.h"
28 #include "crypto/random.h"
29 #include "extensions/browser/event_router.h"
30 #include "extensions/browser/extension_system.h"
31 #include "extensions/browser/guest_view/guest_view_base.h"
32 #include "grit/browser_resources.h"
33 #include "url/gurl.h"
34
35 using apps::AppWindow;
36 using content::RenderViewHost;
37 using content::ResourceRedirectDetails;
38 using content::WebContents;
39 using content::WebContentsObserver;
40
41 namespace extensions {
42
43 namespace identity_private = api::identity_private;
44
45 WebAuthFlow::WebAuthFlow(
46     Delegate* delegate,
47     Profile* profile,
48     const GURL& provider_url,
49     Mode mode)
50     : delegate_(delegate),
51       profile_(profile),
52       provider_url_(provider_url),
53       mode_(mode),
54       embedded_window_created_(false) {
55 }
56
57 WebAuthFlow::~WebAuthFlow() {
58   DCHECK(delegate_ == NULL);
59
60   // Stop listening to notifications first since some of the code
61   // below may generate notifications.
62   registrar_.RemoveAll();
63   WebContentsObserver::Observe(NULL);
64
65   if (!app_window_key_.empty()) {
66     apps::AppWindowRegistry::Get(profile_)->RemoveObserver(this);
67
68     if (app_window_ && app_window_->web_contents())
69       app_window_->web_contents()->Close();
70   }
71 }
72
73 void WebAuthFlow::Start() {
74   apps::AppWindowRegistry::Get(profile_)->AddObserver(this);
75
76   // Attach a random ID string to the window so we can recoginize it
77   // in OnAppWindowAdded.
78   std::string random_bytes;
79   crypto::RandBytes(WriteInto(&random_bytes, 33), 32);
80   base::Base64Encode(random_bytes, &app_window_key_);
81
82   // identityPrivate.onWebFlowRequest(app_window_key, provider_url_, mode_)
83   scoped_ptr<base::ListValue> args(new base::ListValue());
84   args->AppendString(app_window_key_);
85   args->AppendString(provider_url_.spec());
86   if (mode_ == WebAuthFlow::INTERACTIVE)
87     args->AppendString("interactive");
88   else
89     args->AppendString("silent");
90
91   scoped_ptr<Event> event(
92       new Event(identity_private::OnWebFlowRequest::kEventName, args.Pass()));
93   event->restrict_to_browser_context = profile_;
94   ExtensionSystem* system = ExtensionSystem::Get(profile_);
95
96   extensions::ComponentLoader* component_loader =
97       system->extension_service()->component_loader();
98   if (!component_loader->Exists(extension_misc::kIdentityApiUiAppId)) {
99     component_loader->Add(
100         IDR_IDENTITY_API_SCOPE_APPROVAL_MANIFEST,
101         base::FilePath(FILE_PATH_LITERAL("identity_scope_approval_dialog")));
102   }
103
104   system->event_router()->DispatchEventWithLazyListener(
105       extension_misc::kIdentityApiUiAppId, event.Pass());
106 }
107
108 void WebAuthFlow::DetachDelegateAndDelete() {
109   delegate_ = NULL;
110   base::MessageLoop::current()->DeleteSoon(FROM_HERE, this);
111 }
112
113 void WebAuthFlow::OnAppWindowAdded(AppWindow* app_window) {
114   if (app_window->window_key() == app_window_key_ &&
115       app_window->extension_id() == extension_misc::kIdentityApiUiAppId) {
116     app_window_ = app_window;
117     WebContentsObserver::Observe(app_window->web_contents());
118
119     registrar_.Add(
120         this,
121         content::NOTIFICATION_WEB_CONTENTS_RENDER_VIEW_HOST_CREATED,
122         content::NotificationService::AllBrowserContextsAndSources());
123   }
124 }
125
126 void WebAuthFlow::OnAppWindowRemoved(AppWindow* app_window) {
127   if (app_window->window_key() == app_window_key_ &&
128       app_window->extension_id() == extension_misc::kIdentityApiUiAppId) {
129     app_window_ = NULL;
130     registrar_.RemoveAll();
131
132     if (delegate_)
133       delegate_->OnAuthFlowFailure(WebAuthFlow::WINDOW_CLOSED);
134   }
135 }
136
137 void WebAuthFlow::BeforeUrlLoaded(const GURL& url) {
138   if (delegate_ && embedded_window_created_)
139     delegate_->OnAuthFlowURLChange(url);
140 }
141
142 void WebAuthFlow::AfterUrlLoaded() {
143   if (delegate_ && embedded_window_created_ && mode_ == WebAuthFlow::SILENT)
144     delegate_->OnAuthFlowFailure(WebAuthFlow::INTERACTION_REQUIRED);
145 }
146
147 void WebAuthFlow::Observe(int type,
148                           const content::NotificationSource& source,
149                           const content::NotificationDetails& details) {
150   DCHECK(app_window_);
151
152   if (!delegate_)
153     return;
154
155   if (!embedded_window_created_) {
156     DCHECK(type == content::NOTIFICATION_WEB_CONTENTS_RENDER_VIEW_HOST_CREATED);
157
158     RenderViewHost* render_view(
159         content::Details<RenderViewHost>(details).ptr());
160     WebContents* web_contents = WebContents::FromRenderViewHost(render_view);
161     GuestViewBase* guest = GuestViewBase::FromWebContents(web_contents);
162     WebContents* embedder = guest ? guest->embedder_web_contents() : NULL;
163     if (web_contents &&
164         (embedder == WebContentsObserver::web_contents())) {
165       // Switch from watching the app window to the guest inside it.
166       embedded_window_created_ = true;
167       WebContentsObserver::Observe(web_contents);
168
169       registrar_.RemoveAll();
170       registrar_.Add(this,
171                      content::NOTIFICATION_RESOURCE_RECEIVED_REDIRECT,
172                      content::Source<WebContents>(web_contents));
173       registrar_.Add(this,
174                      content::NOTIFICATION_WEB_CONTENTS_TITLE_UPDATED,
175                      content::Source<WebContents>(web_contents));
176     }
177   } else {
178     // embedded_window_created_
179     switch (type) {
180       case content::NOTIFICATION_RESOURCE_RECEIVED_REDIRECT: {
181         ResourceRedirectDetails* redirect_details =
182             content::Details<ResourceRedirectDetails>(details).ptr();
183         if (redirect_details != NULL)
184           BeforeUrlLoaded(redirect_details->new_url);
185         break;
186       }
187       case content::NOTIFICATION_WEB_CONTENTS_TITLE_UPDATED: {
188         std::pair<content::NavigationEntry*, bool>* title =
189             content::Details<std::pair<content::NavigationEntry*, bool> >(
190                 details).ptr();
191
192         if (title->first) {
193           delegate_->OnAuthFlowTitleChange(
194               base::UTF16ToUTF8(title->first->GetTitle()));
195         }
196         break;
197       }
198       default:
199         NOTREACHED()
200             << "Got a notification that we did not register for: " << type;
201         break;
202     }
203   }
204 }
205
206 void WebAuthFlow::RenderProcessGone(base::TerminationStatus status) {
207   if (delegate_)
208     delegate_->OnAuthFlowFailure(WebAuthFlow::WINDOW_CLOSED);
209 }
210
211 void WebAuthFlow::DidStartProvisionalLoadForFrame(
212     content::RenderFrameHost* render_frame_host,
213     const GURL& validated_url,
214     bool is_error_page,
215     bool is_iframe_srcdoc) {
216   if (!render_frame_host->GetParent())
217     BeforeUrlLoaded(validated_url);
218 }
219
220 void WebAuthFlow::DidFailProvisionalLoad(
221     content::RenderFrameHost* render_frame_host,
222     const GURL& validated_url,
223     int error_code,
224     const base::string16& error_description) {
225   TRACE_EVENT_ASYNC_STEP_PAST1("identity",
226                                "WebAuthFlow",
227                                this,
228                                "DidFailProvisionalLoad",
229                                "error_code",
230                                error_code);
231   if (delegate_)
232     delegate_->OnAuthFlowFailure(LOAD_FAILED);
233 }
234
235 void WebAuthFlow::DidStopLoading(RenderViewHost* render_view_host) {
236   AfterUrlLoaded();
237 }
238
239 void WebAuthFlow::DidNavigateMainFrame(
240     const content::LoadCommittedDetails& details,
241     const content::FrameNavigateParams& params) {
242   if (delegate_ && details.http_status_code >= 400)
243     delegate_->OnAuthFlowFailure(LOAD_FAILED);
244 }
245
246 }  // namespace extensions