public UserFullModel GetById(int id, [ValueProvider(typeof(HeaderValueProviderFactory<string>))] string sessionKey) { return this.PerformOperationAndHandleExceptions(() => { ValidateSessionKey(sessionKey); var context = this.ContextFactory.Create(); using (context) { var usersDbSet = context.Set<User>(); var searchedUser = usersDbSet.FirstOrDefault(u => u.Id == id); var user = usersDbSet.FirstOrDefault(u => u.SessionKey == sessionKey); if (user == null || user.Role.Permission != "admin") { var errResponse = this.Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Invalid user authentication"); throw new HttpResponseException(errResponse); } if (searchedUser == null) { var errResponse = this.Request.CreateErrorResponse(HttpStatusCode.NotFound, "No such user"); throw new HttpResponseException(errResponse); } var models = new UserFullModel() { Id = searchedUser.Id, Nickname = searchedUser.Nickname, AuthCode = searchedUser.AuthCode, SessionKey = searchedUser.SessionKey, Permission = searchedUser.Role.Permission, Amount = searchedUser.Amount, Cars = searchedUser.Cars.AsQueryable().Select(CarModel.FromCar) }; return models; } }); }
public HttpResponseMessage PutEditUser(int id, UserFullModel model, [ValueProvider(typeof(HeaderValueProviderFactory<string>))] string sessionKey) { return this.PerformOperationAndHandleExceptions(() => { var context = this.ContextFactory.Create(); var admin = this.LoginUser(sessionKey, context); var user = context.Set<User>().Find(id); if (user == null) { var errResponse = this.Request.CreateErrorResponse(HttpStatusCode.Conflict, "The user does not exist"); throw new HttpResponseException(errResponse); } if (admin.Role.Permission != "admin") { var errResponse = this.Request.CreateErrorResponse(HttpStatusCode.BadRequest, "You have no permissions to do change cars"); throw new HttpResponseException(errResponse); } if (model.Amount != null && model.Amount != user.Amount) { user.Amount = model.Amount; } if (model.Nickname != null && model.Nickname != user.Nickname) { user.Nickname = model.Nickname; } if (model.Permission != null && model.Permission != user.Role.Permission) { var permission = context.Set<Role>().FirstOrDefault(r => r.Permission == model.Permission); if (permission == null) { var errResponse = this.Request.CreateErrorResponse(HttpStatusCode.Conflict, "Such permissions do not exists, they are admin registered and anonymous"); throw new HttpResponseException(errResponse); } user.Role = permission; } if (model.SessionKey != null && model.SessionKey != user.SessionKey) { user.SessionKey = model.SessionKey; } if (model.AuthCode != null && model.AuthCode != user.AuthCode) { user.AuthCode = model.AuthCode; } if (model.Username != null && model.Username != user.Username) { user.Username = model.Username; } context.SaveChanges(); var response = this.Request.CreateResponse(HttpStatusCode.NoContent); return response; }); }