示例#1
0
        public object Get(GetUser request)
        {
            if ((request.ID == null && request.SteamId == null) || (request.SteamId == 0 && request.ID == 0))
            {
                throw new ArgumentNullException();
            }
            string cacheKey = UrnId.Create<User>(request.SteamId.ToString());
            return Request.ToOptimizedResultUsingCache(
                base.Cache,
                cacheKey,
                TimeSpan.FromMinutes(5),
                () =>
                {
                    User user = null;
                    if (request.ID > 0)
                    {
                        user = Db.SingleById<User>(request.ID);
                    }

                    if (request.SteamId > 0)
                    {
                        // user = session.Query<User>().SingleOrDefault(u => u.SteamId == request.SteamId);
                    }

                    return user;
                });
        }
示例#2
0
 public object Post(GetUser request)
 {
     GetUserResponse response=new GetUserResponse();
     response.User= Db.SingleById<UserAuth>(request.Id);
     response.Roles = Db.Select<aspnet_Roles>();
        return response;
 }
        public async Task <ActionResult <UserOutputModel> > Login([FromBody] GetUser model)
        {
            OperationResult <UserOutputModel> authenticationOperation = await Mediator.Send(model);

            if (authenticationOperation.IsSuccessful)
            {
                return(Ok(authenticationOperation.Result));
            }

            return(Errors(authenticationOperation.Errors));
        }
示例#4
0
        /// <summary>
        /// The put.
        /// </summary>
        /// <param name="user">
        /// The user.
        /// </param>
        private void Put(GetUser user)
        {
            // Arrange
            user.Username = RandomGenerator.GetRandomString(10);

            // Act
            var response = Client.PutAsJsonAsync(GetUrRequestUri(user), user).Result;

            // Assert
            Assert.AreEqual(HttpStatusCode.OK, response.StatusCode, "PUT User not OK.");
            Assert.AreEqual(user.Username, Get(user).Username, "PUT User not updated.");
        }
示例#5
0
        public void TestUpdateUser()
        {
            var user = UserBuilder.New().WithId(Guid.Parse("57ffdf20-ea87-4e72-9b80-fa3d77aef2b7")).Build();

            new CreateUser().CreateNewRegister(user);
            var  userCopia  = new GetUser().GetRegisterById(user.Id);
            User userSecond = UserBuilder.New().WithId(Guid.Parse("57ffdf20-ea87-4e72-9b80-fa3d77aef2b7")).Build();

            new UpdateUser().UpdateRegister(userSecond);
            Assert.IsTrue(userCopia.Email.ToString() != userSecond.Email.ToString());
            Assert.IsTrue(userCopia.Id.ToString() == user.Id.ToString() & userCopia.Id.ToString() == userSecond.Id.ToString());
        }
示例#6
0
        public void Get_NonExisting_User()
        {
            var userMock = new Mock <IUserRepository>();

            userMock.Setup(m => m.GetById(It.IsAny <int>())).Returns(() => null);

            IGetUser target = new GetUser(userMock.Object);

            Exception ex = Assert.Throws <ArgumentNullException>(() => target.Invoke(1));

            Assert.True(ex.Message.Contains("Cannot find user with id=1"));
        }
示例#7
0
        public dynamic GetUserList()
        {
            try
            {
                var request = mFactory.CreateRequest();
                request.Resource = string.Format("user/list?apikey={0}", "fghnoxeqrdecu9xyzw0lydeu86izx7824hzp4jlc3awfhvyigk1vhtiqimqknkuv");;
                request.Method   = Method.POST;
                request.AddHeader("Content-Type", "application/json");
                request.RequestFormat = DataFormat.Json;
                request.AddBody(new
                {
                    secretkey = "gtsf6ygej8bqngnjvffqrrowxh6yk0yoqsvrmxavbtxeh3p2izjouikp6y6olgl3"
                });

                var blocker = new AutoResetEvent(false);

                IRestResponse httpResponse = null;
                var           client       = mFactory.CreateClient();
                client.BaseUrl = new Uri("https://api.vsee.com/");
                client.ExecuteAsync(request, response =>
                {
                    httpResponse = response;
                    blocker.Set();
                });
                blocker.WaitOne();

                if (httpResponse != null && (httpResponse.StatusCode == HttpStatusCode.OK || httpResponse.StatusCode == HttpStatusCode.Created))
                {
                    dynamic        list     = (new RestSharp.Deserializers.JsonDeserializer()).Deserialize <dynamic>(httpResponse);
                    List <GetUser> userlist = new List <GetUser>();
                    if (list.Count > 0 && list["data"] != null && list["data"].Count > 0)
                    {
                        for (int i = 0; i < list["data"].Count; i++)
                        {
                            string result = GetURI("", "", list["data"][i]);
                            if (!string.IsNullOrEmpty(result))
                            {
                                GetUser user = new GetUser();
                                user.username = list["data"][i];
                                user.uri      = result;
                                userlist.Add(user);
                            }
                        }
                    }
                    return(userlist);
                }
            }
            catch (Exception ex)
            {
            }
            return(null);
        }
        public void GetById_GetInvalidUser_ObjectNotFoundException()
        {
            // Arrange
            var userRepository = new Mock <IRepositoryAsync <UserEntity> >();
            var getUser        = new GetUser(
                userRepository.Object);

            // Act
            Action act = () => getUser.GetById(_user.Id);

            // Assert
            Assert.Throws <ObjectNotFoundException>(act);
        }
