Beispiel #1
0
 protected void Page_Load(object sender, EventArgs e)
 {
     AuthHelper.LoginCheck(Session, Request, Response, Server);
 }
Beispiel #2
0
        public async Task Invoke(HttpContext context, CommandExecutor commandExecutor, IServiceProvider serviceProvider, ILogger <WebsocketConnection> logger)
        {
            if (context.WebSockets.IsWebSocketRequest)
            {
                WebSocket webSocket = await context.WebSockets.AcceptWebSocketAsync();

                if (!AuthHelper.CheckApiAuth(context.Request.Query["key"], context.Request.Query["secret"], options))
                {
                    await webSocket.Send(new WrongApiResponse());

                    await webSocket.CloseAsync(WebSocketCloseStatus.PolicyViolation, "Wrong API key or secret", CancellationToken.None);

                    return;
                }

                WebsocketConnection connection = new WebsocketConnection(webSocket, context);

                connectionManager.AddConnection(connection);
                await connection.Send(new ConnectionResponse()
                {
                    ConnectionId = connection.Id
                });

                while (webSocket.State == WebSocketState.Open || webSocket.State == WebSocketState.Connecting)
                {
                    try
                    {
                        string message = await connection.Websocket.Receive();

                        if (!string.IsNullOrEmpty(message))
                        {
                            _ = Task.Run(async() =>
                            {
                                CommandBase command = JsonHelper.DeserializeCommand(message);

                                if (command != null)
                                {
                                    ResponseBase response = await commandExecutor.ExecuteCommand(command,
                                                                                                 serviceProvider.CreateScope().ServiceProvider, connection.Information, logger,
                                                                                                 connection);

                                    if (response != null)
                                    {
                                        await connection.Send(response);
                                    }
                                }
                            });
                        }
                    }
                    catch (OperationCanceledException)
                    {
                        break;
                    }
                    catch (Exception ex)
                    {
                        logger.LogError(ex.Message);
                    }
                }

                connectionManager.RemoveConnection(connection);
            }
        }
Beispiel #3
0
        private string HandlePost(DynamicDictionary _parameters)
        {
            User user;

            if (AuthHelper.IsAuthorized(Request, out user))
            {
                HydrantWikiManager hwManager = new HydrantWikiManager();

                string sLatitude       = Request.Form["latitudeInput"];
                string sLongitude      = Request.Form["longitudeInput"];
                string sAccuracy       = Request.Form["accuracyInput"];
                string sDeviceDateTime = Request.Form["positionDateTimeInput"];

                double lat      = 0.0;
                double lon      = 0.0;
                double accuracy = -1;

                DateTime deviceDateTime = DateTime.MinValue;
                GeoPoint geoPoint       = null;

                if (Double.TryParse(sLatitude, out lat))
                {
                    if (Double.TryParse(sLongitude, out lon))
                    {
                        //Ignore positions that are 0.0 and 0.0 exactly
                        if (!(lat.Equals(0) &&
                              lon.Equals(0)))
                        {
                            geoPoint = new GeoPoint {
                                X = lon, Y = lat
                            };
                        }
                    }
                }

                Double.TryParse(sAccuracy, out accuracy);
                DateTime.TryParse(sDeviceDateTime, out deviceDateTime);

                //If we got a timestamp that was a zero date, ignore it and use now.
                if (deviceDateTime == DateTime.MinValue)
                {
                    deviceDateTime = DateTime.UtcNow;
                }

                //We will accept a tag without a photo, but not one without a position.
                if (geoPoint != null)
                {
                    Tag tag = new Tag
                    {
                        Active               = true,
                        DeviceDateTime       = deviceDateTime,
                        LastModifiedDateTime = DateTime.UtcNow,
                        UserGuid             = user.Guid,
                        VersionTimeStamp     = DateTime.UtcNow.ToString("u"),
                        Position             = geoPoint,
                        Status               = TagStatus.Pending
                    };

                    if (Request.Files.Any())
                    {
                        tag.ImageGuid = Guid.NewGuid();
                    }
                    else
                    {
                        tag.ImageGuid = null;
                    }

                    try
                    {
                        hwManager.Persist(tag);
                        hwManager.LogVerbose(user.Guid, "Tag Saved");

                        if (tag.ImageGuid != null)
                        {
                            HttpFile file = Request.Files.First();

                            long fileSize = file.Value.Length;

                            try
                            {
                                byte[] data = new byte[fileSize];

                                file.Value.Read(data, 0, (int)fileSize);

                                hwManager.PersistOriginal(tag.ImageGuid.Value, ".jpg", "image/jpg", data);
                                hwManager.LogVerbose(user.Guid, "Tag Image Saved");

                                Image original = ImageHelper.GetImage(data);

                                data = ImageHelper.GetThumbnailBytesOfMaxSize(original, 800);
                                hwManager.PersistWebImage(tag.ImageGuid.Value, ".jpg", "image/jpg", data);

                                data = ImageHelper.GetThumbnailBytesOfMaxSize(original, 100);
                                hwManager.PersistThumbnailImage(tag.ImageGuid.Value, ".jpg", "image/jpg", data);
                            }
                            catch (Exception ex)
                            {
                                hwManager.LogException(user.Guid, ex);
                            }
                        }

                        return(@"{ ""Result"":""Success"" }");
                    }
                    catch (Exception ex)
                    {
                        hwManager.LogException(user.Guid, ex);
                    }
                }
                else
                {
                    //No position
                    hwManager.LogWarning(user.Guid, "No position");

                    return(@"{ ""Result"":""Failure - No position"" }");
                }
            }

            return(@"{ ""Result"":""Failure"" }");
        }
