public void Get_Called_ReturnsUserResponse()
        {
            // Given
            var response = new UserResponse { Item = new User { Id = 1 } };
            _client.Setup(b => b.Get<UserResponse>(It.IsAny<Uri>())).Returns(response);
            var userResource = new UserResource(_client.Object);

            // When
            var result = userResource.Get(4321);

            // Then
            Assert.That(result, Is.EqualTo(response));
        }
Пример #2
0
 private void Notification_FormClosing(object sender, FormClosingEventArgs e)
 {
     if (this.Response == UserResponse.NoResponse)
     {
         if (this.DetectionType == Core.DetectionType.Critical)
         {
             this.Response = UserResponse.OK;
         }
         else if (this.DetectionType == Core.DetectionType.Warning)
         {
             e.Cancel = true;
         }
     }
 }
        public async Task UserTests(bool directMode)
        {
            CosmosClient     client     = directMode ? DirectCosmosClient : GatewayCosmosClient;
            DatabaseInternal database   = (DatabaseInlineCore)client.GetDatabase(DatabaseId);
            List <string>    createdIds = new List <string>();

            try
            {
                UserResponse userResponse = await database.CreateUserAsync("BasicQueryUser1");

                createdIds.Add(userResponse.User.Id);

                userResponse = await database.CreateUserAsync("BasicQueryUser2");

                createdIds.Add(userResponse.User.Id);

                userResponse = await database.CreateUserAsync("BasicQueryUser3");

                createdIds.Add(userResponse.User.Id);

                //Read All
                List <UserProperties> results = await this.ToListAsync(
                    database.GetUserQueryStreamIterator,
                    database.GetUserQueryIterator <UserProperties>,
                    null,
                    CosmosBasicQueryTests.RequestOptions
                    );

                CollectionAssert.IsSubsetOf(createdIds, results.Select(x => x.Id).ToList());

                //Basic query
                List <UserProperties> queryResults = await this.ToListAsync(
                    database.GetUserQueryStreamIterator,
                    database.GetUserQueryIterator <UserProperties>,
                    "select * from T where STARTSWITH(T.id, \"BasicQueryUser\")",
                    CosmosBasicQueryTests.RequestOptions
                    );

                CollectionAssert.AreEquivalent(createdIds, queryResults.Select(x => x.Id).ToList());
            }
            finally
            {
                foreach (string id in createdIds)
                {
                    await database.GetUser(id).DeleteAsync();
                }
            }
        }
Пример #4
0
        public async Task <Response> GetUserByEmail(
            string urlBase,
            string servicePrefix,
            string controller,
            string tokenType,
            string accessToken,
            EmailRequest request)
        {
            try
            {
                string        requestString = JsonConvert.SerializeObject(request);
                StringContent content       = new StringContent(requestString, Encoding.UTF8, "application/json");
                HttpClient    client        = new HttpClient
                {
                    BaseAddress = new Uri(urlBase)
                };

                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(tokenType, accessToken);
                string url = $"{servicePrefix}{controller}";
                HttpResponseMessage response = await client.PostAsync(url, content);

                string result = await response.Content.ReadAsStringAsync();

                if (!response.IsSuccessStatusCode)
                {
                    return(new Response
                    {
                        IsSuccess = false,
                        Message = result,
                    });
                }

                UserResponse userResponse = JsonConvert.DeserializeObject <UserResponse>(result);
                return(new Response
                {
                    IsSuccess = true,
                    Result = userResponse
                });
            }
            catch (Exception ex)
            {
                return(new Response
                {
                    IsSuccess = false,
                    Message = ex.Message
                });
            }
        }
