Free cookie consent management tool by TermsFeed Policy Generator

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

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

#1648 fixed updating of client information

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