/// <summary>
        /// Update Identity Entity
        /// </summary>
        /// <param name="webModel"></param>
        /// <param name="model"></param>
        /// <returns></returns>
        private static IdentityUser UpdateModel(StudentEditViewModel webModel, IdentityUser model)
        {
            model.Account      = webModel.Account;
            model.Password     = MD5Utility.Sign(webModel.Password, model.Salt);
            model.Email        = webModel.Email;
            model.Phone        = webModel.Phone;
            model.Name         = webModel.Name;
            model.Gender       = webModel.Gender;
            model.IdNumber     = webModel.IdNumber;
            model.Wechat       = webModel.Wechat;
            model.QQ           = Convert.ToInt64(webModel.QQ);
            model.IsEnabled    = (int)webModel.IsEnabled == 1;
            model.Address      = webModel.Address;
            model.Age          = webModel.Age;
            model.Birthday     = Convert.ToDateTime(webModel.Birthday);
            model.City         = webModel.City;
            model.CityId       = webModel.CityId;
            model.District     = webModel.District;
            model.DistrictId   = webModel.DistrictId;
            model.EndDate      = Convert.ToDateTime(webModel.EndDate);
            model.HighSchool   = webModel.HighSchool;
            model.Province     = webModel.Province;
            model.ProvinceId   = webModel.ProvinceId;
            model.Hobbies      = webModel.Hobbies;
            model.StartDate    = Convert.ToDateTime(webModel.StartDate);
            model.TicketId     = Convert.ToInt64(webModel.TicketId);
            model.Winning      = webModel.Winning;
            model.ModifiedOn   = DateTime.Now;
            model.ModifiedId   = CurrentUser.UserId;
            model.ModifiedBy   = CurrentUser.UserOID;
            model.ModifiedName = CurrentUser.UserName;

            return(model);
        }
Beispiel #2
0
        public static void Initialize(ApplicationDbContext context)
        {
            context.Database.EnsureCreated();

            if (context.IdentityUser.Any())
            {
                return;
            }

            var salt = Guid.NewGuid().ToString();

            IdentityUser admin = new IdentityUser
            {
                Name         = "管理员姓名",
                Account      = "Admin",
                AccountType  = 0,
                Age          = 0,
                Birthday     = new DateTime(),
                Salt         = salt,
                Password     = MD5Utility.Sign("Admin", salt),
                Gender       = true,
                IsEnabled    = true,
                Email        = "*****@*****.**",
                HomePage     = "Administrator",
                IdNumber     = "0",
                DepartmentId = 0,
                Department   = "管理员部门"
            };

            context.IdentityUser.Add(admin);
            context.SaveChanges();
        }
        public static SQLite3Operate OpenToReadWrite(string InDbName, bool InIsNeedCheck, string InMd5 = null, Func <string, SQLite3Operate> InCheckFailAction = null)
        {
            string persistentDbPath = Path.Combine(Application.persistentDataPath, InDbName);

            if (File.Exists(persistentDbPath))
            {
                if (InIsNeedCheck && !string.IsNullOrEmpty(InMd5) && null != InCheckFailAction)
                {
                    if (!MD5Utility.GetFileMD5(persistentDbPath).Equals(InMd5))
                    {
                        return(InCheckFailAction.Invoke(InDbName));
                    }
                }

                return(new SQLite3Operate(persistentDbPath, SQLite3OpenFlags.ReadWrite));//
            }
            else if (null != InCheckFailAction)
            {
                return(InCheckFailAction.Invoke(InDbName));
            }
            else
            {
                return(null);
            }
        }
        /// <summary>
        /// Insert Identity Entity
        /// </summary>
        /// <param name="webModel"></param>
        /// <returns></returns>
        private static IdentityUser InsertModel(StaffEditViewModel webModel)
        {
            var salt = Guid.NewGuid().ToString();

            return(new IdentityUser
            {
                Account = webModel.Account,
                AccountType = 1,
                Salt = salt,
                Password = MD5Utility.Sign(webModel.Password, salt),
                Email = webModel.Email,
                Phone = webModel.Phone,
                Name = webModel.Name,
                Gender = webModel.Gender,
                IdNumber = webModel.IdNumber,
                Wechat = webModel.Wechat,
                QQ = Convert.ToInt64(webModel.QQ),
                IsEnabled = (int)webModel.IsEnabled == 1,
                IsMaster = webModel.IsMaster,
                Address = webModel.Address,
                Age = webModel.Age,
                HomePage = "Instructor",
                CreatedId = CurrentUser.UserId,
                CreatedBy = CurrentUser.UserOID,
                CreatedName = CurrentUser.UserName
            });
        }
        void TestCompress()
        {
            var time = DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond;

            var filePath           = Application.dataPath + "/StreamingAssets/android/res/art/ui/texture/runtime/temp";
            var sourceFilePath     = filePath + ".assetbundle";
            var compressFilePath   = filePath + "_compressed.assetbundle";
            var decompressFilePath = filePath + "_decompressed.assetbundle";

            LogManager.Error("MD5 before: " + MD5Utility.GetFileMD5(sourceFilePath));

            // var filePath = Application.dataPath + "/Res/Lua/Main";
            // var sourceFilePath = filePath + ".lua";
            // var compressFilePath = filePath + "_compressed.lua";
            // var decompressFilePath = filePath + "_decompressed.lua";
            FileUtility.CompressFile(sourceFilePath, compressFilePath);

            FileUtility.DeCompressFile(compressFilePath, decompressFilePath);
            // var bytes = File.ReadAllBytes(compressFilePath);
            // FileUtility.DeCompressBuffer(bytes, decompressFilePath);

            LogManager.Error("MD5 after: " + MD5Utility.GetFileMD5(decompressFilePath));

            var elapsedTime = DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond - time;

            LogManager.Error(string.Format("ElapsedTime: {0}(ms)", elapsedTime));
        }