示例#9
0
        public void TestGetAllUser()
        {
            var userPrimeiro = UserBuilder.New().Build();
            var userSecond   = UserBuilder.New().Build();
            var userThird    = UserBuilder.New().Build();

            new CreateUser().CreateNewRegister(userPrimeiro);
            new CreateUser().CreateNewRegister(userSecond);
            new CreateUser().CreateNewRegister(userThird);
            List <User> listUsers = new GetUser().GetAllRegister();

            Assert.IsTrue(listUsers.Count == 3);
        }
 public object Get(GetUser request)
 {
     var dbUser = _userRepo.GetById(request.Id);
     var dbUserRole = _roleRepo.GetById(dbUser.RoleId);
     return new UserDTO
     {
         FullName = dbUser.FullName,
         Id = dbUser.Id,
         UserName = dbUser.UserName,
         RoleId = dbUser.RoleId,
         RoleName = dbUserRole.RoleName
     };
 }
示例#11
0
        public async Task get_user_endpoint_should_return_not_found_when_no_user_with_id_exists()
        {
            var id = new AggregateId();

            var query = new GetUser(id);

            // Check if exception is thrown

            var response = await Act(query);

            response.Should().NotBeNull();
            response.StatusCode.Should().Be(HttpStatusCode.NotFound);
        }
示例#12
0
		public TList<User> GetUser(GetUser request){

			var httpRequest = RequestContext.Get<IHttpRequest>();
					
			var userSession = httpRequest.GetSession();
							
			long? totalCount=null;
				
			var pager= httpRequest.BuildPager();
				
			var visitor = ReadExtensions.CreateExpression<User>();
			var predicate = PredicateBuilder.True<User>();
				
			if (userSession.HasRole(RoleNames.Admin))
			{
				if(request.Id.HasValue && request.Id.Value!=default(int))
					predicate= q=>q.Id==request.Id;

				if(!request.UserName.IsNullOrEmpty()) 
					predicate= q=>q.UserName.StartsWith(request.UserName) ;

				if(userSession.UserName.ToLower()!=RoleNames.Admin.ToLower())
					predicate=predicate.And(q=>q.UserName!=RoleNames.Admin);
					
			}
			else
			{
				var id = int.Parse(userSession.UserAuthId);
				predicate= q=>q.Id==id;
			}
				
			visitor.Where(predicate).OrderBy(r=>r.UserName);


			return AuthRepoProxy.Execute(db=>{

				if(pager.PageNumber.HasValue)
				{
					totalCount=  db.Count(predicate);								
					int rows= pager.PageSize.HasValue? pager.PageSize.Value:Defs.PageSize;
					visitor.Limit(pager.PageNumber.Value*rows, rows);
				}
				
				return new TList<User>(){
					TotalCount=totalCount,
					Result=db.Select(visitor)
				};

			});
		
		}