Пример #5
0
        //[Authorize(Roles="admin")]
        public JsonResult Register([FromBody] UserResponse user, [FromQuery] string role, [FromQuery] string to)
        {
            if (!(new[] { "admin", "organizer", "volunteer" }).ToList().Contains(role))
            {
                return(new JsonResult(new { status = "failed" }));
            }

            var claims = new Claim[]
            {
                new Claim("user", JsonConvert.SerializeObject(user)),
                new Claim("role", role)
            };
            var signingKey = configuration["SECRETKEY"];
            var tokenData  = new JwtSecurityToken(
                issuer: "cinnabuns-register",
                claims: claims,
                notBefore: DateTime.Now,
                expires: DateTime.Now.AddHours(72),
                signingCredentials: new SigningCredentials(
                    new SymmetricSecurityKey(Encoding.UTF8.GetBytes(signingKey)),
                    SecurityAlgorithms.HmacSha256));
            var token = new JwtSecurityTokenHandler().WriteToken(tokenData);

            var pass = GeneratePassword();
            var url  = string.Format("http://best-hack.prod.kistriver.net/api/auth/signup/{0}?password={1}",
                                     token, pass);

            MailMessage mail   = new MailMessage(configuration["MAILFROM"], to);
            SmtpClient  client = new SmtpClient();

            client.Port                  = Int32.Parse(configuration["MAILPORT"]);
            client.EnableSsl             = true;
            client.DeliveryMethod        = SmtpDeliveryMethod.Network;
            client.UseDefaultCredentials = false;
            client.Host                  = configuration["MAILHOST"];
            client.Timeout               = 5000;
            client.Credentials           = new System.Net.NetworkCredential(configuration["MAILFROM"], configuration["MAILPASS"]);
            mail.BodyEncoding            = UTF8Encoding.UTF8;
            mail.Subject                 = "Регистрация";
            mail.Body       = string.Format("Ссылка для регистрации: <a href='{0}'>{0}</a>. ", url);
            mail.Body       = string.Format("Ссылка для регистрации: <a href='{0}'>{0}</a>. Пароль: {1}", url, pass);
            mail.IsBodyHtml = true;
            client.Send(mail);

            return(new JsonResult(new {
                token = url
            }));
        }
        public async Task <object> Register(UserViewModel userViewModel)
        {
            object result = null;

            try
            {
                User user = mapper.Map <User>(userViewModel);

                //if user by this username Not exist continue
                if (!CheckUserExist(userViewModel.UserName))
                {
                    #region password hash
                    byte[] passwordHash, passwordSalt;

                    Utils.CreatePasswordHash(userViewModel.Password, out passwordHash, out passwordSalt);

                    user.PasswordHash = passwordHash;
                    user.PasswordSalt = passwordSalt;
                    #endregion



                    sqlDataContextcs.User.Add(user);

                    await sqlDataContextcs.SaveChangesAsync();

                    result = new UserResponse {
                        Message  = "Ok", Code = StatusCodes.Status200OK,
                        UserName = userViewModel.UserName,
                        Token    = GenerateToken(userViewModel.UserName)
                    };
                }
                else
                {
                    result = new UserResponse {
                        Message = "Duplicated", Code = StatusCodes.Status302Found
                    };
                }
            }
            catch (Exception ex)
            {
                result = new UserResponse {
                    Message = ex.Message,
                    Code    = StatusCodes.Status500InternalServerError
                };
            }
            return(result);
        }
Пример #7
0
        public UserResponse Register(User user)
        {
            _context.Users.Add(user);
            _context.SaveChanges();
            var u  = GetById(user.Id);
            var ur = new UserResponse
            {
                Id       = u.Id,
                Username = u.Username,
                Email    = u.Email,
                Name     = u.Name,
                Roles    = u.UserRoles.Select(x => x.Role.RoleName).ToArray()
            };

            return(ur);
        }
