PageRenderTime 43ms CodeModel.GetById 18ms app.highlight 19ms RepoModel.GetById 1ms app.codeStats 0ms

/BlogEngine/BlogEngine.NET/App_Code/RoleService.cs

#
C# | 322 lines | 218 code | 41 blank | 63 comment | 40 complexity | f612be2d4162abe9ffc727b1f815aece MD5 | raw file
  1namespace App_Code
  2{
  3    using System;
  4    using System.Collections.Generic;
  5    using System.Linq;
  6    using System.Web.Script.Services;
  7    using System.Web.Security;
  8    using System.Web.Services;
  9
 10    using BlogEngine.Core;
 11    using BlogEngine.Core.Json;
 12
 13    /// <summary>
 14    /// Membership service to support AJAX calls
 15    /// </summary>
 16    [WebService(Namespace = "http://tempuri.org/")]
 17    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
 18    [ScriptService]
 19    public sealed class RoleService : WebService
 20    {
 21        #region Constants and Fields
 22
 23        #endregion
 24
 25        #region Constructors and Destructors
 26
 27        /// <summary>
 28        /// Initializes a new instance of the <see cref="RoleService"/> class.
 29        /// </summary>
 30        public RoleService()
 31        {
 32        }
 33
 34        #endregion
 35
 36        #region Public Methods
 37
 38        /// <summary>
 39        /// Adds a role.
 40        /// </summary>
 41        /// <param name="roleName">
 42        /// The role name.
 43        /// </param>
 44        /// <returns>
 45        /// JSON Response
 46        /// </returns>
 47        [WebMethod]
 48        public JsonResponse Add(string roleName)
 49        {
 50            if (!Security.IsAuthorizedTo(Rights.CreateNewRoles))
 51            {
 52                return GetNotAuthorized();
 53            }
 54            else if (Utils.StringIsNullOrWhitespace(roleName))
 55            {
 56                return new JsonResponse() { Message = Resources.labels.roleNameIsRequired };
 57            }
 58            else if (Roles.RoleExists(roleName))
 59            {
 60                return new JsonResponse() { Message = string.Format(Resources.labels.roleAlreadyExists, roleName) };
 61            }
 62            else
 63            {
 64                var response = new JsonResponse();
 65
 66                try
 67                {
 68                    Roles.CreateRole(roleName);
 69                    response.Success = true;
 70                    response.Message = string.Format(Resources.labels.roleHasBeenCreated, roleName);
 71
 72                }
 73                catch (Exception ex)
 74                {
 75                    Utils.Log(string.Format("Roles.AddRole: {0}", ex.Message));
 76                    response.Success = false;
 77                    response.Message = string.Format(Resources.labels.couldNotCreateRole, roleName);
 78                }
 79
 80                return response;
 81            }
 82        }
 83
 84        /// <summary>
 85        /// The delete.
 86        /// </summary>
 87        /// <param name="id">
 88        /// The role id.
 89        /// </param>
 90        /// <returns>
 91        /// JSON Response.
 92        /// </returns>
 93        [WebMethod]
 94        public JsonResponse Delete(string id)
 95        {
 96            if (!Security.IsAuthorizedTo(Rights.DeleteRoles))
 97            {
 98                return GetNotAuthorized();
 99            }
100            else if (Utils.StringIsNullOrWhitespace(id))
101            {
102                return new JsonResponse() { Message = Resources.labels.roleNameIsRequired };
103            }
104
105            try
106            {
107                Right.OnRoleDeleting(id);
108                Roles.DeleteRole(id);
109                return new JsonResponse() { Success = true, Message = string.Format(Resources.labels.roleHasBeenDeleted, id) };
110            }
111            catch (Exception ex)
112            {
113                Utils.Log(string.Format("Roles.DeleteRole: {0}", ex.Message));
114                return new JsonResponse() { Message = string.Format(Resources.labels.couldNotDeleteRole, id) };
115            }
116        }
117
118        /// <summary>
119        /// Saves the rights for a specific Role. 
120        /// </summary>
121        /// <param name="roleName">The name of the role whose rights are being updated.</param>
122        /// <param name="rightsCollection">A dictionary of rights that a role is allowed to have.</param>
123        /// <returns></returns>
124        [WebMethod]
125        public JsonResponse SaveRights(string roleName, Dictionary<string, bool> rightsCollection)
126        {
127            if (!Security.IsAuthorizedTo(Rights.EditRoles))
128            {
129                return new JsonResponse() { Message = Resources.labels.notAuthorized };
130            }
131            else if (Utils.StringIsNullOrWhitespace(roleName) || !Roles.RoleExists(roleName))
132            {
133                return new JsonResponse() { Message = Resources.labels.invalidRoleName };
134            }
135            else if (rightsCollection == null)
136            {
137                return new JsonResponse() { Message = Resources.labels.rightsCanNotBeNull };
138            }
139            else
140            {
141
142                // The rights collection can be empty, just not null. An empty array would indicate that a role is
143                // being updated to include no rights at all.
144                // Remove spaces from each key (i.e. so "Edit Own User" becomes EditOwnUser).
145                rightsCollection = rightsCollection.ToDictionary(r => r.Key.Replace(" ", string.Empty), r => r.Value, StringComparer.OrdinalIgnoreCase);
146
147                // Validate the dictionary before doing any altering to Rights.
148                foreach (var right in rightsCollection)
149                {
150                    if (!Right.RightExists(right.Key))
151                    {
152                        return new JsonResponse() { Success = false, Message = String.Format(Resources.labels.noRightExists, right.Key) };
153                    }
154                    else if (right.Value == false)
155                    {
156                        return new JsonResponse() { Success = false, Message = Resources.labels.doNotPassRightsWithFalseValue };
157                    }
158                }
159
160                foreach (var right in Right.GetAllRights())
161                {
162                    if (right.Flag != Rights.None)
163                    {
164                        if (rightsCollection.ContainsKey(right.Name))
165                        {
166                            right.AddRole(roleName);
167                        }
168                        else
169                        {
170                            right.RemoveRole(roleName);
171                        }
172                    }
173                }
174
175                BlogEngine.Core.Providers.BlogService.SaveRights();
176                return new JsonResponse() { Success = true, Message = string.Format(Resources.labels.rightsUpdatedForRole, roleName) };
177            }
178
179        }
180
181        /// <summary>
182        /// Edits a role.
183        /// </summary>
184        /// <param name="id">
185        /// The row id.
186        /// </param>
187        /// <param name="bg">
188        /// The background.
189        /// </param>
190        /// <param name="vals">
191        /// The values.
192        /// </param>
193        /// <returns>
194        /// JSON Response.
195        /// </returns>
196        [WebMethod]
197        public JsonResponse Edit(string id, string bg, string[] vals)
198        {
199            if (!Security.IsAuthorizedTo(Rights.EditRoles))
200            {
201                return GetNotAuthorized();
202            }
203            else if (Utils.StringIsNullOrWhitespace(id))
204            {
205                return new JsonResponse() { Message = Resources.labels.idArgumentNull };
206            }
207            else if (vals == null)
208            {
209                return new JsonResponse() { Message = Resources.labels.valsArgumentNull };
210            }
211            else if (vals.Length == 0 || Utils.StringIsNullOrWhitespace(vals[0]))
212            {
213                return new JsonResponse() { Message = Resources.labels.roleNameIsRequired };
214            }
215
216            var response = new JsonResponse();
217
218            try
219            {
220                Right.OnRenamingRole(id, vals[0]);
221
222                string[] usersInRole = Roles.GetUsersInRole(id);
223                if (usersInRole.Length > 0)
224                {
225                    Roles.RemoveUsersFromRoles(usersInRole, new string[] { id });
226                }
227
228                Roles.DeleteRole(id);
229                Roles.CreateRole(vals[0]);
230
231                if (usersInRole.Length > 0)
232                {
233                    Roles.AddUsersToRoles(usersInRole, new string[] { vals[0] });
234                }
235
236                Right.RefreshAllRights();
237               
238                response.Success = true;
239                response.Message = string.Format(Resources.labels.roleUpdatedFromTo, id, vals[0]);
240            }
241            catch (Exception ex)
242            {
243                Utils.Log(string.Format("Roles.UpdateRole: {0}", ex.Message));
244                response.Message = string.Format(Resources.labels.couldNotUpdateRole, vals[0]);
245            }
246
247            return response;
248        }
249
250        /// <summary>
251        /// Returns the default rights for the role.
252        /// </summary>
253        /// <param name="roleName">The roleName.</param>
254        /// <returns>
255        /// JSON Response containing delimited default rights.
256        /// </returns>
257        [WebMethod]
258        public JsonResponse GetDefaultRoleRights(string roleName)
259        {
260            if (!Security.IsAuthorizedTo(Rights.EditRoles))
261            {
262                return GetNotAuthorized();
263            }
264            else if (Utils.StringIsNullOrWhitespace(roleName))
265            {
266                return new JsonResponse() { Message = Resources.labels.roleNameArgumentNull };
267            }
268
269            List<Rights> defaultRights = Right.GetDefaultRights(roleName);
270
271            var response = new JsonResponse()
272            {
273                Success = true,
274                Data = string.Join("|", defaultRights.Select(r => Utils.FormatIdentifierForDisplay(r.ToString())).ToArray())
275            };
276
277            return response;
278        }
279
280        /// <summary>
281        /// Returns the rights for the role.
282        /// </summary>
283        /// <param name="roleName">The roleName.</param>
284        /// <returns>
285        /// JSON Response containing delimited rights.
286        /// </returns>
287        [WebMethod]
288        public JsonResponse GetRoleRights(string roleName)
289        {
290            if (!Security.IsAuthorizedTo(Rights.EditRoles))
291            {
292                return GetNotAuthorized();
293            }
294            else if (Utils.StringIsNullOrWhitespace(roleName))
295            {
296                return new JsonResponse() { Message = Resources.labels.roleNameArgumentNull };
297            }
298
299            IEnumerable<Right> roleRights = Right.GetRights(roleName);
300
301            var response = new JsonResponse()
302            {
303                Success = true,
304                Data = string.Join("|", roleRights.Select(r => r.DisplayName).ToArray())
305            };
306
307            return response;
308        }
309
310        #endregion
311
312        #region Methods
313
314        private static JsonResponse GetNotAuthorized()
315        {
316            return new JsonResponse() { Success = false, Message = Resources.labels.notAuthorized };
317        }
318
319        #endregion
320
321    }
322}