Beispiel #4
0
        protected override void Seed(Data.HotelContext context)
        {
            //  This method will be called after migrating to the latest version.
            context.RoomStates.AddOrUpdate(x => x.StateName,
                                           new RoomState {
                StateName = "Vacant", StateColor = "00ACAC", StateAllow = "YYNNY"
            },
                                           new RoomState {
                StateName = "Booked", StateColor = "F59C1A", StateAllow = "NYNNN"
            },
                                           new RoomState {
                StateName = "Occupied", StateColor = "FF5B57", StateAllow = "NNYNN"
            },
                                           new RoomState {
                StateName = "Cleaning", StateColor = "348FE2", StateAllow = "NNNYN"
            },
                                           new RoomState {
                StateName = "Maintance", StateColor = "929BA1", StateAllow = "NNNNY"
            },
                                           new RoomState {
                StateName = "Late Checkout", StateColor = "727CB6", StateAllow = "NNYNN"
            });
            context.RoomCategories.AddOrUpdate(x => x.CategoryName,
                                               new RoomCategory {
                CategoryName = "Big"
            },
                                               new RoomCategory {
                CategoryName = "Medium"
            },
                                               new RoomCategory {
                CategoryName = "Small"
            });
            context.RoomPriceKinds.AddOrUpdate(x => x.KindName,
                                               new RoomPriceKind {
                KindName = "WeekDay", KindColor = "43A047", KindDescription = ""
            },
                                               new RoomPriceKind {
                KindName = "WeekEnd", KindColor = "D32F2F", KindDescription = ""
            },
                                               new RoomPriceKind {
                KindName = "Holiday", KindColor = "00695C", KindDescription = ""
            });
            context.Settings.AddOrUpdate(x => x.Key,
                                         new Setting {
                Key = "app.name", Value = "Hotel Management System"
            },
                                         new Setting {
                Key = "hotel.name", Value = "Hotel Universal"
            },
                                         new Setting {
                Key = "hotel.address", Value = "Jl. Jalan Perum \nTangerang, 14000"
            },
                                         new Setting {
                Key = "hotel.logo", Value = ""
            },
                                         new Setting {
                Key = "hotel.phone", Value = "08965555555"
            },
                                         new Setting {
                Key = "hotel.email", Value = "*****@*****.**"
            },
                                         new Setting {
                Key = "time.checkin", Value = "12:00:00"
            },
                                         new Setting {
                Key = "time.checkout", Value = "13:00:00"
            },
                                         new Setting {
                Key = "time.fullcharge", Value = "18:00:00"
            },
                                         new Setting {
                Key = "penalty", Value = "20000"
            },
                                         new Setting {
                Key = "deposit", Value = "50000"
            });
            context.TransactionCategories.AddOrUpdate(x => x.CategoryName,
                                                      new TransactionCategory {
                CategoryName = "Cash", CategoryColor = "558B2F", CategoryIcon = "fa-money", IsIncome = true
            },
                                                      new TransactionCategory {
                CategoryName = "Income", CategoryColor = "1565C0", CategoryIcon = "fa-credit-card", IsIncome = true
            },
                                                      new TransactionCategory {
                CategoryName = "Salary", CategoryColor = "F57F17", CategoryIcon = "fa-usd", IsIncome = true
            },
                                                      new TransactionCategory {
                CategoryName = "Food & Drinks", CategoryColor = "00838F", CategoryIcon = "fa-cutlery", IsIncome = false
            },
                                                      new TransactionCategory {
                CategoryName = "Transportation", CategoryColor = "BF360C", CategoryIcon = "fa-rocket", IsIncome = false
            },
                                                      new TransactionCategory {
                CategoryName = "Comunication", CategoryColor = "311B92", CategoryIcon = "fa-phone", IsIncome = false
            },
                                                      new TransactionCategory {
                CategoryName = "Tax", CategoryColor = "1B5E20", CategoryIcon = "fa-gavel", IsIncome = false
            },
                                                      new TransactionCategory {
                CategoryName = "Utilities", CategoryColor = "FF8F00", CategoryIcon = "fa-cogs", IsIncome = false
            },
                                                      new TransactionCategory {
                CategoryName = "Insurance", CategoryColor = "3E2723", CategoryIcon = "fa-heart", IsIncome = false
            },
                                                      new TransactionCategory {
                CategoryName = "Loan", CategoryColor = "0097A7", CategoryIcon = "fa-university", IsIncome = false
            },
                                                      new TransactionCategory {
                CategoryName = "Uncategorized Income", CategoryColor = "000000", CategoryIcon = "fa-asterisk", IsIncome = true
            },
                                                      new TransactionCategory {
                CategoryName = "Uncategorized Outcome", CategoryColor = "000000", CategoryIcon = "fa-asterisk", IsIncome = false
            });
            context.BookingTypes.AddOrUpdate(x => x.TypeName,
                                             new BookingType {
                TypeName = "Walk-In", IsLocal = true
            },
                                             new BookingType {
                TypeName = "Telephone", IsLocal = true
            },
                                             new BookingType {
                TypeName = "Traveloka", IsLocal = false
            },
                                             new BookingType {
                TypeName = "Agoda", IsLocal = false
            });
            context.InvoiceKinds.AddOrUpdate(x => x.Id,
                                             new InvoiceDetailKind {
                Id = 1, KindName = "Room Invoice"
            },
                                             new InvoiceDetailKind {
                Id = 2, KindName = "Room Move Charge"
            },
                                             new InvoiceDetailKind {
                Id = 3, KindName = "Room Late Checkout"
            },
                                             new InvoiceDetailKind {
                Id = 4, KindName = "Room Price by Online"
            },
                                             new InvoiceDetailKind {
                Id = 97, KindName = "Deposit"
            },
                                             new InvoiceDetailKind {
                Id = 98, KindName = "Cashback"
            },
                                             new InvoiceDetailKind {
                Id = 99, KindName = "Pinalty"
            },
                                             new InvoiceDetailKind {
                Id = 100, KindName = "Pay Cash"
            },
                                             new InvoiceDetailKind {
                Id = 101, KindName = "Pay Card"
            },
                                             new InvoiceDetailKind {
                Id = 200, KindName = "Uncategorized In"
            },
                                             new InvoiceDetailKind {
                Id = 201, KindName = "Uncategorized Out"
            });
            context.SaveChanges();

            var is_exists = context.Settings.Where(x => x.Key == "app.key").Any();

            if (!is_exists)
            {
                context.Settings.Add(new Setting {
                    Key = "app.key", Value = AppHelper.GenerateRandomStr(32)
                });
                context.SaveChanges();
            }

            var big     = context.RoomCategories.Where(x => x.CategoryName == "Big").Single();
            var vacant  = context.RoomStates.Where(x => x.StateName == "Vacant").Single();
            var weekday = context.RoomPriceKinds.Where(x => x.KindName == "WeekDay").Single();

            SettingHelper.Load();

            context.Users.AddOrUpdate(x => x.Username,
                                      new User {
                Username = "******",
                Fullname = "Administrator",
                Password = AuthHelper.HashText("admin", SettingHelper.AppKey),
                Level    = 0,
                IsActive = true
            });

            context.RoomCalendars.AddOrUpdate(x => x.DateAt,
                                              new RoomCalendar {
                DateAt = DateTime.Today, RoomPriceKindId = weekday.Id
            });
            context.Rooms.AddOrUpdate(x => x.RoomNumber,
                                      new Room {
                RoomNumber = "201", RoomStateId = vacant.Id, RoomCategoryId = big.Id
            });
            context.SaveChanges();
        }
Beispiel #5
0
        public HttpResponseMessage UserInfo(UserInfoModel model)
        {
            string Result = string.Empty;

            try
            {
                //请求中包含的固定参数
                model.SOURCE      = ParametersFilter.FilterSqlHtml(model.SOURCE, 24);
                model.CREDENTIALS = ParametersFilter.FilterSqlHtml(model.CREDENTIALS, 24);
                model.ADDRESS     = HttpHelper.IPAddress();
                model.TERMINAL    = ParametersFilter.FilterSqlHtml(model.TERMINAL, 1);
                model.INDEX       = ParametersFilter.FilterSqlHtml(model.INDEX, 24);
                model.METHOD      = ParametersFilter.FilterSqlHtml(model.METHOD, 24);
                model.DATA        = System.Web.HttpUtility.UrlDecode(model.DATA);

                #region MyRegion
                //DATA装换为json字符串
                string datatojson = ApiHelper.DATAToJson(model.DATA);

                string UserAccount = JObject.Parse(datatojson)["UserAccount"].ToString();

                //图片Model
                ImgModel imgModel = new ImgModel();

                imgModel.ImgIp        = ApiHelper.ImgURL();
                imgModel.ImgDisk      = SingleXmlInfo.GetInstance().GetWebApiConfig("imgDisk");
                imgModel.ImgRoot      = SingleXmlInfo.GetInstance().GetWebApiConfig("imgRoot");
                imgModel.ImgAttribute = "user";
                imgModel.UserAccount  = UserAccount;
                imgModel.ImgName      = "userAvatar";
                imgModel.ImgString    = model.UserAvatar;

                //URL编码
                model.DATA = System.Web.HttpUtility.UrlEncode(model.DATA);

                //保存的图片名称
                model.UserAvatar = imgModel.ImgIp + imgModel.UserAccount + "/" + imgModel.ImgAttribute + "/" + imgModel.ImgName + ".jpg";

                //返回结果
                Result = ApiHelper.HttpRequest(username, password, Url, model);

                ////解析返回结果
                JObject jsons = (JObject)JsonConvert.DeserializeObject(Result);

                if (jsons["DATA"][0]["Result"].ToString() == "1")
                {
                    ApiHelper.HttpRequest(ApiHelper.GetImgUploadURL("imgUploadIp", "imgUpload"), imgModel);

                    model.UserMobile  = jsons["DATA"][0]["UserMobile"].ToString();
                    model.UserAccount = jsons["DATA"][0]["UserAccount"].ToString();

                    //返回凭证
                    jsons["CREDENTIALS"] = AuthHelper.AuthUserSet(model);
                    Result = JsonConvert.SerializeObject(jsons);
                }
                #endregion

                #region Redis_DATA
                //UserCheckBLL B = new UserCheckBLL();
                //Dictionary<string, string> redisData = B.UserInfo_Redis(model.DATA);

                //string imgStr = model.UserAvatar;

                //model.UserAvatar = redisData["UserAvatar"];
                //string Str = JsonConvert.SerializeObject(model, JSetting);

                ////返回结果
                //Result = ApiHelper.HttpRequest(username, password, Url, Str);

                //////解析返回结果
                //JObject jsons = (JObject)JsonConvert.DeserializeObject(Result);

                //if (jsons["DATA"][0]["Result"].ToString() == "1")
                //{
                //    // CharConversion.SaveImg(imgStr, model.UserAvatar, "~/Avatar/");

                //    //实例化Redis请求参数
                //    RedisModel.BaseModel redis = new RedisModel.BaseModel();

                //    redis.RedisIP = SingleXmlInfo.GetInstance().GetWebApiConfig("redisAddress");
                //    redis.RedisPort = SingleXmlInfo.GetInstance().GetWebApiConfig("redisPort");
                //    redis.RedisPassword = SingleXmlInfo.GetInstance().GetWebApiConfig("redisPassword");
                //    redis.RedisKey = "PAY_USER_Info_ " + redisData["UserAccount"];
                //    redis.RedisValue = ApiHelper.DictionaryToStr(redisData);
                //    redis.LifeCycle = "50000";
                //    redis.RedisFunction = "StringSet";

                //    //获取Redis中的验证码
                //    string b = ApiHelper.HttpRequest(ApiHelper.GetRedisURL(redis.RedisFunction), redis);
                //}
                #endregion

                ///写日志
                string RequestAction = "api/" + username + "/" + HttpContext.Current.Request.RequestContext.RouteData.Values["action"].ToString() + ":";
                LogHelper.LogResopnse(RequestAction + Result);
            }
            catch (Exception ex)
            {
                LogHelper.LogError(ex.ToString());
            }

            HttpResponseMessage Respend = new HttpResponseMessage {
                Content = new StringContent(Result, Encoding.GetEncoding("UTF-8"), "application/json")
            };

            return(Respend);
        }
