private bool ValidatePatchRequset(CompanyUsersApiPatchRequest req) { if (req.UserId <= 0) { return(false); } if (req.CompanyUserId <= 0) { return(false); } if (req.AuthToken == null) { return(false); } if (req.LoginToken == null) { return(false); } if ((req.AccessLevel & AccessLevelMasks.MechanicMask) != 0 && req.AccessLevel > -1 && req.AccessLevel < 16) { return(true); } return(false); }
private void HandlePatchRequest(HttpListenerContext ctx) { try { #region Input Validation if (!ctx.Request.HasEntityBody) { WriteBodyResponse(ctx, 400, "Bad Request", "No Body"); return; } CompanyUsersApiPatchRequest entry = JsonDataObjectUtil <CompanyUsersApiPatchRequest> .ParseObject(ctx); if (!ValidatePatchRequset(entry)) { WriteBodyResponse(ctx, 400, "Bad Request", "Incorrect Format"); return; } #endregion MySqlDataManipulator connection = new MySqlDataManipulator(); using (connection) { bool res = connection.Connect(MySqlDataManipulator.GlobalConfiguration.GetConnectionString()); if (!res) { WriteBodyResponse(ctx, 500, "Unexpected Server Error", "Connection to database failed"); return; } #region User Validation OverallUser mappedUser = connection.GetUserById(entry.UserId); if (mappedUser == null) { WriteBodyResponse(ctx, 404, "Not Found", "User was not found on on the server"); return; } if (!UserVerificationUtil.LoginTokenValid(mappedUser, entry.LoginToken)) { WriteBodyResponse(ctx, 401, "Not Authorized", "Login token was incorrect."); return; } if (!UserVerificationUtil.AuthTokenValid(mappedUser, entry.AuthToken)) { WriteBodyResponse(ctx, 401, "Not Authorized", "Auth token was incorrect."); return; } if ((mappedUser.AccessLevel & AccessLevelMasks.AdminMask) == 0) { WriteBodyResponse(ctx, 401, "Not Authorized", "User was not an admin"); return; } #endregion #region Action Handling OverallUser user = connection.GetUserById(entry.CompanyUserId); if (user == null) { WriteBodyResponse(ctx, 404, "Not Found", "Company User was not found on the server"); return; } user.AccessLevel = entry.AccessLevel; if (!connection.UpdateUserAccessLevel(user)) { WriteBodyResponse(ctx, 500, "Internal Server Error", "Error occurred while updating user's access level: " + connection.LastException.Message); return; } WriteBodylessResponse(ctx, 200, "OK"); #endregion } } catch (Exception e) { WriteBodyResponse(ctx, 500, "Internal Server Error", e.Message); } }