Free cookie consent management tool by TermsFeed Policy Generator

source: branches/ClientUserManagement/HeuristicLab.Services.Access/3.3/AccessService.cs @ 7614

Last change on this file since 7614 was 7614, checked in by ascheibe, 12 years ago

#1648 started working on a user administration interface

File size: 32.9 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2012 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 System.Collections.Generic;
24using System.Linq;
25using System.ServiceModel;
26using System.ServiceModel.Channels;
27using System.Web.Security;
28using HeuristicLab.GeoIP;
29using DA = HeuristicLab.Services.Access.DataAccess;
30using DT = HeuristicLab.Services.Access.DataTransfer;
31
32namespace HeuristicLab.Services.Access {
33  [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
34  public class AccessService : IAccessService {
35    private IUserManager userManager;
36    private IUserManager UserManager {
37      get {
38        if (userManager == null) userManager = AccessServiceLocator.Instance.UserManager;
39        return userManager;
40      }
41    }
42
43    private IRoleVerifier roleVerifier;
44    private IRoleVerifier RoleVerifier {
45      get {
46        if (roleVerifier == null) roleVerifier = AccessServiceLocator.Instance.RoleVerifier;
47        return roleVerifier;
48      }
49    }
50
51    #region Client Members
52    public bool ClientExists(Guid id) {
53      if (id != Guid.Empty) {
54        using (DA.ClientManagementDataContext context = new DA.ClientManagementDataContext()) {
55          return (context.Resources.Where(x => x.Id == id).Count() != 0);
56        }
57      }
58      return false;
59    }
60
61    public DT.Client GetClient(Guid id) {
62      using (DA.ClientManagementDataContext context = new DA.ClientManagementDataContext()) {
63        var query = from c in context.GetTable<DA.Resource>().OfType<DA.Client>()
64                    where c.Id == id
65                    select c;
66        if (query.Count() > 0) {
67          return Convert.ToDto(query.FirstOrDefault());
68        } else {
69          return null;
70        }
71      }
72    }
73
74    public IEnumerable<DT.Client> GetClients(IEnumerable<Guid> ids) {
75      using (DA.ClientManagementDataContext context = new DA.ClientManagementDataContext()) {
76        var query = from c in context.GetTable<DA.Resource>().OfType<DA.Client>()
77                    where ids.Contains(c.Id)
78                    select Convert.ToDto(c);
79        return query.ToList();
80      }
81    }
82
83    public IEnumerable<DT.Client> GetAllClients() {
84      using (DA.ClientManagementDataContext context = new DA.ClientManagementDataContext()) {
85        var query = from c in context.GetTable<DA.Resource>().OfType<DA.Client>()
86                    select Convert.ToDto(c);
87        return query.ToList();
88      }
89    }
90
91    public void AddClient(DT.Client client) {
92      string country = string.Empty;
93
94      OperationContext opContext = OperationContext.Current;
95
96      if (opContext != null) {
97        MessageProperties properties = opContext.IncomingMessageProperties;
98        RemoteEndpointMessageProperty endpoint = properties[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty;
99        string ipAdr = endpoint.Address;
100        country = GeoIPLookupService.Instance.GetCountryName(ipAdr);
101      }
102
103      using (DA.ClientManagementDataContext context = new DA.ClientManagementDataContext()) {
104        DA.Client entity = Convert.ToEntity(client);
105
106        if (country != string.Empty) {
107          var query = from c in context.GetTable<DA.Country>()
108                      where c.Name == country
109                      select c;
110          if (query.Count() > 0) {
111            entity.CountryId = query.First().Id;
112          }
113        }
114
115        if (entity.OperatingSystem != null) {
116          string osversion = entity.OperatingSystem.Name;
117          var query = from os in context.GetTable<DA.OperatingSystem>()
118                      where os.Name == osversion
119                      select os;
120          if (query.Count() > 0) {
121            entity.OperatingSystem = query.First();
122          }
123        }
124
125        if (entity.ClientType != null) {
126          string cType = entity.ClientType.Name;
127          var query = from t in context.GetTable<DA.ClientType>()
128                      where t.Name == cType
129                      select t;
130          if (query.Count() > 0) {
131            entity.ClientType = query.First();
132          }
133        }
134
135        context.Resources.InsertOnSubmit(entity);
136        context.SubmitChanges();
137      }
138    }
139
140    public void UpdateClient(DT.Client client) {
141      AddClient(client);
142    }
143
144    public void DeleteClient(DT.Client client) {
145      RoleVerifier.AuthenticateForAllRoles(AccessServiceRoles.Administrator);
146
147      using (DA.ClientManagementDataContext context = new DA.ClientManagementDataContext()) {
148        //load client because we could get a detached object
149        var query = from c in context.GetTable<DA.Resource>().OfType<DA.Client>()
150                    where c.Id == client.Id
151                    select c;
152        if (query.Count() > 0) {
153
154          //delete affiliation first
155          var queryMapping = context.ResourceResourceGroups.Where(x => x.ResourceId == client.Id);
156          if (queryMapping.Count() > 0) {
157            context.ResourceResourceGroups.DeleteAllOnSubmit(queryMapping);
158          }
159
160          context.Resources.DeleteOnSubmit(query.First());
161          context.SubmitChanges();
162        }
163      }
164    }
165    #endregion
166
167    #region ClientGroup
168    public IEnumerable<DT.ClientGroup> GetAllClientGroups() {
169      using (DA.ClientManagementDataContext context = new DA.ClientManagementDataContext()) {
170        var query = from c in context.GetTable<DA.Resource>().OfType<DA.ClientGroup>()
171                    select Convert.ToDto(c);
172        return query.ToList();
173      }
174    }
175
176    public IEnumerable<DT.ClientGroup> GetClientGroups(IEnumerable<Guid> ids) {
177      using (DA.ClientManagementDataContext context = new DA.ClientManagementDataContext()) {
178        var query = from c in context.GetTable<DA.Resource>().OfType<DA.ClientGroup>()
179                    where ids.Contains(c.Id)
180                    select Convert.ToDto(c);
181        return query.ToList();
182      }
183    }
184
185    public Guid AddClientGroup(DT.ClientGroup group) {
186      using (DA.ClientManagementDataContext context = new DA.ClientManagementDataContext()) {
187        if (group.Id == Guid.Empty)
188          group.Id = Guid.NewGuid();
189
190        var entity = Convert.ToEntity(group);
191        context.Resources.InsertOnSubmit(entity);
192        context.SubmitChanges();
193        return entity.Id;
194      }
195    }
196
197    public void UpdateClientGroup(DT.ClientGroup group) {
198      AddClientGroup(group);
199    }
200
201    public void DeleteClientGroup(DT.ClientGroup clientGroup) {
202      RoleVerifier.AuthenticateForAllRoles(AccessServiceRoles.Administrator);
203
204      using (DA.ClientManagementDataContext context = new DA.ClientManagementDataContext()) {
205        //load clientGroup because we could get a detached object
206        var query = from c in context.GetTable<DA.Resource>().OfType<DA.ClientGroup>()
207                    where c.Id == clientGroup.Id
208                    select c;
209        if (query.Count() > 0) {
210          context.Resources.DeleteOnSubmit(query.First());
211          context.SubmitChanges();
212        }
213      }
214    }
215
216    public void AddResourceToGroup(DT.Resource resource, DT.ClientGroup group) {
217      using (DA.ClientManagementDataContext context = new DA.ClientManagementDataContext()) {
218        DA.ResourceResourceGroup rrg = new DA.ResourceResourceGroup() {
219          ResourceId = resource.Id,
220          ResourceGroupId = group.Id
221        };
222
223        context.ResourceResourceGroups.InsertOnSubmit(rrg);
224        context.SubmitChanges();
225      }
226    }
227
228    public void RemoveResourceFromGroup(DT.Resource resource, DT.ClientGroup group) {
229      using (DA.ClientManagementDataContext context = new DA.ClientManagementDataContext()) {
230        var query = context.ResourceResourceGroups.Where(x => x.ResourceId == resource.Id && x.ResourceGroupId == group.Id);
231        if (query.Count() > 0) {
232          context.ResourceResourceGroups.DeleteOnSubmit(query.First());
233          context.SubmitChanges();
234        }
235      }
236    }
237    #endregion
238
239    #region ClientGroupMapping
240    public IEnumerable<DT.ClientGroupMapping> GetClientGroupMapping() {
241      using (DA.ClientManagementDataContext context = new DA.ClientManagementDataContext()) {
242        var query = from c in context.GetTable<DA.ResourceResourceGroup>()
243                    select Convert.ToDto(c);
244        return query.ToList();
245      }
246    }
247    #endregion
248
249    #region Resource
250    public IEnumerable<DT.Resource> GetResources() {
251      using (DA.ClientManagementDataContext context = new DA.ClientManagementDataContext()) {
252        var query = from r in context.Resources
253                    select Convert.ToDto(r);
254        return query.ToList();
255      }
256    }
257    #endregion
258
259    #region ClientLog
260    public DT.ClientLog GetLastClientLog(Guid clientId) {
261      using (DA.ClientManagementDataContext context = new DA.ClientManagementDataContext()) {
262        var query = from r in context.ClientLogs
263                    where r.ResourceId == clientId
264                    select r;
265        return Convert.ToDto(query.OrderBy(x => x.Timestamp).LastOrDefault());
266      }
267    }
268
269    public IEnumerable<DT.ClientLog> GetClientLogs(Guid clientId) {
270      using (DA.ClientManagementDataContext context = new DA.ClientManagementDataContext()) {
271        var query = from r in context.ClientLogs
272                    where r.ResourceId == clientId
273                    select Convert.ToDto(r);
274        return query.ToList();
275      }
276    }
277
278    public IEnumerable<DT.ClientLog> GetClientLogsSince(DateTime startDate) {
279      using (DA.ClientManagementDataContext context = new DA.ClientManagementDataContext()) {
280        var query = from r in context.ClientLogs
281                    where r.Timestamp >= startDate
282                    select Convert.ToDto(r);
283        return query.ToList();
284      }
285    }
286
287    public void AddClientLog(DT.ClientLog log) {
288      using (DA.ClientManagementDataContext context = new DA.ClientManagementDataContext()) {
289        context.ClientLogs.InsertOnSubmit(Convert.ToEntity(log));
290        context.SubmitChanges();
291      }
292    }
293
294    public void DeleteClientLog(DT.ClientLog log) {
295      RoleVerifier.AuthenticateForAllRoles(AccessServiceRoles.Administrator);
296
297      using (DA.ClientManagementDataContext context = new DA.ClientManagementDataContext()) {
298        context.ClientLogs.DeleteOnSubmit(Convert.ToEntity(log));
299        context.SubmitChanges();
300      }
301    }
302    #endregion
303
304    #region User
305    private DT.User BuildUserDto(Guid userId) {
306      DA.aspnet_User aspUser = null;
307      DA.aspnet_Membership aspMembership = null;
308      DA.User accessUser = null;
309
310      using (DA.ASPNETAuthenticationDataContext context = new DA.ASPNETAuthenticationDataContext()) {
311        var userQuery = from u in context.aspnet_Users
312                        where u.UserId == userId
313                        select u;
314        if (userQuery.Count() == 1) {
315          aspUser = userQuery.First();
316        }
317
318        var memQuery = from u in context.aspnet_Memberships
319                       where u.UserId == userId
320                       select u;
321        if (memQuery.Count() == 1) {
322          aspMembership = memQuery.First();
323        }
324      }
325
326      if (aspUser != null || aspMembership != null) {
327        using (DA.ClientManagementDataContext context = new DA.ClientManagementDataContext()) {
328          var query = from u in context.UserGroupBases.OfType<DA.User>()
329                      where u.Id == userId
330                      select u;
331          if (query.Count() == 1) {
332            accessUser = query.First();
333          } else {
334            //if the user is not in the access db add it (this makes it easy to upgrade with an existing asp.net authentication db)
335            DA.User user = new DA.User();
336            user.Id = userId;
337            user.FullName = "Not set";
338            context.UserGroupBases.InsertOnSubmit(user);
339            context.SubmitChanges();
340            accessUser = user;
341          }
342        }
343      }
344
345      if (aspUser == null || aspMembership == null || accessUser == null) {
346        throw new Exception("User with id " + userId + " not found.");
347      } else {
348        return Convert.ToDto(accessUser, aspUser, aspMembership);
349      }
350    }
351
352    private DT.LightweightUser BuildLightweightUserDto(Guid userId) {
353      DA.aspnet_User aspUser = null;
354      DA.User accessUser = null;
355      List<DA.aspnet_Role> roles = new List<DA.aspnet_Role>();
356      List<DA.UserGroup> groups = new List<DA.UserGroup>();
357
358
359      using (DA.ASPNETAuthenticationDataContext context = new DA.ASPNETAuthenticationDataContext()) {
360        var userQuery = from u in context.aspnet_Users
361                        where u.UserId == userId
362                        select u;
363        if (userQuery.Count() == 1) {
364          aspUser = userQuery.First();
365          roles = (from ur in context.aspnet_UsersInRoles
366                   where ur.UserId == aspUser.UserId
367                   join r in context.aspnet_Roles on ur.RoleId equals r.RoleId
368                   select r).ToList();
369        }
370      }
371
372      if (aspUser != null) {
373        using (DA.ClientManagementDataContext context = new DA.ClientManagementDataContext()) {
374          var query = from u in context.UserGroupBases.OfType<DA.User>()
375                      where u.Id == userId
376                      select u;
377          if (query.Count() == 1) {
378            accessUser = query.First();
379            groups = (from ug in context.UserGroupUserGroups
380                      where ug.UserGroupUserGroupId == accessUser.Id
381                      join g in context.UserGroupBases.OfType<DA.UserGroup>() on ug.UserGroupId equals g.Id
382                      select g).ToList();
383          } else {
384            //if the user is not in the access db add it (this makes it easy to upgrade with an existing asp.net authentication db)
385            DA.User user = new DA.User();
386            user.Id = userId;
387            user.FullName = "Not set";
388            context.UserGroupBases.InsertOnSubmit(user);
389            context.SubmitChanges();
390            accessUser = user;
391          }
392        }
393      }
394
395      if (aspUser == null || accessUser == null) {
396        throw new Exception("User with id " + userId + " not found.");
397      } else {
398        return Convert.ToDto(accessUser, aspUser, roles, groups);
399      }
400    }
401
402    public DT.LightweightUser Login() {
403      Guid userId = UserManager.CurrentUserId;
404      return BuildLightweightUserDto(userId);
405    }
406
407    public IEnumerable<DT.UserGroup> GetGroupsOfCurrentUser() {
408      Guid userId = UserManager.CurrentUserId;
409
410      using (DA.ClientManagementDataContext context = new DA.ClientManagementDataContext()) {
411        //TODO: this has to be done recursive, so check if a group is in another
412        //group because then the user is also in this group...
413        var query = from g in context.UserGroupUserGroups
414                    from ug in context.UserGroupBases.OfType<DA.UserGroup>()
415                    where g.UserGroupId == userId && g.UserGroupUserGroupId == ug.Id
416                    select Convert.ToDto(ug);
417        return query.ToList();
418      }
419    }
420
421    public IEnumerable<DT.Role> GetRolesOfCurrentUser() {
422      Guid userId = UserManager.CurrentUserId;
423
424      using (DA.ASPNETAuthenticationDataContext context = new DA.ASPNETAuthenticationDataContext()) {
425        var query = from ur in context.aspnet_UsersInRoles
426                    from r in context.aspnet_Roles
427                    where ur.UserId == userId && ur.RoleId == r.RoleId
428                    select Convert.ToDto(r);
429        return query.ToList();
430      }
431    }
432
433
434    public IEnumerable<DT.LightweightUser> GetAllLightweightUsers() {
435      List<Guid> accessUserGuids = null;
436
437      using (DA.ASPNETAuthenticationDataContext context = new DA.ASPNETAuthenticationDataContext()) {
438        var query = from u in context.aspnet_Users
439                    select u.UserId;
440        accessUserGuids = query.ToList();
441      }
442      return accessUserGuids.Select(x => BuildLightweightUserDto(x));
443    }
444
445    public IEnumerable<DT.User> GetAllUsers() {
446      RoleVerifier.AuthenticateForAllRoles(AccessServiceRoles.Administrator);
447
448      List<Guid> accessUserGuids = null;
449
450      using (DA.ASPNETAuthenticationDataContext context = new DA.ASPNETAuthenticationDataContext()) {
451        var query = from u in context.aspnet_Users
452                    select u.UserId;
453        accessUserGuids = query.ToList();
454      }
455
456      return accessUserGuids.Select(x => BuildUserDto(x));
457    }
458
459    public IEnumerable<DT.User> GetUsers(IEnumerable<Guid> ids) {
460      RoleVerifier.AuthenticateForAllRoles(AccessServiceRoles.Administrator);
461
462      List<Guid> accessUserGuids = null;
463
464      using (DA.ClientManagementDataContext context = new DA.ClientManagementDataContext()) {
465        var query = from u in context.UserGroupBases.OfType<DA.User>()
466                    where ids.Contains(u.Id)
467                    select u.Id;
468        accessUserGuids = query.ToList();
469      }
470
471      if (accessUserGuids.Count() != ids.Count()) {
472        throw new Exception("Couldn't find one or more users for the given user ids.");
473      }
474
475      return accessUserGuids.Select(x => BuildUserDto(x));
476    }
477
478    public IEnumerable<DT.LightweightUser> GetLightweightUsers(IEnumerable<Guid> ids) {
479      List<Guid> accessUserGuids = null;
480
481      using (DA.ClientManagementDataContext context = new DA.ClientManagementDataContext()) {
482        var query = from u in context.UserGroupBases.OfType<DA.User>()
483                    where ids.Contains(u.Id)
484                    select u.Id;
485        accessUserGuids = query.ToList();
486      }
487
488      if (accessUserGuids.Count() != ids.Count()) {
489        throw new Exception("Couldn't find one or more users for the given user ids.");
490      }
491
492      return accessUserGuids.Select(x => BuildLightweightUserDto(x));
493    }
494
495    public DT.User AddUser(DT.User user) {
496      RoleVerifier.AuthenticateForAllRoles(AccessServiceRoles.Administrator);
497
498      DA.User accessUser;
499      DA.aspnet_User aspUser;
500      DA.aspnet_Membership aspMembership;
501      bool userExistsInASP;
502
503      Convert.ToEntity(user, out accessUser, out aspUser, out aspMembership, out userExistsInASP);
504
505      if (userExistsInASP) {
506        if (accessUser.Id == null || accessUser.Id == Guid.Empty) {
507          accessUser.Id = aspMembership.UserId;
508        }
509        using (DA.ClientManagementDataContext context = new DA.ClientManagementDataContext()) {
510          context.UserGroupBases.InsertOnSubmit(accessUser);
511          context.SubmitChanges();
512        }
513        MembershipUser membershipUser = Membership.GetUser((object)accessUser.Id);
514        if (membershipUser != null) {
515          membershipUser.Email = aspMembership.Email;
516          membershipUser.IsApproved = aspMembership.IsApproved;
517          membershipUser.Comment = aspMembership.Comment;
518          Membership.UpdateUser(membershipUser);
519        }
520      } else {
521        MembershipUser membershipUser = Membership.CreateUser(aspUser.UserName, aspUser.UserName, aspMembership.Email);
522        membershipUser.IsApproved = aspMembership.IsApproved;
523        membershipUser.Comment = aspMembership.Comment;
524        Membership.UpdateUser(membershipUser);
525
526        Guid userId = (Guid)membershipUser.ProviderUserKey;
527        accessUser.Id = userId;
528
529        using (DA.ClientManagementDataContext context = new DA.ClientManagementDataContext()) {
530          context.UserGroupBases.InsertOnSubmit(accessUser);
531          context.SubmitChanges();
532        }
533      }
534
535      using (DA.ASPNETAuthenticationDataContext context = new DA.ASPNETAuthenticationDataContext()) {
536        var newAspUser = context.aspnet_Users.Where(x => x.UserId == accessUser.Id).FirstOrDefault();
537        var newAspMembership = context.aspnet_Memberships.Where(x => x.UserId == accessUser.Id).FirstOrDefault();
538        return Convert.ToDto(accessUser, newAspUser, newAspMembership);
539      }
540    }
541
542    public void DeleteUser(DT.User user) {
543      RoleVerifier.AuthenticateForAllRoles(AccessServiceRoles.Administrator);
544
545      if (user.Id != null && user.Id != Guid.Empty) {
546        //delete asp.net user
547        Membership.DeleteUser(user.UserName);
548        using (DA.ClientManagementDataContext context = new DA.ClientManagementDataContext()) {
549          var query = context.UserGroupBases.OfType<DA.User>().Where(x => x.Id == user.Id);
550          if (query.Count() > 0) {
551
552            //delete affiliation first
553            var queryMapping = context.UserGroupUserGroups.Where(x => x.UserGroupId == user.Id);
554            if (queryMapping.Count() > 0) {
555              context.UserGroupUserGroups.DeleteAllOnSubmit(queryMapping);
556            }
557
558            //delete user from access db
559            context.UserGroupBases.DeleteOnSubmit(query.First());
560            context.SubmitChanges();
561          }
562        }
563      }
564    }
565
566    public void UpdateUser(DT.User user) {
567      RoleVerifier.AuthenticateForAllRoles(AccessServiceRoles.Administrator);
568
569      AddUser(user);
570    }
571
572    public void AddUserToRole(DT.Role role, DT.User user) {
573      RoleVerifier.AuthenticateForAllRoles(AccessServiceRoles.Administrator);
574
575      //TODO: usernames and rolenames have to be unique!
576      MembershipUser msUser = Membership.GetUser((object)user.Id);
577      if (msUser != null) {
578        Roles.AddUserToRole(msUser.UserName, role.Name);
579      }
580    }
581
582    public void RemoveUserFromRole(DT.Role role, DT.User user) {
583      RoleVerifier.AuthenticateForAllRoles(AccessServiceRoles.Administrator);
584
585      MembershipUser msUser = Membership.GetUser((object)user.Id);
586      if (msUser != null) {
587        Roles.RemoveUserFromRole(msUser.UserName, role.Name);
588      }
589    }
590
591    public bool ChangePassword(Guid userId, string oldPassword, string newPassword) {
592      MembershipUser msUser = Membership.GetUser(userId);
593      if (msUser != null) {
594        return msUser.ChangePassword(oldPassword, newPassword);
595      }
596      return false;
597    }
598
599    public string ResetPassword(Guid userId) {
600      RoleVerifier.AuthenticateForAllRoles(AccessServiceRoles.Administrator);
601
602      MembershipUser msUser = Membership.GetUser(userId);
603      if (msUser != null) {
604        return msUser.ResetPassword();
605      } else {
606        throw new Exception("Password reset failed.");
607      }
608    }
609    #endregion
610
611    #region UserGroup
612    public IEnumerable<DT.UserGroup> GetAllUserGroups() {
613      using (DA.ClientManagementDataContext context = new DA.ClientManagementDataContext()) {
614        var query = from u in context.UserGroupBases.OfType<DA.UserGroup>()
615                    select Convert.ToDto(u);
616        return query.ToList();
617      }
618    }
619
620    public IEnumerable<DT.UserGroup> GetUserGroupsOfUser(Guid userId) {
621
622      using (DA.ClientManagementDataContext context = new DA.ClientManagementDataContext()) {
623        var groupIds = from g in context.UserGroupUserGroups
624                       where g.UserGroupId == userId
625                       select g.UserGroupUserGroupId;
626
627        var query = from g in context.UserGroupBases.OfType<DA.UserGroup>()
628                    where groupIds.Contains(g.Id)
629                    select Convert.ToDto(g);
630
631        return query.ToList();
632      }
633    }
634
635    public IEnumerable<DT.UserGroup> GetUserGroups(IEnumerable<Guid> ids) {
636      using (DA.ClientManagementDataContext context = new DA.ClientManagementDataContext()) {
637        var query = from u in context.UserGroupBases.OfType<DA.UserGroup>()
638                    where ids.Contains(u.Id)
639                    select Convert.ToDto(u);
640        return query.ToList();
641      }
642    }
643
644    public Guid AddUserGroup(DT.UserGroup group) {
645      using (DA.ClientManagementDataContext context = new DA.ClientManagementDataContext()) {
646        //because id is not automatically set because of user, we have to do it here manually for group
647        group.Id = Guid.NewGuid();
648        context.UserGroupBases.InsertOnSubmit(Convert.ToEntity(group));
649        context.SubmitChanges();
650        return group.Id;
651      }
652    }
653
654    public void UpdateUserGroup(DT.UserGroup group) {
655      AddUserGroup(group);
656    }
657
658    public void DeleteUserGroup(DT.UserGroup group) {
659      RoleVerifier.AuthenticateForAllRoles(AccessServiceRoles.Administrator);
660
661      using (DA.ClientManagementDataContext context = new DA.ClientManagementDataContext()) {
662        context.UserGroupBases.DeleteOnSubmit(Convert.ToEntity(group));
663        context.SubmitChanges();
664      }
665    }
666
667    public void AddUserGroupBaseToGroup(DT.UserGroupBase resource, DT.UserGroup group) {
668      using (DA.ClientManagementDataContext context = new DA.ClientManagementDataContext()) {
669        DA.UserGroupUserGroup ugug = new DA.UserGroupUserGroup();
670        ugug.UserGroupId = resource.Id;
671        ugug.UserGroupUserGroupId = group.Id;
672        context.UserGroupUserGroups.InsertOnSubmit(ugug);
673        context.SubmitChanges();
674      }
675    }
676
677    public void RemoveUserGroupBaseFromGroup(DT.UserGroupBase resource, DT.UserGroup userGroup) {
678      using (DA.ClientManagementDataContext context = new DA.ClientManagementDataContext()) {
679        var query = from u in context.UserGroupUserGroups
680                    where u.UserGroupId == resource.Id && u.UserGroupUserGroupId == userGroup.Id
681                    select u;
682
683        if (query.Count() == 1) {
684          context.UserGroupUserGroups.DeleteOnSubmit(query.First());
685          context.SubmitChanges();
686        }
687      }
688    }
689
690    public IEnumerable<DT.UserGroupBase> GetUsersAndGroups() {
691      using (DA.ClientManagementDataContext context = new DA.ClientManagementDataContext()) {
692        var query = from u in context.UserGroupBases
693                    select Convert.ToDto(u);
694        return query.ToList();
695      }
696    }
697
698    public IEnumerable<DT.UserGroupMapping> GetUserGroupMapping() {
699      using (DA.ClientManagementDataContext context = new DA.ClientManagementDataContext()) {
700        var query = from u in context.UserGroupUserGroups
701                    select Convert.ToDto(u);
702        return query.ToList();
703      }
704    }
705    #endregion
706
707    #region UserGroupBase
708    public IEnumerable<DT.UserGroupBase> GetAllLeightweightUsersAndGroups() {
709      //TODO: it must be possible to include a role so not all users are returned but only the ones who are allowed to use a certain service
710      List<DT.UserGroup> userGroups = new List<DT.UserGroup>();
711      List<DT.UserGroupBase> result = new List<DT.UserGroupBase>();
712
713      // this is just for generating users from asp.net authenticaton db; we should maybe provide an updatescript instead
714      List<Guid> accessUserGuids = null;
715      using (DA.ASPNETAuthenticationDataContext context = new DA.ASPNETAuthenticationDataContext()) {
716        var query = from u in context.aspnet_Users
717                    select u.UserId;
718        accessUserGuids = query.ToList();
719      }
720      var lightweightUsers = accessUserGuids.Select(x => BuildLightweightUserDto(x));
721
722      using (DA.ClientManagementDataContext context = new DA.ClientManagementDataContext()) {
723        var query = from u in context.UserGroupBases.OfType<DA.UserGroup>()
724                    select Convert.ToDto(u);
725        userGroups = query.ToList();
726      }
727
728      result.AddRange(lightweightUsers);
729      result.AddRange(userGroups);
730
731      return result;
732    }
733
734    public IEnumerable<DT.UserGroupBase> GetLeightweightUsersAndGroups(IEnumerable<Guid> ids) {
735      List<DA.UserGroupBase> dbUserGroupsBases = new List<DA.UserGroupBase>();
736      List<DT.UserGroupBase> result = new List<DT.UserGroupBase>();
737
738      using (DA.ClientManagementDataContext context = new DA.ClientManagementDataContext()) {
739        var query = from u in context.UserGroupBases
740                    where ids.Contains(u.Id)
741                    select u;
742        dbUserGroupsBases = query.ToList();
743      }
744
745      foreach (var ugb in dbUserGroupsBases) {
746        if (ugb.GetType() == typeof(DA.User)) {
747          var user = BuildLightweightUserDto(ugb.Id);
748          result.Add(user);
749        } else if (ugb.GetType() == typeof(DA.UserGroup)) {
750          var group = Convert.ToDto(ugb as DA.UserGroup);
751          result.Add(group);
752        }
753      }
754      return result;
755    }
756    #endregion
757
758    #region Roles
759    public IEnumerable<DT.Role> GetRoles() {
760      using (DA.ASPNETAuthenticationDataContext context = new DA.ASPNETAuthenticationDataContext()) {
761        var query = from u in context.aspnet_Roles
762                    select Convert.ToDto(u);
763        return query.ToList();
764      }
765    }
766
767    public DT.Role AddRole(DT.Role role) {
768      RoleVerifier.AuthenticateForAllRoles(AccessServiceRoles.Administrator);
769
770      Roles.CreateRole(role.Name);
771      return role;
772    }
773
774    public void DeleteRole(DT.Role role) {
775      RoleVerifier.AuthenticateForAllRoles(AccessServiceRoles.Administrator);
776
777      Roles.DeleteRole(role.Name);
778    }
779
780    public IEnumerable<DT.Role> GetUserRoles(DT.User user) {
781      var roles = Roles.GetRolesForUser(user.UserName);
782      return roles.Select(x => new DT.Role() { Name = x });
783    }
784
785    public void AddRoleToGroup(DT.UserGroup userGroup, DT.Role role) {
786      Guid[] userIds;
787      string[] aspUsers;
788
789      using (DA.ClientManagementDataContext accessContext = new DA.ClientManagementDataContext()) {
790        userIds = (from u in accessContext.UserGroupUserGroups
791                   where u.UserGroupUserGroupId == userGroup.Id
792                   select u.UserGroupId).ToArray();
793      }
794
795      using (DA.ASPNETAuthenticationDataContext aspContext = new DA.ASPNETAuthenticationDataContext()) {
796        aspUsers = (from u in aspContext.aspnet_Users
797                    where userIds.Contains(u.UserId)
798                    select u.UserName).ToArray();
799      }
800
801      Roles.AddUsersToRole(aspUsers, role.Name);
802
803    }
804
805    public void RemoveRoleFromGroup(DT.UserGroup userGroup, DT.Role role) {
806      RoleVerifier.AuthenticateForAllRoles(AccessServiceRoles.Administrator);
807
808      Guid[] userIds;
809      string[] aspUsers;
810
811      using (DA.ClientManagementDataContext accessContext = new DA.ClientManagementDataContext()) {
812        userIds = (from u in accessContext.UserGroupUserGroups
813                   where u.UserGroupUserGroupId == userGroup.Id
814                   select u.UserGroupId).ToArray();
815      }
816
817      using (DA.ASPNETAuthenticationDataContext aspContext = new DA.ASPNETAuthenticationDataContext()) {
818        aspUsers = (from u in aspContext.aspnet_Users
819                    where userIds.Contains(u.UserId)
820                    select u.UserName).ToArray();
821      }
822
823      Roles.RemoveUsersFromRole(aspUsers.ToArray(), role.Name);
824    }
825    #endregion
826
827    #region Error Reporting
828    public void ReportError(DT.ClientError error) {
829      using (DA.ClientManagementDataContext context = new DA.ClientManagementDataContext()) {
830        context.ClientErrors.InsertOnSubmit(Convert.ToEntity(error));
831        context.SubmitChanges();
832      }
833    }
834
835    public IEnumerable<DT.ClientError> GetClientErrors() {
836      RoleVerifier.AuthenticateForAllRoles(AccessServiceRoles.Administrator);
837
838      using (DA.ClientManagementDataContext context = new DA.ClientManagementDataContext()) {
839        var query = from c in context.ClientErrors
840                    select Convert.ToDto(c);
841        return query.ToList();
842      }
843    }
844
845    public IEnumerable<DT.ClientError> GetLastClientErrors(DateTime startDate) {
846      RoleVerifier.AuthenticateForAllRoles(AccessServiceRoles.Administrator);
847
848      using (DA.ClientManagementDataContext context = new DA.ClientManagementDataContext()) {
849        var query = from c in context.ClientErrors
850                    where c.Timestamp >= startDate
851                    select Convert.ToDto(c);
852        return query.ToList();
853      }
854    }
855
856    public void DeleteError(DT.ClientError error) {
857      RoleVerifier.AuthenticateForAllRoles(AccessServiceRoles.Administrator);
858
859      using (DA.ClientManagementDataContext context = new DA.ClientManagementDataContext()) {
860        var query = context.ClientErrors.Where(x => x.Id == error.Id);
861        if (query.Count() > 0) {
862          context.ClientErrors.DeleteOnSubmit(query.First());
863          context.SubmitChanges();
864        }
865      }
866    }
867    #endregion
868  }
869}
Note: See TracBrowser for help on using the repository browser.