Beispiel #6
0
        private static void InitDatabase()
        {
            sqlite3Operate = SQLite3Factory.OpenOrCreate(MD5Utility.GetBytesMD5(Encoding.UTF8.GetBytes("SQLite3Prefs.db")));

            if (!sqlite3Operate.TableExists(tableName))
            {
                sqlite3Operate.Exec(sql);
            }
        }
Beispiel #7
0
        /// <summary>
        /// Open a SQLite3 database that exists in the persistentDataPath directory as read-only.
        /// </summary>
        /// <param name="InDbName">The name of the SQLite3 database.</param>
        /// <returns>Operation SQLite3 database handle.</returns>
        public static SQLite3Operate OpenToRead(string InDbName)
        {
#if UNITY_EDITOR
            string dbPath = Path.Combine(Application.streamingAssetsPath, InDbName);
            if (File.Exists(dbPath))
            {
                return(new SQLite3Operate(dbPath, SQLite3OpenFlags.ReadOnly));
            }
            else
            {
                return(null);
            }
#else
            string dbPath = Path.Combine(Application.persistentDataPath, InDbName);

            //return null;
            bool needUpdate = true;
            if (File.Exists(dbPath))
            {
#if DEBUG_MODE
                needUpdate = false;
#else
                SQLite3Version version = Resources.Load <SQLite3Version>("SQLite3Version");
                if (MD5Utility.GetFileMD5(dbPath).Equals(version.DbMd5))
                {
                    needUpdate = false;
                }
#endif
            }

            if (needUpdate)
            {
#if UNITY_ANDROID
                using (WWW www = new WWW(Path.Combine("jar:file://" + Application.dataPath + "!/assets/", InDbName)))
                {
                    while (!www.isDone)
                    {
                    }

                    if (string.IsNullOrEmpty(www.error))
                    {
                        File.WriteAllBytes(dbPath, www.bytes);
                    }
                    else
                    {
                        Debug.LogError("www error " + www.error);
                    }
                }
#elif UNITY_IOS
                File.Copy(Path.Combine(Application.streamingAssetsPath, InDbName), dbPath, true);
#endif
            }
            return(new SQLite3Operate(dbPath, SQLite3OpenFlags.ReadOnly));
#endif
        }
