Beispiel #1
0
        internal virtual async Task GrantClaims(ClaimsIdentity identity)
        {
            var sessionToken = Context.OwinContext.Get <SessionToken>("sessionToken");

            if (sessionToken.AccountProductId.HasValue)
            {
                var products = await AuthProduct.AccountProductsGetAsync(sessionToken.AccountId, sessionToken.SystemId);

                var product = products.FirstOrDefault(e => e.AccountProductId == sessionToken.AccountProductId.Value);

                if (object.Equals(product, null) || product.IsDisabled)
                {
                    Context.Response.Headers.Add("Product-IsDisabled", new[] { bool.TrueString });
                }

                if (object.Equals(product, null) || product.IsExpired)
                {
                    Context.Response.Headers.Add("Product-IsExpired", new[] { bool.TrueString });
                }

                if (!object.Equals(product, null) && !product.IsDisabled)
                {
                    UserManagerHelper.GetAllowedModules(products, sessionToken.AccountProductId.Value, identity);
                }
            }
        }
        public async Task <IHttpActionResult> PostToken()
        {
            return(await CurrentAccountExecuteAsync(async delegate(Account user)
            {
                AuthenticationTicket ticket;
                var sessionId = UserManagerHelper.Session(Request, out ticket);
                var sessions = await _auth.SessionTokensGetAsync(user.Id);

                var sessionToken = sessions.FirstOrDefault(e => e.Id == sessionId);
                if (object.Equals(sessionToken, null))
                {
                    return AccountUnauthorized();
                }

                var products = await _authProduct.AccountProductsGetAsync(sessionToken.AccountId, sessionToken.SystemId);

                var scopeWorker = SaaSScopeWorkerFactory.Create(sessionToken.Scope);
                scopeWorker.FilterProducts(products, sessionToken);

                var offeringProducts = products.Where(e => !e.IsDisabled && !e.IsMinor && !e.IsPPC);

                var product = offeringProducts.FirstOrDefault(e => !e.IsFree) ??
                              offeringProducts.FirstOrDefault();

                return await PostToken(products, product, sessions, sessionToken, user, ticket);
            }));
        }
        public async Task <IHttpActionResult> PostToken(Guid accountProductId, bool setAsDefault = false)
        {
            return(await CurrentAccountExecuteAsync(async delegate(Account user)
            {
                if (!user.IsActivated && !user.IsAnonymous)
                {
                    return AccountNotActivated();
                }

                AuthenticationTicket ticket;
                var sessionId = UserManagerHelper.Session(Request, out ticket);
                var sessions = await _auth.SessionTokensGetAsync(user.Id);

                var sessionToken = sessions.FirstOrDefault(e => e.Id == sessionId);
                if (object.Equals(sessionToken, null))
                {
                    return AccountUnauthorized();
                }

                var products = await _authProduct.AccountProductsGetAsync(sessionToken.AccountId, sessionToken.SystemId);

                var scopeWorker = SaaSScopeWorkerFactory.Create(sessionToken.Scope);
                scopeWorker.FilterProducts(products, sessionToken);

                var product = products.FirstOrDefault(e => e.AccountProductId == accountProductId && !e.IsDisabled);

                return await PostToken(products, product, sessions, sessionToken, user, ticket);
            }));
        }
        public async Task <IEnumerable <UserModel> > GetUserByUserType(UserType userType)
        {
            var users = _context.Users.Where(w => w.UserType == userType.ToString()).ToList();
            List <UserModel> userListModel = null;

            foreach (var user in users)
            {
                UserModel userModel = new UserModel()
                {
                    Id                  = user.Id,
                    Address1            = user.Address1,
                    Age                 = user.Age,
                    Birthday            = user.Birthday,
                    CivilStatus         = user.CivilStatus,
                    ContactNumber       = user.ContactNumber,
                    Country             = user.Country,
                    Department          = user.Department,
                    FirstName           = user.FirstName,
                    Gender              = user.Gender,
                    HireDate            = user.HireDate,
                    HobbiesAndInterest  = user.HobbiesAndInterest,
                    LanguagesSpoken     = user.LanguagesSpoken,
                    LastName            = user.LastName,
                    Password            = user.Password,
                    PasswordAttemptFail = user.PasswordAttemptFail,
                    State               = user.State,
                    UserName            = user.UserName,
                    UserType            = UserManagerHelper.GetUserType(user.UserType)
                };
                userListModel.Add(userModel);
            }
            return(userListModel);
        }
        internal async Task <IHttpActionResult> PostToken(List <ViewAccountProduct> products, ViewAccountProduct product,
                                                          List <SessionToken> sessions, SessionToken session,
                                                          Account user, AuthenticationTicket ticket)
        {
            if (object.Equals(product, null))
            {
                return(ProductNotFound());
            }

            var scopeWorker = SaaSScopeWorkerFactory.Create(session.Scope, _auth, _authProduct);

            if (!scopeWorker.ValidateSessionTokenAsync(user, sessions, session, product))
            {
                return(ErrorContent("invalid_grant", "You are logged into too many devices.", HttpStatusCode.Conflict));
            }

            if (!await scopeWorker.ValidateAccountSystemAsync(user, session, product))
            {
                return(ErrorContent("invalid_grant", "Your license is currently associated with another device.", HttpStatusCode.Conflict));
            }

            var modules        = UserManagerHelper.GetAllowedModules(products, product.AccountProductId, ticket.Identity);
            var activeProducts = UserManagerHelper.GetActiveProducts(products, modules, product.AccountProductId);

            var moduleFeatures = AccountController.GetModuleFeatures(product, modules);

            var client = GetClient(session.ClientId);
            var oldId  = OauthManager.UpdateTicket(user, session, ticket, product, client);
            await _auth.SessionTokenInsertAsync(session, oldId, false, product.IsPPC);

            return(Ok(OauthManager.ReleaseToken(session, ticket, modules, moduleFeatures, activeProducts, user)));
        }