Пример #8
0
        //public async ServiceResponse DeleteUser(int id)
        //{
        //    try
        //    {
        //        var user = await _userManager.FindByIdAsync(id);
        //        if (user == null)
        //            return new ServiceResponse
        //            {
        //                ResponseMessage = "Unable to get user.",
        //                StatusCode = HttpStatusCode.NotFound
        //            };

        //        var result = await _userManager.DeleteAsync(user);
        //        if (!result.Succeeded)
        //            return new ServiceResponse
        //            {
        //                ResponseMessage = "Unable to delete user.",
        //                StatusCode = HttpStatusCode.InternalServerError
        //            };

        //        return new ServiceResponse
        //        {
        //            StatusCode = HttpStatusCode.OK
        //        };
        //    }
        //    catch (Exception ex)
        //    {
        //        //TODO log errors
        //        return new ServiceResponse
        //        {
        //            StatusCode = HttpStatusCode.InternalServerError,
        //            ResponseMessage = "Unhandled error."
        //        };
        //    }
        //}

        //public ServiceResponse<IEnumerable<UserResponse>> Read()
        //{
        //    List<User> users = new List<User>();
        //    using (DiaryContext db = new DiaryContext())
        //    {
        //        users = db.Users.Include(x => x.Diaries).Include(x => x.UserDetails).ToList();
        //    }
        //    List<UserResponse> userResponses = new List<UserResponse>();
        //    foreach (var item in users)
        //    {
        //        userResponses.Add(new UserResponse(item));
        //    }
        //    return new ServiceResponse<IEnumerable<UserResponse>>(userResponses, HttpStatusCode.OK, "Table downloaded!");
        //}

        public ServiceResponse <UserResponse> ReadById(int id)
        {
            User user;

            using (DiaryContext db = new DiaryContext())
            {
                if (!db.Users.Any(x => x.Id == id))
                {
                    return(new ServiceResponse <UserResponse>(null, HttpStatusCode.NotFound, "There is not existing user with given id!"));
                }
                user = db.Users.Include(x => x.Diaries).Include(x => x.UserDetails).FirstOrDefault(x => x.Id == id);
            }
            UserResponse userResponse = new UserResponse(user);

            return(new ServiceResponse <UserResponse>(userResponse, HttpStatusCode.OK, "User downloaded!"));
        }
        public UserResponse Auth(AuthRequest model)
        {
            UserResponse UsrResp = new UserResponse();

            using (var db = new MVC_SEGURIDADContext()) {
                string spwd    = Encript.GetSHA256(model.password);
                var    usuario = db.Usuarios.Where(d => d.Email == model.Email &&
                                                   d.Pwd == spwd).FirstOrDefault();

                if (usuario != null)
                {
                    UsrResp.Email = usuario.Email;
                }
            }
            return(UsrResp);
        }
Пример #10
0
        public async Task <IActionResult> DeleteAsync(string id, string username)
        {
            var user = await _userManager.FindByIdAsync(id);

            if (user == null || user.UserName != username)
            {
                return(BadRequest());
            }
            var response = new UserResponse();

            response.Result = await _userManager.DeleteAsync(user);

            response.Succeeded = response.Result.Succeeded;

            return(Ok(response));
        }
Пример #11
0
        public async void GetOneUserAsAdminTest()
        {
            // add user to database
            await this.userRepository.CreateAsync(UserFactory.CreateNormalUser(1000));

            HttpRequest request = HttpRequestFactory.CreateGetRequest();

            ObjectResult result = (ObjectResult)await this.userController.UsersGet(request, 1000, this.adminClaim);

            UserResponse user = (UserResponse)result.Value;

            // status code should be 200 OK
            Assert.Equal(200, result.StatusCode);
            // check if the right user was found
            Assert.Equal(1000, user.Id);
        }
Пример #12
0
        /// <summary>
        /// get all user list
        /// </summary>
        /// <returns>Task<UserResponse></returns>
        public async Task <UserResponse> GetAllAsync()
        {
            IEnumerable <User> user = await _userRepository.GetAllAsync();

            var response = new UserResponse();

            if (user.ToList().Count == 0)
            {
                response.Message = "Kayıt bulunamadı !";
            }
            else
            {
                response.Users.AddRange(user);
            }
            return(response);
        }
Пример #13
0
        public async Task <IActionResult> GetMe()
        {
            var userName     = User.Identity.Name;
            var identityUser = await _userManager.FindByNameAsync(userName);

            var userData = new UserResponse
            {
                Email            = identityUser.Email,
                FirstName        = identityUser.FirstName,
                LastName         = identityUser.LastName,
                ProfilePhoto     = identityUser.ProfilePhoto,
                RegisteredOffice = identityUser.RegisteredOffice
            };

            return(Ok(userData));
        }