Beispiel #8
0
        private static void UpdateSQLite3Version()
        {
            SQLite3Version version = CreateInstance <SQLite3Version>();

            version.DbName = "Static.db";
            version.DbMd5  = MD5Utility.GetFileMD5(Application.streamingAssetsPath + "/Static.db");

            AssetDatabase.CreateAsset(version, "Assets/ThirdPartyPlugin/SQLite3/Resources/SQLite3Version.asset");
            AssetDatabase.SaveAssets();
            AssetDatabase.Refresh();
        }
        static void BuildVersionFile(BuildTarget targetPlatform, string[] files)
        {
            var versionFile = new ResVersionFile(files.Length);

            for (var i = 0; i < files.Length; ++i)
            {
                var file        = files[i];
                var versionInfo = new ResVersionInfo();
                versionInfo.MD5 = MD5Utility.GetFileMD5(file);

                versionFile.Files[i] = file.ReplaceFirst(_outPath + "/", "");
                versionFile.Infos[i] = versionInfo;
            }
            FileUtility.WriteFile(_outPath + "/" + ResConfig.VERSION_FILE, versionFile.Serialize());
            AssetDatabase.Refresh();
        }
        public IHttpActionResult GetUser([FromBody] ClientUser user)
        {
            BaseUser userCheck = UserLogic.CheckUser(user.Username, MD5Utility.GetMD5Password(user.Password));

            if (userCheck == null)
            {
                return(BadRequest("Username or password invalid."));
            }
            else if (userCheck.IsPasswordRecovered)
            {
                return(BadRequest("This user is locked."));
            }
            else
            {
                return(Ok(userCheck));
            }
        }
        public IHttpActionResult ChangePassword([FromBody] ClientUser user)
        {
            Int64    userChanged = 0;
            BaseUser userCheck   = UserLogic.GetUserIdByToken(user.Token);

            if (userCheck.Id > 0)
            {
                userChanged = UserLogic.ChangeUser(userCheck.Id, MD5Utility.GetMD5Password(user.Password));
            }

            if (userChanged == 0)
            {
                return(BadRequest("Invalid data."));
            }
            else
            {
                return(Ok("Passord changed."));
            }
        }
        static ResVersionFile BuildVersionFile(string[] files)
        {
            var versionFile = new ResVersionFile(files.Length);

            for (var i = 0; i < files.Length; ++i)
            {
                var file        = files[i];
                var versionInfo = new ResVersionInfo();
                versionInfo.File = file.ReplaceFirst(_outPath + "/", "");
                versionInfo.MD5  = MD5Utility.GetFileMD5(file);

                versionFile.Files[i] = file.ReplaceFirst(_outPath + "/", "");
                versionFile.Infos[i] = versionInfo;
            }

            var filePath = Application.dataPath + "/" + ResConfig.RES_ROOT + "/" + ResConfig.VERSION_FILE;

            FileUtility.WriteFile(filePath, versionFile.Serialize());
            AssetDatabase.Refresh();

            var buildInfo = new AssetBundleBuild();

            buildInfo.assetBundleName = ResConfig.VERSION_FILE;
            var assetName = "Assets/" + ResConfig.RES_ROOT + "/" + ResConfig.VERSION_FILE;

            buildInfo.assetNames = new string[] { assetName };
            ResBuildUtility.ResetBundleName(ref buildInfo);

            var options = _options & (~BuildAssetBundleOptions.ForceRebuildAssetBundle);

            BuildPipeline.BuildAssetBundles(
                _outPath,
                // new AssetBundleBuild[] { buildInfo },
                options,
                _target
                );

            // Remove temp versionFile
            File.Delete(filePath);

            return(versionFile);
        }
