Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 7612 was 7612, checked in by ascheibe, 13 years ago

#1648

  • added a ws method for resetting a password
  • added user role checking for the service
File size: 32.8 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      List<Guid> accessUserGuids = null;
447
448      using (DA.ASPNETAuthenticationDataContext context = new DA.ASPNETAuthenticationDataContext()) {
449        var query = from u in context.aspnet_Users
450                    select u.UserId;
451        accessUserGuids = query.ToList();
452      }
453
454      return accessUserGuids.Select(x => BuildUserDto(x));
455    }
456
457    public IEnumerable<DT.User> GetUsers(IEnumerable<Guid> ids) {
458      List<Guid> accessUserGuids = null;
459
460      using (DA.ClientManagementDataContext context = new DA.ClientManagementDataContext()) {
461        var query = from u in context.UserGroupBases.OfType<DA.User>()
462                    where ids.Contains(u.Id)
463                    select u.Id;
464        accessUserGuids = query.ToList();
465      }
466
467      if (accessUserGuids.Count() != ids.Count()) {
468        throw new Exception("Couldn't find one or more users for the given user ids.");
469      }
470
471      return accessUserGuids.Select(x => BuildUserDto(x));
472    }
473
474    public IEnumerable<DT.LightweightUser> GetLightweightUsers(IEnumerable<Guid> ids) {
475      List<Guid> accessUserGuids = null;
476
477      using (DA.ClientManagementDataContext context = new DA.ClientManagementDataContext()) {
478        var query = from u in context.UserGroupBases.OfType<DA.User>()
479                    where ids.Contains(u.Id)
480                    select u.Id;
481        accessUserGuids = query.ToList();
482      }
483
484      if (accessUserGuids.Count() != ids.Count()) {
485        throw new Exception("Couldn't find one or more users for the given user ids.");
486      }
487
488      return accessUserGuids.Select(x => BuildLightweightUserDto(x));
489    }
490
491    public DT.User AddUser(DT.User user) {
492      roleVerifier.AuthenticateForAllRoles(AccessServiceRoles.Administrator);
493
494      DA.User accessUser;
495      DA.aspnet_User aspUser;
496      DA.aspnet_Membership aspMembership;
497      bool userExistsInASP;
498
499      Convert.ToEntity(user, out accessUser, out aspUser, out aspMembership, out userExistsInASP);
500
501      if (userExistsInASP) {
502        if (accessUser.Id == null || accessUser.Id == Guid.Empty) {
503          accessUser.Id = aspMembership.UserId;
504        }
505        using (DA.ClientManagementDataContext context = new DA.ClientManagementDataContext()) {
506          context.UserGroupBases.InsertOnSubmit(accessUser);
507          context.SubmitChanges();
508        }
509        MembershipUser membershipUser = Membership.GetUser((object)accessUser.Id);
510        if (membershipUser != null) {
511          membershipUser.Email = aspMembership.Email;
512          membershipUser.IsApproved = aspMembership.IsApproved;
513          membershipUser.Comment = aspMembership.Comment;
514          Membership.UpdateUser(membershipUser);
515        }
516      } else {
517        MembershipUser membershipUser = Membership.CreateUser(aspUser.UserName, aspUser.UserName, aspMembership.Email);
518        membershipUser.IsApproved = aspMembership.IsApproved;
519        membershipUser.Comment = aspMembership.Comment;
520        Membership.UpdateUser(membershipUser);
521
522        Guid userId = (Guid)membershipUser.ProviderUserKey;
523        accessUser.Id = userId;
524
525        using (DA.ClientManagementDataContext context = new DA.ClientManagementDataContext()) {
526          context.UserGroupBases.InsertOnSubmit(accessUser);
527          context.SubmitChanges();
528        }
529      }
530
531      using (DA.ASPNETAuthenticationDataContext context = new DA.ASPNETAuthenticationDataContext()) {
532        var newAspUser = context.aspnet_Users.Where(x => x.UserId == accessUser.Id).FirstOrDefault();
533        var newAspMembership = context.aspnet_Memberships.Where(x => x.UserId == accessUser.Id).FirstOrDefault();
534        return Convert.ToDto(accessUser, newAspUser, newAspMembership);
535      }
536    }
537
538    public void DeleteUser(DT.User user) {
539      roleVerifier.AuthenticateForAllRoles(AccessServiceRoles.Administrator);
540
541      if (user.Id != null && user.Id != Guid.Empty) {
542        //delete asp.net user
543        Membership.DeleteUser(user.UserName);
544        using (DA.ClientManagementDataContext context = new DA.ClientManagementDataContext()) {
545          var query = context.UserGroupBases.OfType<DA.User>().Where(x => x.Id == user.Id);
546          if (query.Count() > 0) {
547
548            //delete affiliation first
549            var queryMapping = context.UserGroupUserGroups.Where(x => x.UserGroupId == user.Id);
550            if (queryMapping.Count() > 0) {
551              context.UserGroupUserGroups.DeleteAllOnSubmit(queryMapping);
552            }
553
554            //delete user from access db
555            context.UserGroupBases.DeleteOnSubmit(query.First());
556            context.SubmitChanges();
557          }
558        }
559      }
560    }
561
562    public void UpdateUser(DT.User user) {
563      roleVerifier.AuthenticateForAllRoles(AccessServiceRoles.Administrator);
564
565      AddUser(user);
566    }
567
568    public void AddUserToRole(DT.Role role, DT.User user) {
569      roleVerifier.AuthenticateForAllRoles(AccessServiceRoles.Administrator);
570
571      //TODO: usernames and rolenames have to be unique!
572      MembershipUser msUser = Membership.GetUser((object)user.Id);
573      if (msUser != null) {
574        Roles.AddUserToRole(msUser.UserName, role.Name);
575      }
576    }
577
578    public void RemoveUserFromRole(DT.Role role, DT.User user) {
579      roleVerifier.AuthenticateForAllRoles(AccessServiceRoles.Administrator);
580
581      MembershipUser msUser = Membership.GetUser((object)user.Id);
582      if (msUser != null) {
583        Roles.RemoveUserFromRole(msUser.UserName, role.Name);
584      }
585    }
586
587    public bool ChangePassword(Guid userId, string oldPassword, string newPassword) {
588      MembershipUser msUser = Membership.GetUser(userId);
589      if (msUser != null) {
590        return msUser.ChangePassword(oldPassword, newPassword);
591      }
592      return false;
593    }
594
595    public string ResetPassword(Guid userId) {
596      roleVerifier.AuthenticateForAllRoles(AccessServiceRoles.Administrator);
597
598      MembershipUser msUser = Membership.GetUser(userId);
599      if (msUser != null) {
600        return msUser.ResetPassword();
601      } else {
602        throw new Exception("Password reset failed.");
603      }
604    }
605    #endregion
606
607    #region UserGroup
608    public IEnumerable<DT.UserGroup> GetAllUserGroups() {
609      using (DA.ClientManagementDataContext context = new DA.ClientManagementDataContext()) {
610        var query = from u in context.UserGroupBases.OfType<DA.UserGroup>()
611                    select Convert.ToDto(u);
612        return query.ToList();
613      }
614    }
615
616    public IEnumerable<DT.UserGroup> GetUserGroupsOfUser(Guid userId) {
617
618      using (DA.ClientManagementDataContext context = new DA.ClientManagementDataContext()) {
619        var groupIds = from g in context.UserGroupUserGroups
620                       where g.UserGroupId == userId
621                       select g.UserGroupUserGroupId;
622
623        var query = from g in context.UserGroupBases.OfType<DA.UserGroup>()
624                    where groupIds.Contains(g.Id)
625                    select Convert.ToDto(g);
626
627        return query.ToList();
628      }
629    }
630
631    public IEnumerable<DT.UserGroup> GetUserGroups(IEnumerable<Guid> ids) {
632      using (DA.ClientManagementDataContext context = new DA.ClientManagementDataContext()) {
633        var query = from u in context.UserGroupBases.OfType<DA.UserGroup>()
634                    where ids.Contains(u.Id)
635                    select Convert.ToDto(u);
636        return query.ToList();
637      }
638    }
639
640    public Guid AddUserGroup(DT.UserGroup group) {
641      using (DA.ClientManagementDataContext context = new DA.ClientManagementDataContext()) {
642        //because id is not automatically set because of user, we have to do it here manually for group
643        group.Id = Guid.NewGuid();
644        context.UserGroupBases.InsertOnSubmit(Convert.ToEntity(group));
645        context.SubmitChanges();
646        return group.Id;
647      }
648    }
649
650    public void UpdateUserGroup(DT.UserGroup group) {
651      AddUserGroup(group);
652    }
653
654    public void DeleteUserGroup(DT.UserGroup group) {
655      roleVerifier.AuthenticateForAllRoles(AccessServiceRoles.Administrator);
656
657      using (DA.ClientManagementDataContext context = new DA.ClientManagementDataContext()) {
658        context.UserGroupBases.DeleteOnSubmit(Convert.ToEntity(group));
659        context.SubmitChanges();
660      }
661    }
662
663    public void AddUserGroupBaseToGroup(DT.UserGroupBase resource, DT.UserGroup group) {
664      using (DA.ClientManagementDataContext context = new DA.ClientManagementDataContext()) {
665        DA.UserGroupUserGroup ugug = new DA.UserGroupUserGroup();
666        ugug.UserGroupId = resource.Id;
667        ugug.UserGroupUserGroupId = group.Id;
668        context.UserGroupUserGroups.InsertOnSubmit(ugug);
669        context.SubmitChanges();
670      }
671    }
672
673    public void RemoveUserGroupBaseFromGroup(DT.UserGroupBase resource, DT.UserGroup userGroup) {
674      using (DA.ClientManagementDataContext context = new DA.ClientManagementDataContext()) {
675        var query = from u in context.UserGroupUserGroups
676                    where u.UserGroupId == resource.Id && u.UserGroupUserGroupId == userGroup.Id
677                    select u;
678
679        if (query.Count() == 1) {
680          context.UserGroupUserGroups.DeleteOnSubmit(query.First());
681          context.SubmitChanges();
682        }
683      }
684    }
685
686    public IEnumerable<DT.UserGroupBase> GetUsersAndGroups() {
687      using (DA.ClientManagementDataContext context = new DA.ClientManagementDataContext()) {
688        var query = from u in context.UserGroupBases
689                    select Convert.ToDto(u);
690        return query.ToList();
691      }
692    }
693
694    public IEnumerable<DT.UserGroupMapping> GetUserGroupMapping() {
695      using (DA.ClientManagementDataContext context = new DA.ClientManagementDataContext()) {
696        var query = from u in context.UserGroupUserGroups
697                    select Convert.ToDto(u);
698        return query.ToList();
699      }
700    }
701    #endregion
702
703    #region UserGroupBase
704    public IEnumerable<DT.UserGroupBase> GetAllLeightweightUsersAndGroups() {
705      //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
706      List<DT.UserGroup> userGroups = new List<DT.UserGroup>();
707      List<DT.UserGroupBase> result = new List<DT.UserGroupBase>();
708
709      // this is just for generating users from asp.net authenticaton db; we should maybe provide an updatescript instead
710      List<Guid> accessUserGuids = null;
711      using (DA.ASPNETAuthenticationDataContext context = new DA.ASPNETAuthenticationDataContext()) {
712        var query = from u in context.aspnet_Users
713                    select u.UserId;
714        accessUserGuids = query.ToList();
715      }
716      var lightweightUsers = accessUserGuids.Select(x => BuildLightweightUserDto(x));
717
718      using (DA.ClientManagementDataContext context = new DA.ClientManagementDataContext()) {
719        var query = from u in context.UserGroupBases.OfType<DA.UserGroup>()
720                    select Convert.ToDto(u);
721        userGroups = query.ToList();
722      }
723
724      result.AddRange(lightweightUsers);
725      result.AddRange(userGroups);
726
727      return result;
728    }
729
730    public IEnumerable<DT.UserGroupBase> GetLeightweightUsersAndGroups(IEnumerable<Guid> ids) {
731      List<DA.UserGroupBase> dbUserGroupsBases = new List<DA.UserGroupBase>();
732      List<DT.UserGroupBase> result = new List<DT.UserGroupBase>();
733
734      using (DA.ClientManagementDataContext context = new DA.ClientManagementDataContext()) {
735        var query = from u in context.UserGroupBases
736                    where ids.Contains(u.Id)
737                    select u;
738        dbUserGroupsBases = query.ToList();
739      }
740
741      foreach (var ugb in dbUserGroupsBases) {
742        if (ugb.GetType() == typeof(DA.User)) {
743          var user = BuildLightweightUserDto(ugb.Id);
744          result.Add(user);
745        } else if (ugb.GetType() == typeof(DA.UserGroup)) {
746          var group = Convert.ToDto(ugb as DA.UserGroup);
747          result.Add(group);
748        }
749      }
750      return result;
751    }
752    #endregion
753
754    #region Roles
755    public IEnumerable<DT.Role> GetRoles() {
756      using (DA.ASPNETAuthenticationDataContext context = new DA.ASPNETAuthenticationDataContext()) {
757        var query = from u in context.aspnet_Roles
758                    select Convert.ToDto(u);
759        return query.ToList();
760      }
761    }
762
763    public DT.Role AddRole(DT.Role role) {
764      roleVerifier.AuthenticateForAllRoles(AccessServiceRoles.Administrator);
765
766      Roles.CreateRole(role.Name);
767      return role;
768    }
769
770    public void DeleteRole(DT.Role role) {
771      roleVerifier.AuthenticateForAllRoles(AccessServiceRoles.Administrator);
772
773      Roles.DeleteRole(role.Name);
774    }
775
776    public IEnumerable<DT.Role> GetUserRoles(DT.User user) {
777      var roles = Roles.GetRolesForUser(user.UserName);
778      return roles.Select(x => new DT.Role() { Name = x });
779    }
780
781    public void AddRoleToGroup(DT.UserGroup userGroup, DT.Role role) {
782      Guid[] userIds;
783      string[] aspUsers;
784
785      using (DA.ClientManagementDataContext accessContext = new DA.ClientManagementDataContext()) {
786        userIds = (from u in accessContext.UserGroupUserGroups
787                   where u.UserGroupUserGroupId == userGroup.Id
788                   select u.UserGroupId).ToArray();
789      }
790
791      using (DA.ASPNETAuthenticationDataContext aspContext = new DA.ASPNETAuthenticationDataContext()) {
792        aspUsers = (from u in aspContext.aspnet_Users
793                    where userIds.Contains(u.UserId)
794                    select u.UserName).ToArray();
795      }
796
797      Roles.AddUsersToRole(aspUsers, role.Name);
798
799    }
800
801    public void RemoveRoleFromGroup(DT.UserGroup userGroup, DT.Role role) {
802      roleVerifier.AuthenticateForAllRoles(AccessServiceRoles.Administrator);
803
804      Guid[] userIds;
805      string[] aspUsers;
806
807      using (DA.ClientManagementDataContext accessContext = new DA.ClientManagementDataContext()) {
808        userIds = (from u in accessContext.UserGroupUserGroups
809                   where u.UserGroupUserGroupId == userGroup.Id
810                   select u.UserGroupId).ToArray();
811      }
812
813      using (DA.ASPNETAuthenticationDataContext aspContext = new DA.ASPNETAuthenticationDataContext()) {
814        aspUsers = (from u in aspContext.aspnet_Users
815                    where userIds.Contains(u.UserId)
816                    select u.UserName).ToArray();
817      }
818
819      Roles.RemoveUsersFromRole(aspUsers.ToArray(), role.Name);
820    }
821    #endregion
822
823    #region Error Reporting
824    public void ReportError(DT.ClientError error) {
825      using (DA.ClientManagementDataContext context = new DA.ClientManagementDataContext()) {
826        context.ClientErrors.InsertOnSubmit(Convert.ToEntity(error));
827        context.SubmitChanges();
828      }
829    }
830
831    public IEnumerable<DT.ClientError> GetClientErrors() {
832      roleVerifier.AuthenticateForAllRoles(AccessServiceRoles.Administrator);
833
834      using (DA.ClientManagementDataContext context = new DA.ClientManagementDataContext()) {
835        var query = from c in context.ClientErrors
836                    select Convert.ToDto(c);
837        return query.ToList();
838      }
839    }
840
841    public IEnumerable<DT.ClientError> GetLastClientErrors(DateTime startDate) {
842      roleVerifier.AuthenticateForAllRoles(AccessServiceRoles.Administrator);
843
844      using (DA.ClientManagementDataContext context = new DA.ClientManagementDataContext()) {
845        var query = from c in context.ClientErrors
846                    where c.Timestamp >= startDate
847                    select Convert.ToDto(c);
848        return query.ToList();
849      }
850    }
851
852    public void DeleteError(DT.ClientError error) {
853      roleVerifier.AuthenticateForAllRoles(AccessServiceRoles.Administrator);
854
855      using (DA.ClientManagementDataContext context = new DA.ClientManagementDataContext()) {
856        var query = context.ClientErrors.Where(x => x.Id == error.Id);
857        if (query.Count() > 0) {
858          context.ClientErrors.DeleteOnSubmit(query.First());
859          context.SubmitChanges();
860        }
861      }
862    }
863    #endregion
864  }
865}
Note: See TracBrowser for help on using the repository browser.