Free cookie consent management tool by TermsFeed Policy Generator

source: branches/WebJobManager/HeuristicLab.Clients.Hive.WebJobManager/Services/Imports/AccessAdministrationClient.cs @ 13754

Last change on this file since 13754 was 13754, checked in by jlodewyc, 8 years ago

#2582 User management done, start resource calendar

File size: 15.2 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2015 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
4 *
5 * This file is part of HeuristicLab.
6 *
7 * HeuristicLab is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * HeuristicLab is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
19 */
20#endregion
21
22using System;
23using HeuristicLab.Clients.Common;
24using HeuristicLab.Common;
25using HeuristicLab.Core;
26using System.ServiceModel;
27using HeuristicLab.Clients.Hive.WebJobManager.ViewModels;
28using HeuristicLab.Clients.Hive.WebJobManager.Services;
29using System.Collections.Generic;
30
31namespace HeuristicLab.Clients.Access.Administration
32{
33    [Item("AccessAdministrationClient", "AccessAdministration client.")]
34    public class AccessAdministrationClient : IContent
35    {
36
37        private  WebLoginService weblog;
38        private AccessServiceClient client;
39        public Guid userId { get; set; }
40        #region Properties
41        private ItemList<User> users;
42        public ItemList<User> Users
43        {
44            get
45            {
46                return users;
47            }
48        }
49
50        public ItemList<UserGroup> Groups { get; set; }
51        public ItemList<Role> Roles { get; set; }
52        #endregion
53
54        public AccessAdministrationClient(Guid u) {
55            weblog = WebLoginService.Instance;
56            userId = u;
57        }
58
59        #region Refresh
60        public void RefreshUsers()
61        {
62            users = new ItemList<User>();
63            users.AddRange(CallAccessService<ItemList<User>>(s => new ItemList<User>(s.GetAllUsers())));
64        }
65
66        public void RefreshUsersAsync(Action<Exception> exceptionCallback)
67        {
68            ExecuteActionAsync(RefreshUsers, exceptionCallback);
69        }
70
71        public void RefreshUserGroups()
72        {
73            Groups = new ItemList<UserGroup>();
74            Groups.AddRange(CallAccessService<ItemList<UserGroup>>(s => new ItemList<UserGroup>(s.GetAllUserGroups())));
75        }
76
77        public void RefreshUserGroupsAsync(Action<Exception> exceptionCallback)
78        {
79            ExecuteActionAsync(RefreshUserGroups, exceptionCallback);
80        }
81
82        public void RefreshRoles()
83        {
84            Roles = new ItemList<Role>();
85            Roles.AddRange(CallAccessService<ItemList<Role>>(s => new ItemList<Role>(s.GetRoles())));
86        }
87
88        public void RefreshRolesAsync(Action<Exception> exceptionCallback)
89        {
90            ExecuteActionAsync(RefreshRoles, exceptionCallback);
91        }
92
93        #endregion
94
95        #region Store
96        public void StoreUsers()
97        {
98            foreach (User u in users)
99            {
100                if (u.Modified)
101                {
102                    if (u.Id == Guid.Empty)
103                    {
104                        CallAccessService(s => u.Id = s.AddUser(u).Id);
105                    }
106                    else {
107                        CallAccessService(s => s.UpdateUser(u));
108                    }
109                    u.SetUnmodified();
110                }
111            }
112        }
113
114        public void StoreUsersAsync(Action<Exception> exceptionCallback)
115        {
116            ExecuteActionAsync(StoreUsers, exceptionCallback);
117        }
118
119        public void StoreUserGroups()
120        {
121            foreach (UserGroup g in Groups)
122            {
123                if (g.Modified)
124                {
125                    if (g.Id == Guid.Empty)
126                    {
127                        CallAccessService(s => g.Id = s.AddUserGroup(g));
128                    }
129                    else {
130                        CallAccessService(s => s.UpdateUserGroup(g));
131                    }
132                    g.SetUnmodified();
133                }
134            }
135        }
136
137        public void StoreUserGroupsAsync(Action<Exception> exceptionCallback)
138        {
139            ExecuteActionAsync(StoreUserGroups, exceptionCallback);
140        }
141
142        public void StoreRoles()
143        {
144            foreach (Role g in Roles)
145            {
146                if (g.Modified)
147                {
148                    CallAccessService(s => s.AddRole(g));
149                    g.SetUnmodified();
150                }
151            }
152        }
153
154        public void StoreRolesAsync(Action<Exception> exceptionCallback)
155        {
156            ExecuteActionAsync(StoreRoles, exceptionCallback);
157        }
158        #endregion
159
160        #region Delete
161        public void DeleteUser(User u)
162        {
163            CallAccessService(s => s.DeleteUser(u));
164        }
165
166        public void DeleteUserAsync(User u, Action<Exception> exceptionCallback)
167        {
168            Action deleteUserAction = new Action(delegate { DeleteUser(u); });
169            ExecuteActionAsync(deleteUserAction, exceptionCallback);
170        }
171
172        /* BROKEN
173        public void DeleteUserGroup(UserGroup u)
174        {
175            CallAccessService(s => s.DeleteUserGroup(u));
176        }
177
178        public void DeleteUserGroupAsync(UserGroup u, Action<Exception> exceptionCallback)
179        {
180            Action deleteUserGroupAction = new Action(delegate { DeleteUserGroup(u); });
181            ExecuteActionAsync(deleteUserGroupAction, exceptionCallback);
182        }
183        */
184        public void DeleteRole(Role u)
185        {
186            CallAccessService(s => s.DeleteRole(u));
187        }
188
189        public void DeleteRoleAsync(Role u, Action<Exception> exceptionCallback)
190        {
191            Action deleteRoleAction = new Action(delegate { DeleteRole(u); });
192            ExecuteActionAsync(deleteRoleAction, exceptionCallback);
193        }
194        #endregion
195
196        public void ExecuteActionAsync(Action action, Action<Exception> exceptionCallback)
197        {
198            var call = new Func<Exception>(delegate ()
199            {
200                try
201                {
202                    OnRefreshing();
203                    action();
204                }
205                catch (Exception ex)
206                {
207                    return ex;
208                }
209                finally
210                {
211                    OnRefreshed();
212                }
213                return null;
214            });
215            call.BeginInvoke(delegate (IAsyncResult result)
216            {
217                Exception ex = call.EndInvoke(result);
218                if (ex != null) exceptionCallback(ex);
219            }, null);
220        }
221
222        #region Events
223        public event EventHandler Refreshing;
224        private void OnRefreshing()
225        {
226            EventHandler handler = Refreshing;
227            if (handler != null) handler(this, EventArgs.Empty);
228        }
229        public event EventHandler Refreshed;
230        private void OnRefreshed()
231        {
232            EventHandler handler = Refreshed;
233            if (handler != null) handler(this, EventArgs.Empty);
234        }
235        #endregion
236
237        #region User
238
239        public string resetPassword(Guid id)
240        {
241            return CallAccessService<string>(s => s.ResetPassword(id));
242        }
243        public Guid addUser(Access.User u)
244        {
245            return CallAccessService(s => s.AddUser(u).Id);
246        }
247       
248        public void updateUser(Access.User u)
249        {
250           
251             CallAccessService(s => s.UpdateUser(u));
252        }
253        public List<Role> getRoles(User u)
254        {
255            return CallAccessService(s => s.GetUserRoles(u));
256        }
257        public void addRoleToUser(User u, Role r)
258        {
259            CallAccessService(s => s.AddUserToRole(r, u));
260        }
261        public void deleteUserRole(User u, Role r)
262        {
263            CallAccessService(s => s.RemoveUserFromRole(r, u));
264        }
265        #endregion
266
267        #region Group
268        public Guid addGroup(Access.UserGroup g)
269        {
270            return CallAccessService(s => s.AddUserGroup(g));
271        }
272        public void updateGroup(UserGroup g)
273        {
274            CallAccessService(s => s.UpdateUserGroup(g));
275        }
276        public List<Access.UserGroup> getSubscribedGroups(Guid id)
277        {
278            var maps = CallAccessService(s => s.GetUserGroupMapping());
279            maps = maps.FindAll(x => x.Child == id);
280
281            RefreshUserGroups();
282            RefreshUsers();
283
284            List<Access.UserGroup> members = new List<Access.UserGroup>();
285            foreach (var map in maps)
286            {
287                    UserGroup g = Groups.Find(x => x.Id == map.Parent);
288                    if (g != null)
289                    {
290                        members.Add( g);
291                    }
292            }
293            return members;
294        }
295        public List<Access.UserGroupBase> getGroupMembers(Guid id)
296        {
297            var maps = CallAccessService(s => s.GetUserGroupMapping());
298            maps = maps.FindAll(x => x.Parent == id);
299
300            RefreshUserGroups();
301            RefreshUsers();
302
303            List<Access.UserGroupBase> members = new List<Access.UserGroupBase>();
304            foreach (var map in maps)
305            {
306                User t = users.Find(x => x.Id == map.Child);
307                if (t == null)
308                {
309                    UserGroup g = Groups.Find(x => x.Id == map.Child);
310                    if (g != null)
311                    {
312                        members.Insert(0,g);//Groups always in the front
313                    }
314                }
315                else
316                {
317                    members.Add(t);//members in the back
318                }
319            }
320            return members;
321        }
322
323        public void deleteUserGroup(UserGroup group)
324        {
325            deleteAllMembers(group);
326            CallAccessService(s => s.DeleteUserGroup(group));
327        }
328        private void deleteAllMembers(UserGroup group)
329        {
330            var list = getGroupMembers(group.Id);
331            foreach (var member in list)
332            {//Empties all member connections
333                CallAccessService(s => s.RemoveUserGroupBaseFromGroup(member, group));
334            }
335        }
336        public void addMember(UserGroupBase member, UserGroup group)
337        {
338            CallAccessService(s => s.AddUserGroupBaseToGroup(member, group));
339        }
340        public void deleteMember(UserGroupBase member,UserGroup group)
341        {
342            CallAccessService(s => s.RemoveUserGroupBaseFromGroup(member, group));
343        }
344        #endregion
345
346        #region Roles
347        public Role addRole(Access.Role r)
348        {
349            return CallAccessService(s => s.AddRole(r));
350        }
351        public void deleteRole(string name)
352        {
353            Role r = Roles.Find(x => x.Name == name);
354            CallAccessService(s => s.DeleteRole(r));
355        }
356
357        public List<UserGroupBase> getEnrolled(Role r)
358        {
359            var enroll = new List<UserGroupBase>();
360            RefreshUsers();
361            foreach(var us in users)
362            {
363                var temp = CallAccessService(s => s.GetUserRoles(us));
364                if (temp.Contains(r))
365                    enroll.Add(us);               
366            }
367
368            return enroll;
369        }
370        #endregion
371
372
373        #region Helpers
374        private void getAccessClient()
375        {
376            //build config by code
377            WSHttpBinding binding = new WSHttpBinding();
378            binding.Name = "WSHttpBinding_IAccessService";
379            binding.CloseTimeout = TimeSpan.FromMinutes(1);
380            binding.OpenTimeout = TimeSpan.FromMinutes(1);
381            binding.ReceiveTimeout = TimeSpan.FromMinutes(10);
382            binding.SendTimeout = TimeSpan.FromMinutes(1);
383            binding.BypassProxyOnLocal = false;
384
385            binding.TransactionFlow = false;
386
387            binding.HostNameComparisonMode = HostNameComparisonMode.StrongWildcard;
388            binding.MaxBufferPoolSize = 524288;
389            binding.MaxReceivedMessageSize = 65536;
390            binding.MessageEncoding = WSMessageEncoding.Text;
391
392            binding.TextEncoding = System.Text.Encoding.UTF8;
393            binding.UseDefaultWebProxy = true;
394            binding.AllowCookies = false;
395
396            binding.ReaderQuotas.MaxDepth = 32;
397            binding.ReaderQuotas.MaxStringContentLength = 8192;
398            binding.ReaderQuotas.MaxArrayLength = 16384;
399            binding.ReaderQuotas.MaxBytesPerRead = 4096;
400            binding.ReaderQuotas.MaxNameTableCharCount = 16384;
401
402            binding.ReliableSession.Ordered = true;
403            binding.ReliableSession.InactivityTimeout = TimeSpan.Parse("00:10:00");
404            binding.ReliableSession.Enabled = false;
405
406
407            binding.Security.Mode = SecurityMode.Message;
408            binding.Security.Message.ClientCredentialType = MessageCredentialType.UserName;
409            binding.Security.Message.NegotiateServiceCredential = true;
410            binding.Security.Message.AlgorithmSuite = System.ServiceModel.Security.SecurityAlgorithmSuite.Default;
411
412            binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Windows;
413            binding.Security.Transport.ProxyCredentialType = HttpProxyCredentialType.None;
414            binding.Security.Transport.Realm = "";
415           
416            var end = new EndpointAddress("http://services.heuristiclab.com/AccessService-3.3/AccessService.svc");
417            client = new AccessServiceClient(binding, end);
418            client.ClientCredentials.UserName.UserName = weblog.getLoginViewModel(userId).loginName;
419            //PASSWORD CANNOT BE ENCRYPTED
420            client.ClientCredentials.UserName.Password = weblog.getServiceLocator(userId).Password;
421            client.ClientCredentials.ServiceCertificate.Authentication.CertificateValidationMode = System.ServiceModel.Security.X509CertificateValidationMode.None;
422        }
423        public  void CallAccessService(Action<IAccessService> call)
424        {
425            getAccessClient();
426            try
427            {
428                call(client);
429            }
430            finally
431            {
432                try
433                {
434                    client.Close();
435                }
436                catch (Exception)
437                {
438                    client.Abort();
439                }
440            }
441        }
442        public T CallAccessService<T>(Func<IAccessService, T> call)
443        {
444            getAccessClient();
445            try
446            {
447                return call(client);
448            }
449            finally
450            {
451                try
452                {
453                    client.Close();
454                }
455                catch (Exception)
456                {
457                    client.Abort();
458                }
459            }
460        }
461        #endregion
462    }
463}
Note: See TracBrowser for help on using the repository browser.