Beispiel #1
0
        public UserDTO Login(UserDTO userDto)
        {
            // Retrieve the user information from DB
            var user = _repository.GetUser().WithEmail(userDto.Email);

            // Check Email + Password
            // if email not registered; return false
            if (user == null)
            {
                userDto.Password  = string.Empty;
                userDto.IsSuccess = false;
                return(userDto);
            }

            // if password not correct; return false
            if (user.Password != userDto.Password)
            {
                userDto.Password  = string.Empty;
                userDto.IsSuccess = false;
                return(userDto);
            }

            // if correct; return new token
            userDto.FirstName = user.FirstName;
            userDto.LastName  = user.LastName;
            userDto.Password  = string.Empty;
            userDto.Token     = Guid.NewGuid().ToString();
            userDto.IsSuccess = true;
            userDto.UserId    = user.UserId;
            return(userDto);
        }
        public async Task <PagedResponse <PhotoContract> > GetPagedAsync([FromUri] string continuationToken)
        {
            try
            {
                _telemetryClient.TrackEvent("UserPhotoController GetPagedAsync invoked");

                var registrationReference = await ValidateAndReturnCurrentUserId();

                var user = await _repository.GetUser(null, registrationReference);

                var stream = await _repository.GetUserPhotoStream(user.UserId, continuationToken, true);

                return(stream);
            }
            catch (DataLayerException ex)
            {
                _telemetryClient.TrackException(ex);

                if (ex.Error == DataLayerError.Unknown)
                {
                    throw ServiceExceptions.UnknownInternalFailureException(ServiceExceptions.Source);
                }

                throw ServiceExceptions.DataLayerException(ex.Message);
            }
        }
Beispiel #3
0
        public UserView GetUser(Guid id)
        {
            var user  = repository.GetUser(id);
            var _user = mapper.Map <UserView>(user);

            return(_user);
        }
Beispiel #4
0
        public pw_users GetUser(string email, string password, out Dictionary <string, string> parameters)
        {
            parameters = new Dictionary <string, string>();
            pw_users res;

            if (string.IsNullOrEmpty(email) || string.IsNullOrEmpty(password))
            {
                res = null;
                parameters.Add("code", "400");
                parameters.Add("msg", "You must send email and password");
                return(res);
            }
            try
            {
                res = _db.GetUser(email);
                if (res == null || res.password != password)
                {
                    parameters.Add("code", "401");
                    parameters.Add("msg", "Invalid email or password");
                    res = null;
                }
            }
            catch (Exception e)
            {
                _debug(e, new { }, "Ошибка возникла при получении одного документа по id");
                res = null;
            }
            return(res);
        }
Beispiel #5
0
        public async Task <IActionResult> CreateMessage(int userId, [FromBody] MessageForCreationDto messageForCreation)
        {
            var sender = await _repo.GetUser(userId);

            //if (sender.Id != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value))
            //{
            //    return Unauthorized();
            //}
            messageForCreation.SenderId = userId;
            var recipient = await _repo.GetUser(messageForCreation.RecipientId);

            if (recipient == null)
            {
                return(BadRequest("Could not find user"));
            }
            var message = _mapper.Map <Message>(messageForCreation);

            _repo.Add(message);
            if (await _repo.SaveAll())
            {
                var messageToReturn = _mapper.Map <MessageToReturnDto>(message);
                return(CreatedAtRoute("GetMessage", new { id = message.Id }, messageToReturn));
            }
            throw new Exception("Creating the message failed on save");
        }
Beispiel #6
0
        public async Task <IActionResult> CreateBooking(int userId, [FromBody] BookingToCreateDto bookingForCreation)
        {
            if (bookingForCreation.UserId != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value))
            {
                return(Unauthorized());
            }
            var userFromRepo = await _repository.GetUser(bookingForCreation.UserId);

            if (userFromRepo.UserRole != UserRole.Admin)
            {
                return(Unauthorized());
            }
            if (!ValidateBookingExists(bookingForCreation.BookingType))
            {
                return(BadRequest("Booking type does not exist"));
            }

            var bookingToCreate = _mapper.Map <BookingToCreateDto, BookingSubject>(bookingForCreation);

            userFromRepo.BookingSubjects.Add(bookingToCreate);
            if (await _repository.SaveAll())
            {
                var bookingToReturn = _mapper.Map <BookingToCreateDto>(bookingToCreate);
                return(CreatedAtRoute("GetBooking", new { id = bookingToReturn.Id }, bookingToReturn));
            }
            return(BadRequest("Error in creating Booking"));
        }