Beispiel #6
0
        public async Task <IHttpActionResult> Products(Guid accountProductId)
        {
            try
            {
                AuthenticationTicket ticket;
                var session      = UserManagerHelper.Session(Request, out ticket);
                var sessionToken = await _auth.SessionTokenGetAsync(session);

                if (object.Equals(sessionToken, null))
                {
                    return(Unauthorized());
                }

                int usedPerSystem = 0;

                if (sessionToken.SystemId.HasValue)
                {
                    var accountSystems = await _auth.AccountSystemsGetAsync(new AccountProductPair(sessionToken.AccountId, accountProductId));

                    usedPerSystem = accountSystems.Count(e => e.SystemId == sessionToken.SystemId.Value);
                }
                return(Ok(new { usedPerSystem = usedPerSystem }));
            }
            catch (Exception exc) { return(Request.HttpExceptionResult(exc)); }
        }
Beispiel #7
0
        public HttpResponseMessage GetAllUserList(String CompanyCode)
        {
            QueryResultBase queryResult = new QueryResultBase();

            queryResult.QueryData  = UserManagerHelper.GetAllUserList(CompanyCode);
            queryResult.ResultCode = QueryResultCodeEnum.QUERY_SUCCESS;


            return(HttpResponseExtension.toJson(JsonConvert.SerializeObject(queryResult)));
        }
Beispiel #8
0
        static void Main(string[] args)
        {
            MySqlConnectPoolHelper.getPool().InitMySqlConnectPool();
            UserManagerHelper.InitUserManager();
            CompanyManagerHelper.Initialize();
            CompanyManagerHelper.StartAlarmStoreService();
            CompanyManagerHelper.StartDataStoreService();
            FileServerHelper.Initialize();

            //CompanyManagerHelper.StartDeviceStatusThread();

            //跨域配置
            // config.EnableCors(new EnableCorsAttribute("*", "*", "*"));


            //var _client = RedisManager.GetClient();
            //routeTemplate: "api/{controller}/{id}",



            LoggerManager.Log.Info("服务启动开始...\n");
            try
            {
                Assembly.Load("IotCloudService.IotWebServerWebApi, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null");
                HttpSelfHostConfiguration configuration = new HttpSelfHostConfiguration("http://127.0.0.1:8081");
                using (HttpSelfHostServer httpServer = new HttpSelfHostServer(configuration))
                {
                    httpServer.Configuration.EnableCors();

                    httpServer.Configuration.MapHttpAttributeRoutes();
                    httpServer.Configuration.Filters.Add(new ApiSecurityFilter());

                    httpServer.Configuration.Routes.MapHttpRoute(
                        name: "DefaultApi",
                        routeTemplate: "api/{controller}/{action}/{id}",
                        defaults: new { id = RouteParameter.Optional });

                    httpServer.OpenAsync().Wait();
                    Console.WriteLine("Press Enter to quit.");
                    Console.ReadLine();
                }
            }
            catch (Exception ex)
            {
                LoggerManager.Log.Info(ex.Message);

                LoggerManager.Log.Info("出现异常,服务退出!\n");
                Console.ReadLine();
            }
        }
        public async Task <IHttpActionResult> Logout()
        {
            if (User.Identity.IsAuthenticated)
            {
                AuthenticationTicket ticket;
                try
                {
                    var session = UserManagerHelper.Session(Request, out ticket);
                    await _auth.SessionTokenDeleteAsync(session);
                }
                catch (Exception exc) { _oautLogLogger.Error(exc); }
            }

            return(Ok());
        }
