Example #1
0
        public async Task <IActionResult> GetUserTemplates()
        {
            Domain.Model.User currentUser = await EnsureCurrentUser();

            string userId = currentUser.Id.ToLower();

            IEnumerable <Template> userTemplates = await _templateRepo.GetItemsAsync(
                p => p.DocType == TemplateDocumentType.User &&
                p.UserId.ToLower() == userId, p => new Template()
            {
                Id                 = p.Id,
                Name               = p.Name,
                Description        = p.Description,
                CategoryId         = p.CategoryId,
                SubcategoryId      = p.SubcategoryId,
                IsReusableTemplate = p.IsReusableTemplate
            });     //Force documentdb to query only these fields

            if (userTemplates == null)
            {
                logger.LogError("API GetUserTemplates error: User Templates not found. User {UserId}", userId);
                return(StatusCode(StatusCodes.Status500InternalServerError));
            }
            return(Ok(userTemplates));
        }
Example #2
0
        public async Task Update(Guid id, Domain.Model.User model)
        {
            var sql = new StringBuilder();

            sql.Append($"UPDATED {table}");
            sql.Append(" SET Name = @name, Gender = @gender, BirthDate = @birthDate, Email = @email, Password = @password, UpdateOn = UpdateOn");
            sql.Append(" WHERE Id = @id");

            await using var connection = new SqlConnection(_configuration.GetConnectionString("DatabaseConnection"));
            connection.Open();

            var dictionary = new Dictionary <string, object>
            {
                { "@id", model.Id },
                { "@name", model.Name },
                { "@gender", model.Gender },
                { "@birthDate", model.BirthDate },
                { "@email", model.Email },
                { "@password", model.Password },
                { "@updateOn", model.UpdatedOn }
            };

            var parameters = new DynamicParameters(dictionary);

            await connection.ExecuteScalarAsync(sql.ToString(), parameters);

            await Task.CompletedTask;
        }
Example #3
0
        public async Task Insert(Domain.Model.User model)
        {
            var sql = new StringBuilder();

            sql.Append($"INSERT INTO {table}");
            sql.Append(" (Id, Name, Gender,  BirthDate, Email, Password, CreatedOn)");
            sql.Append(" VALUES(@id, @name, @gender, @birthDate, @email, @password, @createdOn)");

            await using var connection = new SqlConnection(_configuration.GetConnectionString("DatabaseConnection"));
            connection.Open();

            var dictionary = new Dictionary <string, object>
            {
                { "@id", model.Id },
                { "@name", model.Name },
                { "@gender", model.Gender },
                { "@birthDate", model.BirthDate },
                { "@email", model.Email },
                { "@password", model.Password },
                { "@createdOn", model.CreatedOn }
            };

            var parameters = new DynamicParameters(dictionary);

            await connection.ExecuteScalarAsync(sql.ToString(), parameters);

            await Task.CompletedTask;
        }
Example #4
0
        public async Task <IActionResult> GetTemplateById(string templateId)
        {
            Template template = await _templateRepo.GetItemAsync(templateId);

            //Not found
            if (template == null)
            {
                logger.LogError("API GetTemplateById error: Template with id {TemplateId} not found.", templateId);
                return(StatusCode(StatusCodes.Status500InternalServerError));
            }

            //If not a template, return error
            if (template.DocType != TemplateDocumentType.User && template.DocType != TemplateDocumentType.CommonTemplate)
            {
                logger.LogError("API GetTemplateById error: {TemplateId} is not a template.", templateId);
                return(StatusCode(StatusCodes.Status500InternalServerError));
            }

            //If user template, check user
            if (template.DocType == TemplateDocumentType.User)
            {
                Domain.Model.User currentUser = await EnsureCurrentUser();

                string userId = currentUser.Id.ToLower();

                //If user doesn't match, return error
                if (template.UserId.ToLower() != userId)
                {
                    logger.LogError("API GetTemplateById error: Template with id {TemplateId} was found but the user {UserId} does not match.", templateId, userId);
                    return(StatusCode(StatusCodes.Status500InternalServerError));
                }
            }

            return(Ok(template));
        }