示例#13
0
        private void GetUserInfo()
        {
            var request = new GetUser();

            GetUser.ResponseParams response;
            try
            {
                response = request.GetResponse(GetApiClient());
            }
            catch (NetworkErrorException)
            {
                _requestErrors++;
                return;
            }
            catch (RequestException)
            {
                return;
            }

            _requestErrors = 0;

            var managementAccount = GetAccount();

            var updateRecord = false;

            if (managementAccount.Subscribed != response.IsSubscribed)
            {
                updateRecord = true;
            }
            else if (managementAccount.InTrial != response.InTrial)
            {
                updateRecord = true;
            }
            else if (managementAccount.TrialEndsAt != response.TrialEndsAt)
            {
                updateRecord = true;
            }

            if (updateRecord)
            {
                Model.ServerManagementAccounts.Update(_managementAccountId, new ServerManagementAccount
                {
                    Subscribed  = response.IsSubscribed,
                    InTrial     = response.InTrial,
                    TrialEndsAt = response.TrialEndsAt
                });

                // Update the parts of the UI that contain management account information.
                _controller.UpdateSubscriptionInfoBar();
            }
        }
        public ActionResult AddUser([FromBody] GetUser data)
        {
            var userlist = db.Users.Where(x => x.Username == data.Username).Select(x => x.Username).FirstOrDefault();

            if (userlist != data.Username && data.Username != null)
            {
                userService.AddUser(data);
                return(Ok());
            }
            else
            {
                return(BadRequest());
            }
        }
        public ActionResult Update(int id)
        {
            if (id <= 0)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            GetUser user = AccountDAO.DetailUser(id);

            if (user == null)
            {
                return(HttpNotFound());
            }
            return(View(user));
        }
示例#16
0
        public object Get(GetUser request)
        {
            var dbUser     = _userRepo.GetById(request.Id);
            var dbUserRole = _roleRepo.GetById(dbUser.RoleId);

            return(new UserDTO
            {
                FullName = dbUser.FullName,
                Id = dbUser.Id,
                UserName = dbUser.UserName,
                RoleId = dbUser.RoleId,
                RoleName = dbUserRole.RoleName
            });
        }
示例#17
0
        private void btGiaoVien_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            frmGiaovien f = new frmGiaovien();

            if (ExistForm(f))
            {
                return;
            }
            GetUser g = new GetUser(f.SaveU);

            g(User);
            f.MdiParent = this;
            f.Show();
        }
示例#18
0
        private void btnHocSinh_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            frmHocsinh form = new frmHocsinh();

            if (ExistForm(form))
            {
                return;
            }
            GetUser g = new GetUser(form.SaveU);

            g(User);
            form.MdiParent = this;
            form.Show();
        }
示例#19
0
        public void ReturnUserTest_output_list()
        {
            // Arrange
            var users      = new GetUser();
            var repository = new Mock <RepositoryUserEF>();

            repository.Setup(arg => arg.GetAll()).Returns(new List <User>());
            users.user = repository.Object;

            // Act
            var resultCollection = users.ReturnUser();

            // Assert
            Assert.IsNotNull(resultCollection);
        }
示例#20
0
        public GetUser delete(string t11)
        {
            UpdateDal d   = new UpdateDal();
            GetUser   bus = new GetUser();

            try
            {
                bus = d.delete(t11);
            }
            catch
            {
                throw;
            }
            return(bus);
        }
示例#21
0
        public Users()
        {
            InitializeComponent();

            context = new Context();
            db      = new RepositoryUserEF();

            db.db.Resourses.Load();
            getUsr = new GetUser();
            UPDATE();



            this.Closing += MainWindow_Closing;
        }
        List <WrenchCheckOut> getshowdata(List <torquechecktarget> torquetargetlist)
        {
            GetUser gu = new GetUser();
            List <WrenchCheckOut> tempwcolist = new List <WrenchCheckOut>();

            if (torquetargetlist == null)
            {
                return(tempwcolist);
            }
            foreach (torquechecktarget t in torquetargetlist)
            {
                userinfo juser = new userinfo();
                userinfo zuser = new userinfo();
                juser = gu.getuserinfo(gu.getusers(t.operatorID));
                if (juser == null || juser.user == null)
                {
                    users jusers = new users();
                    jusers.username = t.operatorID;
                    juser.user      = jusers;
                    department d = new department();
                    d.departmentName = t.operatorID;
                    juser.department = d;
                }
                if (!string.IsNullOrEmpty(t.qaID))
                {
                    zuser = gu.getuserinfo(gu.getusers(t.qaID));
                }
                wrench tempw = Wrench.selectByguid(t.wrenchID);

                tempwcolist.Add(new WrenchCheckOut()
                {
                    wrenchcode        = tempw.wrenchCode,
                    wrenchbarcode     = tempw.wrenchBarCode,
                    jusername         = (juser == null || juser.user == null)?"":juser.user.username,
                    zusername         = (zuser == null || zuser.user == null)?"":zuser.user.username,
                    juserinfo         = juser,
                    zuserinfo         = zuser,
                    torquetargetvalue = t.torqueTargetValue.ToString(),
                    errorrange        = (t.torqueTargetValue * (1 + Convert.ToDecimal(t.errorRangeMin))).ToString("f2") + "~" + (t.torqueTargetValue * (1 + Convert.ToDecimal(t.errorRangeMax))).ToString("f2"),
                    errormax          = Convert.ToDecimal(t.errorRangeMax).ToString("f4"),
                    errormin          = Convert.ToDecimal(t.errorRangeMin).ToString("f4"),
                    is_good           = t.is_good,
                    checkdate         = t.checkDate.ToString().Replace('T', ' '),
                    guid = t.guid
                });
            }
            return(tempwcolist);
        }