Beispiel #10
0
 public UnitOfWork(ApplicationDbContext context)
 {
     _context      = context;
     Films         = new FilmRepository(_context);
     Genres        = new GenreRepository(_context);
     Users         = new UserRepository(_context);
     Ratings       = new RatingRepository(_context);
     Notifications = new NotificationRepository(_context);
     Awards        = new AwardRepository(_context);
     Persons       = new PersonRepository(_context);
     News          = new NewsRepository(_context);
     ManagerHelper = new UserManagerHelper(_context);
     Reviews       = new ReviewRepository(_context);
     Countries     = new CountryRepository(_context);
 }
Beispiel #11
0
        public HttpResponseMessage GetToken([FromBody] LoginUserInfo loginUser)
        {
            ResultMsg resultMsg = null;
            int       id        = 0;

            //判断参数是否合法
            if (string.IsNullOrEmpty(loginUser.Timestamp) || (int.TryParse(loginUser.Timestamp, out id)))
            {
                resultMsg            = new ResultMsg();
                resultMsg.StatusCode = (int)StatusCodeEnum.ParameterError;
                resultMsg.Info       = StatusCodeEnum.ParameterError.GetEnumText();
                resultMsg.Data       = "";
                return(HttpResponseExtension.toJson(JsonConvert.SerializeObject(resultMsg)));
            }

            UserInfo currUserInfo = UserManagerHelper.CheckUser(loginUser);

            if (currUserInfo == null)
            {
                resultMsg            = new ResultMsg();
                resultMsg.StatusCode = (int)StatusCodeEnum.UnknownUserOrPassword;
                resultMsg.Info       = StatusCodeEnum.UnknownUserOrPassword.GetEnumText();
                resultMsg.Data       = "";
                return(HttpResponseExtension.toJson(JsonConvert.SerializeObject(resultMsg)));
            }

            //插入缓存
            Token token = (Token)HttpRuntime.Cache.Get(id.ToString());

            if (HttpRuntime.Cache.Get(id.ToString()) == null)
            {
                token            = new Token();
                token.StaffId    = id;
                token.SignToken  = Guid.NewGuid();
                token.ExpireTime = DateTime.Now.AddDays(1);
                HttpRuntime.Cache.Insert(token.StaffId.ToString(), token, null, token.ExpireTime, TimeSpan.Zero);
            }

            //返回token信息
            resultMsg            = new ResultMsg();
            resultMsg.StatusCode = (int)StatusCodeEnum.Success;
            resultMsg.Info       = getJsonByObject(currUserInfo);
            resultMsg.Data       = token;

            return(HttpResponseExtension.toJson(JsonConvert.SerializeObject(resultMsg)));
        }