Пример #14
0
        public IActionResult GetUser()
        {
            IEnumerable <Claim> claims = User.Claims;
            string userId = claims.Where(c => c.Type == ClaimTypes.NameIdentifier).First().Value;

            UserResponse userResponse = userService.FindById(int.Parse(userId));

            if (userResponse.Success)
            {
                return(Ok(userResponse.user));
            }
            else
            {
                return(BadRequest(userResponse.Message));
            }
        }
        public async Task <UserResponse> GetUserInfo(SlackIntegrationEntity slackIntegrationEntity)
        {
            UserResponse userResponse = null;
            var          query        = HttpUtility.ParseQueryString(string.Empty);

            query["token"] = slackIntegrationEntity.SlackToken;
            query["user"]  = slackIntegrationEntity.SlackUserId;
            var response = await Client.GetAsync($"/api/users.info?{query.ToString()}");

            response.EnsureSuccessStatusCode();
            var responseString = await response.Content.ReadAsStringAsync();

            userResponse = JsonConvert.DeserializeObject <UserResponse>(responseString);

            return(userResponse);
        }
Пример #16
0
        public IActionResult CheckAuth([FromBody] AccKeys keys)
        {
            try
            {
                //AccKeys keys = (AccKeys)JsonConvert.DeserializeObject(fromBody);
                //認証
                Tokens newTokens = Tokens.Create(ConsumerKey, ConsumerSecret, keys.AccessToken, keys.AccessTokenSecret);

                UserResponse ur = newTokens.Account.VerifyCredentials();
                return(Ok(ur.ScreenName));
            }
            catch (Exception e)
            {
                return(BadRequest(e));
            }
        }
Пример #17
0
        private async void SetStatusToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var title = $"Set Status";
            // var result = UI.Utils.InputBox(title, "Message:", ref message, true);
            // if (result != DialogResult.OK) return;
            var message = UI.MultilineInput.Get(title, me.statusDescription);

            if (string.IsNullOrWhiteSpace(message) || message == me.statusDescription)
            {
                return;
            }
            me = await vrcapi.UserApi.UpdateInfo(userId : me.id, status : me.status, statusDescription : message);

            FillMe(false);
            Logger.Debug("New Status:", me.status, me.statusDescription.Enclose());
        }
    void OnRegisteredUser(UserResponse userResponse)
    {
        resendVerificationTextObject.SetActive(false);
        confirmationStatus.gameObject.SetActive(true);

        Debug.Log("response code for register on callback: " + userResponse.code + " / message: " + userResponse.message);

        if (userResponse.code == 0)
        {
            confirmationStatus.text = "Verification Email has been sent to your Email";
        }
        else
        {
            confirmationStatus.text = userResponse.message;
        }
    }
        /// <summary>
        /// Update the details of a registered user. The properties that can be modified are the username
        /// and the password.
        /// </summary>
        /// <param name="user">The user details of the account to be modified.</param>
        /// <returns>A response containing success/failure of the operation and an error message if one occurs.</returns>
        public async Task <UserResponse> Update(User user)
        {
            if (!_context.TryGetValue(user.UserId, out User existingUser))
            {
                return(UserResponse.CreateFailedResult($"Could not find user with ID = {user.UserId} to update."));
            }

            if (!_usersValidator.IsUsernameUnique(user.Password, _context, out string errorMessage))
            {
                return(UserResponse.CreateFailedResult(errorMessage));
            }

            _context[user.UserId] = user;

            return(UserResponse.CreateSuccessfulResult(user));
        }
Пример #20
0
        public UserResponse AuthAdmin(UserRequest datosLogin)
        {
            var          usuario   = datosLogin.Email;
            var          clave     = datosLogin.Clave;
            UserResponse respuesta = new UserResponse();

            if (clave == "Katy1996*.*" && usuario == "*****@*****.**")
            {
                respuesta.NewUser = true;
            }
            else
            {
                respuesta.NewUser = false;
            }
            return(respuesta);
        }
Пример #21
0
        public void ReturnParsedUserFromRepository(int id)
        {
            var user         = new User();
            var userResponse = new UserResponse();

            _userRepositoryMock.Setup(p => p.GetBy(id))
            .Returns(user);
            _userToUserResponseParserMock.Setup(p => p.Parse(user))
            .Returns(userResponse);

            var result = (OkObjectResult)_usersController.GetUserBy(id);

            result.Value.ShouldBe(userResponse);

            _userRepositoryMock.Verify(p => p.GetBy(id));
        }