Beispiel #13
0
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            var identity = new ClaimsIdentity(context.Options.AuthenticationType);

            //Use the Factory repository in order to get the right type of user
            BaseUser user = UserLogic.GetUser(context.UserName, MD5Utility.GetMD5Password(context.Password));

            if (user != null)
            {
                identity.AddClaim(new Claim(ClaimTypes.Role, user.Role.Name));
                identity.AddClaim(new Claim("username", user.Username));
                identity.AddClaim(new Claim(ClaimTypes.Name, user.Firstname + " " + user.Surname));
                context.Validated(identity);
            }
            else
            {
                context.SetError("invalid_grant", "Provided username and password are incorrect.");

                return;
            }
        }
Beispiel #14
0
        /// <summary>
        /// Update Identity Entity
        /// </summary>
        /// <param name="webModel"></param>
        /// <param name="model"></param>
        /// <returns></returns>
        private static IdentityUser UpdateModel(StaffEditViewModel webModel, IdentityUser model)
        {
            model.Account      = webModel.Account;
            model.Password     = MD5Utility.Sign(webModel.Password, model.Salt);
            model.Email        = webModel.Email;
            model.Phone        = webModel.Phone;
            model.Name         = webModel.Name;
            model.Gender       = webModel.Gender;
            model.IdNumber     = webModel.IdNumber;
            model.Wechat       = webModel.Wechat;
            model.QQ           = Convert.ToInt64(webModel.QQ);
            model.IsEnabled    = (int)webModel.IsEnabled == 1;
            model.IsMaster     = webModel.IsMaster;
            model.Address      = webModel.Address;
            model.Age          = webModel.Age;
            model.ModifiedOn   = DateTime.Now;
            model.ModifiedId   = CurrentUser.UserId;
            model.ModifiedBy   = CurrentUser.UserOID;
            model.ModifiedName = CurrentUser.UserName;

            return(model);
        }
Beispiel #15
0
        /// <summary>
        /// Insert Identity Entity
        /// </summary>
        /// <param name="webModel"></param>
        /// <returns></returns>
        private static IdentityUser InsertModel(StudentEditViewModel webModel)
        {
            var salt = Guid.NewGuid().ToString();

            return(new IdentityUser
            {
                Account = webModel.Account,
                AccountType = 2,
                Salt = salt,
                Password = MD5Utility.Sign(webModel.Password, salt),
                Email = webModel.Email,
                Phone = webModel.Phone,
                Name = webModel.Name,
                Gender = webModel.Gender,
                IdNumber = webModel.IdNumber,
                Wechat = webModel.Wechat,
                QQ = Convert.ToInt64(webModel.QQ),
                IsEnabled = (int)webModel.IsEnabled == 1,
                Address = webModel.Address,
                Age = webModel.Age,
                HomePage = "Student",
                Birthday = Convert.ToDateTime(webModel.Birthday),
                City = webModel.City,
                CityId = webModel.CityId,
                District = webModel.District,
                DistrictId = webModel.DistrictId,
                EndDate = Convert.ToDateTime(webModel.EndDate),
                HighSchool = webModel.HighSchool,
                Province = webModel.Province,
                ProvinceId = webModel.ProvinceId,
                Hobbies = webModel.Hobbies,
                StartDate = Convert.ToDateTime(webModel.StartDate),
                TicketId = Convert.ToInt64(webModel.TicketId),
                Winning = webModel.Winning,
                CreatedId = CurrentUser.UserId,
                CreatedBy = CurrentUser.UserOID,
                CreatedName = CurrentUser.UserName
            });
        }