Beispiel #12
0
        public HttpResponseMessage UpdateUser(UserInfo UpdateUser)
        {
            QueryResultBase queryResult = new QueryResultBase();

            bool Res = UserManagerHelper.ModifyUser(UpdateUser);

            if (Res == true)
            {
                queryResult.ResultCode = QueryResultCodeEnum.QUERY_SUCCESS;
            }
            else
            {
                queryResult.ResultCode = QueryResultCodeEnum.QUERY_ERROR_DB_SQL;
            }


            return(HttpResponseExtension.toJson(JsonConvert.SerializeObject(queryResult)));
        }
        public async Task <IHttpActionResult> Data(bool isIncludeModules = false)
        {
            try
            {
                var sessionProducts = await GetSessionTokenProducts();

                if (object.Equals(sessionProducts.SessionToken, null))
                {
                    return(AccountUnauthorized());
                }

                sessionProducts.Products.Sort(ProductComparer.Comparer);
                sessionProducts.Products.Reverse();

                ProductComparer.ProductOrderer(sessionProducts.Products);

                var accountDetailsProducts = new AccountDetailsProducts
                {
                    Details  = await GetAccountDetails(),
                    Products = sessionProducts.Products.ConvertAll(ProductConvertor.AccountProductConvertor)
                };

                if (isIncludeModules && sessionProducts.SessionToken.AccountProductId.HasValue)
                {
                    var product = sessionProducts.Products.FirstOrDefault(e => e.AccountProductId == sessionProducts.SessionToken.AccountProductId.Value && !e.IsDisabled);

                    if (!object.Equals(product, null))
                    {
                        var modules  = UserManagerHelper.GetAllowedModules(sessionProducts.Products, product.AccountProductId);
                        var active   = UserManagerHelper.GetActiveProducts(sessionProducts.Products, modules, product.AccountProductId);
                        var features = GetModuleFeatures(product, modules);

                        accountDetailsProducts.Id             = product.AccountProductId;
                        accountDetailsProducts.Modules        = modules;
                        accountDetailsProducts.ModuleFeatures = features;
                        accountDetailsProducts.ActiveProducts = active;
                    }
                }

                return(Ok(accountDetailsProducts));
            }
            catch (Exception exc) { return(Request.HttpExceptionResult(exc)); }
        }
Beispiel #14
0
        private async Task <SessionTokenProducts> GetSessionTokenProducts()
        {
            AuthenticationTicket ticket;
            var session      = UserManagerHelper.Session(Request, out ticket);
            var sessionToken = await _auth.SessionTokenGetAsync(session);

            if (object.Equals(sessionToken, null))
            {
                return(new SessionTokenProducts());
            }

            var products = await _authProduct.AccountProductsGetAsync(sessionToken.AccountId, sessionToken.SystemId);

            var scopeWorker = SaaSScopeWorkerFactory.Create(sessionToken.Scope);

            scopeWorker.FilterProducts(products, sessionToken);

            return(new SessionTokenProducts(sessionToken, products));
        }
 public async Task <UserModel> GetUser(string userName)
 {
     if (string.IsNullOrEmpty(userName))
     {
         return(null); //to do: Create custom exceptions
     }
     try
     {
         UserModel userModel = null;
         var       user      = _context.Users.Where(w => w.UserName == userName).FirstOrDefault();
         if (user != null)
         {
             userModel = new UserModel()
             {
                 Id                  = user.Id,
                 Address1            = user.Address1,
                 Age                 = user.Age,
                 Birthday            = user.Birthday,
                 CivilStatus         = user.CivilStatus,
                 ContactNumber       = user.ContactNumber,
                 Country             = user.Country,
                 Department          = user.Department,
                 FirstName           = user.FirstName,
                 Gender              = user.Gender,
                 HireDate            = user.HireDate,
                 HobbiesAndInterest  = user.HobbiesAndInterest,
                 LanguagesSpoken     = user.LanguagesSpoken,
                 LastName            = user.LastName,
                 Password            = user.Password,
                 PasswordAttemptFail = user.PasswordAttemptFail,
                 State               = user.State,
                 UserName            = user.UserName,
                 UserType            = UserManagerHelper.GetUserType(user.UserType)
             };
         }
         return(userModel);
     }
     catch (Exception)
     {
         throw;
     }
 }
Beispiel #16
0
        static void Main(string[] args)
        {
            //跨域配置
            // config.EnableCors(new EnableCorsAttribute("*", "*", "*"));



            UserManagerHelper.InitUserManager();
            CompanyManagerHelper.Initialize();
            CompanyManagerHelper.StartDeviceStatusThread();



            LoggerManager.Log.Info("服务启动开始...\n");
            try
            {
                Assembly.Load("IotCloudService.WebApi, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null");
                HttpSelfHostConfiguration configuration = new HttpSelfHostConfiguration("http://47.100.169.224:8080");
                using (HttpSelfHostServer httpServer = new HttpSelfHostServer(configuration))
                {
                    httpServer.Configuration.EnableCors();

                    httpServer.Configuration.Routes.MapHttpRoute(
                        name: "DefaultApi",
                        routeTemplate: "api/{controller}/{action}/{id}",
                        defaults: new { id = RouteParameter.Optional });

                    httpServer.OpenAsync().Wait();
                    Console.WriteLine("Press Enter to quit.");
                    Console.ReadLine();
                }
            }
            catch (Exception ex)
            {
                LoggerManager.Log.Info(ex.Message);

                LoggerManager.Log.Info("出现异常,服务退出!\n");
                Console.ReadLine();
            }
        }