Beispiel #7
0
        public async Task <GameData> GetGameData(int userId)
        {
            GameData gameData = new GameData();

            try
            {
                gameData.User = await repo.GetUser(userId);

                if (gameData.User == null)
                {
                    gameData.Message = "User not exists!";
                    return(gameData);
                }
                gameData.Question = await repo.GetRandomQuestion(userId);

                gameData.PlayedCount  = repo.GetUserPlayedCount(userId);
                gameData.MaxPlayCount = gameSettings.MaxPlayCount;

                gameData.Message = ((gameData.PlayedCount >= gameData.MaxPlayCount) || gameData.Question == null) ? "There are no more questions" : "";
            }
            catch (Exception ex)
            {
                gameData.Message = "Something went wrong!";
            }

            return(gameData);
        }
Beispiel #8
0
        public async Task <IActionResult> GetUser(int id)
        {
            var user = await _repo.GetUser(id);

            var userToReturn = _mapper.Map <UserForDetailedDto>(user);

            return(Ok(userToReturn));
        }
Beispiel #9
0
        public async Task <IActionResult> GetUser(int id)
        {
            var user = await _repository.GetUser(id);

            var result = _mapper.Map <UserForListDTO>(user);

            return(Ok(result));
        }
Beispiel #10
0
        public async Task <IActionResult> GetUser(int id)
        {
            //önce destination sonra ise kaynak class gönderilir
            var user = await _repo.GetUser(id);

            var userToReturn = _mapper.Map <UserForDetailedDto>(user);

            return(Ok(userToReturn));
        }
Beispiel #11
0
        public void RegisterUser(IFingerprint id, string userName)
        {
            var user = _repository.GetUser((Fingerprint)id);

            if (user == null)
            {
                _repository.AddUser(new User((Fingerprint)id, userName));
            }
        }
Beispiel #12
0
        private void LoadUserInfo(String login)
        {
            User user = repository.GetUser(login);

            tb_manager.Text      = user.Manager;
            cb_adminFlag.Checked = user.AdminFlag;
            tb_userpassword.Clear();
            tb_userlogin.Text    = user.Login;
            cb_isBlocked.Checked = user.IsBlocked;
        }
Beispiel #13
0
        public async Task <AnnotationContract> PostAsync(AnnotationContract annotation)
        {
            try
            {
                _telemetryClient.TrackEvent("AnnotationController PostAsync invoked");
                await ValidateAndReturnCurrentUserId();

                // Get the Gold gifting user.
                var fromUser = await _repository.GetUser(annotation.From.UserId);

                // Check to see if the gifting user has enough of a balance to support gift.
                if ((fromUser.GoldBalance - annotation.GoldCount) < 0)
                {
                    throw ServiceExceptions.UserBalanceTooLow();
                }

                var insertedAnnotation = await _repository.InsertAnnotation(annotation);

                var photoContract = await _repository.GetPhoto(annotation.PhotoId);

                var receiver = await _repository.GetUser(photoContract.User.UserId);

                var goldBalance = receiver.GoldBalance;

                try
                {
                    _telemetryClient.TrackEvent("Gold received Push notification invoked.");

                    // Send push notification to the user receiving Gold
                    await
                    _notificationHandler.SendPushAsync(PushNotificationPlatform.Windows,
                                                       "user:"******"You have received GOLD!",
                                                       photoContract.ThumbnailUrl, annotation.PhotoId, goldBalance);
                }
                catch (Exception e)
                {
                    _telemetryClient.TrackException(e);
                }

                return(insertedAnnotation);
            }
            catch (DataLayerException ex)
            {
                _telemetryClient.TrackException(ex);

                if (ex.Error == DataLayerError.Unknown)
                {
                    throw ServiceExceptions.UnknownInternalFailureException(ServiceExceptions.Source);
                }

                throw ServiceExceptions.DataLayerException(ex.Message);
            }
        }