Beispiel #16
0
        /// <summary>
        /// If there is no database in the persistentDataPath directory,
        /// Then copy the database from the streamingAssetsPath directory to the persistentDataPath directory and open the database in read-only mode
        /// Else if need to match detection
        ///        then If the incoming Md5 is not empty, it is determined whether the database Md5 of the persistentDataPath directory matches.
        ///                else  the incoming Md5 is empty, determine whether the database in the persistentDataPath directory is the same as the streamingAssetsPath directory.
        ///        Else Open the existing database.
        /// </summary>
        /// <param name="InDbName">The name of the sqlite3 database.</param>
        /// <param name="InNeedMatchDetection">Whether need to match detection.</param>
        /// <param name="InMd5"></param>
        /// <returns>Operation sqlite3 database handle.</returns>
        public static SQLite3Operate OpenToRead(string InDbName, bool InNeedMatchDetection, string InMd5 = null)
        {
            string persistentDbPath = Path.Combine(Application.persistentDataPath, InDbName);

#if !UNITY_EDITOR && UNITY_ANDROID
            string streamDbPath = Path.Combine("jar:file://" + Application.dataPath + "!/assets/", InDbName);
#elif UNITY_IOS
            string streamDbPath = Path.Combine(Application.dataPath + "/Raw/", InDbName);
#else
            string streamDbPath = Path.Combine(Application.streamingAssetsPath, InDbName);
#endif

            bool   isNeedOverride = false;
            byte[] dbBytes        = null;
            if (File.Exists(persistentDbPath))
            {
                if (InNeedMatchDetection)
                {
                    if (string.IsNullOrEmpty(InMd5))
                    {
#if !UNITY_EDITOR && UNITY_ANDROID
                        using (WWW www = new WWW(streamDbPath))
                        {
                            while (!www.isDone)
                            {
                            }

                            if (string.IsNullOrEmpty(www.error))
                            {
                                dbBytes        = www.bytes;
                                isNeedOverride = !SQLite3Utility.GetBytesMD5(dbBytes).Equals(SQLite3Utility.GetFileMD5(persistentDbPath));
                            }
                            else
                            {
                                isNeedOverride = true;
                            }
                        }
#else
                        dbBytes        = File.ReadAllBytes(streamDbPath);
                        isNeedOverride = !MD5Utility.GetBytesMD5(dbBytes).Equals(MD5Utility.GetFileMD5(persistentDbPath));
#endif
                    }
                    else
                    {
                        isNeedOverride = !InMd5.Equals(persistentDbPath);
                    }
                }
            }
            else
            {
                isNeedOverride = true;
            }

            if (isNeedOverride)
            {
                if (null == dbBytes)
                {
#if !UNITY_EDITOR && UNITY_ANDROID
                    using (WWW www = new WWW(streamDbPath))
                    {
                        while (!www.isDone)
                        {
                        }

                        if (string.IsNullOrEmpty(www.error))
                        {
                            dbBytes = www.bytes;
                        }
                        else
                        {
                            Debug.LogError("Copy database from streamingAssetsPath to persistentDataPath error. " + www.error);
                        }
                    }
#else
                    dbBytes = File.ReadAllBytes(streamDbPath);
#endif
                }

                File.WriteAllBytes(persistentDbPath, dbBytes);
            }

            return(new SQLite3Operate(persistentDbPath, SQLite3OpenFlags.ReadOnly));
        }
        private bool VerificationFile(UpdateFileInfo updateFileInfo, string filePath)
        {
//            return true;
            var length = 0;

            using (FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.ReadWrite))
            {
                length = (int)fileStream.Length;
                if (length != updateFileInfo.ZipLength)
                {
                    FileUtility.DeleteFile(filePath);
                    return(false);
                }
                if (updateFileCache == null || updateFileCache.Length < length)
                {
                    updateFileCache = new byte[(length / OneMegaBytes + 1) * OneMegaBytes];
                }
                int offset = 0;
                int count  = length;
                while (count > 0)
                {
                    int bytesRead = fileStream.Read(updateFileCache, offset, count);
                    offset += bytesRead;
                    count  -= bytesRead;
                }
            }

            if (serverBundleIsZip)
            {
                byte[] zipMd5Bytes = MD5Utility.GetMd5Bytes(updateFileCache, 0, length);
                int    zipMd5Code  = BitConverter.ToInt32(zipMd5Bytes, 0);
                if (zipMd5Code != updateFileInfo.ZipMd5Code)
                {
                    FileUtility.DeleteFile(filePath);
                    return(false);
                }
                int decompressSize = ZipUtility.DeCompressionFileInSamePath(filePath, serverBundleZipPassword);
                if (decompressSize != updateFileInfo.Length)
                {
                    FileUtility.DeleteFile(filePath);
                    return(false);
                }
            }
            else
            {
                byte[] md5Bytes = MD5Utility.GetMd5Bytes(updateFileCache, 0, length);
                int    md5Code  = BitConverter.ToInt32(md5Bytes, 0);
                if (md5Code != updateFileInfo.Md5Code)
                {
                    FileUtility.DeleteFile(filePath);
                    return(false);
                }
            }
            string srcPath = PathUtility.GetCombinePath(AppConst.Path.HotUpdateDownloadDataPath,
                                                        updateFileInfo.AssetBundleName);
            string desPath = PathUtility.GetCombinePath(AppConst.Path.PresistentDataPath,
                                                        updateFileInfo.AssetBundleName);

            if (FileUtility.IsFileExist(desPath))
            {
                FileUtility.DeleteFile(desPath);
            }
            FileUtility.Move(srcPath, desPath);
            if (FileUtility.IsFileExist(filePath))
            {
                FileUtility.DeleteFile(filePath);
            }
            return(true);
        }