Beispiel #17
0
        public async Task <IHttpActionResult> Modules()
        {
            try
            {
                var sessionProducts = await GetSessionTokenProducts();

                if (object.Equals(sessionProducts.SessionToken, null))
                {
                    return(AccountUnauthorized());
                }

                if (!sessionProducts.SessionToken.AccountProductId.HasValue)
                {
                    return(ProductNotFound());
                }

                var product = sessionProducts.Products.FirstOrDefault(e => e.AccountProductId == sessionProducts.SessionToken.AccountProductId.Value && !e.IsDisabled);

                if (object.Equals(product, null))
                {
                    return(ProductNotFound());
                }

                var modules = UserManagerHelper.GetAllowedModules(sessionProducts.Products, product.AccountProductId);
                var active  = UserManagerHelper.GetActiveProducts(sessionProducts.Products, modules, product.AccountProductId);

                var features = GetModuleFeatures(product, modules);

                return(Ok(new
                {
                    id = product.AccountProductId,
                    email = User.Identity.Name,
                    modules = modules,
                    moduleFeatures = features,
                    activeProducts = active,
                }));
            }
            catch (Exception exc) { return(Request.HttpExceptionResult(exc)); }
        }
Beispiel #18
0
        public async void Returns_CreatedAtActionResult201()
        {
            StatusCode <DirectoryOut> status = new StatusCode <DirectoryOut>(StatusCodes.Status201Created, new DirectoryOut
            {
                ID = Guid.NewGuid()
            });
            Mock <IFileService> fileService = new Mock <IFileService>();

            fileService.Setup(_ => _.CreateDirectoryByUser(It.IsAny <DirectoryPost>(), It.IsAny <string>()))
            .Returns(Task.FromResult(status));

            string username = "******";

            FilesController filesController = new FilesController(fileService.Object, UserManagerHelper.GetUserManager(username));

            filesController.Authenticate(username);

            IActionResult result = await filesController.CreateDirectory(new DirectoryPost());

            Assert.IsType <CreatedAtActionResult>(result);
        }
Beispiel #19
0
        public async void Returns_NotFoundObjectResult_when_ParentDirectoryNotExistsOrNotBelongsToUser()
        {
            StatusCode <List <FileUploadResult> > status = new StatusCode <List <FileUploadResult> >(StatusCodes.Status404NotFound);
            Mock <IFileService> fileService = new Mock <IFileService>();

            fileService.Setup(_ => _.PostByUser(It.IsAny <FilePost>(), It.IsAny <string>()))
            .Returns(Task.FromResult(status));

            string username = "******";

            FilesController filesController = new FilesController(fileService.Object, UserManagerHelper.GetUserManager(username));

            filesController.Authenticate(username);

            FilePost filePost = new FilePost
            {
                ParentDirectoryID = Guid.NewGuid(),
                Files             = new FormFileCollection
                {
                    new FormFile(null, 0, 0, "", "")
                }
            };
            IActionResult result = await filesController.Post(filePost);

            Assert.IsType <NotFoundObjectResult>(result);
        }
Beispiel #20
0
        public async void Returns_BadRequestObjectResult_when_FilePostFilesEmpty()
        {
            StatusCode <List <FileUploadResult> > fileUploadResults = new StatusCode <List <FileUploadResult> >(StatusCodes.Status200OK);
            Mock <IFileService> fileService = new Mock <IFileService>();

            fileService.Setup(_ => _.PostByUser(It.IsAny <FilePost>(), It.IsAny <string>()))
            .Returns(Task.FromResult(fileUploadResults));

            string username = "******";

            FilesController filesController = new FilesController(fileService.Object, UserManagerHelper.GetUserManager(username));

            filesController.Authenticate(username);

            FilePost filePost = new FilePost
            {
                ParentDirectoryID = Guid.NewGuid(),
                Files             = new FormFileCollection()
            };

            IActionResult result = await filesController.Post(filePost);

            Assert.IsType <BadRequestObjectResult>(result);
        }
