private void ReadLocal() { TextAsset txt = CoreEntry.gResLoader.LoadTextAsset("Data/Bulletin", SenLib.AssetType.Csv); if (null != txt) { mData = txt.text; if (!string.IsNullOrEmpty(mData)) { string md5Code = Md5Tool.Md5Sum(mData); string oldCode = PlayerPrefs.GetString("NotieMd5", ""); isNew = !md5Code.Equals(oldCode); PlayerPrefs.SetString("NotieMd5", md5Code); } else { isNew = false; PlayerPrefs.SetString("NotieMd5", ""); } } else { isNew = false; PlayerPrefs.SetString("NotieMd5", ""); } }
public async Task <IHttpActionResult> Post([FromBody] UserLoginModel model) { IUserRepository userRepository = _uow.GetRepository <IUserRepository>(); string hash = Md5Tool.CreateUtf8Hash(model.Password); dynamic user = await userRepository.GetQueryable().AsNoTracking().Include(x => x.UserRoles.Select(y => y.Role)).Where(x => x.UserName == model.UserName && x.Password == hash).Select(x => new { x.UserName, Roles = x.UserRoles.Select(y => y.Role.Name) }).FirstOrDefaultAsync(); if (user != null) { string secretKey = ConfigurationManager.AppSettings["SecretKey"]; double tokenExpiration = double.Parse(ConfigurationManager.AppSettings["TokenExpirationMinutes"]); string token = new CustomJwtAuthorizationProvider().GenerateToken(secretKey, user.UserName, user.Roles, tokenExpiration); return(Ok(new { access_token = token, token_type = "bearer", expires_in = TimeSpan.FromMinutes(tokenExpiration).TotalSeconds })); } return(Unauthorized()); }
public void WriteBulletin(string content) { string md5Code = ""; if (content.StartsWith(BundleCommon.BaseUrl + "\r\n")) { mData = content.Replace(BundleCommon.BaseUrl + "\r\n", ""); md5Code = Md5Tool.Md5Sum(mData); } else if (content.StartsWith(BundleCommon.BaseUrl + "\n")) { mData = content.Replace(BundleCommon.BaseUrl + "\n", ""); md5Code = Md5Tool.Md5Sum(mData); } else if (content.StartsWith(BundleCommon.BaseUrl + "\r")) { mData = content.Replace(BundleCommon.BaseUrl + "\r", ""); md5Code = Md5Tool.Md5Sum(mData); } string oldCode = PlayerPrefs.GetString("NotieMd5", ""); if (string.IsNullOrEmpty(md5Code)) { isNew = false; PlayerPrefs.SetString("NotieMd5", ""); } else { isNew = !md5Code.Equals(oldCode); PlayerPrefs.SetString("NotieMd5", md5Code); } }
public override void OnAuthorization(HttpActionContext actionContext) { AuthenticationHeaderValue authRequest = actionContext.Request.Headers.Authorization; if (authRequest != null && authRequest.Scheme.Equals("basic", StringComparison.OrdinalIgnoreCase)) { string token = authRequest.Parameter; if (!string.IsNullOrEmpty(token)) { string decodedToken = Encoding.UTF8.GetString(Convert.FromBase64String(token)); string username = decodedToken.Substring(0, decodedToken.IndexOf(":", StringComparison.Ordinal)); string password = decodedToken.Substring(decodedToken.IndexOf(":", StringComparison.Ordinal) + 1); if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(password)) { IUserRepository userRepository = _uow.GetRepository <IUserRepository>(); string hash = Md5Tool.CreateUtf8Hash(password); dynamic user = userRepository.GetQueryable().AsNoTracking().Include(x => x.UserRoles.Select(y => y.Role)).Where(x => x.UserName == username && x.Password == hash).Select(x => new { x.UserName, Roles = x.UserRoles.Select(y => y.Role.Name) }).FirstOrDefault(); if (user != null) { IList <Claim> claims = new List <Claim> { new Claim(ClaimTypes.Name, user.UserName), new Claim(ClaimTypes.NameIdentifier, user.UserName) }; AuthorizeAttribute authorizeAttribute = actionContext.ActionDescriptor .GetCustomAttributes <AuthorizeAttribute>(true) .FirstOrDefault(); if (authorizeAttribute != null) { string[] roles = authorizeAttribute.Roles.Split(','); foreach (string role in roles) { if (user.Roles.Contains(role)) { claims.Add(new Claim(ClaimTypes.Role, role)); } } } actionContext.RequestContext.Principal = new ClaimsPrincipal(new ClaimsIdentity(claims, "Basic")); } } } } //actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized); base.OnAuthorization(actionContext); }
public async Task <IHttpActionResult> Register([FromBody] UserRegisterModel model) { IUserRepository userRepository = _uow.GetRepository <IUserRepository>(); User user = new User { UserName = model.UserName, Email = model.Email, Password = Md5Tool.CreateUtf8Hash(model.Password) }; userRepository.Add(user); await _uow.CommitAsync(); return(Ok()); }
public override void OnHandlerMessage(OperationRequest request, OperationResponse response, ClientPeer peer) { User userClient = ParameterTool.GetParameter <User>(request.Parameters, ParameterCode.Register); User userServer = manager.GetUserByUsername(userClient.Username); if (userServer != null) //用户名重复 { response.ReturnCode = (short)ReturnCode.Failure; response.DebugMessage = "用户名重复"; } else //存入数据库 { userClient.Password = Md5Tool.GetMd5(userClient.Password); //md5加密 manager.AddUser(userClient); peer.LoginUser = userClient; response.ReturnCode = (short)ReturnCode.Success; } }
public override void OnHandlerMessage(OperationRequest request, OperationResponse response, ClientPeer peer) { User userClient = ParameterTool.GetParameter <User>(request.Parameters, ParameterCode.Login); User userServer = manager.GetUserByUsername(userClient.Username); if (userServer != null && Md5Tool.GetMd5(userClient.Password) == userServer.Password) //登录成功 { //数据库存在用户 //md5加密过后的客户端密码与数据库的密码比较 response.ReturnCode = (short)ReturnCode.Success; peer.LoginUser = userServer; //保存当前用户 } else //登录失败 { response.ReturnCode = (short)ReturnCode.Failure; response.DebugMessage = "用户名或者密码错误"; } }
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" }); IUserRepository userRepository = _uow.GetRepository <IUserRepository>(); string hash = Md5Tool.CreateUtf8Hash(context.Password); dynamic user = await userRepository.GetQueryable().AsNoTracking().Include(x => x.UserRoles.Select(y => y.Role)).Where(x => x.UserName == context.UserName && x.Password == hash).Select(x => new { x.UserName, Roles = x.UserRoles.Select(y => y.Role.Name) }).FirstOrDefaultAsync(); if (user != null) { ClaimsIdentity identity = new ClaimsIdentity(context.Options.AuthenticationType); //identity.AddClaim(new Claim("sub", user.UserName)); identity.AddClaim(new Claim(ClaimTypes.Name, user.UserName)); identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.UserName)); foreach (string role in user.Roles) { identity.AddClaim(new Claim(ClaimTypes.Role, role)); } AuthenticationTicket ticket = new AuthenticationTicket(identity, new AuthenticationProperties { AllowRefresh = true, IsPersistent = true, IssuedUtc = DateTimeOffset.Now, ExpiresUtc = DateTimeOffset.Now.AddMinutes(double.Parse(ConfigurationManager.AppSettings["TokenExpirationMinutes"])) }); context.Validated(ticket); } else { context.Rejected(); //context.SetError("invalid_grant", "The user name or password is incorrect."); } }
void file_post() { string uid = Request.Headers["uid"]; string f_id = Request.Headers["id"]; string lenSvr = Request.Headers["lenSvr"]; //已传大小 string lenLoc = Request.Headers["lenLoc"]; //本地文件大小 string blockOffset = Request.Headers["blockOffset"]; string blockSize = Request.Headers["blockSize"]; //当前块大小 string blockIndex = Request.Headers["blockIndex"]; //当前块索引,基于1 string blockMd5 = Request.Headers["blockMd5"]; //块MD5 string complete = Request.Headers["complete"]; //true/false string pathSvr = Request.Form["pathSvr"]; //add(2015-03-19): pathSvr = HttpUtility.UrlDecode(pathSvr); if (this.head_val_null_empty("lenLoc, uid, id, blockOffset")) { return; } if (Request.Files.Count < 1) { PageTool.to_content("file is empty"); return; } bool verify = false; string msg = string.Empty; string md5Svr = string.Empty; HttpPostedFile file = Request.Files.Get(0);//文件块 //计算文件块MD5 if (!string.IsNullOrEmpty(blockMd5)) { md5Svr = Md5Tool.calc(file.InputStream); } //文件块大小验证 verify = int.Parse(blockSize) == file.InputStream.Length; if (!verify) { msg = "block size error sizeSvr:" + file.InputStream.Length + " sizeLoc:" + blockSize; } //块MD5验证 if (verify && !string.IsNullOrEmpty(blockMd5)) { verify = md5Svr == blockMd5; if (!verify) { msg = "block md5 error"; } } if (verify) { //2.0保存文件块数据 FileBlockWriter res = new FileBlockWriter(); res.make(pathSvr, Convert.ToInt64(lenLoc)); res.write(pathSvr, Convert.ToInt64(blockOffset), ref file); up6_biz_event.file_post_block(f_id, Convert.ToInt32(blockIndex)); //生成信息 JObject o = new JObject(); o["msg"] = "ok"; o["md5"] = md5Svr; //文件块MD5 o["offset"] = blockOffset; //偏移 msg = JsonConvert.SerializeObject(o); } PageTool.to_content(msg); }
public void InitializeDatabase(SchoolExpressDbContext context) { if (!context.Database.Exists()) { return; } IList <AuthorizeAttribute> authorizeAttributes = Assembly.GetExecutingAssembly().GetTypes() .Where(type => typeof(ApiController).IsAssignableFrom(type)) .SelectMany(type => type.GetMethods()) .Where(method => method.IsPublic && method.IsDefined(typeof(AuthorizeAttribute), true)) .Select(m => m.GetCustomAttributes(typeof(AuthorizeAttribute), true).First() as AuthorizeAttribute).ToList(); string[] controllerRoles = authorizeAttributes.Select(a => a.Roles).Distinct().ToArray(); DbSet <User> userDbSet = context.Set <User>(); User user = userDbSet.FirstOrDefault(x => x.UserName == "admin"); if (user == null) { user = new User { UserName = "******", Email = "*****@*****.**", Password = Md5Tool.CreateUtf8Hash("admin123") }; userDbSet.Add(user); context.SaveChanges(); } DbSet <Role> roleDbSet = context.Set <Role>(); DbSet <UserRole> userRoleDbSet = context.Set <UserRole>(); string[] existingRoles = userRoleDbSet.AsNoTracking().Include(x => x.Role).Where(x => x.UserId == user.Id).Select(x => x.Role.Name).ToArray(); foreach (string roleName in controllerRoles) { bool exist = false; Role role = new Role { Name = roleName }; foreach (string existingRole in existingRoles) { if (existingRole == roleName) { exist = true; break; } } if (!exist) { roleDbSet.Add(role); context.SaveChanges(); context.Entry(role).State = EntityState.Detached; } if (!existingRoles.Contains(roleName)) { //int roleId = roleDbSet.AsNoTracking().Where(x => x.Name == roleName).Select(x => x.Id).First(); UserRole userRole = new UserRole { UserId = user.Id, RoleId = role.Id }; userRoleDbSet.Add(userRole); context.SaveChanges(); context.Entry(userRole).State = EntityState.Detached; } } foreach (string existingRoleName in existingRoles) { bool exist = false; foreach (string roleName in controllerRoles) { if (existingRoleName == roleName) { exist = true; break; } } if (!exist) { Role role = roleDbSet.AsNoTracking().FirstOrDefault(x => x.Name == existingRoleName); if (role != null) { UserRole userRole = new UserRole { UserId = user.Id, RoleId = role.Id }; userRoleDbSet.Attach(userRole); userRoleDbSet.Remove(userRole); context.SaveChanges(); context.Entry(userRole).State = EntityState.Detached; roleDbSet.Attach(role); roleDbSet.Remove(role); context.SaveChanges(); context.Entry(role).State = EntityState.Detached; } } } }
/// <summary> /// 只负责拼接文件块。将接收的文件块数据写入到文件中。 /// 更新记录: /// 2012-04-12 更新文件大小变量类型,增加对2G以上文件的支持。 /// 2012-04-18 取消更新文件上传进度信息逻辑。 /// 2012-10-30 增加更新文件进度功能。 /// 2015-03-19 文件路径由客户端提供,此页面不再查询文件在服务端的路径。减少一次数据库访问操作。 /// 2016-03-31 增加文件夹信息字段 /// 2017-07-11 优化参数检查逻辑 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void Page_Load(object sender, EventArgs e) { string uid = this.headString("uid"); string f_id = this.headString("id"); string lenSvr = this.headString("lenSvr"); //已传大小 string lenLoc = this.headString("lenLoc"); //本地文件大小 string blockOffset = this.headString("blockOffset"); string blockSize = this.headString("blockSize"); //当前块大小 string blockIndex = this.headString("blockIndex"); //当前块索引,基于1 string blockMd5 = this.headString("blockMd5"); //块MD5 string complete = this.headString("complete"); //true/false string pathSvr = Request.Form["pathSvr"]; // string pathLoc = string.Empty; string token = this.headString("token"); // pathSvr = Server.UrlDecode(pathSvr); if (!this.safe_check(lenLoc, uid, f_id, blockOffset, pathSvr)) { return; } //有文件块数据 if (Request.Files.Count > 0) { bool verify = false; string msg = string.Empty; string md5Svr = string.Empty; HttpPostedFile file = Request.Files.Get(0);//文件块 var stm = file.InputStream; var stmLen = int.Parse(blockSize); pathLoc = file.FileName; //加密 ConfigReader cr = new ConfigReader(); var sec = cr.module("path"); var encrypt = (bool)sec.SelectToken("$.security.encrypt"); if (encrypt) { CryptoTool ct = new CryptoTool(); pathSvr = ct.decode(pathSvr); stm = ct.decode(file.InputStream, int.Parse(blockSize)); } //token验证 WebSafe ws = new WebSafe(); FileInf fileSvr = new FileInf(); fileSvr.id = f_id; fileSvr.pathLoc = file.FileName; fileSvr.pathSvr = pathSvr; FileInfo fi = new FileInfo(pathLoc); fileSvr.nameLoc = fi.Name; verify = ws.validToken(token, fileSvr, "block"); //token验证失败 if (!verify) { msg = string.Format("token error loc:{0}", token); } //计算文件块MD5 if (!string.IsNullOrEmpty(blockMd5)) { md5Svr = Md5Tool.calc(stm); } //文件块大小验证 if (verify) { verify = int.Parse(blockSize) == stm.Length; } if (!verify) { msg = "block size error sizeSvr:" + stm.Length + " sizeLoc:" + blockSize; } //块MD5验证 if (verify && !string.IsNullOrEmpty(blockMd5)) { verify = md5Svr == blockMd5; if (!verify) { msg = "block md5 error"; } } if (verify) { PathBuilder pb = new PathBuilder(); pathSvr = pb.relToAbs(pathSvr); //2.0保存文件块数据 FileBlockWriter res = new FileBlockWriter(); res.make(pathSvr, Convert.ToInt64(lenLoc)); res.write(pathSvr, Convert.ToInt64(blockOffset), stm); up6_biz_event.file_post_block(f_id, Convert.ToInt32(blockIndex)); //生成信息 JObject o = new JObject(); o["msg"] = "ok"; o["md5"] = md5Svr; //文件块MD5 o["offset"] = blockOffset; //偏移 msg = JsonConvert.SerializeObject(o); } this.toContentJson(msg); } }