Example #5
0
        public async Task <IActionResult> EditUserTemplate([FromBody] Template template)
        {
            Domain.Model.User currentUser = await EnsureCurrentUser();

            string userId = currentUser.Id.ToLower();

            //Ensure user values and unique ID are set server side.
            template.DocType      = TemplateDocumentType.User;
            template.UserId       = userId;
            template.ModifiedDate = DateTime.Now;

            //Ensure the current user is allowed to edit this template
            Template userTemplate = await _templateRepo.GetItemAsync(template.Id);

            if (userTemplate == null || userTemplate.UserId == null || userTemplate.UserId.ToLower() != userId)
            {
                logger.LogError("API EditUserTemplate error: Template with id {TemplateId} was found but the user {UserId} does not match.", template.Id, userId);
                return(StatusCode(StatusCodes.Status500InternalServerError));
            }
            if (userTemplate.DocType != TemplateDocumentType.User)
            {
                logger.LogError("API EditUserTemplate error: Template with id {TemplateId} is not a user template.", template.Id, userId);
                return(StatusCode(StatusCodes.Status500InternalServerError));
            }

            //Create new user template
            bool status = await _templateRepo.UpdateItemAsync(template.Id, template);

            if (!status)
            {
                Log.Error("API EditUserTemplate error: There was an error while creating the template {TemplateId}", template.Id);
                return(StatusCode(StatusCodes.Status500InternalServerError));
            }
            return(Ok(status));
        }
Example #6
0
        public async Task <IActionResult> DeleteUserTemplate(string templateId)
        {
            Domain.Model.User currentUser = await EnsureCurrentUser();

            string userId = currentUser.Id.ToLower();

            //Ensure the current user is allowed to edit this template
            Template userTemplate = await _templateRepo.GetItemAsync(templateId);

            if (userTemplate == null || userTemplate.UserId == null || userTemplate.UserId.ToLower() != userId)
            {
                logger.LogError("API DeleteUserTemplate error: Template with id {TemplateId} was found but the user {UserId} does not match.", templateId, userId);
                return(StatusCode(StatusCodes.Status500InternalServerError));
            }
            if (userTemplate.DocType != TemplateDocumentType.User)
            {
                logger.LogError("API DeleteUserTemplate error: Template with id {TemplateId} is not a user template.", templateId, userId);
                return(StatusCode(StatusCodes.Status500InternalServerError));
            }

            //Delete user template
            bool status = await _templateRepo.DeleteItemAsync(templateId);

            if (!status)
            {
                logger.LogError("API DeleteUserTemplate error: There was an error while deleting the template {TemplateId}", templateId);
                return(StatusCode(StatusCodes.Status500InternalServerError));
            }
            return(Ok(status));
        }