Beispiel #6
0
        protected void Page_Load(object sender, EventArgs e)
        {
            //需要登录才能看到
            AuthHelper.LoginCheck(Session, Request, Response, Server);
            AuthHelper.StudentOnlyPage(Session, Request, Response, Server);

            Models.Student student;
            if (Session["user"] is Models.Student s)
            {
                student = s;
            }
            else
            {
                //登录的不是学生,转到登录界面
                Session.Remove("user");
                Response.Redirect("~/Login.aspx");
                return;
            }

            //用学生对象的院系id去获取该院系的对象
            var departmentService = new DepartmentServiceImpl();
            var did        = student.DepartmentId;
            var department = (Department)departmentService.GetById(did);

            //赋值:学号
            SpanStudentNumber.InnerText = student.StudentNumber;
            //赋值:学生姓名
            SpanName.InnerText = student.Name;
            //赋值:院系中文名
            SpanDepartment.InnerText = department.ChinesaeName;

            //利用学生的班级id获取该班对象
            var classService = new ClassServiceImpl();
            var cid          = student.ClassId;
            var aClass       = (Class)classService.GetById(cid);

            //利用课程号查老师获得老师所属院系
            //赋值:班级名称
            SpanClass.InnerText = aClass.Name;

            //该生的课程数据绑定
            var courses       = new CourseServiceImpl().Get(student);
            var studentCourse = courses as Course[] ?? courses.ToArray();

            _thisStudentCourse = studentCourse;
            foreach (var course in studentCourse)
            {
                var thisCourseTeacherId = new CourseServiceImpl().GetTeacherIdByCourseId(course.CourseId);
                var thisTeacher         = new TeacherServiceImpl().GetByTeacherId(thisCourseTeacherId);
                var thisTeacherDep      = new DepartmentServiceImpl().GetByDepId(thisTeacher.DepartmentId);
                //得到当前学生的某个课程的成绩
                var thisStudentScore =
                    new ScoreServiceImpl().GetByCourseIdAndStudentId(course.CourseId, student.StudentId);
                string[] str1 =
                {
                    course.CourseId.ToString(), course.Name, thisStudentScore.Mark.ToString(),
                    thisTeacherDep.ChinesaeName
                };
                dep.Add(str1);
            }
        }
Beispiel #7
0
 public IActionResult Index()
 {
     ViewData["isAdmin"] = AuthHelper.isAdmin(User, _context);
     return(View());
 }
Beispiel #8
0
 public string Logout()
 {
     AuthHelper.Logout();
     System.Threading.Thread.Sleep(200);
     return("注销成功");
 }
        public async Task SearchUsersTest()
        {
            // trying to make it more robust by adding on extra so don't have chance of bad data affecting next test run
            string dateString = DateTime.UtcNow.ToFileTime().ToString();
            string searchWord = dateString.Substring(dateString.Length - 7);

            // Create users
            SocialPlusClient client = new SocialPlusClient(TestConstants.ServerApiBaseUrl);

            PostUserResponse postUserResponse;
            string           firstName = "FirstYouThere" + searchWord;
            string           lastName  = "YouThere" + searchWord;
            string           bio       = string.Empty;

            postUserResponse = await TestUtilities.DoLogin(client, firstName, lastName, bio);

            string auth1 = AuthHelper.CreateSocialPlusAuth(postUserResponse.SessionToken);

            PostUserResponse postUserResponse2;
            string           firstName2 = "Larry" + searchWord;
            string           lastName2  = "GoWhere" + searchWord;
            string           bio2       = string.Empty;

            postUserResponse2 = await TestUtilities.DoLogin(client, firstName2, lastName2, bio2);

            string auth2 = AuthHelper.CreateSocialPlusAuth(postUserResponse2.SessionToken);

            PostUserResponse postUserResponse3;
            string           firstName3 = "Larry" + searchWord;
            string           lastName3  = "NotHere" + searchWord;
            string           bio3       = string.Empty;

            postUserResponse3 = await TestUtilities.DoLogin(client, firstName3, lastName3, bio3);

            string auth3 = AuthHelper.CreateSocialPlusAuth(postUserResponse3.SessionToken);

            // Delay a bit to allow data to get into the search
            await Task.Delay(TestConstants.SearchDelay);

            // Search on first name
            HttpOperationResponse <FeedResponseUserCompactView> search1 = await client.Search.GetUsersWithHttpMessagesAsync(query : firstName, cursor : null, limit : 5, authorization : auth1);

            // Search on last name
            HttpOperationResponse <FeedResponseUserCompactView> search2 = await client.Search.GetUsersWithHttpMessagesAsync(query : lastName2, cursor : null, limit : 5, authorization : auth1);

            // Search on something that results more than one user
            HttpOperationResponse <FeedResponseUserCompactView> search3 = await client.Search.GetUsersWithHttpMessagesAsync(query : "Larry" + searchWord, cursor : null, limit : 3, authorization : auth1);

            // Search on one that hits in multiple fields in one entry
            HttpOperationResponse <FeedResponseUserCompactView> search4 = await client.Search.GetUsersWithHttpMessagesAsync(query : "YouThere" + searchWord, cursor : null, limit : 5, authorization : auth1);

            // Clean up first user
            HttpOperationResponse <object> deleteUser1 = await client.Users.DeleteUserWithHttpMessagesAsync(authorization : auth1);

            // search on that first user shouldn't come back anything
            string anon = TestUtilities.GetAnonAuth();
            HttpOperationResponse <FeedResponseUserCompactView> search5 = await client.Search.GetUsersWithHttpMessagesAsync(query : firstName, cursor : null, limit : 10, authorization : anon);

            // Clean up second user
            HttpOperationResponse <object> deleteUser2 = await client.Users.DeleteUserWithHttpMessagesAsync(authorization : auth2);

            // Clean up third user
            HttpOperationResponse <object> deleteUser3 = await client.Users.DeleteUserWithHttpMessagesAsync(authorization : auth3);

            // *** Verify section - do this after deleting because left behind users affect results
            // Verify first search
            Assert.IsTrue(search1.Response.IsSuccessStatusCode);
            Assert.AreEqual(search1.Body.Data.Count, 1);
            Assert.AreEqual(search1.Body.Data[0].FirstName, firstName);
            Assert.AreEqual(search1.Body.Data[0].LastName, lastName);
            Assert.AreEqual(search1.Body.Data[0].UserHandle, postUserResponse.UserHandle);

            // Verify second search
            Assert.IsTrue(search2.Response.IsSuccessStatusCode);
            Assert.AreEqual(search2.Body.Data.Count, 1);
            Assert.AreEqual(search2.Body.Data[0].FirstName, firstName2);
            Assert.AreEqual(search2.Body.Data[0].LastName, lastName2);
            Assert.AreEqual(search2.Body.Data[0].UserHandle, postUserResponse2.UserHandle);

            // Verify third search
            Assert.IsTrue(search3.Response.IsSuccessStatusCode);
            List <UserCompactView> search3OrderedData = search3.Body.Data.OrderBy(x => x.LastName).ToList();

            Assert.AreEqual(search3OrderedData.Count, 2);
            Assert.AreEqual(search3OrderedData[0].FirstName, firstName2);
            Assert.AreEqual(search3OrderedData[0].LastName, lastName2);
            Assert.AreEqual(search3OrderedData[0].UserHandle, postUserResponse2.UserHandle);
            Assert.AreEqual(search3OrderedData[1].FirstName, firstName3);
            Assert.AreEqual(search3OrderedData[1].LastName, lastName3);
            Assert.AreEqual(search3OrderedData[1].UserHandle, postUserResponse3.UserHandle);

            // Verify fourth search
            Assert.IsTrue(search4.Response.IsSuccessStatusCode);
            Assert.AreEqual(search4.Body.Data.Count, 1);
            Assert.AreEqual(search4.Body.Data[0].FirstName, firstName);
            Assert.AreEqual(search4.Body.Data[0].LastName, lastName);
            Assert.AreEqual(search4.Body.Data[0].UserHandle, postUserResponse.UserHandle);

            // Verify fifth search - should be 0 since user was deleted
            Assert.IsTrue(search5.Response.IsSuccessStatusCode);
            Assert.AreEqual(search5.Body.Data.Count, 0);

            // Verify deletions
            Assert.IsTrue(deleteUser1.Response.IsSuccessStatusCode);
            Assert.IsTrue(deleteUser2.Response.IsSuccessStatusCode);
            Assert.IsTrue(deleteUser3.Response.IsSuccessStatusCode);
        }