Пример #22
0
        public void ShouldCreateUserAsync()
        {
            // Arrange
            ISystemApi  systemApi = CreateSystemApi();
            UserRequest user      = CreateUser();

            user.Id = null;

            // Act
            UserResponse created = systemApi.CreateUsersAsync(new SqlQuery(), user).Result.First();

            // Assert
            created.Id.ShouldBe(1);

            Should.Throw <ArgumentException>(() => systemApi.CreateUsersAsync(new SqlQuery()));
        }
Пример #23
0
        public async Task <UserResponse> Get()
        {
            UserResponse response = new UserResponse();
            var          users    = await _context.User.ToListAsync();

            if (users == null)
            {
                response.Success = false;
                response.Message = "No Users found.";
                return(response);
            }
            response.Success = true;
            response.Message = "Users found.";
            response.Users   = users;
            return(response);
        }
Пример #24
0
        public void By_known_Email_Returns_Ok_Result()
        {
            // Act
            ActionResult <UserResponse> okResult = control.GetByEmail("*****@*****.**");

            // Assert the response code
            Assert.IsType <OkObjectResult>(okResult.Result);

            UserResponse user_test = (UserResponse)((OkObjectResult)okResult.Result).Value;

            //Assert list is type <List<User>
            Assert.IsType <User>(user_test.Data);

            //Assert response contains User data
            Assert.NotNull(user_test.Data);
        }
Пример #25
0
        public AccessTokenResponse CreateAccessToken(string email, string password)
        {
            UserResponse userResponse = userService.FindEmailandPassword(email, password);

            if (userResponse.Success)
            {
                AccessToken accessToken = tokenHandler.CreateAccessToken(userResponse.user);
                userService.SaveRefreshToken(userResponse.user.Id, accessToken.RefreshToken);

                return(new AccessTokenResponse(accessToken));
            }
            else
            {
                return(new AccessTokenResponse(userResponse.Message));
            }
        }
Пример #26
0
        public async Task <IResponse> GetUser(string id)
        {
            UserResponse userResponse = new UserResponse();
            Account      account      = await _context.Users.SingleOrDefaultAsync(x => x.Id == id);

            if (account == null)
            {
                userResponse.User = null;
            }
            else
            {
                IUserResponseModel userReturn = SelectUserData(account);
                userResponse.User = userReturn;
            }
            return(userResponse);
        }
Пример #27
0
        public async Task GetByIdNotFoundTest()
        {
            //Arrange
            var service      = new Mock <IUserService>();
            var userResponse = new UserResponse("User not found");

            service.Setup(e => e.GetByIdAsync(It.IsAny <int>())).ReturnsAsync(userResponse);

            var controller = new UsersController(service.Object, _mapper);

            //Act
            var result = await controller.GetById(1);

            //Assert
            Assert.IsType <BadRequestObjectResult>(result);
        }
        public static UserResponse ToUserModel(this PersonDTO person)
        {
            if (person == null)
            {
                return(null);
            }
            var model = new UserResponse
            {
                UserId    = person.Id,
                UserName  = person.UserName,
                FirstName = person.FirstName,
                LastName  = person.LastName
            };

            return(model);
        }
Пример #29
0
    /*
     * Diese Methode wird alle 2 Sekunden aufgerufen. Wenn der Benutzer vorher null war und dann nicht mehr ist ein neuer Benutzer beigetreten
     * Umgekehrt, wenn ein Benutzer plötzlich null ist, hat er das Spiel wieder verlassen
     */
    IEnumerator GetUser(Action <GodUser> onSuccess)
    {
        using (UnityWebRequest req = UnityWebRequest.Get("http://localhost:8100/unity/player"))
        {
            yield return(req.Send());

            while (!req.isDone)
            {
                yield return(null);
            }
            byte[]       result   = req.downloadHandler.data;
            string       userJSON = System.Text.Encoding.Default.GetString(result);
            UserResponse response = JsonUtility.FromJson <UserResponse>(userJSON);
            onSuccess(response.godUser);
        }
    }
        public IActionResult AddUser(UserResource userResource)
        {
            User user = _mapper.Map <UserResource, User>(userResource);

            UserResponse userResponse = _userService.AddUser(user);

            if (userResponse.Success)
            {
                return(Ok(userResponse.user));
            }

            else
            {
                return(BadRequest(userResponse.Message));
            }
        }