示例#23
0
        public List <GetUser> FindUserByUserToken(string token)
        {
            List <DbUser> dbUserList = _userRepository.FindUserByUserToken(token);
            var           userList   = new List <GetUser>();

            foreach (DbUser a in dbUserList)
            {
                var user = new GetUser();
                user.UserID = a.LoginId;
                user.Name   = a.Name;
                //user.Password = a.Password;
                user.CityName = a.CityName;
                userList.Add(user);
            }
            return(userList);
        }
        public void GetByPagination_GetUsersIfIndexLessZero_InvalidOperationException()
        {
            // Arrange
            var userRepository = new Mock <IRepositoryAsync <UserEntity> >();

            var getUser = new GetUser(
                userRepository.Object);

            int invalidIndex = -1;

            // Act
            Action act = () => getUser.GetByPagination(invalidIndex);

            // Assert
            Assert.Throws <InvalidOperationException>(act);
        }
示例#25
0
        static void Main(string[] args)
        {
            var container = CreateContainer();

            using (var scope = container.CreateChildContainer())
            {
                var dispatcher = scope.Resolve<IQueryDispatcher>();

                var query = new GetUser(1);
                var user = dispatcher.Execute(query);

                Console.WriteLine("Hello {0}.", user.DisplayName);
            }

            Console.ReadLine();
        }
示例#26
0
        public void Get_User()
        {
            var userMock = new Mock <IUserRepository>();

            userMock.Setup(m => m.GetById(It.IsAny <int>())).Returns(new User
            {
                Id    = 1,
                Login = "******"
            });
            IGetUser target = new GetUser(userMock.Object);

            var result = target.Invoke(1);

            Assert.NotNull(result);
            Assert.True(result.Id == 1);
            Assert.True(result.Login == "user1");
        }
        public async Task get_user_query_should_return_null_when_user_does_not_exist()
        {
            var id = Guid.NewGuid();

            var query = new GetUser(id);

            // Check if exception is thrown

            var requestResult = _queryHandler
                                .Awaiting(c => c.HandleAsync(query));

            requestResult.Should().NotThrow();

            var result = await requestResult();

            result.Should().BeNull();
        }
示例#28
0
        public static BaseHelper GetUserList(Model.GetUserList data)
        {
            var retVal      = new BaseHelper();
            var objJSONPage = new Output.GetUserList();

            try
            {
                var entityPage = GetUser.GetUserList(data, objJSONPage);
                if (objJSONPage.ResultCode == 1)
                {
                    retVal.SQLElapsed += entityPage.SQLElapsed;
                    retVal.SQLInfo($"sp : {entityPage.SQLDetail}, elapsed : {entityPage.SQLElapsed}");

                    retVal.IsError = (entityPage.ResultCode == 1) ? false : true;
                }
                else
                {
                    objJSONPage.ResultCode   = objJSONPage.ResultCode;
                    objJSONPage.ErrorMessage = objJSONPage.ErrorMessage;
                }
            }
            catch (Exception ex)
            {
                retVal.Exception = ex;

                if (ex is System.Data.SqlClient.SqlException sqlEx)
                {
                    retVal.SQLInfo($"sp:{sqlEx.Procedure}, line:{sqlEx.LineNumber}, detail:{data.SqlDetail}");
                    retVal.SQLException = true;

                    objJSONPage.ResultCode   = 69998;
                    objJSONPage.ErrorMessage = "SQL Exception";
                }
                else
                {
                    objJSONPage.ResultCode   = 69999;
                    objJSONPage.ErrorMessage = "Unknown Error";
                }
            }
            finally
            {
                retVal.SerializeObject <Output.GetUserList>(objJSONPage);
            }

            return(retVal);
        }
