async Task IResponse.Response(HttpContext context, WebSocketConnection conn, NpgsqlConnection npgConn) { await conn.ReceiveAsync(); long id = conn.Int64Message.Value; await conn.ReceiveAsync(); string token = conn.TextMessage; using (var cmd = npgConn.CreateCommand()) { if (!AuthorizationChecker.ValidateToken(cmd, id, token)) { await conn.SendByteAsync((byte)EResponse.AccountError); return; } try { cmd.CommandText = $"DELETE FROM account WHERE id={id};"; cmd.ExecuteNonQuery(); } catch (NpgsqlException) { await conn.SendByteAsync((byte)EResponse.ServerError); return; } await conn.SendByteAsync((byte)EResponse.Ok); } }
private void OnRegistrationCommandExecute() { Password = new AuthorizationChecker(User).GetHashPassword(Password); _unitOfWork.Users.Insert(User); _unitOfWork.SaveChanges(); _parentViewModel.ChangePageWithDialog(new ShortMessageViewModel("Успешная регистрация!"), 1000, _previousViewModel); }
async Task IResponse.Response(HttpContext context, WebSocketConnection conn, NpgsqlConnection npgConn) { await conn.ReceiveAsync(); long userId = conn.Int64Message.Value; await conn.ReceiveAsync(); string authToken = conn.TextMessage; await conn.ReceiveAsync(); string groupName = conn.TextMessage; await conn.ReceiveAsync(); string password = Account.Hash.Password(conn.Int32Message.Value.ToString()); try { using (var cmd = npgConn.CreateCommand()) { if (!AuthorizationChecker.ValidateToken(cmd, userId, authToken)) { await conn.SendByteAsync((byte)EResponse.AccountError); return; } int groupId; cmd.CommandText = $"INSERT INTO animal_group (owner_id, name, passwd) VALUES({userId}, '{groupName}', '{password}') RETURNING id;"; using (var reader = cmd.ExecuteReader()) { if (reader.Read()) { groupId = reader.GetInt32(0); } else { await conn.SendByteAsync((byte)EResponse.ServerError); return; } } cmd.CommandText = $"INSERT INTO participates VALUES({groupId}, {userId});"; cmd.ExecuteNonQuery(); await conn.SendByteAsync((byte)EResponse.Ok); } } catch (NpgsqlException e) { await conn.SendByteAsync((byte)EResponse.ServerError); throw e; } }
async Task IResponse.Response(HttpContext context, WebSocketConnection conn, NpgsqlConnection npgConn) { await conn.ReceiveAsync(); long id = conn.Int64Message.Value; await conn.ReceiveAsync(); string authToken = conn.TextMessage; await conn.ReceiveAsync(); long animalId = conn.Int64Message.Value; await conn.ReceiveAsync(); string memoJson = conn.TextMessage; Memo memo = new Memo(); memo.ReadJson(JObject.Parse(memoJson)); using (var cmd = npgConn.CreateCommand()) { if (!AuthorizationChecker.ValidateToken(cmd, id, authToken)) { await conn.SendByteAsync((byte)EResponse.AccountError); return; } if (!AuthorizationChecker.CheckAuthorizationOnAnimal(cmd, id, animalId)) { await conn.SendByteAsync((byte)EResponse.AccountError); return; } // Insert new memo on the database if (memo.PhotoString == null) { cmd.CommandText = $"INSERT INTO memo (animal_id, date_time, title, content) VALUES({animalId}, {memo.When}, '{memo.Title}', '{memo.Content}');"; } else { cmd.CommandText = $"INSERT INTO memo (animal_id, date_time, title, content, images) VALUES({animalId}, {memo.When}, '{memo.Title}', '{memo.Content}', '{memo.PhotoString}');"; } if (cmd.ExecuteNonQuery() == 0) { await conn.SendByteAsync((byte)EResponse.ServerError); } else { await conn.SendByteAsync((byte)EResponse.Ok); } } }
public ClientProfileViewModel(IViewModel previousViewModel, User user) { _rootViewModel = ViewModelManager.GetFirstOrDefaultInstance <MainWindowViewModel>(); _parentViewModel = previousViewModel; _authorizationChecker = new AuthorizationChecker(user); User = user; SaveCommand = new Command(OnSaveCommandExecute, OnSaveCommandCanExecute); BackCommand = new Command(OnBackCommandExecute); }
public Startup(IWebHostEnvironment env) { ConfigureLogger(); _configuration = new ConfigurationBuilder() .AddJsonFile("appsettings.json") .AddJsonFile($"appsettings.{env.EnvironmentName}.json") .AddUserSecrets <Startup>() .Build(); AuthorizationChecker.CheckAllEndpoints(); }
public bool Authorize(HttpContext httpContext) { if (httpContext == null) { throw new ArgumentNullException("httpContext"); } IPrincipal user = httpContext.User; if (!user.Identity.IsAuthenticated) { return(false); } return(AuthorizationChecker.HasAccess(user.Identity.Name, action)); }
public Startup(IWebHostEnvironment env) { ConfigureLogger(); _configuration = new ConfigurationBuilder() .AddJsonFile("appsettings.json") .AddJsonFile($"appsettings.{env.EnvironmentName}.json") .AddUserSecrets <Startup>() .AddEnvironmentVariables("Meetings_") .Build(); _loggerForApi.Information("Connection string:" + _configuration[MeetingsConnectionString]); AuthorizationChecker.CheckAllEndpoints(); }
async Task IResponse.Response(HttpContext context, WebSocketConnection conn, NpgsqlConnection npgConn) { await conn.ReceiveAsync(); long id = conn.Int64Message.Value; await conn.ReceiveAsync(); string authToken = conn.TextMessage; await conn.ReceiveAsync(); long animalId = conn.Int64Message.Value; await conn.ReceiveAsync(); long memoId = conn.Int64Message.Value; using (var cmd = npgConn.CreateCommand()) { if (!AuthorizationChecker.ValidateToken(cmd, id, authToken)) { await conn.SendByteAsync((byte)EResponse.AccountError); return; } if (!AuthorizationChecker.CheckAuthorizationOnAnimal(cmd, id, animalId)) { await conn.SendByteAsync((byte)EResponse.AccountError); return; } // Actual deletion work cmd.CommandText = $"DELETE FROM memo WHERE id={memoId};"; if (cmd.ExecuteNonQuery() == 0) { // On DB error await conn.SendByteAsync((byte)EResponse.ServerError); } else { // Success await conn.SendByteAsync((byte)EResponse.Ok); } } }
async Task IResponse.Response(HttpContext context, WebSocketConnection conn, NpgsqlConnection npgConn) { await conn.ReceiveAsync(); long id = conn.Int64Message.Value; await conn.ReceiveAsync(); string authToken = conn.TextMessage; await conn.ReceiveAsync(); long animalId = conn.Int64Message.Value; try { using (var cmd = npgConn.CreateCommand()) { if (!AuthorizationChecker.ValidateToken(cmd, id, authToken)) { await conn.SendByteAsync((byte)EResponse.AccountError); return; } if (!AuthorizationChecker.CheckAuthorizationOnAnimal(cmd, id, animalId)) { await conn.SendByteAsync((byte)EResponse.AccountError); return; } cmd.CommandText = $"DELETE FROM weights WHERE pet_id={animalId};" + $"DELETE FROM managed WHERE pet_id={animalId};" + $"DELETE FROM animal WHERE id={animalId};"; cmd.ExecuteNonQuery(); await conn.SendByteAsync((byte)EResponse.Ok); } } catch (NpgsqlException e) { await conn.SendByteAsync((byte)EResponse.ServerError); throw e; } }
protected override bool AuthorizeCore(HttpContextBase httpContext) { if (httpContext == null) { throw new ArgumentNullException("httpContext"); } IPrincipal user = httpContext.User; if (!user.Identity.IsAuthenticated) { return(false); } var access = AuthorizationChecker.HasAccess(httpContext.User.Identity.Name, action); if (access || (string.IsNullOrEmpty(Roles) && string.IsNullOrEmpty(Users))) { return(access); } return(base.AuthorizeCore(httpContext)); }
private void OnTryEnterCommandExecute() { _authorizationChecker = new AuthorizationChecker(new User { Login = Login, Password = Password }); if (_authorizationChecker.IsAdmin()) { _rootViewModel.ChangePage(new ManagerMainViewModel()); } else if (_authorizationChecker.IsMatchUser()) { User user = _authorizationChecker.GetUser(); _rootViewModel.ChangePageWithDialog(new ShortMessageViewModel("Успешная авторизация!"), 1111, new ClientMainViewModel(user)); } else if (_authorizationChecker.IsExistsLogin()) { _rootViewModel.ChangePageWithDialog(new ShortMessageViewModel("Неверный пароль!"), 777); } else { _rootViewModel.ChangePageWithDialog(new ShortMessageViewModel("Пользователь не зарегистрирован!"), 777); } }
async Task IResponse.Response(HttpContext context, WebSocketConnection conn, NpgsqlConnection npgConn) { await conn.ReceiveAsync(); long id = conn.Int64Message.Value; await conn.ReceiveAsync(); string authToken = conn.TextMessage; await conn.ReceiveAsync(); int groupId = conn.Int32Message.Value; await conn.ReceiveAsync(); int password = conn.Int32Message.Value; try { using (var cmd = npgConn.CreateCommand()) { if (!AuthorizationChecker.ValidateToken(cmd, id, authToken)) { await conn.SendByteAsync((byte)EResponse.AccountError); return; } string hashedPassword = Account.Hash.Password(password.ToString()); cmd.CommandText = $"SELECT passwd FROM animal_group WHERE id={groupId};"; using (var reader = cmd.ExecuteReader()) { if (reader.Read()) { string passwd = reader.GetString(0); if (passwd != hashedPassword) { await conn.SendByteAsync((byte)EResponse.PasswordError); return; } } else { await conn.SendByteAsync((byte)EResponse.UnknownGroup); return; } } cmd.CommandText = $"INSERT INTO participates VALUES({groupId}, {id});"; cmd.ExecuteNonQuery(); await conn.SendByteAsync((byte)EResponse.Ok); } } catch (NpgsqlException e) { await conn.SendByteAsync((byte)EResponse.ServerError); throw e; } }
async Task IResponse.Response(HttpContext context, WebSocketConnection conn, NpgsqlConnection npgConn) { await conn.ReceiveAsync(); long id = conn.Int64Message.Value; await conn.ReceiveAsync(); string authToken = conn.TextMessage; await conn.ReceiveAsync(); long animalId = conn.Int64Message.Value; await conn.ReceiveAsync(); string password = conn.TextMessage; await conn.ReceiveAsync(); string name = conn.TextMessage; await conn.ReceiveAsync(); ulong birthday = conn.UInt64Message.Value; await conn.ReceiveAsync(); short sex = conn.Int16Message.Value; await conn.ReceiveAsync(); long species = conn.Int64Message.Value; try { using (var cmd = npgConn.CreateCommand()) { if (!AuthorizationChecker.ValidateToken(cmd, id, authToken)) { await conn.SendByteAsync((byte)EResponse.AccountError); return; } if (!AuthorizationChecker.CheckAuthorizationOnAnimal(cmd, id, animalId)) { await conn.SendByteAsync((byte)EResponse.AccountError); return; } int groupId; string hashedPassword = Account.Hash.Password(password); cmd.CommandText = $"SELECT group_id FROM managed WHERE pet_id={animalId};"; using (var reader = cmd.ExecuteReader()) { if (reader.Read()) { groupId = reader.GetInt32(0); } else { await conn.SendByteAsync((byte)EResponse.UnknownAnimal); return; } } cmd.CommandText = $"SELECT passwd FROM animal_group WHERE id={groupId};"; using (var reader = cmd.ExecuteReader()) { if (reader.Read()) { string passwd = reader.GetString(0); if (passwd != hashedPassword) { await conn.SendByteAsync((byte)EResponse.PasswordError); return; } } else { await conn.SendByteAsync((byte)EResponse.UnknownAnimal); return; } } cmd.CommandText = $"UPDATE animal SET species={species}, name='{name}', birth={birthday}, sex={sex} WHERE id={animalId};"; if (cmd.ExecuteNonQuery() == 0) { await conn.SendByteAsync((byte)EResponse.ServerError); } else { await conn.SendByteAsync((byte)EResponse.Ok); } } } catch (NpgsqlException e) { await conn.SendByteAsync((byte)EResponse.ServerError); throw e; } }
async Task IResponse.Response(HttpContext context, WebSocketConnection conn, NpgsqlConnection npgConn) { await conn.ReceiveAsync(); long id = conn.Int64Message.Value; await conn.ReceiveAsync(); string authToken = conn.TextMessage; await conn.ReceiveAsync(); string commitJson = conn.TextMessage; var commit = new WeightCommit(); if (!commit.ReadJson(JObject.Parse(commitJson))) { await conn.SendByteAsync((byte)EResponse.ServerError); return; } using (var cmd = npgConn.CreateCommand()) { if (!AuthorizationChecker.ValidateToken(cmd, id, authToken)) { await conn.SendByteAsync((byte)EResponse.AccountError); return; } if (!AuthorizationChecker.CheckAuthorizationOnAnimal(cmd, id, commit.AnimalId)) { await conn.SendByteAsync((byte)EResponse.AccountError); return; } // Actual update work foreach (var pair in commit.Changes) { var change = pair.Value; switch (change.ChangeType) { case WeightCommit.Change.Type.Upsert: cmd.CommandText = $"INSERT INTO weights (pet_id, measured, weights) " + // insert $"VALUES({commit.AnimalId}, {change.Date}, {change.Weight}) " + // values $"ON CONFLICT (pet_id, measured) DO " + // on conflict $"UPDATE SET weights={change.Weight};"; // update break; case WeightCommit.Change.Type.Delete: cmd.CommandText = $"DELETE FROM weights " + $"WHERE pet_id={commit.AnimalId} " + $"AND measured={change.Date};"; break; default: cmd.CommandText = ""; break; } if (cmd.CommandText.Length != 0) { int trial = 0; int affectionCount; do { if (trial++ == 3) // Max of 3 trials { // Do not increase successCount goto UPDATE_FAILURE; } affectionCount = cmd.ExecuteNonQuery(); } while (affectionCount == 0); } UPDATE_FAILURE : { } } await conn.SendByteAsync((byte)EResponse.Ok); } }
async Task IResponse.Response(HttpContext context, WebSocketConnection conn, NpgsqlConnection npgConn) { await conn.ReceiveAsync(); long id = conn.Int64Message.Value; await conn.ReceiveAsync(); string authToken = conn.TextMessage; await conn.ReceiveAsync(); int groupId = conn.Int32Message.Value; await conn.ReceiveAsync(); string password = conn.TextMessage; await conn.ReceiveAsync(); string name = conn.TextMessage; await conn.ReceiveAsync(); ulong birthday = conn.UInt64Message.Value; await conn.ReceiveAsync(); short sex = conn.Int16Message.Value; await conn.ReceiveAsync(); long species = conn.Int64Message.Value; await conn.ReceiveAsync(); double weight = double.Parse(conn.TextMessage); await conn.ReceiveAsync(); ulong today = conn.UInt64Message.Value; try { using (var cmd = npgConn.CreateCommand()) { if (!AuthorizationChecker.ValidateToken(cmd, id, authToken)) { await conn.SendByteAsync((byte)EResponse.AccountError); return; } if (!AuthorizationChecker.CheckAuthorizationOnGroup(cmd, id, groupId)) { await conn.SendByteAsync((byte)EResponse.AccountError); return; } string hashedPassword = Account.Hash.Password(password); cmd.CommandText = $"SELECT passwd FROM animal_group WHERE id={groupId};"; using (var reader = cmd.ExecuteReader()) { if (reader.Read()) { string passwd = reader.GetString(0); if (passwd != hashedPassword) { await conn.SendByteAsync((byte)EResponse.PasswordError); return; } } else { await conn.SendByteAsync((byte)EResponse.UnknownGroup); return; } } long animalId; cmd.CommandText = $"INSERT INTO animal (species, name, birth, sex) VALUES({species}, '{name}', {birthday}, {sex}) RETURNING id;"; using (var reader = cmd.ExecuteReader()) { if (reader.Read()) { animalId = reader.GetInt64(0); } else { await conn.SendByteAsync((byte)EResponse.ServerError); return; } } cmd.CommandText = $"INSERT INTO managed VALUES({groupId}, {animalId});"; cmd.ExecuteNonQuery(); cmd.CommandText = $"INSERT INTO weights VALUES({animalId}, {today}, {weight});"; cmd.ExecuteNonQuery(); await conn.SendByteAsync((byte)EResponse.Ok); } } catch (NpgsqlException e) { await conn.SendByteAsync((byte)EResponse.ServerError); throw e; } }
public void authentication_checker_passed() { SecurityProvider.Get.AuthenticationService.AuthenticateUser("Admin", "AdminPassword"); Assert.AreEqual(true, AuthorizationChecker.HasAuthorization("Administrator")); }
async Task IResponse.Response(HttpContext context, WebSocketConnection conn, NpgsqlConnection npgConn) { await conn.ReceiveAsync(); long id = conn.Int64Message.Value; await conn.ReceiveAsync(); string authToken = conn.TextMessage; try { using (var cmd = npgConn.CreateCommand()) { if (!AuthorizationChecker.ValidateToken(cmd, id, authToken)) { await conn.SendByteAsync((byte)EResponse.AccountError); return; } LinkedList <int> groupIdList = new LinkedList <int>(); cmd.CommandText = $"SELECT group_id FROM participates WHERE account_id={id};"; using (var reader = cmd.ExecuteReader()) { while (reader.Read()) { int groupId = reader.GetInt32(0); groupIdList.AddLast(groupId); } } var groups = new List <Group>(); var idEntries = new Dictionary <Group, LinkedList <long> >(); foreach (var groupId in groupIdList) { Group group; cmd.CommandText = $"SELECT owner_id, name FROM animal_group WHERE id={groupId};"; using (var reader = cmd.ExecuteReader()) { if (reader.Read()) { long owner = reader.GetInt64(0); string name = reader.GetString(1); group = new Group(groupId, owner, name); groups.Add(group); } else { continue; } } var animalIdList = new LinkedList <long>(); cmd.CommandText = $"SELECT pet_id FROM managed WHERE group_id={groupId};"; using (var reader = cmd.ExecuteReader()) { while (reader.Read()) { long animalId = reader.GetInt64(0); animalIdList.AddLast(animalId); } } idEntries.Add(group, animalIdList); } var entries = new Dictionary <Group, LinkedList <Animal> >(); foreach (var group in groups) { var animals = new LinkedList <Animal>(); var idEntry = idEntries[group]; foreach (var animalId in idEntry) { var weights = new SortedDictionary <ulong, double>(); cmd.CommandText = $"SELECT measured, weights FROM weights WHERE pet_id={animalId};"; using (var reader = cmd.ExecuteReader()) { while (reader.Read()) { ulong when = checked ((ulong)reader.GetInt64(0)); double weight = reader.GetDouble(1); weights.Add(when, weight); } } cmd.CommandText = $"SELECT species, name, birth, sex FROM animal WHERE id={animalId};"; using (var reader = cmd.ExecuteReader()) { if (reader.Read()) { long species = reader.GetInt64(0); string name = reader.GetString(1); ulong birthday = checked ((ulong)reader.GetInt64(2)); short sex = reader.GetInt16(3); var animal = new Animal(animalId, species, birthday, name, (Sex)sex, weights); animals.AddLast(animal); } else { continue; } } } entries.Add(group, animals); } await conn.SendByteAsync((byte)EResponse.Ok); foreach (Group group in groups) { await conn.SendByteAsync((byte)EResponse.BeginGroup); await conn.SendTextAsync(group.ToJson().ToString()); foreach (Animal animal in entries[group]) { await conn.SendTextAsync(animal.ToJson().ToString()); } await conn.SendByteAsync((byte)EResponse.EndOfGroup); } await conn.SendByteAsync((byte)EResponse.EndOfList); } } catch (NpgsqlException e) { await conn.SendByteAsync((byte)EResponse.ServerError); throw e; } }
public void authentication_checker_failed() { SecurityProvider.Get.AuthenticationService.AuthenticateUser("Operator", "OperatorPassword"); Assert.AreEqual(false, AuthorizationChecker.HasAuthorization("Administrator")); }
async Task IResponse.Response(HttpContext context, WebSocketConnection conn, NpgsqlConnection npgConn) { await conn.ReceiveAsync(); long accountId = conn.Int64Message.Value; await conn.ReceiveAsync(); string authToken = conn.TextMessage; await conn.ReceiveAsync(); long animalId = conn.Int64Message.Value; await conn.ReceiveAsync(); ulong when = conn.UInt64Message.Value; using (var cmd = npgConn.CreateCommand()) { if (!AuthorizationChecker.ValidateToken(cmd, accountId, authToken)) { await conn.SendByteAsync((byte)EResponse.AccountError); return; } if (!AuthorizationChecker.CheckAuthorizationOnAnimal(cmd, accountId, animalId)) { await conn.SendByteAsync((byte)EResponse.AccountError); return; } // Send list of memo LinkedList <Memo> memoList = new LinkedList <Memo>(); cmd.CommandText = $"SELECT id, title, content, images FROM memo WHERE animal_id={animalId} AND date_time={when};"; using (var reader = cmd.ExecuteReader()) { while (reader.Read()) { long id = reader.GetInt64(0); string title = reader.GetString(1); string content = reader.GetString(2); string photoString; if (reader.IsDBNull(3)) { photoString = null; } else { photoString = reader.GetString(3); } memoList.AddLast(new Memo(id, when, title, content, photoString)); } } await conn.SendByteAsync((byte)EResponse.BeginList); foreach (var memo in memoList) { await conn.SendTextAsync(memo.ToJson().ToString()); } await conn.SendByteAsync((byte)EResponse.Ok); } }
public void authentication_checker_re_authenticate_failed() { SecurityProvider.Get.AuthenticationService.DeAuthenticateCurrentUser(); Assert.AreEqual(false, AuthorizationChecker.HasAuthorization("Administrator", () => SecurityProvider.Get.AuthenticationService.AuthenticateUser("Admin", "AdminPassword1"))); }
async Task IResponse.Response(HttpContext context, WebSocketConnection conn, NpgsqlConnection npgConn) { await conn.ReceiveAsync(); long id = conn.Int64Message.Value; await conn.ReceiveAsync(); string authToken = conn.TextMessage; await conn.ReceiveAsync(); long animalId = conn.Int64Message.Value; await conn.ReceiveAsync(); string commitJson = conn.TextMessage; Memo.Commit commit = new Memo.Commit(); commit.ReadJson(JObject.Parse(commitJson)); if (commit.HasChange) { using (var cmd = npgConn.CreateCommand()) { if (!AuthorizationChecker.ValidateToken(cmd, id, authToken)) { await conn.SendByteAsync((byte)EResponse.AccountError); return; } if (!AuthorizationChecker.CheckAuthorizationOnAnimal(cmd, id, animalId)) { await conn.SendByteAsync((byte)EResponse.AccountError); return; } // Update memo on the database var cmdBuilder = new StringBuilder("UPDATE memo SET "); var changeQueryList = new List <string>(); if (commit.Title != null) { changeQueryList.Add($"title='{commit.Title}'"); } if (commit.Content != null) { changeQueryList.Add($"content='{commit.Content}'"); } if (commit.PhotoString != null) { changeQueryList.Add($"images='{commit.PhotoString}'"); } cmdBuilder.Append(string.Join(", ", changeQueryList)); cmdBuilder.Append($" WHERE id={commit.Id};"); cmd.CommandText = cmdBuilder.ToString(); if (cmd.ExecuteNonQuery() == 0) { await conn.SendByteAsync((byte)EResponse.ServerError); } else { await conn.SendByteAsync((byte)EResponse.Ok); } } } else { await conn.SendByteAsync((byte)EResponse.Ok); } }