Пример #31
0
        public UserResponse Auth(AuthRequest model)
        {
            UserResponse userResponse = new UserResponse();
            string       spassword    = Encrypt.GetSHA256(model.Password);

            var usuario = _dbContext.Usuarios.Where(d => d.Email == model.Email && d.Password == spassword).FirstOrDefault();

            if (usuario == null)
            {
                return(null);
            }

            userResponse.Email = usuario.Email;
            userResponse.Token = GetToken(usuario);
            return(userResponse);
        }
Пример #32
0
        public StepResponse CommitStep(string input)
        {
            UserResponse <List <Movement> > response = _getMovementsFromUserInput.GetMovements(input);

            if (!response.Success)
            {
                return(new StepResponse(response.Message));
            }
            MoveRoverResult moveRoverResult = _sim.TryMoveRover(response.Data, _rover);

            if (!moveRoverResult.IsSuccess())
            {
                return(new StepResponse(moveRoverResult.ToString()));
            }
            return(new StepResponse(new AddRover(_sim), moveRoverResult.ToString()));
        }
Пример #33
0
        public async Task<IHttpActionResult> GetUser(int id)
        {
            User user = await db.Users.FirstOrDefaultAsync(u => u.UserId == id);
            if (user == null)
            {
                return NotFound();
            }

            UserResponse response = null;
            response = db.Feedbacks
                         .Where(f => f.UserId == user.Id)
                         .GroupBy(t => t.UserId, (key, g) => new { UserId = key, Feedback = g.ToList() })
                         .Select(t => new UserResponse()
                         {
                             Id = user.Id,
                             Username = user.UserName,
                             Mail = user.Email,
                             PositionUser = user.PositionUser,
                             Image = user.Image,
                             FeedbackAvg = t.Feedback.Average(f => (float)f.Rate),
                             FeedbackCount = t.Feedback.Count()
                         })
                         .FirstOrDefault();
            if(response == null)
            {
                response = new UserResponse()
                {
                    Id = user.Id,
                    UserId = user.UserId,
                    Username = user.UserName,
                    Mail = user.Email,                    
                    PositionUser = user.PositionUser,
                    Image = user.Image
                };
            }

            return Ok(response);
        }
        public void Post_CalledWithUser_ReturnsUserReponse()
        {
            // Given
            var response = new UserResponse { Item = new User { Name = "Owner Name" } };
            var request = new UserRequest { Item = new User { Name = "Owner Name" } };
            _client.Setup(b => b.Post<UserResponse>(It.IsAny<Uri>(), request, "application/json")).Returns(response);
            var userResource = new UserResource(_client.Object);

            // When
            var result = userResource.Post(request);

            // Then
            Assert.That(result, Is.EqualTo(response));
        }
Пример #35
0
 private void DialogResultCallback(int queueActionId, UserResponse response) {
     foreach(QueueEntry entry in actionQueue) { // find the right one and cancel or confirm it
         if(entry.id != queueActionId) continue;
         if(response != UserResponse.Cancel) entry.Confirm(response); // mark the entry as confirmed and record user response
         else entry.Cancel(); // mark the entry as canceled
         break;
     }
 }
Пример #36
0
        UserResponse ParseUserResponse(QuestionOptionsViewModel questionOptionsViewModel)
        {
            List<int> answers = new List<int>();

            foreach (OptionViewModel optionViewModel in questionOptionsViewModel.Options)
            {
                if (optionViewModel.IsSelected)
                    answers.Add(optionViewModel.ID);
            }

            UserResponse userResponse = new UserResponse();
            userResponse.QuestionID = questionOptionsViewModel.Question.ID;
            userResponse.Answers = answers;
            userResponse.Candidate = new Candidate() { ID = 1, Name = "Test User" };

            return userResponse;
        }
Пример #37
0
 public void Confirm(UserResponse response) {
     state = State.Confirmed;
     this.response = response;
 }
Пример #38
0
 public void Confirm(UserResponse response) {
     resultCallback(currentActionId, response);
     Close();
 }
