PageRenderTime 36ms CodeModel.GetById 15ms app.highlight 15ms RepoModel.GetById 2ms app.codeStats 0ms

/BlogEngine/BlogEngine.NET/App_Code/UserService.cs

#
C# | 236 lines | 170 code | 33 blank | 33 comment | 33 complexity | 4068a397dcac9f5beaa9bec2e51f3413 MD5 | raw file
  1namespace App_Code
  2{
  3    using System;
  4    using System.Linq;
  5    using System.Web.Script.Services;
  6    using System.Web.Security;
  7    using System.Web.Services;
  8
  9    using BlogEngine.Core;
 10    using BlogEngine.Core.Json;
 11
 12    /// <summary>
 13    /// The user service.
 14    /// </summary>
 15    [WebService(Namespace = "http://tempuri.org/")]
 16    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
 17    [ScriptService]
 18    public class UserService : WebService
 19    {
 20        #region Constants and Fields
 21
 22        /// <summary>
 23        /// The response.
 24        /// </summary>
 25        private readonly JsonResponse response;
 26
 27        #endregion
 28
 29        #region Constructors and Destructors
 30
 31        /// <summary>
 32        /// Initializes a new instance of the <see cref="UserService"/> class.
 33        /// </summary>
 34        public UserService()
 35        {
 36            this.response = new JsonResponse();
 37        }
 38
 39        #endregion
 40
 41        #region Public Methods
 42
 43        /// <summary>
 44        /// Adds the specified user.
 45        /// </summary>
 46        /// <param name="user">The user to add.</param>
 47        /// <param name="pwd">The password to add.</param>
 48        /// <param name="email">The email to add.</param>
 49        /// <param name="roles">Roles for new user</param>
 50        /// <returns>JSON Response.</returns>
 51        [WebMethod]
 52        public JsonResponse Add(string user, string pwd, string email, string[] roles)
 53        {
 54            if (!Security.IsAuthorizedTo(Rights.CreateNewUsers))
 55            {
 56                return new JsonResponse() { Message = Resources.labels.notAuthorized };
 57            }
 58            else if (Utils.StringIsNullOrWhitespace(user))
 59            {
 60                return new JsonResponse() { Message = Resources.labels.userArgumentInvalid };
 61            }
 62            else if (Utils.StringIsNullOrWhitespace(pwd))
 63            {
 64                return new JsonResponse() { Message = Resources.labels.passwordArgumentInvalid };
 65            }
 66            else if (Utils.StringIsNullOrWhitespace(email) || !Utils.IsEmailValid(email))
 67            {
 68                return new JsonResponse() { Message = Resources.labels.emailArgumentInvalid };
 69            }
 70
 71            user = user.Trim();
 72            email = email.Trim();
 73            pwd = pwd.Trim();
 74
 75            if (Membership.GetUser(user) != null)
 76            {
 77                return new JsonResponse() { Message = string.Format(Resources.labels.userAlreadyExists, user) };
 78            }
 79
 80            try
 81            {
 82                Membership.CreateUser(user, pwd, email);
 83
 84                if (Security.IsAuthorizedTo(Rights.EditOtherUsersRoles))
 85                {
 86                    if (roles.GetLength(0) > 0)
 87                    {
 88                        Roles.AddUsersToRoles(new string[] { user }, roles);
 89                    }
 90                }
 91
 92                return new JsonResponse() { Success = true, Message = string.Format(Resources.labels.userHasBeenCreated, user) };
 93            }
 94            catch (Exception ex)
 95            {
 96                Utils.Log("UserService.Add: ", ex);
 97                return new JsonResponse() { Message = string.Format(Resources.labels.couldNotCreateUser, user, ex.Message) };
 98            }
 99
100        }
101
102        /// <summary>
103        /// Deletes the specified id.
104        /// </summary>
105        /// <param name="id">The username.</param>
106        /// <returns>JSON Response</returns>
107        [WebMethod]
108        public JsonResponse Delete(string id)
109        {
110            if (string.IsNullOrEmpty(id))
111            {
112                this.response.Success = false;
113                this.response.Message = Resources.labels.userNameIsRequired;
114                return this.response;
115            }
116
117            bool isSelf = id.Equals(Security.CurrentUser.Identity.Name, StringComparison.OrdinalIgnoreCase);
118
119            if (isSelf && !Security.IsAuthorizedTo(Rights.DeleteUserSelf))
120            {
121                return new JsonResponse() { Message = Resources.labels.notAuthorized };
122            }
123            else if (!isSelf && !Security.IsAuthorizedTo(Rights.DeleteUsersOtherThanSelf))
124            {
125                return new JsonResponse() { Message = Resources.labels.notAuthorized };
126            }
127
128            // Last check - it should not be possible to remove the last use who has the right to Add and/or Edit other user accounts. If only one of such a 
129            // user remains, that user must be the current user, and can not be deleted, as it would lock the user out of the BE environment, left to fix
130            // it in XML or SQL files / commands. See issue 11990
131            bool adminsExist = false;
132            MembershipUserCollection users = Membership.GetAllUsers();
133            foreach (MembershipUser user in users)
134            {
135                string[] roles = Roles.GetRolesForUser(user.UserName);
136
137                // look for admins other than 'id' 
138                if (!id.Equals(user.UserName, StringComparison.OrdinalIgnoreCase) && (Right.HasRight(Rights.EditOtherUsers, roles) || Right.HasRight(Rights.CreateNewUsers, roles)))
139                {
140                    adminsExist = true;
141                    break;
142                }
143            }
144
145            if (!adminsExist)
146            {
147                return new JsonResponse() { Message = Resources.labels.cannotDeleteLastAdmin };
148            }
149
150            string[] userRoles = Roles.GetRolesForUser(id);
151
152            try
153            {
154                if (userRoles.Length > 0)
155                {
156                    Roles.RemoveUsersFromRoles(new string[] { id }, userRoles);
157                }
158                
159                Membership.DeleteUser(id);
160            }
161            catch (Exception ex)
162            {
163                Utils.Log(string.Format("Users.Delete : {0}", ex.Message));
164                this.response.Success = false;
165                this.response.Message = string.Format(Resources.labels.couldNotDeleteUser, id);
166                return this.response;
167            }
168
169            this.response.Success = true;
170            this.response.Message = string.Format(Resources.labels.userHasBeenDeleted, id);
171            return this.response;
172        }
173
174        /// <summary>
175        /// Edits the specified id.
176        /// </summary>
177        /// <param name="id">The user id.</param>
178        /// <param name="bg">The background.</param>
179        /// <param name="vals">The values.</param>
180        /// <returns>JSON Response</returns>
181        [WebMethod]
182        public JsonResponse Edit(string id, string bg, string[] vals)
183        {
184            try
185            {
186                this.response.Success = false;
187
188                bool isSelf = id.Equals(Security.CurrentUser.Identity.Name, StringComparison.OrdinalIgnoreCase);
189
190                if (string.IsNullOrEmpty(vals[0]))
191                {
192                    this.response.Message = Resources.labels.emailIsRequired;
193                    return this.response;
194                }
195
196                if (
197                    Membership.GetAllUsers().Cast<MembershipUser>().Any(
198                        u => u.Email.ToLowerInvariant() == vals[0].ToLowerInvariant()))
199                {
200                    this.response.Message = Resources.labels.userWithEmailExists;
201                    return this.response;
202                }
203
204                if (isSelf && !Security.IsAuthorizedTo(Rights.EditOwnUser))
205                {
206                    this.response.Message = Resources.labels.notAuthorized;
207                    return this.response;
208                }
209                else if (!isSelf && !Security.IsAuthorizedTo(Rights.EditOtherUsers))
210                {
211                    this.response.Message = Resources.labels.notAuthorized;
212                    return this.response;
213                }
214
215                var usr = Membership.GetUser(id);
216                if (usr != null)
217                {
218                    usr.Email = vals[0];
219                    Membership.UpdateUser(usr);
220                }
221
222                this.response.Success = true;
223                this.response.Message = string.Format(Resources.labels.userUpdated, id);
224                return this.response;
225            }
226            catch (Exception ex)
227            {
228                Utils.Log(string.Format("UserService.Update: {0}", ex.Message));
229                this.response.Message = string.Format(Resources.labels.couldNotUpdateUser, id);
230                return this.response;
231            }
232        }
233
234        #endregion
235    }
236}