Statistics
| Branch: | Revision:

root / trunk / Pithos.Client.WPF / PithosAccount.cs @ 5d80d038

History | View | Annotate | Download (7.1 kB)

1
#region
2
/* -----------------------------------------------------------------------
3
 * <copyright file="PithosAccount.cs" company="GRNet">
4
 * 
5
 * Copyright 2011-2012 GRNET S.A. All rights reserved.
6
 *
7
 * Redistribution and use in source and binary forms, with or
8
 * without modification, are permitted provided that the following
9
 * conditions are met:
10
 *
11
 *   1. Redistributions of source code must retain the above
12
 *      copyright notice, this list of conditions and the following
13
 *      disclaimer.
14
 *
15
 *   2. Redistributions in binary form must reproduce the above
16
 *      copyright notice, this list of conditions and the following
17
 *      disclaimer in the documentation and/or other materials
18
 *      provided with the distribution.
19
 *
20
 *
21
 * THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
22
 * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
23
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
24
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
25
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
26
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
27
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
28
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
29
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
31
 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
32
 * POSSIBILITY OF SUCH DAMAGE.
33
 *
34
 * The views and conclusions contained in the software and
35
 * documentation are those of the authors and should not be
36
 * interpreted as representing official policies, either expressed
37
 * or implied, of GRNET S.A.
38
 * </copyright>
39
 * -----------------------------------------------------------------------
40
 */
41
#endregion
42

    
43
// </copyright>
44
// -----------------------------------------------------------------------
45

    
46
using System.Reflection;
47
using Pithos.Client.WPF.Preferences;
48
using Pithos.Client.WPF.Properties;
49
using Pithos.Interfaces;
50
using Pithos.Network;
51
using log4net;
52
using System.Windows.Forms;
53
using System.IO;
54
using Newtonsoft.Json;
55
using System.Collections.Generic;
56
using System.Collections.Specialized;
57

    
58

    
59
namespace Pithos.Client.WPF
60
{
61
    using System;
62
    using System.Linq;
63
    using System.Net;
64
    using System.Diagnostics.Contracts;
65
    using System.Diagnostics;
66
    using System.Net.Sockets;
67

    
68
    /// <summary>
69
    /// TODO: Update summary.
70
    /// </summary>
71
    /// <summary>
72
    /// Retrieves an account name and token from PITHOS
73
    /// </summary>
74
    public static class PithosAccount
75
    {
76
        private static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
77

    
78
        /// <summary>
79
        /// Asynchronously retrieves PITHOS credentials
80
        /// </summary>
81
        /// <param name="loginUrl">URL to retrieve the account info from PITHOS. Must end with =</param>
82
        /// <returns>The credentials wrapped in a Task</returns>
83
        public static NetworkCredential RetrieveCredentials(string loginUrl,string accountName=null)
84
        {
85
            Contract.Requires(Uri.IsWellFormedUriString(loginUrl, UriKind.Absolute));
86

    
87
            if (!Uri.IsWellFormedUriString(loginUrl, UriKind.Absolute))
88
                throw new ArgumentException("The pithos site parameter must be a valid absolute URL", "loginUrl");
89
            
90
            //int port = GetFreePort();
91
            
92
            //TODO:Force logout here to take care of existing cookies
93

    
94

    
95
            //var listenerUrl = String.Format("http://127.0.0.1:{0}", port);
96
            var listenerUrl = "pithos://127.0.0.1";
97

    
98
            
99

    
100
            //var receiveCredentials = ListenForRedirectAsync(port);
101

    
102
            //var logoutUrl = loginUrl.Replace("login", "im/logout");
103
            //var logoutProcess=Process.Start(logoutUrl);            
104
            //TaskEx.Delay(2000).Wait();
105

    
106
            //<= 0.13
107
            var uriBuilder = new UriBuilder(loginUrl)
108
                                 {
109
                                     Query = String.Format("next={0}&force=", listenerUrl)
110
                                 };
111

    
112
            var retrieveUri = uriBuilder.Uri;
113

    
114
            var logoutUrl= (from server in Settings.Default.Servers
115
                           where server.LoginUri == loginUrl
116
                               select new Uri(server.LogoutUri)).FirstOrDefault();
117

    
118
            var browser = new LoginView(retrieveUri,logoutUrl,accountName);            
119
            if (true == browser.ShowDialog())
120
            {
121
                return new NetworkCredential(browser.Account, browser.Token);
122
            }
123
            return null;
124

    
125
/*
126

    
127
            Log.InfoFormat("[RETRIEVE] Open Browser at {0}", retrieveUri);
128
            Process.Start(retrieveUri.ToString());
129

    
130
            return receiveCredentials;
131
*/
132
        }
133

    
134
        public static Uri GetLoginUri(string serverUrl)
135
        {
136
            return GetLoginUri(new Uri(serverUrl));
137
        }
138

    
139
        public static Uri GetLoginUri(Uri serverUri)
140
        {
141
            //<=0.13
142
            var loginUri = serverUri.Combine("login");
143
            //var loginUri = new Uri("https://astakos.synnefo.dev.grnet.gr/astakos/weblogin/login");
144
//            WebClient webClient = new WebClient();     
145
//           string catalogResult = webClient.UploadString(tokenUri, "");
146
//            MessageBox.Show(tokenUri.ToString());
147

    
148
            WebRequest webRequest = WebRequest.Create(serverUri);
149
            webRequest.Method = "POST";
150

    
151
      try
152
         {
153
            using (WebResponse response = webRequest.GetResponse())
154
            {
155
                try
156
                {
157
                    using (Stream stream = response.GetResponseStream())
158
                    {
159
                        StreamReader read = new StreamReader(stream, true);
160
                        String responseStr = read.ReadToEnd();
161
                        
162
                        dynamic okeanosServices = JsonConvert.DeserializeObject(responseStr);
163

    
164
                        Uri webLogin = new Uri(okeanosServices["access"]["serviceCatalog"][0]["endpoints"][0]["publicURL"].ToString());
165

    
166
                        webLogin = webLogin.Combine("login");
167

    
168
                        //foreach (var service in okeanosServices["access"]["serviceCatalog"])
169
                        //{
170
                        //    foreach (var epoint in service["endpoints"])
171
                        //    {
172
                        //    }
173
                        //}
174
                    //    Dictionary<string, string> OkeanosServices = JsonConvert.DeserializeObject<Dictionary<string, string>>(responseStr);
175
                        return webLogin;
176
                    }
177
                }
178

    
179
                catch (Exception ex)
180
                {
181
                    MessageBox.Show("Stream Failed");
182
                    return loginUri;
183
                }
184

    
185

    
186
           }
187
        }
188
        
189
       catch (Exception ex)
190
       {
191
            MessageBox.Show("Service URL Failed");
192
            return loginUri;
193
       }
194
     }
195

    
196

    
197
    }
198
}