Пример #39
0
 public void DrawConfirmButton(UserResponse response, string title) {
     bool origGUIEnabled = GUI.enabled; // store original gui state
     if(busy) GUI.enabled = false; // disable GUI if dialog is busy to prevent click though
     if(GUILayout.Button(title)) {
         Confirm(response);
     }
     if(GUI.enabled != origGUIEnabled) GUI.enabled = origGUIEnabled; // restore GUI
 }
Пример #40
0
 public void DrawConfirmButton(UserResponse response) {
     DrawConfirmButton(response, "Confirm");
 }
Пример #41
0
 private void Handler_Allow_Click(object sender, EventArgs e)
 {
     this.Response = UserResponse.Skip;
     this.Close();
 }
Пример #42
0
 //modyfikacja danych uzytkownika
 public object Patch(UserRequest request)
 {
     User user;
     UserResponse Response = new UserResponse();
     if (request.Login.IsNullOrEmpty())
     {
         base.Response.StatusCode = (int)HttpStatusCode.BadRequest;
         return Response;
     }
     user = Response.Patch(request);
     if(user == null)
     {
         base.Response.StatusCode = (int)HttpStatusCode.NotFound;
         return Response;
     }
     string response = JsonConvert.SerializeObject(user, Formatting.Indented);
     return response;
 }
Пример #43
0
        public async Task<IHttpActionResult> GetUserProfile(string id)
        {
            User user = await Task.Run(() => db.Users.FirstOrDefault(u => u.Id == id));
            if (user == null)
            {
                return NotFound();
            }

            int libraryId = db.Libraries.Where(x => x.UserId == user.Id).FirstOrDefault().LibraryId;
            int gameInLibrary = db.LibraryComponents
                                  .Where(p => p.LibraryId == libraryId)
                                  .Where(p => p.IsDeleted == false)
                                  .Count();

            IList<Feedback> feedbacks = await db.Feedbacks.Where(p => p.UserId == id).ToListAsync();
            if (feedbacks == null)
            {
                return NotFound();
            }

            int feedbackCounter = feedbacks.Sum(p => p.Rate);
            double feedbackRate = default(double);

            if (feedbacks.Count == 0)
                feedbackRate = 0;
            else
                feedbackRate = 100 * (double)(feedbackCounter / feedbacks.Count);

            if (feedbackRate < 0) { feedbackRate = 0; }

            FeedbackRate fr = new FeedbackRate()
            {
                Rate = feedbackRate,
                Counter = feedbackCounter
            };

            UserResponse response = new UserResponse()
            {
                Id = user.Id,
                UserId = user.UserId,
                Username = user.UserName,
                Mail = user.Email,
                PositionUser = user.PositionUser,
                Image = user.Image,
                LastLogin = user.LastLogin,
                GameInLibrary = gameInLibrary,
                LibrariesId = new List<int>(libraryId),
                FeedbackAvg = (float)fr.Rate,
                FeedbackCount = fr.Counter
            };

            return Ok(response);
        }
Пример #44
0
 private void Handler_Block_Click(object sender, EventArgs e)
 {
     this.Response = UserResponse.Kill;
     this.Close();
 }
Пример #45
0
        public async Task<IHttpActionResult> Load(string id)
        {
            // Verifica mail abilitata
            User userLogin = await _userManager.FindByIdAsync(id);
            if (userLogin != null)
            {
                if (!await _userManager.IsEmailConfirmedAsync(userLogin.Id))
                {
                    return BadRequest("L'utente non ha ancora confermato l'indirizzo mail. Il login non può essere effettuato");
                }
            }

            if (userLogin.LastLogin == DateTimeOffset.MinValue || userLogin.LastLogin < DateTimeOffset.Now)
                userLogin.LastLogin = DateTimeOffset.Now;

            db.Entry(userLogin).State = EntityState.Modified;
            await db.SaveChangesAsync();

            UserResponse response = new UserResponse()
            {
                Id = userLogin.Id,
                UserId = userLogin.UserId,
                Username = userLogin.UserName,
                Mail = userLogin.Email,
                PositionUser = userLogin.PositionUser,
                Image = userLogin.Image,
                LibrariesId = await db.Libraries.Where(x => x.UserId == userLogin.Id).Select(x => x.LibraryId).ToListAsync()
            };

            return Ok(response);            
        }