Beispiel #14
0
        public bool ValidateUser(string login, string password)
        {
            var u = _repository.GetUser(login);

            if (u == null)
            {
                return(false);
            }

            return(u.Password == Encrypt(password));
        }
Beispiel #15
0
 public ActionResult GetUser(Guid id)
 {
     if (TAuth.IsAdmin())
     {
         return(View(repo.GetUser(id)));
     }
     else
     {
         return(RedirectToAction("Index", "Home"));
     }
 }
        public UserModel GetUser()
        {
            var id = HttpContext.Current.User.Identity.Name;

            if (id == null)
            {
                return(null);
            }
            var user = _repository.GetUser(id);

            return(user);
        }
        public IActionResult EditUser(string Id)
        {
            var user = _repo.GetUser((string)Id);

            return(View(new UsersViewModel
            {
                UserId = user.Id,
                Email = user.Email,
                Username = user.UserName,
                FirstName = user.FirstName,
                LastName = user.LastName
            }));
        }
        public async Task <IActionResult> GetUser(int id)
        {
            var user = await _repo.GetUser(id);

            var userToReturn = _mapper.Map <UserForDetailedDto>(user);

            if (userToReturn == null)
            {
                return(NotFound("User not found."));
            }

            return(Ok(userToReturn));
        }
Beispiel #19
0
        public ResultOperation SavePublicationForQuiz(QuizViewModel quizModelView)
        {
            try
            {
                using (IRepository repository = Repository.Repository.CreateRepository())
                {
                    Domain.Quiz quiz = repository.GetQuizWithAnswers(quizModelView.Quiz.Id);

                    if (quiz != null && quiz.Creator == repository.GetUser(this.currentUserId))
                    {
                        quiz.IsPublished    = true;
                        quiz.Access         = quizModelView.Access;
                        quiz.ExpirationDate = quizModelView.ExpirationDate.Value;
                        quiz.Url            = quizModelView.Url;

                        if (quizModelView.UserIds != null)
                        {
                            // new users to be added
                            var newUsers = quizModelView.UserIds.Where(
                                r => !quiz.Answers.Any(answer => answer.User.Id == r)).ToList();

                            quiz.Answers.RemoveAll(r => !quizModelView.UserIds.Contains(r.User.Id));

                            // Adding new items to the list
                            foreach (var item in newUsers)
                            {
                                quiz.Answers.Add(new Domain.Answer()
                                {
                                    IsOpen = true,
                                    User   = repository.GetUser(item)
                                });
                            }
                            repository.SaveQuiz(quiz);

                            return(true);
                        }
                    }
                    else
                    {
                        messages.Add("Quiz was not found.");
                    }
                }
            }
            catch (Exception ex)
            {
                LogException(ex);
                messages.Add(DefaultErrorMessage());
            }

            return(messages);
        }
Beispiel #20
0
        public async Task <IActionResult> CreateGalleryPhoto(int bookingId, int userId, [FromForm] PhotoToCreateDto photoToCreateDto)
        {
            if (userId != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value))
            {
                return(Unauthorized());
            }
            var userFromRepo = await _repository.GetUser(userId);

            if (userFromRepo == null || userFromRepo.UserRole != UserRole.Admin)
            {
                return(Unauthorized());
            }
            var bookingFromRepo = await _repository.GetBooking(bookingId);

            if (bookingFromRepo == null)
            {
                return(BadRequest("Booking does not exist"));
            }
            var file         = photoToCreateDto.File;
            var uploadResult = new ImageUploadResult();

            if (file.Length > 0)
            {
                using (var stream = file.OpenReadStream())
                {
                    var imageUploadParams = new ImageUploadParams()
                    {
                        File           = new FileDescription(file.FileName, stream),
                        Transformation = new Transformation().Width(600).Height(600).Crop("fill")
                    };
                    uploadResult = _cloudinary.Upload(imageUploadParams);
                }
            }
            photoToCreateDto.Url      = uploadResult.Uri.ToString();
            photoToCreateDto.PublicId = uploadResult.PublicId;
            if (bookingFromRepo.GalleryPictures.Count == 0)
            {
                photoToCreateDto.IsMain = true;
            }

            var fileToUpload = _mapper.Map <GalleryPicture>(photoToCreateDto);

            bookingFromRepo.GalleryPictures.Add(fileToUpload);
            if (await _repository.SaveAll())
            {
                var photoToReturn = _mapper.Map <PhotoToReturnDto>(fileToUpload);
                return(CreatedAtRoute("GetPhoto", new { id = photoToReturn.Id, bookingId = bookingId }, photoToReturn));
            }

            return(BadRequest("An Error occurred while uploading the photo"));
        }