Beispiel #21
0
        public async void Returns_FileOut_when_FileExistAndBelongsToUser()
        {
            FileOut file = new FileOut
            {
                ID   = Guid.NewGuid(),
                Name = Guid.NewGuid().ToString()
            };

            Mock <IFileService> fileService = new Mock <IFileService>();

            fileService.Setup(_ => _.GetByIdAndUser(It.IsAny <Guid>(), It.IsAny <string>()))
            .Returns(Task.FromResult(new StatusCode <FileOut>(StatusCodes.Status200OK, file)));

            string username = "******";

            FilesController filesController = new FilesController(fileService.Object, UserManagerHelper.GetUserManager(username));

            filesController.Authenticate(username);

            IActionResult result = await filesController.Get(Guid.NewGuid());

            OkObjectResult okObjectResult = result as OkObjectResult;

            Assert.NotNull(okObjectResult);
            Assert.IsType <FileOut>(okObjectResult.Value);
        }
Beispiel #22
0
        public async void Returns_ListFileUploadResult()
        {
            List <FileUploadResult> fileUploadResults = new List <FileUploadResult>();
            Mock <IFileService>     fileService       = new Mock <IFileService>();

            fileService.Setup(_ => _.PostByUser(It.IsAny <FilePost>(), It.IsAny <string>()))
            .Returns(Task.FromResult(new StatusCode <List <FileUploadResult> >(StatusCodes.Status200OK, fileUploadResults)));

            string username = "******";

            FilesController filesController = new FilesController(fileService.Object, UserManagerHelper.GetUserManager(username));

            filesController.Authenticate(username);

            FilePost filePost = new FilePost
            {
                ParentDirectoryID = null,
                Files             = new FormFileCollection
                {
                    new FormFile(new MemoryStream(Encoding.UTF8.GetBytes("Some content")), 0, 12, "file", "file.txt")
                }
            };

            IActionResult result = await filesController.Post(filePost);

            OkObjectResult okObjectResult = result as OkObjectResult;

            Assert.NotNull(okObjectResult);

            Assert.IsType <List <FileUploadResult> >(okObjectResult.Value);
        }
Beispiel #23
0
        public async void Returns_PatchedFileOut_when_Success()
        {
            FileOut file = new FileOut
            {
                ID = Guid.NewGuid()
            };

            Mock <IFileService> fileService = new Mock <IFileService>();

            fileService.Setup(_ => _.PatchByIdAndFilePatchAndUser(It.IsAny <Guid>(), It.IsAny <JsonPatchDocument <FilePatch> >(), It.IsAny <string>()))
            .Returns(Task.FromResult(new StatusCode <FileOut>(StatusCodes.Status200OK, file)));

            string username = "******";

            FilesController filesController = new FilesController(fileService.Object, UserManagerHelper.GetUserManager(username));

            filesController.Authenticate(username);

            IActionResult result = await filesController.Patch(Guid.NewGuid(), new JsonPatchDocument <FilePatch>());

            OkObjectResult okObjectResult = result as OkObjectResult;

            Assert.NotNull(okObjectResult);
            Assert.IsType <FileOut>(okObjectResult.Value);
        }
Beispiel #24
0
        public async void Returns_DownloadingFile_when_FileExistAndBelongsToUser()
        {
            byte[] content  = Encoding.UTF8.GetBytes("File content ...");
            string fileName = "file.txt";

            Mock <IFileService> fileService = new Mock <IFileService>();

            fileService.Setup(_ => _.DownloadByIdAndUser(It.IsAny <Guid>(), It.IsAny <string>()))
            .Returns(Task.FromResult(new StatusCode <DownloadFileInfo>(StatusCodes.Status200OK, new DownloadFileInfo(fileName, content))));

            string username = "******";

            FilesController filesController = new FilesController(fileService.Object, UserManagerHelper.GetUserManager(username));

            filesController.Authenticate(username);

            IActionResult result = await filesController.Download(Guid.NewGuid());

            FileContentResult fileContentResult = result as FileContentResult;

            Assert.NotNull(fileContentResult);

            Assert.NotNull(fileContentResult.FileDownloadName);
            Assert.NotNull(fileContentResult.FileContents);
            Assert.NotNull(fileContentResult.ContentType);
        }
Beispiel #25
0
        public async void Returns_OkObjectResult200_when_DirectoryExistAndBelongsToUser()
        {
            StatusCode <DirectoryOut> status      = new StatusCode <DirectoryOut>(StatusCodes.Status200OK);
            Mock <IFileService>       fileService = new Mock <IFileService>();

            fileService.Setup(_ => _.GetDirectoryByIdAndUser(It.IsAny <Guid>(), It.IsAny <string>()))
            .Returns(Task.FromResult(status));

            string username = "******";

            FilesController filesController = new FilesController(fileService.Object, UserManagerHelper.GetUserManager(username));

            filesController.Authenticate(username);

            IActionResult result = await filesController.GetFromDirectory(Guid.NewGuid());

            Assert.IsType <OkObjectResult>(result);
        }
