Free cookie consent management tool by TermsFeed Policy Generator

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

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

#1174 added a dialog for changing the user password

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