Merge branch 'master' into history
[potlatch2.git] / net / systemeD / potlatch2 / save / OAuthPanel.mxml
1 <?xml version="1.0" encoding="utf-8"?>
2 <mx:TitleWindow
3     xmlns:fx="http://ns.adobe.com/mxml/2009"
4         xmlns:mx="library://ns.adobe.com/flex/mx"
5         layout="vertical"
6         horizontalAlign="center" title="Authorisation Required"
7         creationComplete="getRequestToken()"
8         height="290">
9         
10         <mx:ViewStack id="contentStack" width="100%" height="100%">
11         
12         <mx:VBox id="okPanel" width="100%" height="100%">
13           <mx:Text width="100%" text="{getAuthText()}"/>
14           <mx:VBox width="100%" id="gotLinkBox" visible="false">
15             <mx:Text width="100%">
16               <mx:text>
17                 Click the link below to open a web page where
18                 you will be asked to authorise access to this app.
19               </mx:text>
20             </mx:Text>
21             <mx:LinkButton id="link"
22                 label="http://oauth.dev.openstreetmap.org/oauth/authorize?somekey"
23                 click="openURL(authoriseURL); tryAccessButton.enabled=true;"/>
24             <mx:Text id="authorized" width="100%">
25               <mx:text>Once you've authorised the access click the 'Try Access' button below</mx:text> <!-- ' -->
26             </mx:Text>
27             <mx:Text styleName="failText" visible="false" id="deniedLabel">
28               <mx:text><![CDATA[<b>Access was denied, please check, and try again</b>]]></mx:text>
29             </mx:Text>
30             <mx:HBox width="100%" horizontalAlign="right">
31               <mx:CheckBox id="rememberMe" label="Remember authorisation" selected="true"/>
32             </mx:HBox>
33           </mx:VBox>
34         </mx:VBox>
35         
36         <mx:VBox id="permFailPanel" width="100%" height="100%">
37           <mx:Text id="permFail" styleName="failText" width="100%" condenseWhite="true">
38             <mx:htmlText><![CDATA[
39               <p>The server refused this application's credentials -- an authorisation link
40               could not be obtained.
41               </p><p>
42               <b>OAuth access will not be possible.</b>
43               </p><p>
44               Please contact application vendor to find out what's going on.
45             ]]></mx:htmlText>
46           </mx:Text>
47         </mx:VBox>
48         
49         <mx:VBox id="tempFailPanel" width="100%" height="100%">
50           <mx:Text id="tempFail" width="100%">
51             <mx:text>
52               There was a problem contacting the server to get authorisation.
53               This may be a temporary error, try again later.
54             </mx:text>
55           </mx:Text>
56         </mx:VBox>
57         
58         </mx:ViewStack>
59         
60         <mx:ControlBar horizontalAlign="right">
61         
62             <mx:ProgressBar id="progress" label="Contacting server..." labelPlacement="top"
63                 indeterminate="true"/>
64         <mx:Spacer width="100%"/>
65
66             <mx:Button id="cancelButton" label="Cancel" click="PopUpManager.removePopUp(this);" styleName="titleWindowButton" />
67             <mx:Button id="tryAccessButton" label="Try Access" click="getAccessToken()" enabled="false" styleName="titleWindowButton" />
68         </mx:ControlBar>
69         
70         <fx:Script><![CDATA[
71                 import flash.display.InteractiveObject;
72         import flash.events.Event;
73         import flash.net.*;
74                 import flash.system.Capabilities;
75         import mx.managers.PopUpManager;
76         import net.systemeD.halcyon.connection.*;
77         import org.iotashan.oauth.*;
78                 import flash.external.ExternalInterface;
79
80         private var connection:Connection;
81         private var requestToken:OAuthToken;
82         private var _accessToken:OAuthToken;
83         private var authoriseURL:String;
84         private var lastHTTPStatus:int = 0;
85         private var waiting:Boolean = false;
86         
87         public static var ACCESS_TOKEN_EVENT:String = "gotAccessToken";
88         
89         private function getAuthText():String {
90             return "To save data you must authorise this application to edit "+
91                     connection.serverName + " on your behalf.";
92         }
93         
94                 public function setConnection(connection:Connection):void {
95                         this.connection=connection;
96                         if (waiting) { waiting=false; getRequestToken(); }
97                 }
98
99         private function openURL(url:String):void {
100                         if (ExternalInterface.available) {
101                                 var winH:int = 560;
102                                 var winW:int = 600;
103                                 var leftPos:int  = (Capabilities.screenResolutionX - winW) / 2;
104                                 var topPos:int = (Capabilities.screenResolutionY - winH) / 2;
105                                 ExternalInterface.call( "window.open", url,"oAuthWin","height=" + winH + ",width=" + winW +",top=" + topPos + ", left=" + leftPos +", toolbar=no,scrollbars=no,status=no,location=no,menubar=no,directories=no");
106                                 }               
107                         else
108                         {
109                                 var urlRequest:URLRequest = new URLRequest(url);
110                                 navigateToURL(urlRequest,"_blank");
111                         }
112                 }
113         
114         private function getRequestToken():void {
115             if (!connection) { waiting=true; return; }  // in case the connection hasn't been set yet
116
117             var sig:IOAuthSignatureMethod = new OAuthSignatureMethod_HMAC_SHA1();
118             var consumer:OAuthConsumer = getConsumer();
119             var url:String = connection.getParam("oauth_request_url", "http://127.0.0.1:3000/oauth/request_token");
120             
121             var params:Object = new Object();
122             var oauthRequest:OAuthRequest = new OAuthRequest("GET", url, params, consumer, null);
123             var urlStr:Object = oauthRequest.buildRequest(sig, OAuthRequest.RESULT_TYPE_URL_STRING)
124
125                         //register the "pressTry" function so the oAuth callback page can try to advance the editor directly to the next step
126                         ExternalInterface.addCallback("pressTry", pressTry);            
127                         
128             // build the actual request
129             var urlReq:URLRequest = new URLRequest(String(urlStr));
130             var loader:URLLoader = new URLLoader();
131             loader.addEventListener(Event.COMPLETE, loadedRequestToken);
132             loader.addEventListener(IOErrorEvent.IO_ERROR, requestTokenError);
133             loader.addEventListener(HTTPStatusEvent.HTTP_STATUS, recordStatus);
134             loader.load(urlReq);
135         }
136         
137         private function recordStatus(event:HTTPStatusEvent):void {
138             lastHTTPStatus = event.status;
139         }
140         
141         private function requestTokenError(event:IOErrorEvent):void {
142             trace("error occured... last status was: "+lastHTTPStatus);
143             
144             if ( lastHTTPStatus == 401 ) {
145                 // this means authorisation was refused -- refused at this stage
146                 // means our consumer token is broken
147                 contentStack.selectedChild = permFailPanel;
148             } else {
149                 contentStack.selectedChild = tempFailPanel;
150             }
151             progress.visible = false;
152         }
153         
154         private function loadedRequestToken(event:Event):void {
155             trace("Yay! response: "+URLLoader(event.target).data);
156             requestToken = getResponseToken(URLLoader(event.target));
157             
158             var url:String = connection.getParam("oauth_auth_url", "http://127.0.0.1:3000/oauth/authorize");            
159             link.label = url;
160                         authoriseURL = url + "?oauth_token="+requestToken.key;
161                         progress.visible = false;
162             gotLinkBox.visible = true;
163         }
164
165         private function getResponseToken(loader:URLLoader):OAuthToken {
166             var vars:URLVariables = new URLVariables(loader.data);
167             
168             // build out request token
169             var token:OAuthToken = new OAuthToken(
170                 String(vars["oauth_token"]),
171                 String(vars["oauth_token_secret"]));
172             return token;
173         }
174         
175         private function getAccessToken():void {
176             var sig:IOAuthSignatureMethod = new OAuthSignatureMethod_HMAC_SHA1();
177             var consumer:OAuthConsumer = getConsumer();
178             var url:String = connection.getParam("oauth_access_url", "http://127.0.0.1:3000/oauth/access_token");
179
180             var oauthRequest:OAuthRequest = new OAuthRequest("GET", url, null, consumer, requestToken);
181             var urlStr:Object = oauthRequest.buildRequest(sig, OAuthRequest.RESULT_TYPE_URL_STRING)
182
183             var urlReq:URLRequest = new URLRequest(String(urlStr));
184             var loader:URLLoader = new URLLoader();
185             loader.addEventListener(Event.COMPLETE, loadedAccessToken);
186             loader.addEventListener(IOErrorEvent.IO_ERROR, accessTokenError);
187             loader.addEventListener(HTTPStatusEvent.HTTP_STATUS, recordStatus);
188             loader.load(urlReq);
189             
190             progress.label = "Checking access";
191             progress.visible = true;  
192         }
193         
194         private function loadedAccessToken(event:Event):void {
195             trace("Yay! response: "+URLLoader(event.target).data);
196             progress.label = "Received Access";
197             progress.indeterminate = false;
198             progress.setProgress(100,100);
199             PopUpManager.removePopUp(this);
200             
201             _accessToken = getResponseToken(URLLoader(event.target));
202             connection.setAuthToken(_accessToken);
203             dispatchEvent(new Event(ACCESS_TOKEN_EVENT));
204         }
205         
206         public function get accessToken():OAuthToken {
207             return _accessToken;
208         }
209         
210         public function get shouldRemember():Boolean {
211             return rememberMe.selected;
212         }
213         
214         private function accessTokenError(event:IOErrorEvent):void {
215             if ( lastHTTPStatus == 401 ) {
216                 deniedLabel.htmlText = "<b>Access was denied, please check, and try again</b>";
217             } else {
218                 deniedLabel.htmlText = "<b>Error occurred</b> ("+lastHTTPStatus+"): please try again";
219             }
220             deniedLabel.visible = true;
221         }
222         
223         private function getConsumer():OAuthConsumer {
224             var key:String = connection.getParam("oauth_consumer_key", "");
225             var secret:String = connection.getParam("oauth_consumer_secret", "");
226             return new OAuthConsumer(key, secret);
227         }
228                 
229                 public function pressTry():void {
230                         getAccessToken();
231                 }
232         
233         ]]></fx:Script>
234 </mx:TitleWindow>
235