示例#29
0
        public async Task <Result <UserModel> > Handle(GetUser request, CancellationToken cancellationToken)
        {
            var isValid = await _validator.IsValidAsync(request);

            if (!isValid)
            {
                return(Result.Failure <UserModel>("Validation failed"));
            }

            var user = await _context.Users.Where(x => x.Sub == request.UserSub).FirstAsync(cancellationToken);

            return(new UserModel
            {
                FirstName = user.FirstName,
                LastName = user.LastName
            });
        }
示例#30
0
        /// <summary>
        /// The post.
        /// </summary>
        /// <param name="item">
        /// The item.
        /// </param>
        /// <returns>
        /// The <see cref="HttpResponseMessage"/>.
        /// </returns>
        /// <remarks>
        /// POST users
        /// </remarks>
        public HttpResponseMessage Post(PostUser item)
        {
            var user = new User()
            {
                Username = item.Username,
                Password = EncryptedString.Create(item.Password, _encryptionService)
            };

            if (user.IsValid)
            {
                _userDataMapper.Insert(user);

                GetUser createdItem = _mapper.Map <User, GetUser>(user);
                return(CreatedHttpResponse(createdItem.ID, createdItem));
            }

            return(Request.CreateResponse(HttpStatusCode.BadRequest, user.ValidationErrors));
        }
示例#31
0
        public object Get(GetUser userById)
        {
            var  documentStore = this.ResolveService <IDocumentStore>();
            User loadedUser;

            var log = this.CreateLog(
                ActivityLog.LoggedActivities.Read,
                userById.Id);

            using (var session = documentStore.OpenSession())
            {
                loadedUser = session.Load <User>(userById.Id);
                session.Store(log);
                session.SaveChanges();
            }

            return(loadedUser);
        }
示例#32
0
        public void GetByPagination_GetUsers_Users()
        {
            // Arrange
            var userRepository = new Mock <IRepositoryAsync <UserEntity> >();

            var getUser = new GetUser(
                userRepository.Object);

            userRepository.Setup(r => r.GetAll())
            .Returns(_users.AsQueryable());

            // Act
            var result = getUser.GetByPagination(0);

            // Assert
            Assert.NotNull(result);
            Assert.Equal(_users, result);
        }
示例#33
0
        public void TestRetrieve_Success()
        {
            string actualUserId    = string.Empty;
            string actualFirstName = string.Empty;

            Mock <IDynamoDBContext> context = new Mock <IDynamoDBContext>();

            context.Setup(D => D.LoadAsync <WeighInUser>(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <CancellationToken>())).Returns((string a, string b, object c) =>
            {
                actualUserId     = a;
                actualFirstName  = b;
                WeighInUser user = new WeighInUser()
                {
                    UserId             = a,
                    FirstName          = b,
                    UserKey            = "TestKey",
                    StartingWeight     = 88.8m,
                    StartingWeightDate = new DateTime(2018, 7, 16)
                };
                return(Task.FromResult <WeighInUser>(user));
            });

            TestAwsFactory factory = new TestAwsFactory()
            {
                DynamoDBContext = context.Object
            };

            using (GetUser getUser = new GetUser(factory))
            {
                string jsonResult = getUser.Retrieve("UnitTestId", "Unit");

                Console.WriteLine(jsonResult);

                Assert.That(actualUserId, Is.EqualTo("UnitTestId"), "actualUserId");
                Assert.That(actualFirstName, Is.EqualTo("Unit"), "actualFirstName");

                dynamic user = JObject.Parse(jsonResult);
                Assert.That((string)user.UserId, Is.EqualTo("UnitTestId"), "UserId");
                Assert.That((string)user.FirstName, Is.EqualTo("Unit"), "FirstName");
                Assert.That((string)user.UserKey, Is.EqualTo("TestKey"), "UserKey");
                Assert.That((decimal)user.StartingWeight, Is.EqualTo(88.8m), "StartingWeight");
                Assert.That((DateTime)user.StartingWeightDate, Is.EqualTo(new DateTime(2018, 7, 16)), "StartingWeightDate");
            }
        }
示例#34
0
        public void GetByEmail_GetUser_User()
        {
            // Arrange
            var userRepository = new Mock <IRepositoryAsync <UserEntity> >();

            var getUser = new GetUser(
                userRepository.Object);
            var usersQueryable = _users.AsQueryable();

            userRepository.Setup(r => r.GetAll())
            .Returns(usersQueryable);

            // Act
            var result = getUser.GetByEmail(_users.ElementAt(0).Email);

            // Assert
            Assert.NotNull(result);
            Assert.Equal(_users.ElementAt(0).Email, result.Email);
        }