Example #7
0
        /// <summary>
        /// Renders the recent friends.
        /// </summary>
        /// <param name="retrieveLastSevenDaysOfFriendsActivity">The retrieve last seven days of friends activity.</param>
        /// <returns></returns>
        private string RenderRecentFriends(IEnumerable <RecentActivityByUser> retrieveLastSevenDaysOfFriendsActivity)
        {
            var groupedByUserId = from u in retrieveLastSevenDaysOfFriendsActivity
                                  group u by u.UserId into g
                                  select new { Activity = g };

            StringBuilder builder = new StringBuilder();

            foreach (var group in groupedByUserId)
            {
                List <RecentActivityByUser> activityByUsers = group.Activity.ToList();
                string result = _statisticService.RenderActivity(activityByUsers);

                if (!string.IsNullOrEmpty(result))
                {
                    int userId             = activityByUsers[0].UserId;
                    Domain.Model.User user = _userRepository.RetrieveByPrimaryKey(userId);

                    string userHtml = string.Format(@"<ul class=""recentfriendactivity"">
                                  <li>{0}
                                    <ul>{1}</ul>
                                  </li>
                                </ul>", user.DisplayName, result);

                    builder.AppendLine(userHtml);
                }
            }
            return(builder.ToString());
        }
        public async Task Insert(Domain.Model.User entity)
        {
            await this._context.Users.AddAsync(UserDomainToUserEntityMapper.MapFrom(entity));

            await this._context.SaveChangesAsync();

            await Task.CompletedTask;
        }
        public void CreateUser(Domain.Model.User user)
        {
            User testUser = _userRepo.GetUserByName(user.Username);

            if (testUser == null)
            {
                _userRepo.SaveUser(user);
            }
        }
Example #10
0
 /// <summary>
 /// Implementions of IRenderManagePhotoView.
 /// </summary>
 /// <param name="user">The user.</param>
 /// <param name="authorization">The authorization.</param>
 /// <returns></returns>
 private IEnumerable <IRenderManagePhotoView> Implementions(Domain.Model.User user, Authorization authorization)
 {
     return(new List <IRenderManagePhotoView>
     {
         new AddTagsView(user, _tagService, authorization),
         new ApplyActionView(user, _tagService, authorization),
         new GetManagePhotoView(user, _tagService, authorization),
         new SearchActionView(user, _tagService, authorization)
     });
 }
Example #11
0
        public async Task <ActionResult> LoginAsync([FromBody] Domain.Model.User login)
        {
            if (this.ModelState.IsValid)
            {
                var token = await this._service.LoginAsync(login);

                return(this.Ok(token));
            }

            throw new BusinessException(MessagesErrorsModel(this.ModelState));
        }
Example #12
0
        public void Update(Domain.Model.User user)
        {
            if (user == null)
            {
                throw new ArgumentNullException(nameof(user));
            }

            var mongoUser = MapToMongoUser(user);

            _repository.ReplaceOne(u => u.Id == mongoUser.Id, mongoUser);
        }
Example #13
0
 private static MongoUser MapToMongoUser(Domain.Model.User user)
 {
     return(new MongoUser
     {
         Id = user.Id,
         Email = user.Email,
         Password = user.Password,
         CreationTime = user.CreationTime,
         State = user.State
     });
 }
        public async Task <IActionResult> GetCurrentUser()
        {
            Domain.Model.User currentUser = await EnsureCurrentUser();

            if (currentUser == null)
            {
                logger.LogError("API GetCurrentUser error: User not found.");
                return(StatusCode(StatusCodes.Status500InternalServerError));
            }
            return(Ok(currentUser));
        }
Example #15
0
        /// <summary>
        /// Saves the new user.
        /// </summary>
        /// <param name="view">The view.</param>
        /// <returns></returns>
        private ActionResult SaveNewUser(UserRegisterView view)
        {
            Domain.Model.User user = view.GetUser();
            _fileService.CreateBucket(user.Username.ToLower());
            _userRepository.Save(user);

            Domain.Model.User newUser = _userRepository.RetrieveUserByLoginCredentials(user.Username, user.Password);
            _userSession.Login(newUser, false, string.Format("~/{0}/dashboard", newUser.Username));
            ActionResult action = RedirectToAction("Index", user.Username);

            return(action);
        }
Example #16
0
 public void SaveUser(Domain.Model.User user)
 {
     if (user.Id <= 0 || GetUserByName(user.Username) != null)
     {
         _context.Users.Add(user);
     }
     else
     {
         _context.Entry(user).State = System.Data.EntityState.Modified;
     }
     _context.SaveChanges();
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="ManagePhotoBase"/> class.
 /// </summary>
 /// <param name="urlService">The URL service.</param>
 /// <param name="user">The user.</param>
 /// <param name="mediaRepository">The media repository.</param>
 /// <param name="tagRepsitory">The tag repsitory.</param>
 /// <param name="paginationService">The pagination service.</param>
 /// <param name="authorization">The authorization.</param>
 protected ManagePhotoBase(
     IUserUrlService urlService,
     Domain.Model.User user,
     IMediaRepository mediaRepository,
     ITagRepository tagRepsitory, IPaginationService<Media> paginationService, Authorization authorization)
 {
     this.urlService = urlService;
     _paginationService = paginationService;
     this.tagRepsitory = tagRepsitory;
     this.mediaRepository = mediaRepository;
     this.user = user;
     this.authorization = authorization;
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="ManagePhotoBase"/> class.
 /// </summary>
 /// <param name="urlService">The URL service.</param>
 /// <param name="user">The user.</param>
 /// <param name="mediaRepository">The media repository.</param>
 /// <param name="tagRepsitory">The tag repsitory.</param>
 /// <param name="paginationService">The pagination service.</param>
 /// <param name="authorization">The authorization.</param>
 protected ManagePhotoBase(
     IUserUrlService urlService,
     Domain.Model.User user,
     IMediaRepository mediaRepository,
     ITagRepository tagRepsitory, IPaginationService <Media> paginationService, Authorization authorization)
 {
     this.urlService      = urlService;
     _paginationService   = paginationService;
     this.tagRepsitory    = tagRepsitory;
     this.mediaRepository = mediaRepository;
     this.user            = user;
     this.authorization   = authorization;
 }
Example #19
0
        /// <summary>
        /// Gets the user.
        /// </summary>
        /// <returns></returns>
        public Domain.Model.User GetUser()
        {
            Domain.Model.User user = new Domain.Model.User
            {
                DisplayName = DisplayName,
                Email       = Email,
                FirstName   = FirstName,
                LastName    = LastName,
                Password    = _cryptographyService.Encrypt(Password),
                Username    = Username
            };

            return(user);
        }
Example #20
0
        public async Task Update(Domain.Model.User user)
        {
            User entityUser = await this.GetUserById(user.Id);

            await this.SafeExecution(
                async() =>
            {
                this.mapper.Map <Domain.Model.User, User>(user, entityUser);

                this.dbContext.Update(entityUser);

                await this.dbContext.SaveChangesAsync();
            },
                "Error updating user");
        }
Example #21
0
        public ActionResult Settings(SettingsView form)
        {
            IDictionary <string, string> crumbs = GetBreadCrumbs("settings", UrlService.UserUrl("settings"));

            SetAuthorizationAndUrlService(form);

            if (ModelState.IsValid)
            {
                Domain.Model.User user = form.GetSettings(Owner);
                form.UIMessage = "Account settings saved.";

                _userRepository.Save(user);
            }

            return(View(form, crumbs));
        }
        /// <summary>
        /// Call the UserService to retrieve the current user
        /// Throws an exception if the current user is not found.
        /// </summary>
        /// <returns>User object</returns>
        protected async Task <Domain.Model.User> EnsureCurrentUser()
        {
            if (_currentUser != null)
            {
                return(_currentUser);
            }

            IUser currentClaimUser = await _userProfile.GetCurrentUser();

            _currentUser = new Domain.Model.User()
            {
                Id = currentClaimUser.UserPrincipalName, Name = currentClaimUser.DisplayName
            };

            if (_currentUser == null)
            {
                throw new Exception("User not found.");
            }
            return(_currentUser);
        }
        public async Task Update(Guid id, Domain.Model.User model)
        {
            var entity = UserDomainToUserEntityMapper.MapFrom(model);
            var user   = this._context.Users.FirstOrDefault(u => u.Id.Equals(id));

            if (user != null)
            {
                user.Name      = entity.Name;
                user.Email     = entity.Email;
                user.Password  = entity.Password;
                user.CreatedOn = entity.CreatedOn;
                user.UpdatedOn = entity.UpdatedOn;

                this._context.Users.Update(user);
            }

            await this._context.SaveChangesAsync();

            await Task.CompletedTask;
        }
Example #24
0
        public void Insert(Domain.Model.User user)
        {
            if (user == null)
            {
                throw new ArgumentNullException(nameof(user));
            }

            try
            {
                var mongoUser = MapToMongoUser(user);
                _repository.Insert(mongoUser);
            }
            catch (MongoWriteException ex)
            {
                if (ex.WriteError.Code == 11000)
                {
                    throw new DuplicateEmailException();
                }
                throw;
            }
        }
Example #25
0
 public System.DateTime SetRandom(Site site, Domain.Model.User user)
 {
     System.DateTime generated;
     if (site.ProgramStarts != null && site.ProgramEnds != null)
     {
         System.DateTime startDate = site.ProgramStarts > user.CreatedAt
             ? (System.DateTime)site.ProgramStarts
             : user.CreatedAt;
         generated = _faker
                     .Date
                     .Between(startDate, (System.DateTime)site.ProgramEnds);
     }
     else
     {
         generated = _faker
                     .Date
                     .Between(user.CreatedAt, user.CreatedAt.AddDays(60));
     }
     _dateTimeProvider.SetDateTime(generated);
     return(generated);
 }
Example #26
0
        public ActionResult Register(FormCollection collection)
        {
            string msg      = string.Empty;
            string email    = Request.Form["email"];
            string name     = Request.Form["name"];
            string password = Request.Form["password"];

            if (repository.IsDuplicateUser(email))
            {
                msg = "User is already exists!";
            }
            else
            {
                Domain.Model.User obj = new Domain.Model.User();
                obj.Email   = email;
                obj.Mobile  = name;
                obj.Pssword = password;
                repository.Insert(obj);
                msg = "Registration Successfully complete!";
            }

            return(View());
        }
Example #27
0
        public ActionResult Index(string username, AccountDetailsView detailsView)
        {
            IDictionary <string, string> crumbs = GetBreadCrumbs("details", UrlService.UserUrl("account"));

            if (ModelState.IsValid)
            {
                detailsView.Password = _cryptographyService.Encrypt(detailsView.Password);
                Domain.Model.User savedUser = detailsView.GetUser();
                savedUser.Settings = Owner.Settings;
                savedUser.Id       = Owner.Id;
                _userRepository.Save(savedUser);

                detailsView.UIMessage           = "Account details saved.";
                detailsView.Password            = _cryptographyService.Decrypt(savedUser.Password);
                detailsView                     = SetAuthorizationAndUrlService(detailsView);
                detailsView.Authorization.Owner = savedUser;
            }
            else
            {
                ValidationHelper.ValidationHackRemoveNameAndBlankKey(ModelState);
            }

            return(View(detailsView, crumbs));
        }
Example #28
0
        public async Task <IActionResult> CreateUserTemplate([FromBody] Template template)
        {
            Domain.Model.User currentUser = await EnsureCurrentUser();

            string userId = currentUser.Id.ToLower();

            //Ensure user values and unique ID are set server side.
            template.BaseTemplateId = template.Id;
            template.Id             = Guid.NewGuid().ToString();
            template.DocType        = TemplateDocumentType.User;
            template.UserId         = userId;
            template.CreationDate   = DateTime.Now;
            template.ModifiedDate   = DateTime.Now;

            //Create new user template
            string newId = await _templateRepo.CreateItemAsync(template);

            if (string.IsNullOrEmpty(newId))
            {
                logger.LogError("API CreateUserTemplate error: There was an error while creating the template {TemplateName}", template.Name);
                return(StatusCode(StatusCodes.Status500InternalServerError));
            }
            return(Ok(newId));
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="ApplyActionView"/> class.
 /// </summary>
 /// <param name="user">The user.</param>
 /// <param name="tagService">The tag service.</param>
 /// <param name="authorization">The authorization.</param>
 public ApplyActionView(Domain.Model.User user, ITagService tagService, Authorization authorization)
     : base(user, authorization)
 {
     _tagService = tagService;
 }
        /// <summary>
        /// Gets the user.
        /// </summary>
        /// <returns></returns>
        public Domain.Model.User GetUser()
        {
            Domain.Model.User user = new Domain.Model.User
                                         {
                                             DisplayName = DisplayName,
                                             Email = Email,
                                             FirstName = FirstName,
                                             LastName = LastName,
                                             Password = _cryptographyService.Encrypt(Password),
                                             Username = Username
                                         };

            return user;
        }
        public void CalculateBadges(Domain.Model.User user, Domain.Model.BadgeType badgeType)
        {
            var value = user.CodeReviews.Count(e => e.Type == CodeReviewType.Request);

            this.CalculateMinThresholdedBadge(user, value, badgeType);
        }
        private async Task <int> CreateUsers(int howMany, bool household, bool quiet)
        {
            int created = 0;

            int[]   familyOptions = { 1, 2, 3, 4, 5, FamilyRandomIndicator, GroupRandomIndicator };
            float[] familyWeights = { 0.25F, 0.35F, 0.21F, 0.10F, 0.04F, 0.047F, 0.003F };

            var issues = new List <string>();

            // make the participants
            var users = await _userDataGenerator.Generate(Site.Id, howMany);

            var minDateTime = DateTime.MaxValue;
            var maxDateTime = DateTime.MinValue;

            if (!quiet)
            {
                Console.Write($"Inserting {howMany} users... ");
            }

            ProgressBar progress = quiet ? null : new ProgressBar();

            try
            {
                var rand                 = new Bogus.Randomizer();
                int familyMembers        = 0;
                Domain.Model.User parent = null;

                // insert the participants
                foreach (var user in users)
                {
                    bool currentUserParent = false;

                    // set an appropriate random date and time for insertion
                    var setDateTime = _dateTimeDataGenerator.SetRandom(Site);

                    if (setDateTime < minDateTime)
                    {
                        minDateTime = setDateTime;
                    }
                    if (setDateTime > maxDateTime)
                    {
                        maxDateTime = setDateTime;
                    }

                    if (familyMembers > 0)
                    {
                        // we are processing family members
                        user.User.LastName = parent.LastName;
                        if (rand.Int(1, 100) > 5)
                        {
                            user.User.Username = null;
                        }

                        // insert the family member
                        try
                        {
                            await _facade
                            .UserService
                            .AddHouseholdMemberAsync(parent.Id, user.User);

                            created++;
                        }
                        catch (GraException gex)
                        {
                            issues.Add($"Household username: {user.User.Username} - {gex.Message}");
                        }
                        familyMembers--;
                    }
                    else
                    {
                        // not processing family members, should this person be a head of household?
                        if (household && rand.Int(1, 100) <= 31)
                        {
                            currentUserParent = true;

                            familyMembers = rand.WeightedRandom <int>(familyOptions, familyWeights);
                            if (familyMembers == FamilyRandomIndicator)
                            {
                                familyMembers = rand.Int(6, 10);
                            }
                            else if (familyMembers == GroupRandomIndicator)
                            {
                                familyMembers = rand.Int(11, 100);
                            }
                        }

                        // insert the created user
                        try
                        {
                            var inserted = await _facade
                                           .UserService
                                           .RegisterUserAsync(user.User, user.Password);

                            if (currentUserParent)
                            {
                                parent = inserted;
                            }
                            created++;
                        }
                        catch (Exception ex)
                        {
                            issues.Add($"Username: {user.User.Username} - {ex.Message}");
                        }
                    }

                    if (progress != null)
                    {
                        progress.Report((double)created / howMany);
                    }
                }
            }
            finally
            {
                if (progress != null)
                {
                    progress.Dispose();
                }
            }

            Console.WriteLine($"Created {created} random users in {Site.Name}.");
            Console.WriteLine($"Users registered between {minDateTime} and {maxDateTime}.");

            if (issues.Count > 0)
            {
                Console.WriteLine("Some issues were encountered:");
                foreach (string issue in issues)
                {
                    Console.WriteLine($"- {issue}");
                }
            }

            await DisplayUserCount();

            return(howMany == created ? 0 : 1);
        }