Beispiel #10
0
 protected void GridView_RowInserting(object sender, DevExpress.Web.Data.ASPxDataInsertingEventArgs e)
 {
     e.NewValues["Pass"] = AuthHelper.GetMD5("123456");
 }
        public async Task SearchUpdatedTopicTest()
        {
            string dateString  = DateTime.UtcNow.ToFileTime().ToString();
            string searchWord1 = "OriginalText" + dateString.Substring(dateString.Length - 7);
            string searchWord2 = "UpdatedText" + dateString.Substring(dateString.Length - 7);

            SocialPlusClient client = new SocialPlusClient(TestConstants.ServerApiBaseUrl);

            PostUserResponse postUserResponse;
            string           firstName = "FirstUser";
            string           lastName  = "FirstUserLastName";
            string           bio       = string.Empty;

            postUserResponse = await TestUtilities.DoLogin(client, firstName, lastName, bio);

            string auth = AuthHelper.CreateSocialPlusAuth(postUserResponse.SessionToken);

            string           topicTitle       = "My Favorite Topic";
            string           originalText     = "Sports. #" + searchWord1;
            BlobType         blobType         = BlobType.Image;
            string           blobHandle       = "http://myBlobHandle/";
            string           language         = "en-US";
            string           deepLink         = "Sports!";
            string           categories       = "sports, ncurrency";
            string           friendlyName     = "Game On!";
            string           group            = "mygroup";
            PostTopicRequest postTopicRequest = new PostTopicRequest(publisherType: PublisherType.User, text: originalText, title: topicTitle, blobType: blobType, blobHandle: blobHandle, language: language, deepLink: deepLink, categories: categories, friendlyName: friendlyName, group: group);
            HttpOperationResponse <PostTopicResponse> postTopicOperationResponse = await client.Topics.PostTopicWithHttpMessagesAsync(request : postTopicRequest, authorization : auth);

            // If the post topic operation failed, clean up
            if (postTopicOperationResponse == null || !postTopicOperationResponse.Response.IsSuccessStatusCode || postTopicOperationResponse.Body == null || string.IsNullOrWhiteSpace(postTopicOperationResponse.Body.TopicHandle))
            {
                await client.Users.DeleteUserWithHttpMessagesAsync(authorization : auth);

                Assert.Fail("Failed to post topic");
            }

            string topicHandle = postTopicOperationResponse.Body.TopicHandle;

            string                updatedText               = "Movies. #" + searchWord2;
            PutTopicRequest       putTopicRequest           = new PutTopicRequest(text: updatedText, title: topicTitle, categories: categories);
            HttpOperationResponse putTopicOperationResponse = await client.Topics.PutTopicWithHttpMessagesAsync(topicHandle, request : putTopicRequest, authorization : auth);

            // If the put topic operation failed, clean up
            if (putTopicOperationResponse == null || !putTopicOperationResponse.Response.IsSuccessStatusCode)
            {
                await client.Topics.DeleteTopicWithHttpMessagesAsync(topicHandle : topicHandle, authorization : auth);

                await client.Users.DeleteUserWithHttpMessagesAsync(authorization : auth);

                Assert.Fail("Failed to update topic");
            }

            // Delay a bit to allow data to get into the search
            await Task.Delay(TestConstants.SearchDelay);

            // Search on original text
            HttpOperationResponse <FeedResponseTopicView> search1 = await client.Search.GetTopicsWithHttpMessagesAsync(query : searchWord1, cursor : null, authorization : auth);

            // Search on updated text
            HttpOperationResponse <FeedResponseTopicView> search2 = await client.Search.GetTopicsWithHttpMessagesAsync(query : searchWord2, cursor : null, authorization : auth);

            // Clean up topic
            HttpOperationResponse <object> deleteTopic = await client.Topics.DeleteTopicWithHttpMessagesAsync(topicHandle : topicHandle, authorization : auth);

            // Clean up user
            HttpOperationResponse <object> deleteUser = await client.Users.DeleteUserWithHttpMessagesAsync(authorization : auth);

            // Verify now - verify after cleanup so that failed asserts don't cause data to be left behind and interfere with future tests
            // Verify Search 1
            Assert.IsTrue(search1.Response.IsSuccessStatusCode);
            Assert.AreEqual(search1.Body.Data.Count, 0);

            // Verify Search 2
            Assert.IsTrue(search2.Response.IsSuccessStatusCode);
            Assert.AreEqual(search2.Body.Data.Count, 1);
            Assert.AreEqual(search2.Body.Data[0].TopicHandle, topicHandle);
            Assert.AreEqual(search2.Body.Data[0].Title, topicTitle);
            Assert.AreEqual(search2.Body.Data[0].Text, updatedText);
            Assert.AreEqual(search2.Body.Data[0].BlobType, blobType);
            Assert.AreEqual(search2.Body.Data[0].BlobHandle, blobHandle);
            Assert.AreEqual(search2.Body.Data[0].Language, language);
            Assert.AreEqual(search2.Body.Data[0].DeepLink, deepLink);
            Assert.AreEqual(search2.Body.Data[0].Categories, categories);
            Assert.AreEqual(search2.Body.Data[0].FriendlyName, friendlyName);
            Assert.AreEqual(search2.Body.Data[0].Group, group);

            // Verify deletions
            Assert.IsTrue(deleteTopic.Response.IsSuccessStatusCode);
            Assert.IsTrue(deleteUser.Response.IsSuccessStatusCode);
        }
        public async Task SearchTopicsTest()
        {
            // generate unique string
            string searchWord = "#" + Guid.NewGuid().ToString().Replace("-", string.Empty);

            // create user
            SocialPlusClient client1 = new SocialPlusClient(TestConstants.ServerApiBaseUrl);
            PostUserResponse postUserResponse;
            string           firstName = "FirstUser";
            string           lastName  = "FirstUserLastName";
            string           bio       = string.Empty;

            postUserResponse = await TestUtilities.DoLogin(client1, firstName, lastName, bio);

            string auth = AuthHelper.CreateSocialPlusAuth(postUserResponse.SessionToken);

            // First Topic
            string           topicTitle       = string.Empty;
            string           topicText        = searchWord;
            BlobType         blobType         = BlobType.Unknown;
            string           blobHandle       = string.Empty;
            string           language         = string.Empty;
            string           deepLink         = string.Empty;
            string           categories       = string.Empty;
            string           friendlyName     = string.Empty;
            string           group            = string.Empty;
            PostTopicRequest postTopicRequest = new PostTopicRequest(publisherType: PublisherType.User, text: topicText, title: topicTitle, blobType: blobType, blobHandle: blobHandle, language: language, deepLink: deepLink, categories: categories, friendlyName: friendlyName, group: group);
            HttpOperationResponse <PostTopicResponse> postTopicOperationResponse = await client1.Topics.PostTopicWithHttpMessagesAsync(request : postTopicRequest, authorization : auth);

            // If the first post topic operation failed, clean up
            if (postTopicOperationResponse == null || postTopicOperationResponse.Body == null || string.IsNullOrWhiteSpace(postTopicOperationResponse.Body.TopicHandle))
            {
                await client1.Users.DeleteUserWithHttpMessagesAsync(authorization : auth);

                Assert.Fail("Failed to post first topic");
            }

            // Large delay to increase the difference in freshness between the two topics.
            // Search results are influenced by weight (not used right now), freshness, and relevance.
            // Azure Search's relevance score seems to vary a little bit even though both topics here
            // are exactly the same. By increasing the freshness difference, these small variations in
            // relevance score get washed out, and this test will pass deterministically.
            await Task.Delay(10 *TestConstants.SearchDelay);

            // create a second Topic
            string           topicTitle2       = string.Empty;
            string           topicText2        = searchWord;
            PostTopicRequest postTopicRequest2 = new PostTopicRequest(publisherType: PublisherType.User, text: topicText2, title: topicTitle2, blobType: blobType, blobHandle: blobHandle, language: language, deepLink: deepLink, categories: categories, friendlyName: friendlyName, group: group);
            HttpOperationResponse <PostTopicResponse> postTopicOperationResponse2 = await client1.Topics.PostTopicWithHttpMessagesAsync(request : postTopicRequest2, authorization : auth);

            // If the second post topic operation failed, clean up
            if (postTopicOperationResponse2 == null || postTopicOperationResponse2.Body == null || string.IsNullOrWhiteSpace(postTopicOperationResponse2.Body.TopicHandle))
            {
                await client1.Topics.DeleteTopicWithHttpMessagesAsync(postTopicOperationResponse.Body.TopicHandle, auth);

                await client1.Users.DeleteUserWithHttpMessagesAsync(authorization : auth);

                Assert.Fail("Failed to post second topic");
            }

            // Delay a bit to allow data to get into the search
            await Task.Delay(TestConstants.SearchDelay);

            // Only one result
            HttpOperationResponse <FeedResponseTopicView> search1 = await client1.Search.GetTopicsWithHttpMessagesAsync(query : searchWord, cursor : null, limit : 1, authorization : auth);

            // Now get the second one after that cursor
            HttpOperationResponse <FeedResponseTopicView> search2 = await client1.Search.GetTopicsWithHttpMessagesAsync(query : searchWord, cursor : int.Parse(search1.Body.Cursor), limit : 1, authorization : auth);

            // Now get all in one
            HttpOperationResponse <FeedResponseTopicView> search3 = await client1.Search.GetTopicsWithHttpMessagesAsync(query : searchWord, cursor : null, limit : 2, authorization : auth);

            // Delete topics and see if search works
            HttpOperationResponse <object> deleteTopic1 = await client1.Topics.DeleteTopicWithHttpMessagesAsync(postTopicOperationResponse.Body.TopicHandle, auth);

            HttpOperationResponse <object> deleteTopic2 = await client1.Topics.DeleteTopicWithHttpMessagesAsync(postTopicOperationResponse2.Body.TopicHandle, auth);

            // now search to see if works after deleted
            HttpOperationResponse <FeedResponseTopicView> search4 = await client1.Search.GetTopicsWithHttpMessagesAsync(query : searchWord, cursor : null, limit : 10, authorization : auth);

            // Clean up first user
            HttpOperationResponse <object> deleteUser1 = await client1.Users.DeleteUserWithHttpMessagesAsync(authorization : auth);

            // Verify now - verify after all is cleaned up so any failures isn't leaving behind stuff to cause failure next time test is ran
            // Verify Search 1
            Assert.IsTrue(search1.Response.IsSuccessStatusCode);
            Assert.AreEqual(search1.Body.Data.Count, 1);
            Assert.AreEqual(search1.Body.Data[0].TopicHandle, postTopicOperationResponse2.Body.TopicHandle);
            Assert.AreEqual(search1.Body.Data[0].Title, topicTitle2);
            Assert.AreEqual(search1.Body.Data[0].Text, topicText2);
            Assert.AreEqual(search1.Body.Data[0].BlobType, blobType);
            Assert.AreEqual(search1.Body.Data[0].BlobHandle, blobHandle);
            Assert.AreEqual(search1.Body.Data[0].Language, language);
            Assert.AreEqual(search1.Body.Data[0].DeepLink, deepLink);
            Assert.AreEqual(search1.Body.Data[0].Categories, categories);
            Assert.AreEqual(search1.Body.Data[0].FriendlyName, friendlyName);
            Assert.AreEqual(search1.Body.Data[0].Group, group);

            // Verify Search 2
            Assert.IsTrue(search2.Response.IsSuccessStatusCode);
            Assert.AreEqual(search2.Body.Data.Count, 1);
            Assert.AreEqual(search2.Body.Data[0].TopicHandle, postTopicOperationResponse.Body.TopicHandle);
            Assert.AreEqual(search2.Body.Data[0].Title, topicTitle);
            Assert.AreEqual(search2.Body.Data[0].Text, topicText);
            Assert.AreEqual(search2.Body.Data[0].BlobType, blobType);
            Assert.AreEqual(search2.Body.Data[0].BlobHandle, blobHandle);
            Assert.AreEqual(search2.Body.Data[0].Language, language);
            Assert.AreEqual(search2.Body.Data[0].DeepLink, deepLink);
            Assert.AreEqual(search2.Body.Data[0].Categories, categories);
            Assert.AreEqual(search2.Body.Data[0].FriendlyName, friendlyName);
            Assert.AreEqual(search2.Body.Data[0].Group, group);

            // Verify Search 3
            Assert.IsTrue(search3.Response.IsSuccessStatusCode);
            Assert.AreEqual(search3.Body.Data.Count, 2);
            Assert.AreEqual(search3.Body.Data[0].TopicHandle, postTopicOperationResponse2.Body.TopicHandle);
            Assert.AreEqual(search3.Body.Data[0].Title, topicTitle2);
            Assert.AreEqual(search3.Body.Data[0].Text, topicText2);
            Assert.AreEqual(search3.Body.Data[0].BlobType, blobType);
            Assert.AreEqual(search3.Body.Data[0].BlobHandle, blobHandle);
            Assert.AreEqual(search3.Body.Data[0].Language, language);
            Assert.AreEqual(search3.Body.Data[0].DeepLink, deepLink);
            Assert.AreEqual(search3.Body.Data[0].Categories, categories);
            Assert.AreEqual(search3.Body.Data[0].FriendlyName, friendlyName);
            Assert.AreEqual(search3.Body.Data[0].Group, group);

            Assert.AreEqual(search3.Body.Data[1].TopicHandle, postTopicOperationResponse.Body.TopicHandle);
            Assert.AreEqual(search3.Body.Data[1].Title, topicTitle);
            Assert.AreEqual(search3.Body.Data[1].Text, topicText);
            Assert.AreEqual(search3.Body.Data[1].BlobType, blobType);
            Assert.AreEqual(search3.Body.Data[1].BlobHandle, blobHandle);
            Assert.AreEqual(search3.Body.Data[1].Language, language);
            Assert.AreEqual(search3.Body.Data[1].DeepLink, deepLink);
            Assert.AreEqual(search3.Body.Data[1].Categories, categories);
            Assert.AreEqual(search3.Body.Data[1].FriendlyName, friendlyName);
            Assert.AreEqual(search3.Body.Data[1].Group, group);

            // Verify Search 4
            Assert.IsTrue(search4.Response.IsSuccessStatusCode);
            Assert.AreEqual(search4.Body.Data.Count, 0);

            // Verify deletions
            Assert.IsTrue(deleteTopic1.Response.IsSuccessStatusCode);
            Assert.IsTrue(deleteTopic2.Response.IsSuccessStatusCode);
            Assert.IsTrue(deleteUser1.Response.IsSuccessStatusCode);
        }