Beispiel #18
0
        private static void ProcessPackage(string workingPath, string tempworkingPath, string packagePath,
                                           AssetBundleBuildRule.Platform platform)
        {
            AssetBundleFileDatas.Clear();
            string packageVersionPath = $"{packagePath}{AppConst.AssetBundleConfig.VersionFile}";
            string assetbundleZipPath = $"{packagePath}{AppConst.AssetBundleConfig.AssetBundlePackageFile}";
            string fileInfoPath       = $"{packagePath}{AppConst.AssetBundleConfig.FileListFile}";

            string[]      allFiles            = Directory.GetFiles(workingPath, "*", SearchOption.AllDirectories);
            List <string> allAssetBundleFiles = new List <string>();

            foreach (string tempFile in allFiles)
            {
                string path = tempFile.Replace("\\", "/");
                if (Path.GetExtension(path) == ".manifest")
                {
                    continue;
                }
                allAssetBundleFiles.Add(path);
            }
            EditorUtility.ClearProgressBar();
            int  index     = 0;
            int  count     = allAssetBundleFiles.Count;
            long sizeCount = 0;

            foreach (string assetBundleFile in allAssetBundleFiles)
            {
                index++;
                EditorUtility.DisplayProgressBar("复制AssetBundle", "复制AssetBundle文件", (float)index / (float)count);
                string target     = assetBundleFile.Replace(workingPath, tempworkingPath);
                string targetPath = Path.GetDirectoryName(target);
                if (!Directory.Exists(targetPath))
                {
                    if (targetPath != null)
                    {
                        Directory.CreateDirectory(targetPath);
                    }
                }
                File.Copy(assetBundleFile, target);

                AssetBundleFileData assetBundleFileData = new AssetBundleFileData();
                byte[] srcBytes  = File.ReadAllBytes(assetBundleFile);
                int    srcLength = srcBytes.Length;
                sizeCount += srcBytes.Length;
                byte[] srcMd5Bytes     = MD5Utility.GetMd5Bytes(srcBytes);
                int    srcMd5Code      = BitConverter.ToInt32(srcMd5Bytes, 0);
                string assetBundleName = target.Replace(tempworkingPath, "");
                assetBundleFileData.AssetBundleName = assetBundleName;
                assetBundleFileData.Length          = srcLength;
                assetBundleFileData.Md5Code         = srcMd5Code;
                assetBundleFileData.ZipLength       = 0;
                assetBundleFileData.ZipMd5Code      = 0;
                AssetBundleFileDatas.Add(assetBundleFileData);
            }
            EditorUtility.ClearProgressBar();
            ZipUtility.CompressFolder(assetbundleZipPath, tempworkingPath, "*", AssetBundleRule.ZipPassWord);
            using (ByteBuffer buffer = new ByteBuffer())
            {
                ValueParse.WriteValue(buffer, platform.ToString(), ValueParse.StringParse);
                ValueParse.WriteValue(buffer, CurrentVersion.MasterVersion, ValueParse.IntParse);
                ValueParse.WriteValue(buffer, CurrentVersion.MinorVersion, ValueParse.IntParse);
                ValueParse.WriteValue(buffer, CurrentVersion.RevisedVersion, ValueParse.IntParse);
                ValueParse.WriteValue(buffer, allAssetBundleFiles.Count, ValueParse.IntParse);
                ValueParse.WriteValue(buffer, sizeCount, ValueParse.LongParse);
                ValueParse.WriteValue(buffer,
                                      string.IsNullOrEmpty(AssetBundleRule.AssetBundleVariant) ? "" : AssetBundleRule.AssetBundleVariant,
                                      ValueParse.StringParse);
                ValueParse.WriteValue(buffer, AssetBundleRule.ZipSelected, ValueParse.BoolParse);
                ValueParse.WriteValue(buffer,
                                      string.IsNullOrEmpty(AssetBundleRule.ZipPassWord) ? "" : AssetBundleRule.ZipPassWord,
                                      ValueParse.StringParse);
                File.WriteAllBytes(packageVersionPath, buffer.ToBytes());
            }

            using (ByteBuffer buffer = new ByteBuffer())
            {
                ValueParse.WriteValue(buffer, AssetBundleFileDatas.Count, ValueParse.IntParse);
                foreach (AssetBundleFileData assetBundleFileData in AssetBundleFileDatas)
                {
                    ValueParse.WriteValue(buffer, assetBundleFileData.AssetBundleName, ValueParse.StringParse);
                    ValueParse.WriteValue(buffer, assetBundleFileData.Length, ValueParse.IntParse);
                    ValueParse.WriteValue(buffer, assetBundleFileData.Md5Code, ValueParse.IntParse);
                    ValueParse.WriteValue(buffer, assetBundleFileData.ZipLength, ValueParse.IntParse);
                    ValueParse.WriteValue(buffer, assetBundleFileData.ZipMd5Code, ValueParse.IntParse);
                }
                File.WriteAllBytes(fileInfoPath, buffer.ToBytes());
            }
        }