Beispiel #26
0
        public async void Returns_NotFoundObjectResult_when_ParentDirectoryNotExistsOrNotBelongsToUser()
        {
            StatusCode <DirectoryOut> status      = new StatusCode <DirectoryOut>(StatusCodes.Status404NotFound);
            Mock <IFileService>       fileService = new Mock <IFileService>();

            fileService.Setup(_ => _.CreateDirectoryByUser(It.IsAny <DirectoryPost>(), It.IsAny <string>()))
            .Returns(Task.FromResult(status));

            string username = "******";

            FilesController filesController = new FilesController(fileService.Object, UserManagerHelper.GetUserManager(username));

            filesController.Authenticate(username);

            IActionResult result = await filesController.CreateDirectory(new DirectoryPost());

            Assert.IsType <NotFoundObjectResult>(result);
        }
Beispiel #27
0
        public async void Returns_NotFoundObjectResult404_when_FileNotExistOrNotBelongsToUser()
        {
            StatusCode <FileOut> status      = new StatusCode <FileOut>(StatusCodes.Status404NotFound);
            Mock <IFileService>  fileService = new Mock <IFileService>();

            fileService.Setup(_ => _.GetByIdAndUser(It.IsAny <Guid>(), It.IsAny <string>()))
            .Returns(Task.FromResult(status));

            string username = "******";

            FilesController filesController = new FilesController(fileService.Object, UserManagerHelper.GetUserManager(username));

            filesController.Authenticate(username);

            IActionResult result = await filesController.Get(Guid.NewGuid());

            Assert.IsType <NotFoundObjectResult>(result);
        }
Beispiel #28
0
        public async void Returns_ParentDirectoryOfDeletingFile_when_FileExistAndBelongsToUser()
        {
            Guid parentId = Guid.NewGuid();
            StatusCode <DirectoryOut> status = new StatusCode <DirectoryOut>(StatusCodes.Status200OK, new DirectoryOut
            {
                ID = parentId
            });

            Mock <IFileService> fileService = new Mock <IFileService>();

            fileService.Setup(_ => _.DeleteByIdAndUser(It.IsAny <Guid>(), It.IsAny <string>()))
            .Returns(Task.FromResult(status));

            string username = "******";

            FilesController filesController = new FilesController(fileService.Object, UserManagerHelper.GetUserManager(username));

            filesController.Authenticate(username);

            IActionResult result = await filesController.Delete(Guid.NewGuid());

            OkObjectResult okObjectResult = result as OkObjectResult;

            Assert.NotNull(okObjectResult);

            DirectoryOut parentDirectoryOut = okObjectResult.Value as DirectoryOut;

            Assert.NotNull(parentDirectoryOut);
            Assert.Equal(parentId, parentDirectoryOut.ID);
        }
        protected WikiDownApiControllerBase(IDocumentStore documentStore = null)
        {
            this.DocumentStore = documentStore ?? MvcApplication.DocumentStore;

            this.userManagerLazy = UserManagerHelper.GetLazy(this.DocumentStore);
        }
        public async void Returns_OkObjectResult200_when_ThreadExistsAndContainsMessages()
        {
            StatusCode <ThreadOut> status         = new StatusCode <ThreadOut>(StatusCodes.Status200OK);
            Mock <IMessageService> messageService = new Mock <IMessageService>();

            messageService.Setup(_ => _.GetMessagesByThreadAndFilterAndUser(It.IsAny <Guid>(), It.IsAny <MessageFilter>(), It.IsAny <string>()))
            .Returns(Task.FromResult(status));

            MessagesController messagesController = new MessagesController(messageService.Object, UserManagerHelper.GetUserManager(ADMIN_USERNAME));

            messagesController.Authenticate(ADMIN_USERNAME);

            MessageFilter messageFilter = new MessageFilter
            {
                NumberOfLastMessage = 5
            };

            IActionResult result = await messagesController.GetMessagesFromThread(Guid.NewGuid(), messageFilter);

            Assert.NotNull(result);
            Assert.IsType <OkObjectResult>(result);
        }