Beispiel #13
0
 public OrderController(DataContext dataContext, AuthHelper authHelper)
 {
     this.dataContext = dataContext;
     this.authHelper  = authHelper;
 }
        public HttpResponseMessage Post([FromBody] JToken body)
        {
            using (var session = NHibernateHelper.CreateSessionFactory())
            {
                using (var transaction = session.BeginTransaction())
                {
                    if (AuthHelper.JwtAuth() != 1)
                    {
                        return(WebApiHelper.ObjectToHttpResponseMessage("No token was supplied", System.Net.HttpStatusCode.Unauthorized));
                    }


                    var stateId = Convert.ToInt32(AuthHelper.GetKey("stateId"));

                    var id = body.Value <decimal>("Id");

                    var r = PopulateRegistration(body);

                    var     registration = new Registration();
                    Renewal renewal      = null;

                    if (id != 0)
                    {
                        // Existing Registration
                        var registrations = new List <Registration>(session.CreateCriteria(typeof(Registration)).List <Registration>());
                        registration = registrations.FirstOrDefault(x => x.Id == id);
                    }
                    else
                    {
                        // New Registration
                        var renewalType         = new List <RenewalType>(session.CreateCriteria(typeof(RenewalType)).List <RenewalType>());
                        var renewalTypeToInsert = renewalType.FirstOrDefault(x => x.Id >= 1);

                        var costing             = new List <Costing>(session.CreateCriteria(typeof(Costing)).List <Costing>());
                        var costingTypeToInsert = costing.FirstOrDefault(x => x.Category.Id == r.Category.Id && x.State.Id == stateId);

                        renewal = new Renewal
                        {
                            Date         = DateTime.Now,
                            RenewalType  = renewalTypeToInsert,
                            Registration = registration,
                            Amount       = costingTypeToInsert.RenewalCost
                        };

                        registration.Renewals.Add(renewal);
                    }

                    if (registration != null)
                    {
                        //
                        registration.CacNumber = r.CacNumber ?? "";
                        var isRenewal = r.Renewals.FirstOrDefault(x => x.Id == 0) != null ? true : false;
                        if (isRenewal)
                        {
                            registration.LastRenewalDate = DateTime.Now;

                            var renewalType         = new List <RenewalType>(session.CreateCriteria(typeof(RenewalType)).List <RenewalType>());
                            var renewalTypeToInsert = renewalType.FirstOrDefault(x => x.Id >= 2);

                            var costing             = new List <Costing>(session.CreateCriteria(typeof(Costing)).List <Costing>());
                            var costingTypeToInsert = costing.FirstOrDefault(x => x.Category.Id == r.Category.Id && x.State.Id == stateId);

                            renewal = new Renewal
                            {
                                Date         = DateTime.Now,
                                RenewalType  = renewalTypeToInsert,
                                Registration = registration,
                                Amount       = costingTypeToInsert.RenewalCost
                            };
                            registration.Renewals.Add(renewal);
                        }
                        else
                        {
                            registration.LastRenewalDate = r.LastRenewalDate;
                        }

                        registration.RegistrationDate            = r.RegistrationDate;
                        registration.ProprietorFirstName         = r.ProprietorFirstName ?? "";
                        registration.ProprietorLastName          = r.ProprietorLastName ?? "";
                        registration.ProprietorGender            = r.ProprietorGender ?? "";
                        registration.ProprietorNinNumber         = r.ProprietorNinNumber ?? "";
                        registration.ProprietorIsMedicalDirector = r.ProprietorIsMedicalDirector;
                        registration.ProprietorMobile1           = r.ProprietorMobile1 ?? "";
                        registration.ProprietorMobile2           = r.ProprietorMobile2 ?? "";
                        registration.ProprietorEmailAddress      = r.ProprietorEmailAddress ?? "";

                        registration.MedicalDirectorFirstName    = r.MedicalDirectorFirstName ?? "";
                        registration.MedicalDirectorLastName     = r.MedicalDirectorLastName ?? "";
                        registration.MedicalDirectorGender       = r.MedicalDirectorGender;
                        registration.MedicalDirectorNinNumber    = r.MedicalDirectorNinNumber ?? "";
                        registration.MedicalDirectorMobile1      = r.MedicalDirectorMobile1 ?? "";
                        registration.MedicalDirectorMobile2      = r.MedicalDirectorMobile2 ?? "";
                        registration.MedicalDirectorEmailAddress = r.MedicalDirectorEmailAddress ?? "";

                        registration.AdministratorFirstName = r.AdministratorFirstName ?? "";
                        registration.AdministratorLastName  = r.AdministratorLastName ?? "";
                        registration.AdministratorMobile1   = r.AdministratorMobile1 ?? "";
                        registration.AdministratorMobile2   = r.AdministratorMobile2 ?? "";

                        registration.EstablishmentName = r.EstablishmentName ?? "";

                        registration.TypeOfEstablishment = r.TypeOfEstablishment;

                        registration.ProfessionalBody = r.ProfessionalBody;

                        registration.NoOfBeds = r.NoOfBeds;

                        registration.AddressLine1 = r.AddressLine1 ?? "";
                        registration.AddressLine2 = r.AddressLine2 ?? "";
                        registration.LandMark     = r.LandMark ?? "";

                        registration.Latitude  = r.Latitude;
                        registration.Longitude = r.Longitude;

                        // Add
                        foreach (var rs in r.RegistrationTypeOfEstablishmentStaffing)
                        {
                            rs.Registration = registration;
                        }
                        registration.RegistrationTypeOfEstablishmentStaffing = r.RegistrationTypeOfEstablishmentStaffing;


                        foreach (var rs in r.RegistrationServices)
                        {
                            var registrationService = registration.RegistrationServices.FirstOrDefault(x => x.Service.Name == rs.Service.Name);

                            if (registrationService != null)
                            {
                                registrationService.Selected = rs.Selected;
                            }
                            else
                            {
                                var serviceToAdd = session.CreateCriteria(typeof(Service)).List <Service>().FirstOrDefault(x => x.Name == rs.Service.Name);

                                var regService = new RegistrationService
                                {
                                    Registration = registration,
                                    Service      = serviceToAdd,
                                    Selected     = rs.Selected
                                };
                                // if not in db, add it
                                registration.AddRegistrationService(regService);
                            }
                        }

                        registration.ProfessionalBodyAttendance    = r.ProfessionalBodyAttendance ?? "";
                        registration.ProfessionalBodyInvolvement   = r.ProfessionalBodyInvolvement ?? "";
                        registration.ProfessionalBodyRemarks       = r.ProfessionalBodyRemarks ?? "";
                        registration.ProfessionalBodyFirstName     = r.ProfessionalBodyFirstName ?? "";
                        registration.ProfessionalBodyLastName      = r.ProfessionalBodyLastName ?? "";
                        registration.ProfessionalBodyPosition      = r.ProfessionalBodyPosition ?? "";
                        registration.ProfessionalBodySignatureDate = r.ProfessionalBodySignatureDate;

                        registration.AcceptanceDetailsAccepted = r.AcceptanceDetailsAccepted;
                        registration.AcceptanceDetailsReason   = r.AcceptanceDetailsReason ?? "";

                        registration.Category =
                            (from x in session.CreateCriteria(typeof(Category)).List <Category>()
                             where x.Id == r.Category.Id
                             select x).FirstOrDefault();

                        registration.Location =
                            (from x in session.CreateCriteria(typeof(Location)).List <Location>()
                             where x.Id == r.Location.Id
                             select x).FirstOrDefault();

                        registration.Created  = DateTime.Now;
                        registration.Modified = DateTime.Now;
                        registration.Deleted  = false;
                    }

                    session.SaveOrUpdate(registration);
                    if (renewal != null)
                    {
                        session.SaveOrUpdate(renewal);
                    }
                    transaction.Commit();

                    return(Get(registration.Id));
                }
            }
        }