Beispiel #21
0
        public async Task <IActionResult> AddPhotoForUser(int userId,
                                                          [FromForm] PhotoForCreationDto photoForCreationDto)
        {
            if (userId != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value))
            {
                return(Unauthorized());
            }

            var userFromRepo = await _repo.GetUser(userId);

            var file = photoForCreationDto.File;

            var uploadResult = new ImageUploadResult();

            if (true /*file.Length > 0*/)
            {
                using (var stream = file.OpenReadStream())
                {
                    var uploadParams = new ImageUploadParams()
                    {
                        File           = new FileDescription(file.Name, stream),
                        Transformation = new Transformation()
                                         .Width(500).Height(500).Crop("fill").Gravity("face")
                    };

                    uploadResult = _cloudinary.Upload(uploadParams);
                }
            }

            photoForCreationDto.Url      = uploadResult.Uri.ToString();
            photoForCreationDto.PublicId = uploadResult.PublicId;

            var photo = _mapper.Map <Photo>(photoForCreationDto);

            if (!userFromRepo.Photos.Any(u => u.IsMain))
            {
                photo.IsMain = true;
            }

            userFromRepo.Photos.Add(photo);

            if (await _repo.SaveAll())
            {
                // return Ok();    //jut for now
                var photoToReturn = _mapper.Map <PhotoForReturnDto>(photo);
                return(CreatedAtRoute("GetPhoto", new { userId = userId, id = photo.Id },
                                      photoToReturn));
            }

            return(BadRequest("Could not upload the photo"));
        }
        public bool RegistrationUser(string Login, string Password)
        {
            if (repository.GetUser(Login) != null)
            {
                return(false);
            }
            User user = new User()
            {
                Login = Login, Password = Password
            };

            repository.CreateUser(user);
            return(LoginUser(Login, Password));;
        }
Beispiel #23
0
        public async Task <IActionResult> UploadUserPhoto(int userId, IFormFile file)
        {
            if (userId != int.Parse(User.FindFirst(claim => claim.Type == ClaimTypes.NameIdentifier).Value))
            {
                return(Unauthorized("You have not access to modify this user's photo!"));
            }

            var user = await _repository.GetUser(userId);

            if (user == null)
            {
                return(NotFound("User not found!"));
            }

            var directory = Path.Combine(_hostingEnvironment.WebRootPath, "ProfilesPhotos");

            if (!Directory.Exists(directory))
            {
                Directory.CreateDirectory(directory);
            }
            var filePath = Path.Combine(directory, Guid.NewGuid().ToString() + Path.GetExtension(file.FileName));

            if (file == null)
            {
                return(BadRequest("Null file!"));
            }
            if (file.Length == 0)
            {
                return(BadRequest("Empty file"));
            }
            if (file.Length > _pictureSettings.Value.MaxBytes)
            {
                return(BadRequest("File size exceeded!"));
            }
            if (!_pictureSettings.Value.IsSupported(Path.GetExtension(file.FileName)))
            {
                return(BadRequest("Unsupported file extension!"));
            }

            using (var fileStream = new FileStream(filePath, FileMode.Create))
            {
                await file.CopyToAsync(fileStream);
            }

            user.PhotoUrl = filePath;
            await _unitOfWork.CompleteAsync();

            return(Ok());
        }
