/// <summary> /// /// </summary> /// <param name="fileName"></param> /// <returns></returns> private string getIncludeCss(string fileName) { string content; HashString fileKey = fileName.toLowerNotEmpty(); if (!includeCss.TryGetValue(fileKey, out content)) { content = File.ReadAllText(fileName, WebConfig.Encoding); string includeStart = @"/*Include:"; if (content.StartsWith(includeStart, StringComparison.Ordinal)) { int index = content.IndexOf("*/", includeStart.Length); if (index != -1) { content = System.String.Join(@" ", new SubString { String = content, Start = includeStart.Length, Length = index - includeStart.Length }.Split(',') .getArray(value => getIncludeCss(Parameter.ProjectPath + value.ToString() + ".css")) .getAdd(content.Substring(index + 2))); } } includeCss.Add(fileKey, content); } return(content); }
/// <summary> /// 获取成员名称与类型集合 /// </summary> /// <param name="name">列名前缀</param> /// <returns></returns> internal static KeyValue <string, Type>[] GetDataColumns(string name) { if (custom != null) { return(custom.GetDataColumns(name)); } if (Fields != null) { KeyValue <string, Type>[] values; HashString nameKey = name; if (dataColumns.TryGetValue(nameKey, out values)) { return(values); } LeftArray <KeyValue <string, Type> > columns = new LeftArray <KeyValue <string, Type> >(Fields.Length); foreach (Field field in Fields) { if (field.IsSqlColumn) { ((Func <string, KeyValue <string, Type>[]>)AutoCSer.Sql.Metadata.GenericType.Get(field.DataType).GetDataColumnsMethod)(name + "_" + field.FieldInfo.Name); } else { columns.Add(new KeyValue <string, Type>(name + "_" + field.FieldInfo.Name, field.DataType)); } } values = columns.ToArray(); dataColumns.Set(nameKey, values); return(values); } return(null); }
private void simpleButton2_Click(object sender, EventArgs e) { string oldPass = textEdit2.Text; string newPass = textEdit3.Text; string newPassConfirm = textEdit4.Text; if (newPass != newPassConfirm) { XtraMessageBox.Show("Mật khẩu mới và xác nhận MK mới không giống nhau!", "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error); } else { string temp = HashString.MD5Hash(oldPass); if (user.password != temp) { XtraMessageBox.Show("Mật khẩu cũ không đúng!", "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error); } else { temp = HashString.MD5Hash(newPass); user.password = temp; DataProvider.Ins.DB.Users.Add(user); DataProvider.Ins.DB.Users.Attach(user); DataProvider.Ins.DB.Entry(user).State = EntityState.Modified; DataProvider.Ins.DB.SaveChanges(); XtraMessageBox.Show("Thay đổi mật khẩu thành công!", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information); this.Close(); } } }
public Task <User> LoginAsync(string email, string password) { return(CommonOperationAsync(async() => { var user = await _uow.Users.GetByEmailAsync(email); if (user == null) { throw new AuthenticationException(); } /** Hash password **/ var userUtil = await _uow.UserUtils.GetByUserIdAsync(user.Id); var hashed = HashString.Hash(password, userUtil.SpecialValue, AuthorizationUtilConstants.IterationCountForHashing); password = hashed; /*******************/ var result = await _uow.Users.GetByEmailAndPasswordAsync(email, password); if (result == null) { throw new AuthenticationException(); } return result; }, new BusinessBaseRequest { MethodBase = MethodBase.GetCurrentMethod() })); }
uint _deviceId() { Random random_ = new Random(); uint offset_ = (uint)random_.Next(0, 0x400); return(HashString._runHash(@"account", offset_)); }
/// <summary> /// 获取列名集合 /// </summary> /// <param name="name">列名前缀</param> /// <returns></returns> public unsafe static string[] GetColumnNames(string name) { string[] names; HashString nameKey = name; if (columnNames.TryGetValue(nameKey, out names)) { return(names); } LeftArray <string> nameList = new LeftArray <string>(Fields.Length); foreach (Field field in Fields) { if (field.IsSqlColumn) { ((ColumnGroup.Verifyer.GetName)AutoCSer.Sql.Metadata.GenericType.Get(field.FieldInfo.FieldType).UpdaterGetColumnNamesMethod)(ref nameList, name + "_" + field.FieldInfo.Name); } else { nameList.Add(name + "_" + field.FieldInfo.Name); } } columnNames.Set(nameKey, names = nameList.ToArray()); return(names); }
public PerfilController() { this.perfilRepositorio = InversionControl.Current.Resolve <IPerfilRepositorio>(); this.usuarioRepositorio = InversionControl.Current.Resolve <IUsuarioRepositorio>(); this.sessaoDoUsuario = InversionControl.Current.Resolve <ISessaoDoUsuario>(); this.hashString = InversionControl.Current.Resolve <HashString>(); }
/// <summary> /// 获取列名集合 /// </summary> /// <param name="name">列名前缀</param> /// <returns></returns> internal static string[] GetColumnNames(string name) { string[] names; HashString nameKey = name; if (columnNames.TryGetValue(ref nameKey, out names)) { return(names); } LeftArray <string> nameList = new LeftArray <string>(verifyFields.Length); foreach (Field field in verifyFields) { if (field.IsSqlColumn) { ColumnGroup.Verifyer.GetColumnNames(field.FieldInfo.FieldType)(ref nameList, name + "_" + field.FieldInfo.Name); } else { nameList.Add(name + "_" + field.FieldInfo.Name); } } columnNames.Set(ref nameKey, names = nameList.ToArray()); return(names); }
private int getPort(ClientId clientId, string host) { if (ticks == clientId.Tick && host != null) { IPAddress ip = HostPort.HostToIPAddress(host); if (ip != null) { HashString ipHash = ip.ToString(); object arrayLock = clientPool.ArrayLock; Ports ports; Monitor.Enter(arrayLock); if (clientPool.Array[clientId.Index].Identity == clientId.Identity) { try { if (!ipPorts.TryGetValue(ipHash, out ports)) { ipPorts.Add(ipHash, ports = new Ports(config)); } return(ports.Next); } finally { Monitor.Exit(arrayLock); } } Monitor.Exit(arrayLock); } } return(0); }
/// <summary> /// 删除监视路径 /// </summary> /// <param name="path">监视路径</param> internal void Remove(string path) { path = AutoCSer.IO.File.FileNameToLower(path); CreateFlieTimeoutCounter counter; HashString pathKey = path; Monitor.Enter(watcherLock); try { if (watchers.TryGetValue(pathKey, out counter)) { if (--counter.Count == 0) { watchers.Remove(pathKey); } else { watchers[pathKey] = counter; } } } finally { Monitor.Exit(watcherLock); } if (counter.Count == 0 && counter.Watcher != null) { dispose(counter.Watcher); } }
/// <summary> /// 删除数据结构定义 /// </summary> /// <param name="buffer">数据缓冲区</param> /// <returns>被删除数据结构索引标识</returns> internal IndexIdentity RemoveDataStructure(Buffer buffer) { if (CanWrite) { DataStructureBuffer dataStructureBuffer = new DataStructureBuffer(buffer); HashString name = dataStructureBuffer.CacheName; ServerDataStructure dataStructure; if (DataStructures.TryGetValue(name, out dataStructure)) { int index = dataStructure.Identity.Index; FreeIndexs.Add(index); buffer.SetIdentity(new IndexIdentity { Index = index, Identity = Array[index].Free() }); DataStructures.Remove(name); onOperation(buffer); dataStructure.Node.OnRemoved(); return(dataStructure.Identity); } buffer.FreeReference(); return(new IndexIdentity { ReturnType = ReturnType.DataStructureNameNotFound }); } buffer.FreeReference(); return(new IndexIdentity { ReturnType = ReturnType.CanNotWrite }); }
public IActionResult Registro(RegistroViewModel model, string returnUrl = null) { ViewData["ReturnUrl"] = returnUrl; if (ModelState.IsValid) { if (_repoUsuario.EstaDisponible(model.Correo)) { ModelState.AddModelError(string.Empty, "Correo no disponible"); return(View(model)); } var usuario = _repoUsuario.Create(new Usuario { Nombre = model.Nombre, PrimerApellido = model.PrimerApellido, SegundoApellido = model.SegundoApellido, NumeroCelular = model.NumeroCelular, NombreUsuario = model.Correo, Correo = model.Correo, HashContrasena = HashString.Encrypt(model.Contrasena), FechaNacimiento = model.FechaNacimiento }); if (usuario.Id <= 0) { ModelState.AddModelError(string.Empty, "Error al generar el usuario"); return(View(model)); } return(RedirectToLocal(returnUrl)); } return(View(model)); }
public override int GetHashCode() { unchecked { return(HashString.GetHashCode()); } }
public IActionResult ChangePassword([FromBody] PasswordVM password) { //get the user id from the JWT token var userid = httpContext?.HttpContext?.User?.FindFirst(JwtRegisteredClaimNames.Sub).Value; if (userid != null) { User user = context.Users.Where(u => u.userId == Guid.Parse(userid)).FirstOrDefault(); //is the old password correct? if (user.password != HashString.HashThat(password.oldPassword, config["salt"])) { return(Json(new JSONResponseVM { success = false, message = "Old password is incorrect" })); } //change the password user.password = HashString.HashThat(password.password, config["salt"]); context.SaveChanges(); return(Json(new JSONResponseVM { success = true, message = "New password created!" })); } return(Json(new JSONResponseVM { success = false, message = "This user doesn't exist" })); }
public void SeedClientApplicationData(ModelBuilder modelBuilder) { foreach (var clientApplication in ClientApplications) { var salt = HashString.GetSalt(); var hashPassword = HashString.Hash(clientApplication.ClientApplicationPassword, salt , AuthorizationUtilConstants.IterationCountForHashing); var clientApplicationUtil = new ClientApplicationUtil() { Id = ClientApplicationUtilId, ClientApplicationId = clientApplication.Id, SpecialValue = salt, }; clientApplication.ClientApplicationPassword = hashPassword; SeedDataUtil.SetCommonFields <ClientApplication, int>(clientApplication, LoggedUserId); SeedDataUtil.SetCommonFields <ClientApplicationUtil, int>(clientApplicationUtil, LoggedUserId); modelBuilder.Entity <ClientApplication>() .HasData(clientApplication); modelBuilder.Entity <ClientApplicationUtil>() .HasData(clientApplicationUtil); ClientApplicationUtilId++; } }
/// <summary> /// 公用错误处理函数 /// </summary> /// <param name="error">错误信息</param> public void Error(string error) { if (!string.IsNullOrEmpty(error)) { bool isLog = false; HashString errorHash = error; Monitor.Enter(errorQueueLock); try { if (errorQueue.Set(ref errorHash, error) == null) { isLog = true; if (errorQueue.Count > 512) { errorQueue.UnsafePopNode(); } } } finally { Monitor.Exit(errorQueueLock); } if (isLog) { DomainServer.WebClientLog.Debug(error, LogLevel.Debug | LogLevel.Info | LogLevel.AutoCSer); } } }
public IActionResult Login([FromBody] LoginVM user) { //TO DO: MAKE THE MUTLPIPLE ACCOUNTS SHOW UP WHEN THE USER THEM if (!ModelState.IsValid) { return(Json(new JSONResponseVM { success = false, message = "Model state is incorrect" })); } string password = HashString.HashThat(user.password, config["salt"]); User theUser = context.Users.Where(u => u.username == user.username && u.password == password).FirstOrDefault(); if (theUser != null) { return(Json(new JSONResponseVM { success = true, message = GenerateJWT.Generate( theUser.userId.ToString(), theUser.portfolioId1.ToString(), config) })); } else { return(Json(new JSONResponseVM { success = false, message = "Incorrect login details" })); } }
public string EncryptPassword(string password) { HashString hash = new HashString(); string hashPassword = hash.ComputeSha256Hash(password); return(hashPassword); }
public async Task <JsonResult> Login([FromBody] LoginVM loginUser) { //hash the password string password = HashString.Hash(loginUser.password, config["salt"]); var user = await context.Users .Where(u => u.username == loginUser.username) .Where(u => u.hashedPassword == password) .FirstOrDefaultAsync(); if (user != null) { //Generate the JWT GenerateJWT jwtGen = new GenerateJWT(); TokenVM token = jwtGen.Generate(user.username, config); return(Json(new JSONTokenResponseVM { message = "Successfully logged in", token = token.token })); } else { return(Json(new JSONResponseVM { success = false, message = "Incorrect login details" })); } }
public void SeedUserData(ModelBuilder modelBuilder) { foreach (var user in Users) { var salt = HashString.GetSalt(); var hashPassword = HashString.Hash(user.Password, salt , AuthorizationUtilConstants.IterationCountForHashing); var userUtil = new UserUtil { Id = UserUtilId, UserId = user.Id, SpecialValue = salt, }; user.Password = hashPassword; SeedDataUtil.SetCommonFields <User, int>(user, LoggedUserId); SeedDataUtil.SetCommonFields <UserUtil, int>(userUtil, LoggedUserId); modelBuilder.Entity <User>() .HasData(user); modelBuilder.Entity <UserUtil>() .HasData(userUtil); UserUtilId++; } }
public Task <ClientApplication> CreateAsync(ClientApplicationRequest request) { return(CommonOperationAsync(async() => { var result = Mapper.Map <ClientApplication>(request); var tempResult = await _uow.ClientApplications.GetByNameAsync(result.ClientApplicationName); tempResult.CheckUniqueValue(AuthorizationConstants.ClientApplicationName); tempResult = await _uow.ClientApplications.GetByCodeAsync(result.ClientApplicationCode); tempResult.CheckUniqueValue(AuthorizationConstants.ClientApplicationCode); var salt = HashString.GetSalt(); var hashPassword = HashString.Hash(result.ClientApplicationPassword, salt, AuthorizationUtilConstants.IterationCountForHashing); result.ClientApplicationPassword = hashPassword; _uow.ClientApplications.Add(result, GetLoggedInUserId()); CreateClientApplicationUtil(result.Id, salt); await _uow.SaveChangesAsync(); return result; }, new BusinessBaseRequest { MethodBase = MethodBase.GetCurrentMethod() })); }
public Task <ClientApplication> LoginAsync(string code, string password) { return(CommonOperationAsync(async() => { ClientApplication clientApplication; try { clientApplication = await GetByClientApplicationCodeAsync(code); } catch (KeyNotFoundException) //Eğer code sistemde yoksa, kayıt bulunamadı yerine authentication hatası fırlatması için try - catch kullanılıyor { throw new AuthenticationException(); } var clientApplicationUtil = await _uow.ClientApplicationUtils.GetByClientApplicationIdAsync(clientApplication.Id); password = HashString.Hash(password, clientApplicationUtil.SpecialValue, AuthorizationUtilConstants.IterationCountForHashing); var client = await _uow.ClientApplications.GetByCodeAndPasswordAsync(code, password); if (client == null) { throw new AuthenticationException(); } return client; }, new BusinessBaseRequest { MethodBase = MethodBase.GetCurrentMethod() })); }
public StringHashGen(uint theMask = 0x7fffffff, HashString hasher = null) { _mask = theMask; if (hasher == null) { hasher = DefaultHashString; } }
public AccountController() { this.usuarioRepositorio = InversionControl.Current.Resolve <UsuarioRepositorio>(); this.acessoFuncionalidadeRepositorio = InversionControl.Current.Resolve <IAcessoFuncionalidadeRepositorio>(); this.hashString = InversionControl.Current.Resolve <HashString>(); this.logarAcaoSistema = InversionControl.Current.Resolve <LogarAcaoDoSistema>(); this.storageServico = InversionControl.Current.Resolve <StorageServico>(); }
public EdicaoPessoalController() { this.perfilRepositorio = InversionControl.Current.Resolve <IPerfilRepositorio>(); this.usuarioRepositorio = InversionControl.Current.Resolve <IUsuarioRepositorio>(); this.sessaoDoUsuario = InversionControl.Current.Resolve <ISessaoDoUsuario>(); this.hashString = InversionControl.Current.Resolve <HashString>(); this.logarAcaoSistema = InversionControl.Current.Resolve <LogarAcaoDoSistema>(); }
static void find_superpeer() { Console.Write("Destination: "); string dest_key = Console.ReadLine(); IPAddress ipAddress = IPAddress.Parse(local_ip); IPEndPoint ipLocalEndPoint = new IPEndPoint(ipAddress, local_port); //Connect to server TcpClient client = new TcpClient(ipLocalEndPoint); client.Connect(server_ip, server_port); SslStream sslStream = new SslStream(client.GetStream(), false, new RemoteCertificateValidationCallback(ValidateServerCertificate), null); authenticate_server(sslStream); TCPCommunication.send_message_tcp(sslStream, "FIND_P"); TCPCommunication.send_message_tcp(sslStream, HashString.GetHashString(pubKey.ToString())); string response = TCPCommunication.recieve_message_tcp(sslStream); if (String.Compare(response, "ACCEPT") == 0) { TCPCommunication.send_message_tcp(sslStream, dest_key); response = TCPCommunication.recieve_message_tcp(sslStream); string[] temp_split = response.Split(':'); dest_ip = temp_split[1]; dest_port = Int32.Parse(temp_split[2]); Console.WriteLine($"destination peer in {dest_ip}:{dest_port}"); //TCPCommunication.send_message_tcp(sslStream, pubKey.ToString()); //response = TCPCommunication.recieve_message_tcp(sslStream); //Console.WriteLine(response); sslStream.Close(); client.Close(); client = new TcpClient(ipLocalEndPoint); Console.WriteLine("Client connecting"); client.Connect(dest_ip, dest_port); Console.WriteLine("Client connected"); sslStream = new SslStream(client.GetStream(), false, new RemoteCertificateValidationCallback(ValidateServerCertificate), null); authenticate_server(sslStream); req_connection(sslStream, client, dest_key); sslStream.Close(); client.Close(); } else if (String.Compare(response, "REJECT") == 0) { Console.WriteLine("Connection rejected"); sslStream.Close(); client.Close(); } }
public void _setAccountName(string nAccountName) { mAccountId = _accountId(nAccountName); mClusterID = HashString._runClusterID(nAccountName); mServerID = HashString._runServerID(nAccountName); mDatabaseId = HashString._runDatabaseId(nAccountName); mTableId = HashString._runTableId(nAccountName); mAccountName = nAccountName; }
protected void appendHtml(ref SubString html) { HashString htmlKey = html; if (!Htmls.ContainsKey(htmlKey)) { Htmls.Add(htmlKey, Htmls.Count); } }
/// <summary> /// 部署服务客户端 /// </summary> /// <param name="config">部署服务客户端配置</param> /// <param name="onClient">部署服务客户端就绪</param> public Client(ClientConfig config = null, Action <OnClientParameter> onClient = null) { this.Config = config ?? ConfigLoader.GetUnion(typeof(ClientConfig)).ClientConfig; this.onClient = onClient; if ((deploys = config.Deploys).Length == 0) { throw new ArgumentNullException(); } IgnoreFileNames = config.IgnoreFileNames.getHash(value => value) ?? HashSetCreator.CreateOnly <string>(); Dictionary <HashString, AutoCSer.Net.TcpInternalServer.ServerAttribute> attributes; if (config.ServerAttributes.length() == 0) { attributes = null; } else { attributes = DictionaryCreator.CreateHashString <AutoCSer.Net.TcpInternalServer.ServerAttribute>(); foreach (KeyValue <string, AutoCSer.Net.TcpInternalServer.ServerAttribute> attribute in config.ServerAttributes.notNull()) { attributes.Add(attribute.Key ?? string.Empty, attribute.Value); } } TcpClient tcpClient; int deployIndex = 0; foreach (ClientDeploy deploy in deploys) { if (deploy.Tasks.length() == 0) { throw new ArgumentNullException("deploys[" + deployIndex.toString() + "].Tasks"); } HashString serverName = deploy.ServerName ?? string.Empty; if (!clients.TryGetValue(serverName, out tcpClient)) { if (serverName.String.Length == 0) { clients.Add(serverName, tcpClient = new TcpClient(this, string.Empty, null)); } else { AutoCSer.Net.TcpInternalServer.ServerAttribute attribute; if (attributes.TryGetValue(serverName, out attribute)) { clients.Add(serverName, tcpClient = new TcpClient(this, serverName.String, attribute)); } else { throw new ArgumentNullException("缺少服务命名 " + serverName); } } } deploys[deployIndex++].TcpClient = tcpClient; } }
internal override void SetInstanceMember(ExecutionContext ctx, HashString name, DyFunction func) { if ((string)name is Builtins.Get or Builtins.Set or Builtins.Length) { ctx.OverloadProhibited(this, (string)name); return; } base.SetInstanceMember(ctx, name, func); }