示例#35
0
        public void GetAll_GetAllUsers_Users()
        {
            // Arrange
            var userRepository = new Mock <IRepositoryAsync <UserEntity> >();
            var getUser        = new GetUser(
                userRepository.Object);

            userRepository.Setup(r => r.GetAll())
            .Returns(_users.AsQueryable());

            // Act
            var result = getUser.GetAll();

            // Assert
            Assert.NotNull(result);
            Assert.Equal(_users, result);
            Assert.Equal("Name1", result.ElementAt(0).Name);
            Assert.Equal("Name2", result.ElementAt(1).Name);
        }
示例#36
0
        private void GetServersFromServerManagement(string recoveryPassword)
        {
            var serverManagement = GetServerManagementAccount();
            if (serverManagement == null)
                return;

            var apiClient = GetApiClientForServerManagement();

            GetUser.ResponseParams response;
            try
            {
                response = new GetUser().GetResponse(apiClient);
            }
            catch (RequestException)
            {
                if (Program.AppEnvDebug)
                    throw;

                MessageBox.Show(@"There was an error communicating with the server. " +
                    @"If this does not automatically rectify soon, please contact support.");
                return;
            }

            if (response.Servers.Count == 0)
                return;

            if (response.Servers.Count > 1)
                throw new NotImplementedException("Multiple server import is not yet supported");

            var server = response.Servers[0];

            var newServerAccount = new ServerAccount
            {
                Managed = true,
                ServerIdentifier = server.Identifier,
                ServerLabel = server.Label,
                HttpsEnabled = server.HttpsEnabled,
                ServerHost = server.Hostname,
                ServerPort = server.Port,
                ServerApiVersion = server.ApiVersion,
                EmailAddress = serverManagement.EmailAddress
            };

            var existingServer = Model.ServerAccounts.Find(new ServerAccount
            {
                ServerIdentifier = newServerAccount.ServerIdentifier,
                EmailAddress = newServerAccount.EmailAddress
            }).FirstOrDefault();
            
            if (existingServer != null)
            {
                // We probably logged out of the management server and logged back in.
                Model.ServerAccounts.Update(existingServer.Id, new ServerAccount {Managed = true});
                return;
            }
            
            // New server account
            LoginToServer(newServerAccount, recoveryPassword);
        }
示例#37
0
		public BLResponse<User> Get (GetUser request)
		{
			return Post (request);
		}
示例#38
0
		public BLResponse<User> Post ( GetUser request)
		{
			return  Controller.GetUser(request, BLRequest);
		}
示例#39
0
        private void GetUserInfo()
        {
            var request = new GetUser();
            GetUser.ResponseParams response;
            try
            {
                response = request.GetResponse(GetApiClient());
            }
            catch (NetworkErrorException)
            {
                _requestErrors++;
                return;
            }
            catch (RequestException)
            {
                return;
            }

            _requestErrors = 0;

            var managementAccount = GetAccount();

            var updateRecord = false;
            if (managementAccount.Subscribed != response.IsSubscribed)
            {
                updateRecord = true;
            }
            else if (managementAccount.InTrial != response.InTrial)
            {
                updateRecord = true;
            }
            else if (managementAccount.TrialEndsAt != response.TrialEndsAt)
            {
                updateRecord = true;
            }

            if (updateRecord)
            {
                Model.ServerManagementAccounts.Update(_managementAccountId, new ServerManagementAccount
                {
                    Subscribed = response.IsSubscribed,
                    InTrial = response.InTrial,
                    TrialEndsAt = response.TrialEndsAt
                });

                // Update the parts of the UI that contain management account information.
                _controller.UpdateSubscriptionInfoBar();
            }
        }