Beispiel #24
0
        public override ResultOperation Save(Quiz entity)
        {
            try
            {
                using (IRepository repository = Repository.Repository.CreateRepository())
                {
                    if (VerifyFields(entity))
                    {
                        Domain.Quiz quiz = null;

                        if (entity.Id != 0)
                        {
                            quiz = repository.GetQuiz(entity.Id);
                            if (quiz == null)
                            {
                                return("Quiz was not found.");
                            }
                            else if (quiz.Creator != repository.GetUser(this.currentUserId))
                            {
                                return("Quiz was not found.");
                            }
                        }
                        else
                        {
                            quiz = new Domain.Quiz()
                            {
                                Creator = repository.GetUser(this.currentUserId)
                            };
                        }

                        quiz.Name        = entity.Name;
                        quiz.Description = entity.Description;

                        repository.SaveQuiz(quiz);

                        entity.Id = quiz.Id;

                        return(true);
                    }
                }
            }
            catch (Exception ex)
            {
                LogException(ex);
                messages.Add(DefaultErrorMessage());
            }

            return(messages);
        }
Beispiel #25
0
        public IActionResult AnimalObservation(int id)
        {
            AnimalObservationViewModel model = new AnimalObservationViewModel();

            model.Animal        = dbContext.getAnimal(id);
            model.User          = dbContext.GetUser(model.Animal.UserId);
            model.Animal.Specie = dbContext.getAnimalSpecie(model.Animal);
            var tempUser = userManager.Users.Where(x => x.Id == model.User.Id).FirstOrDefault();

            if (tempUser != null)
            {
                model.Email = tempUser.Email;
            }
            return(View(model));
        }
Beispiel #26
0
        public void Should_Validate_User_Account_Is_Active()
        {
            // Arrange
            repository.GetCredentialsByResetToken(Arg.Any <string>()).Returns(new Credentials
            {
                // Date NOT in the past
                ResetTokenExpiryDate = new DateTime(2100, 01, 01)
            });
            repository.GetUser(Arg.Any <string>()).Returns(new User {
                Active = false
            });

            // Act
            accountBusiness.ResetPassword("NewPassword", "resetToken");
        }
Beispiel #27
0
        // GET: User/Details/5
        public ActionResult Details(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }

            User user = _repository.GetUser(id.Value);

            if (user == null)
            {
                return(HttpNotFound());
            }
            return(View(user));
        }
Beispiel #28
0
        public async Task <IActionResult> Login([FromForm] LoginModel model)
        {
            if (ModelState.IsValid)
            {
                User user = await _repository.GetUser(model.Email, model.Password);

                if (user != null)
                {
                    await Authenticate(user, model.Remember);

                    return(RedirectToAction("Index", "Home"));
                }
            }
            return(View());
        }
Beispiel #29
0
 public void Init(string email, IRepository repository)
 {
     if (!string.IsNullOrEmpty(email))
     {
         User = repository.GetUser(email);
     }
 }
Beispiel #30
0
        public async Task <IActionResult> CreateComment(int bookingId, [FromBody] CommentDto commentDto)
        {
            if (commentDto.UserId != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value))
            {
                return(Unauthorized());
            }
            var userFromRepo = await _repository.GetUser(commentDto.UserId);

            if (await _authRepository.UserExists(userFromRepo.UserName))
            {
                return(Unauthorized());
            }
            var booking = await _repository.GetBooking(bookingId);

            if (booking == null)
            {
                return(BadRequest("Booking does not exist"));
            }
            commentDto.BookingSubjectId = bookingId;
            var commentToCreate = _mapper.Map <CommentDto, Comment>(commentDto);

            booking.Comments.Add(commentToCreate);
            if (await _repository.SaveAll())
            {
                var commentToReturn = _mapper.Map <CommentToReturnDto>(commentToCreate);
                return(CreatedAtRoute("GetComment", new { id = commentToReturn.Id }, commentToReturn));
            }

            return(BadRequest("Error ocurred while creating comment"));
        }
Beispiel #31
0
 /// <summary>
 /// Инициализация по имени
 /// </summary>
 /// <param name="email">имя пользователя [email]</param>
 public void Init(string email, IRepository repository)
 {
     if (!string.IsNullOrEmpty(email))
     {
         User = repository.GetUser(email);
     }
 }
 public CurrentUser(IRepository repository)
 {
     _repository = repository;
     // TODO replace with reference to the logged in user
     _currentUser = _repository.GetUser(1);
 }
 public void Init(string login, IRepository repository)
 {
     if (!string.IsNullOrEmpty(login))
         User = repository.GetUser(login);
 }