Beispiel #15
0
        public IActionResult IsLogged()
        {
            int?userId = AuthHelper.GetUserId(HttpContext);

            return(Ok(new { isLogged = userId != null }));
        }
Beispiel #16
0
 public string Login()
 {
     AuthHelper.Login("Admin", new string[] { "Admins" }, DateTime.Now.AddDays(1));
     System.Threading.Thread.Sleep(200);
     return("访问成功(已登录)");
 }
Beispiel #17
0
 public IActionResult Logout()
 {
     AuthHelper.LogOut(HttpContext);
     return(Ok());
 }
 public ToggleModule(AuthHelper auth, SyncDbContext db)
 {
     _auth = auth;
     _db   = db;
 }
        public async Task ReplyReport()
        {
            // create two users
            SocialPlusClient client            = new SocialPlusClient(TestConstants.ServerApiBaseUrl);
            PostUserResponse postUserResponse1 = await TestUtilities.PostGenericUser(client);

            string           auth1             = AuthHelper.CreateSocialPlusAuth(postUserResponse1.SessionToken);
            PostUserResponse postUserResponse2 = await TestUtilities.PostGenericUser(client);

            string auth2 = AuthHelper.CreateSocialPlusAuth(postUserResponse2.SessionToken);

            // create a topic from user 1
            var postTopicOperationResponse = await TestUtilities.PostGenericTopic(client, auth1);

            var topicHandle = postTopicOperationResponse.TopicHandle;

            // create a comment from user 2
            var postCommentOperationResponse = await TestUtilities.PostGenericComment(client, auth2, topicHandle);

            var commentHandle = postCommentOperationResponse.CommentHandle;

            // create a reply from user 1
            var postReplyOperationResponse = await TestUtilities.PostGenericReply(client, auth1, commentHandle);

            var replyHandle = postReplyOperationResponse.ReplyHandle;

            // issue a report from user 2
            PostReportRequest postReportRequest1 = new PostReportRequest(Reason.OffensiveContent);
            HttpOperationResponse <object> postReplyReportOperationResponse1 = await client.ReplyReports.PostReportWithHttpMessagesAsync(replyHandle : replyHandle, postReportRequest : postReportRequest1, authorization : auth2);

            // issue another report from user 2
            PostReportRequest postReportRequest2 = new PostReportRequest(Reason.ThreatsCyberbullyingHarassment);
            HttpOperationResponse <object> postReplyReportOperationResponse2 = await client.ReplyReports.PostReportWithHttpMessagesAsync(replyHandle : replyHandle, postReportRequest : postReportRequest2, authorization : auth2);

            // delete reply
            var deleteReplyOperationResponse = await TestUtilities.DeleteReply(client, replyHandle, auth1);

            // delete comment
            var deleteCommentOperationResponse = await TestUtilities.DeleteComment(client, commentHandle, auth2);

            // delete topic
            var deleteTopicOperationResponse = await TestUtilities.DeleteTopic(client, topicHandle, auth1);

            // issue another report from user 2 that should fail
            PostReportRequest postReportRequest3 = new PostReportRequest(Reason.ContentInfringement);
            HttpOperationResponse <object> postReplyReportOperationResponse3 = await client.ReplyReports.PostReportWithHttpMessagesAsync(replyHandle : replyHandle, postReportRequest : postReportRequest3, authorization : auth2);

            // delete users
            var deleteUserOperationResponse1 = await TestUtilities.DeleteUser(client, auth1);

            var deleteUserOperationResponse2 = await TestUtilities.DeleteUser(client, auth2);

            // check failure conditions
            Assert.IsTrue(postReplyReportOperationResponse1.Response.IsSuccessStatusCode);
            Assert.IsTrue(postReplyReportOperationResponse2.Response.IsSuccessStatusCode);
            Assert.IsTrue(deleteReplyOperationResponse.Response.IsSuccessStatusCode);
            Assert.IsTrue(deleteCommentOperationResponse.Response.IsSuccessStatusCode);
            Assert.IsTrue(deleteTopicOperationResponse.Response.IsSuccessStatusCode);
            Assert.IsFalse(postReplyReportOperationResponse3.Response.IsSuccessStatusCode);
            Assert.AreEqual(postReplyReportOperationResponse3.Response.StatusCode, System.Net.HttpStatusCode.NotFound);
            Assert.IsTrue(deleteUserOperationResponse1.Response.IsSuccessStatusCode);
            Assert.IsTrue(deleteUserOperationResponse2.Response.IsSuccessStatusCode);
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(OAuthToken) && !string.IsNullOrEmpty(OauthVerifier))
            {
                string strPostUrl = "https://connectapi.garmin.com/oauth-service/oauth/access_token";

                string strNounce = AuthHelper.GenerateNounce();

                string strParamters  = "oauth_consumer_key=37d14781-5529-4a3a-9c55-aad6b835913c&oauth_nonce=" + strNounce + "&oauth_signature_method=HMAC-SHA1&oauth_timestamp=" + strNounce + "&oauth_token=" + OAuthToken + "&oauth_verifier=" + OauthVerifier + "&oauth_version=1.0";
                string strRequestUrl = "POST&" + AuthHelper.UpperCaseUrlEncode(("https://connectapi.garmin.com/oauth-service/oauth/access_token").ToLower()) + "&" + AuthHelper.UpperCaseUrlEncode(strParamters);

                string HashKey = "fq07vfP6JodQr0EmgnPYUxKPkNNv8pKoib6" + "&" + HttpContext.Current.Session["OAuthToken_Secret"];

                var signature = AuthHelper.GenerateOAuthSignature(HashKey, strRequestUrl);

                string AuthHeader = "oauth_version=\"1.0\", oauth_consumer_key=\"37d14781-5529-4a3a-9c55-aad6b835913c\", oauth_timestamp=\"" + strNounce + "\", oauth_nonce=\"" + strNounce + "\", oauth_signature_method=\"HMAC-SHA1\", oauth_signature=\"" + signature + "\", oauth_verifier=\"" + OauthVerifier + "\", oauth_token=\"" + OAuthToken + "\"";
                try
                {
                    HttpClient hc = new HttpClient();
                    hc.DefaultRequestHeaders.Add("Authorization", "OAuth " + AuthHeader);

                    HttpResponseMessage response = hc.PostAsync(strPostUrl, null).Result;

                    string str = response.Content.ReadAsStringAsync().Result;

                    string strOAuthToken       = str.Split('&')[0];
                    string strOAuthTokenSecret = str.Split('&')[1];
                    strOAuthToken       = strOAuthToken.Split('=')[1];
                    strOAuthTokenSecret = strOAuthTokenSecret.Split('=')[1];

                    HttpContext.Current.Session["OAuthToken_Secret"] = strOAuthTokenSecret;
                    HttpContext.Current.Session["OAuthToken"]        = strOAuthToken;

                    string UserIDUrl = "https://healthapi.garmin.com/wellness-api/rest/user/id";

                    strNounce = AuthHelper.GenerateNounce();
                    string OAuthToken = HttpContext.Current.Session["OAuthToken"].ToString();

                    string startTime = AuthHelper.GenerateNounce(DateTime.Now.AddDays(-90));
                    string EndTime   = strNounce;


                    strParamters  = "oauth_consumer_key=37d14781-5529-4a3a-9c55-aad6b835913c&oauth_nonce=" + strNounce + "&oauth_signature_method=HMAC-SHA1&oauth_timestamp=" + strNounce + "&oauth_token=" + OAuthToken + "&oauth_version=1.0"; //&summaryEndTimeInSeconds=" + EndTime + "&summaryStartTimeInSeconds=" + startTime
                    strRequestUrl = "GET&" + AuthHelper.UpperCaseUrlEncode((UserIDUrl).ToLower()) + "&" + AuthHelper.UpperCaseUrlEncode(strParamters);

                    HashKey = "fq07vfP6JodQr0EmgnPYUxKPkNNv8pKoib6" + "&" + HttpContext.Current.Session["OAuthToken_Secret"];

                    signature = AuthHelper.GenerateOAuthSignature(HashKey, strRequestUrl);

                    // ActivitiesUrl = ActivitiesUrl + "?summaryStartTimeInSeconds={0}&summaryEndTimeInSeconds={1}";

                    //ActivitiesUrl = string.Format(ActivitiesUrl, startTime, EndTime);
                    AuthHeader = "oauth_version=\"1.0\", oauth_consumer_key=\"37d14781-5529-4a3a-9c55-aad6b835913c\", oauth_timestamp=\"" + strNounce + "\", oauth_nonce=\"" + strNounce + "\", oauth_signature_method=\"HMAC-SHA1\", oauth_signature=\"" + signature + "\", oauth_token=\"" + OAuthToken + "\"";
                    try
                    {
                        hc = new HttpClient();
                        hc.DefaultRequestHeaders.Add("Authorization", "OAuth " + AuthHeader);

                        response = hc.GetAsync(UserIDUrl).Result;

                        str = response.Content.ReadAsStringAsync().Result;
                    }
                    catch { }


                    Response.Redirect("Activities.aspx");
                }
                catch { }
            }
        }
        public async Task ManualReportTesting()
        {
            // WARNING: do not run this test unless you are doing a test where you can tolerate 1-3 days of latency
            // and can manually verify the result by inspecting Azure Tables
            Assert.IsTrue(false);

            // create two users with benign profiles
            SocialPlusClient client            = new SocialPlusClient(TestConstants.ServerApiBaseUrl);
            PostUserResponse postUserResponse1 = await TestUtilities.PostGenericUser(client);

            string           auth1             = AuthHelper.CreateSocialPlusAuth(postUserResponse1.SessionToken);
            PostUserResponse postUserResponse2 = await TestUtilities.PostGenericUser(client);

            string auth2 = AuthHelper.CreateSocialPlusAuth(postUserResponse2.SessionToken);

            // issue a Threats / Cyberbullying / Harassment report from user 2 on user 1
            PostReportRequest postReportRequest1 = new PostReportRequest(Reason.ThreatsCyberbullyingHarassment);
            HttpOperationResponse <object> postUserReportOperationResponse1 = await client.UserReports.PostReportWithHttpMessagesAsync(userHandle : postUserResponse1.UserHandle, postReportRequest : postReportRequest1, authorization : auth2);

            // issue a Content Infringment report from user 2
            PostReportRequest postReportRequest2 = new PostReportRequest(Reason.ContentInfringement);
            HttpOperationResponse <object> postUserReportOperationResponse2 = await client.UserReports.PostReportWithHttpMessagesAsync(userHandle : postUserResponse1.UserHandle, postReportRequest : postReportRequest2, authorization : auth2);

            // check failure conditions
            Assert.IsTrue(postUserReportOperationResponse1.Response.IsSuccessStatusCode);
            Assert.IsTrue(postUserReportOperationResponse2.Response.IsSuccessStatusCode);

            // create a threatening topic from user 1
            PostTopicRequest postTopicRequest = new PostTopicRequest(publisherType: PublisherType.User, text: "I am going to beat you up.", title: "You're in big trouble.", blobType: BlobType.Custom, blobHandle: null, categories: null, language: null, deepLink: null, friendlyName: null, group: null);
            HttpOperationResponse <PostTopicResponse> postTopicOperationResponse = await client.Topics.PostTopicWithHttpMessagesAsync(request : postTopicRequest, authorization : auth1);

            string topicHandle = null;

            if (postTopicOperationResponse != null && postTopicOperationResponse.Response.IsSuccessStatusCode)
            {
                topicHandle = postTopicOperationResponse.Body.TopicHandle;
            }

            // issue a Threats / Cyberbullying / Harassment report from user 2
            PostReportRequest postTopicReportRequest1 = new PostReportRequest(Reason.ThreatsCyberbullyingHarassment);
            HttpOperationResponse <object> postTopicReportOperationResponse1 = await client.TopicReports.PostReportWithHttpMessagesAsync(topicHandle : topicHandle, postReportRequest : postTopicReportRequest1, authorization : auth2);

            // check failure conditions
            Assert.IsTrue(postTopicOperationResponse.Response.IsSuccessStatusCode);
            Assert.IsTrue(postTopicReportOperationResponse1.Response.IsSuccessStatusCode);

            // create a benign comment from user 1
            var postCommentOperationResponse = await TestUtilities.PostGenericComment(client, auth1, topicHandle);

            var commentHandle = postCommentOperationResponse.CommentHandle;

            // issue a Child Endangerment / Exploitation report from user 2
            PostReportRequest postCommentReportRequest1 = new PostReportRequest(Reason.ChildEndangermentExploitation);
            HttpOperationResponse <object> postCommentReportOperationResponse1 = await client.CommentReports.PostReportWithHttpMessagesAsync(commentHandle : commentHandle, postReportRequest : postCommentReportRequest1, authorization : auth2);

            // check failure conditions
            Assert.IsTrue(postCommentReportOperationResponse1.Response.IsSuccessStatusCode);

            // create a profanity laden reply from user 1
            PostReplyRequest postReplyRequest = new PostReplyRequest(text: "f**k. shit.");
            HttpOperationResponse <PostReplyResponse> postReplyOperationResponse = await client.CommentReplies.PostReplyWithHttpMessagesAsync(commentHandle : commentHandle, request : postReplyRequest, authorization : auth1);

            string replyHandle = null;

            if (postReplyOperationResponse != null && postReplyOperationResponse.Response.IsSuccessStatusCode)
            {
                replyHandle = postReplyOperationResponse.Body.ReplyHandle;
            }

            // issue an Offensive Content report from user 2
            PostReportRequest postReplyReportRequest1 = new PostReportRequest(Reason.OffensiveContent);
            HttpOperationResponse <object> postReplyReportOperationResponse1 = await client.ReplyReports.PostReportWithHttpMessagesAsync(replyHandle : replyHandle, postReportRequest : postReplyReportRequest1, authorization : auth2);

            // check failure conditions
            Assert.IsTrue(postReplyOperationResponse.Response.IsSuccessStatusCode);
            Assert.IsTrue(postReplyReportOperationResponse1.Response.IsSuccessStatusCode);

            // do NOT clean up the users after the test ends
        }