示例#40
0
        private void RegisterServerComplete(string registrationIdentifier, string clientToken, 
            string recoveryPasswordPlaintext)
        {
            var managementAccount = GetServerManagementAccount();
            var managementApiClient = GetApiClientForServerManagement();

            var serversRequest = new GetUser();
            GetUser.ResponseParams serversResponse;
            try
            {
                serversResponse = serversRequest.GetResponse(managementApiClient);
            }
            catch (RequestException)
            {
                if (Program.AppEnvDebug) throw;

                MessageBox.Show(@"There was an error downloading the required information to setup your account.");
                return;
            }

            if (serversResponse.Servers.Count != 1)
            {
                if (Program.AppEnvDebug) throw new Exception ("Unsupported number of servers for user");

                MessageBox.Show(@"There was an error downloading the required information to setup your account.");
                return;
            }

            var server = serversResponse.Servers[0];
            var serverApiClient = new ServerAPI.ApiClient(
                server.HttpsEnabled, server.Hostname, server.Port, server.ApiVersion);
            var newKeypair = AsymmetricCryptoUtil.GenerateKeyPair();
            var registerRequest = new ServerAPI.Requests.Unauthenticated.RegisterComplete
            {
                RegisterRequestIdentifier = registrationIdentifier,
                ClientToken = clientToken,
                DeviceLabel = "My Desktop App",
                DeviceType = "desktop",
                DeviceSubtype = "windows",
                PublicKeyPem = newKeypair.PublicPem,
                RecoveryPasswordClientHash = HashUtil.GenerateServerRecoveryPasswordHash(
                    managementAccount.EmailAddress, recoveryPasswordPlaintext)
            };

            ServerAPI.Requests.Unauthenticated.RegisterComplete.ResponseParams registerResponse;
            try
            {
                registerResponse = registerRequest.GetResponse(serverApiClient);
            }
            catch (RequestException e)
            {
                if (Program.AppEnvDebug)
                    throw new Exception("Unexpected network error", e);

                MessageBox.Show(@"There was an error downloading the required information to setup your account.");
                return;
            }

            var cryptoKeyId = Model.CryptoKeys.Create(new CryptoKey
            {
                OwnKey = true,
                Trust = true,
                PrivateKeyPem = newKeypair.PrivatePem,
                PublicKeyPem = newKeypair.PublicPem
            });
            var newServer = new ServerAccount
            {
                Managed = true,
                HttpsEnabled = server.HttpsEnabled,
                ServerIdentifier = server.Identifier,
                ServerLabel = server.Label ?? "",
                ServerHost = server.Hostname,
                ServerPort = server.Port,
                ServerApiVersion = server.ApiVersion,
                UserIdentifier = registerResponse.UserIdentifier,
                DeviceIdentifier = registerResponse.DeviceIdentifier,
                EmailAddress = managementAccount.EmailAddress,
                ApiKey = registerResponse.ApiKey,
                CryptoKeyId = cryptoKeyId,
                BackupEncryptionPassword =
                    HashUtil.GenerateDatabaseBackupPasswordHash(managementAccount.EmailAddress, recoveryPasswordPlaintext)
            };
            var newServerAccountId = Model.ServerAccounts.Create(newServer);
            newServer.Id = newServerAccountId;

            //var serverApiClientAuthenticated = new ServerAPI.ApiClient(server.HttpsEnabled,
            //    server.Hostname, server.Port, server.ApiVersion, registerResponse.ApiKey, newKeypair.PrivatePem);

            /*var deviceRegisterRequest = new InitiateDeviceLogin();
            InitiateDeviceLogin.ResponseParams deviceRegisterResponse;
            try
            {
                deviceRegisterResponse = deviceRegisterRequest.GetResponse(serverApiClientAuthenticated);
            }
            catch (RequestException)
            {
                if (Program.AppEnvDebug) throw;

                MessageBox.Show(@"There was an unknown error registering mobile device with the server");
                return;
            }
            
            var linkCode = new LinkCodeRegisterInitialOtpDevice(newServer.HttpsEnabled,
                newServer.ServerHost, newServer.ServerPort, newServer.ServerApiVersion,
                deviceRegisterResponse.LoginRequestIdentifier, newServer.EmailAddress, HashUtil.Sha256(newKeypair.PublicPem));

            using (var form = new SetupOtpDeviceLink(this, linkCode.ToString(), newServer,
                deviceRegisterResponse.LoginRequestIdentifier))
            {
                form.ShowDialog();
                if (!form.Success)
                {
                    MessageBox.Show(@"Link to second device was not established.");
                    return;
                }
            }*/
            
            // We need to verify the new keys with the second device.
            /*var publicKeyHash = HashUtil.Sha256(newKeypair.PublicPem);
            RequestKeyVerification.ResponseParams verificationResponse;
            try
            {
                verificationResponse = new RequestKeyVerification().GetResponse(serverApiClientAuthenticated);
            }
            catch (RequestException)
            {
                if (Program.AppEnvDebug) throw;

                MessageBox.Show(@"There was an error verifying keys with your mobile device.");
                return;
            }

            using (var form = new VerifyKeyOnSecondDevice(
                this, newServerAccountId, publicKeyHash, verificationResponse.MessageIdentifier))
            {
                form.ShowDialog();
                if (!form.Success)
                {
                    MessageBox.Show(
                        @"Could not verify encryption keys with device.\r\n\r\n" +
                        @"You will encounter a lack of functionality until this has been completed.");
                }
            }*/

//            // TODO: Verify the linked device key properly.
//            GetLinkedDevice.ResponseParams linkedDeviceResponse;
//            try
//            {
//                linkedDeviceResponse = new GetLinkedDevice().GetResponse(serverApiClientAuthenticated);
//            }
//            catch (RequestException)
//            {
//                if (Program.AppEnvDebug) throw new Exception("Error getting linked device info");
//
//                MessageBox.Show(@"There was an error verifying mobile device key.");
//                return;
//            }
//             
//            var linkedDeviceCryptoKeyId = Model.CryptoKeys.Create(new CryptoKey
//            {
//                Trust = true,
//                PublicKeyPem = linkedDeviceResponse.PublicKeyPem
//            });
//            Model.ServerAccounts.Update(newServerAccountId, new ServerAccount
//            {
//                LinkedDeviceCryptoKeyId = linkedDeviceCryptoKeyId
//            });


//            ServerAPI.GetUserResponse userInfoResponse;
//            try
//            {
//                userInfoResponse = serverApiClientAuthenticated.GetUser(new ServerAPI.GetUserRequest());
//            }
//            catch (RequestException e)
//            {
//                if (Program.AppEnvDebug)
//                    throw new Exception("Unexpected error getting user info", e);
//
//                MessageBox.Show(@"There was an error retrieving server information.");
//                return;
//            }

            // We can't do this yet. The server sends this to the second device as it is right now,
            // which hasn't been set.
            //if (userInfoResponse.Links.Count == 0)
            //    NewDatabase("My Database", newServerAccountId);

            if (!_syncServers.ContainsKey(newServerAccountId))
            {
                _syncServers.Add(newServerAccountId, new Sync(this, newServerAccountId));
                _syncServers[newServerAccountId].Start();
            }

            UpdateHomePage();
        }
		public BLResponse<User> GetUser(GetUser request, BLRequest blRequest){
			return Client.Execute(proxy=>{
				var u= Users.FirstOrDefault(proxy, f=>f.Id==request.Id);
				if( u==default(User))
					throw new BLException("User not found. Id:'{0}'".Fmt(request.Id));

				var r = new BLResponse<User>();
				if(!IsCayita(blRequest)) r.Result.Add(u);
				else
				{
					var grid = BuildUserGrid(new List<User>());
					var dr =grid.CreateRow(u);
					r.Html= dr.ToString();
				}
				return r;
			});
		}
 /// <summary>
 /// Inits the connection.
 /// </summary>
 /// <param name="login">The login.</param>
 /// <param name="password">The password.</param>
 /// <param name="server">The server.</param>
 /// <param name="serverPort">The server port.</param>
 /// <param name="version">The version.</param>
 /// <param name="uniqId">The uniq id.</param>
 /// <param name="format">The format.</param>
 /// <returns></returns>
 /// <exception cref="SubsonicWS.Exceptions.InvalidUserNameOrPasswordException"></exception>
 public static async Task initConnection(String login, String password, String server, String serverPort, String version, String uniqId, String format = "")
 {
     if (instance == null)
     {
         instance = new ConnectionInformations()
         {
             Login = login,
             Password = password,
             Server = server,
             ServerPort = serverPort,
             Version = version,
             UniqId = uniqId,
             Format = format,
             instanceIsInit = true
         };
     }
     else
     {
         instance.Login = login;
         instance.Password = password;
         instance.Server = server;
         instance.ServerPort = serverPort;
         instance.Version = version;
         instance.UniqId = uniqId;
         instance.Format = format;
         instance.instanceIsInit = true;
     }
     GetUser u = new GetUser();
     try
     {
         await u.Request(login);
     }
     catch (Exceptions.ResponseStatusFailedException e)
     {
         if (e.error.Code == 40)
             throw new Exceptions.InvalidUserNameOrPasswordException(e.error.Message);
         else if (e.error.Code == 60)
             throw new Exceptions.TrialPeriodeEndedException(e.error.Message);
         else
             throw e;
     }
 }