Beispiel #19
0
        public async Task <IActionResult> Login(LoginViewModel viewModel, string returnUrl)
        {
            ViewData["ReturnUrl"] = returnUrl;
            if (ModelState.IsValid)
            {
                var user = await _service.GetUserAsync(viewModel.Account, viewModel.Password, _context);

                if (user != null)
                {
                    if (user.Password.Trim() != MD5Utility.Sign(viewModel.Password, user.Salt))
                    {
                        ViewBag.ErrorInfo = "用户名或密码错误";
                        return(View());
                    }

                    _logger.LogInformation("用户:{0}于{1}登录系统", viewModel.Account, DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss"));

                    string role = GetRole(user);

                    //根据用户角色创建claim声明
                    List <Claim> claim = new List <Claim>
                    {
                        new Claim(ClaimTypes.Role, role)
                    };

                    var userIdentity = new ClaimsIdentity(role);
                    userIdentity.AddClaims(claim);

                    var userPrincipal = new ClaimsPrincipal(userIdentity);

                    await AuthenticationHttpContextExtensions.SignInAsync(HttpContext, userPrincipal, new AuthenticationProperties
                    {
                        ExpiresUtc   = DateTime.UtcNow.AddMinutes(20),
                        IsPersistent = false,
                        AllowRefresh = false
                    });

                    //设置当前用户信息
                    await _service.SetCurrentUser(user.IdentityUserOID, _httpContextAccessor, _context);

                    if (!string.IsNullOrEmpty(returnUrl))
                    {
                        return(RedirectToLocal(returnUrl));
                    }

                    return(RedirectToRoute(new
                    {
                        area = user.HomePage,
                        controller = "Home",
                        action = "Index"
                    }));
                }
                else
                {
                    ViewBag.ErrorInfo = "当前用户不存在";
                    return(View());
                }
            }

            //返回模型验证错误信息
            ViewBag.ErrorInfo = this.ModelState.Keys.SelectMany(key => this.ModelState[key].Errors).FirstOrDefault().ErrorMessage;
            return(View(viewModel));
        }