Beispiel #22
0
 public AuthenticationController(AuthHelper authHelper)
 {
     this.authHelper = authHelper;
 }
Beispiel #23
0
 public void RefreshSession()
 {
     AuthHelper.RefreshSession("/UserProfile");
 }
Beispiel #24
0
 public string AuthenticateDeveloper(bool log = false, string addrole = "", string altrole = "")
 {
     return(AuthHelper.AuthenticateDeveloper(HttpContextFactory.Current, log, addrole, altrole).Message);
 }
Beispiel #25
0
 public void InitCommands()
 {
     GAuthCommand = new Command(async() => { await AuthHelper.GoogleAuth(); });
 }
Beispiel #26
0
        public IActionResult OnGet()
        {
            bool login = AuthHelper.Check(HttpContext);

            if (!login)
            {
                return(RedirectToPage("Login"));
            }

            string filePath = Path.Combine(AppContext.BaseDirectory, "logs", $"{Name}.txt");
            string text;

            using (var logFile = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Read, FileShare.ReadWrite))
            {
                var    bytes  = new List <byte>();
                byte[] buffer = new byte[1024 * 1024 * 3];
                while (true)
                {
                    int length = logFile.Read(buffer, 0, buffer.Length);
                    if (length == 0)
                    {
                        break;
                    }
                    bytes.AddRange(buffer.Take(length));
                }
                text = System.Text.Encoding.UTF8.GetString(bytes.ToArray());
            }

            //string text = System.IO.File.ReadAllText(filePath);
            string[] list = text.Trim().Split(new[] { "-----End-----" }, StringSplitOptions.RemoveEmptyEntries);
            var      logs = new ConcurrentBag <LogModel>();

            Parallel.ForEach(list, item =>
            {
                var log        = new LogModel();
                string[] lines = item.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
                if (lines.Length > 0)
                {
                    log.Time = Convert.ToDateTime(lines[0].Replace("-", ""));
                }
                if (lines.Length > 1)
                {
                    string[] categoryAndLogLevel = lines[1].Split(':');
                    if (categoryAndLogLevel.Length > 0)
                    {
                        log.Loglevel = categoryAndLogLevel[0].Trim();
                    }
                    if (categoryAndLogLevel.Length > 1)
                    {
                        log.Category = string.Join(string.Empty, categoryAndLogLevel.Skip(1));
                    }
                }
                if (lines.Length > 2)
                {
                    log.Content = string.Join(Environment.NewLine, lines.Skip(2));
                }
                logs.Add(log);
            });
            Logs = logs.OrderByDescending(o => o.Time).ToList();
            return(Page());
        }
 public ActionResult SignOut()
 {
     AuthHelper.SignOut(); // DXCOMMENT: Your Signing out logic
     return(RedirectToAction("Index", "Home"));
 }
Beispiel #28
0
 public LoginController(IAuthorizationService authService, AuthHelper helper)
 {
     this.helper = helper;
     this.authService = authService;
 }
 public ActionResult UserMenuItemPartial()
 {
     return(PartialView("UserMenuItemPartial", AuthHelper.GetLoggedInUserInfo()));
 }
Beispiel #30
0
 public string Login(string name, string password)
 {
     AuthHelper.Login("1", "Admin", "Admins", DateTime.Now.AddDays(1));
     System.Threading.Thread.Sleep(200);
     return("Login success");
 }
Beispiel #31
0
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            base.OnActionExecuting(context);

            CurrentUser = AuthHelper.CreateRequestUser(HttpContext.User.Identity as ClaimsIdentity);
        }