Exemplo n.º 1
0
        public async Task ChangePassword(string userId, ChangePasswordDto changePassword)
        {
            if (changePassword.NewPassword != changePassword.ConfirmedNewPassword)
            {
                throw new AuthenticationException(ExceptionMessage.NonMatchingPasswords);
            }

            PasswordVerificationResult verificationResult;
            UserEntity user = await _storage.FindAsync(u => u.Id == Guid.Parse(userId));

            _user = new Common.Models.User(user.Username, user.Email, user.Timezone, user.Locale, true);
            verificationResult = ValidatePassword(_user, user.HashedPassword, changePassword.OldPassword);

            switch (verificationResult)
            {
            case PasswordVerificationResult.Success:
                break;

            case PasswordVerificationResult.Failed:
                throw new AuthenticationException(ExceptionMessage.OldPasswordIncorrect);

            case PasswordVerificationResult.SuccessRehashNeeded:
                break;
            }

            _user = new Common.Models.User(user.Username, user.Email, user.Timezone, user.Locale, true);
            user.HashedPassword = HashPassword(_user, changePassword.NewPassword);
            var updatedUser = await _storage.UpdateAsync(user);

            return;
        }
Exemplo n.º 2
0
 /// <summary>
 /// adds a user
 /// </summary>
 /// <param name="user"></param>
 /// <returns></returns>
 public Common.Models.User AddUser(Common.Models.User user)
 {
     using (var context = new PaymentsDbContext(ContextOptions))
     {
         try
         {
             var dbUser = context.Users.FirstOrDefault(u => u.Fullname == user.Fullname && u.DateOfBirth == user.DateOfBirth);
             if (dbUser == null || string.IsNullOrWhiteSpace(dbUser.Id.ToString()))
             {
                 user.Id = Guid.NewGuid();
                 context.Users.Add(MyMapper.Map <Models.User>(user));
                 context.SaveChanges();
             }
             else
             {
                 user.Id = dbUser.Id;
             }
             return(user);
         }
         catch (Exception ex)
         {
             Log.LogError(ex, $"Failed to create user");
             throw ex;
         }
     }
 }
Exemplo n.º 3
0
        public async Task ResetPassword(ResetPasswordDto resetPassword)
        {
            var user = await _storage.FindAsync(m => m.ResetPasswordToken == resetPassword.ValidationToken);

            if (user == null)
            {
                throw new AuthenticationException(ExceptionMessage.InvalidPasswordResetToken);
            }

            if (DateTimeOffset.Compare(DateTimeOffset.UtcNow, user.ResetPasswordTokenExpiresAt) > 0)
            {
                throw new AuthenticationException(ExceptionMessage.PasswordResetTokenExpired);
            }

            if (resetPassword.NewPassword != resetPassword.ConfirmNewPassword)
            {
                throw new AuthenticationException(ExceptionMessage.NonMatchingPasswords);
            }

            _user = new Common.Models.User(user.Username, user.Email, user.Timezone, user.Locale, true);
            user.HashedPassword = HashPassword(_user, resetPassword.NewPassword);
            // invalidate token after initial use
            user.ResetPasswordTokenExpiresAt = DateTimeOffset.MinValue;
            var updatedUser = await _storage.UpdateAsync(user);

            return;
        }
Exemplo n.º 4
0
        public async Task <JsonWebTokenDto> RegisterUserAsync(RegistrationDto registration)
        {
            if (registration.Password != registration.PasswordConfirmation)
            {
                throw new AuthenticationException(ExceptionMessage.NonMatchingPasswords);
            }

            JsonWebTokenDto jsonWebToken;

            _user = new Common.Models.User(registration.Username, registration.Email, registration.Timezone, registration.Locale, true);

            var userEntity = _mapper.Map <UserEntity>(_user);

            userEntity.HashedPassword = HashPassword(_user, registration.Password);
            await _storage.CreateAsync(userEntity);

            jsonWebToken = GenerateJsonWebToken(new JwtUserClaimsDto(userEntity.Id.ToString()));
            NotificationDto notification = new NotificationDto(userEntity.Id);
            // re-create registration object to avoid queueing password info
            var registrationToQueue = new RegistrationDto()
            {
                Email = registration.Email, Username = registration.Username
            };
            await _messageQueue.SendMessageAsync(registrationToQueue, "registration", queueName : _pubSlackAppQueueName);

            await _notifier.SendWelcomeNotificationAsync(notification);

            await _notifier.SendInitialFeedbackRequestNotificationAsync(notification);

            return(jsonWebToken);
        }
Exemplo n.º 5
0
        // PUT: api/User/5
        public HttpResponseMessage Put(User userInfo)
        {
            Common.Models.User savedUser = this.userRep.SaveUser(userInfo);

            var response = Request.CreateResponse <User>(System.Net.HttpStatusCode.Created, savedUser);

            return(response);
        }
Exemplo n.º 6
0
 public Person()
 {
     Address = new Address();
     Courses = new List<Course>();
     Skills = new List<Skill>();
     Experience = new List<Company>();
     Languageses = new List<Language>();
     ParentRecruiter = new User();
 }
Exemplo n.º 7
0
 public Authentication(INotifier notifier, IMessageQueue messageQueue)
 {
     _user                 = new Common.Models.User();
     _storage              = new UserEntity();
     _mapper               = new InitializeMapper().GetMapper;
     _passwordHasher       = new PasswordHasher <Common.Models.User>();
     _notifier             = notifier;
     _messageQueue         = messageQueue;
     _pubSlackAppQueueName = AppSettings.PubSlackAppQueueName;
 }
Exemplo n.º 8
0
        public async Task<bool> UnreadPost(User user, int postId)
        {
            using (var transactionScope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                var sql = @"DELETE FROM ThreadUserViews WHERE ThreadID = @ThreadID AND UserID = @UserID";
                var result = await connection.ExecuteAsync(sql, new
                {
                    ThreadID = postId,
                    UserID = user.ID
                });

                var success = result == 1;
                if (success) transactionScope.Complete();

                return success;
            }
        }
Exemplo n.º 9
0
        public async Task<bool> ReadPost(User user, int postId)
        {
            using (var transactionScope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                var sql = @"INSERT INTO ThreadUserViews
                            (ThreadID, UserID)
                            VALUES (@ThreadID, @UserID)";
                var result = await connection.ExecuteAsync(sql, new
                {
                    ThreadID = postId,
                    UserID = user.ID
                });

                var success = result == 1;
                if(success)
                {
                    transactionScope.Complete();
                }

                return success;
            }
        }
Exemplo n.º 10
0
        public async Task <IActionResult> PutUser([FromBody] Common.Models.User user)
        {
            if (!ModelState.IsValid)
            {
                return(this.BadRequest(ModelState));
            }

            var userEntity = await this.userHelper.GetUserByEmailAsync(user.Email);

            if (userEntity == null)
            {
                return(this.BadRequest("User not found."));
            }

            var city = await this.cityRepository.GetCityByIdAsync(user.CityId);

            if (city != null)
            {
                userEntity.City = city;
            }

            userEntity.FirstName = user.FirstName;
            userEntity.UserName  = user.UserName;
            userEntity.CityId    = user.CityId;

            var respose = await this.userHelper.UpdateUserAsync(userEntity);

            if (!respose.Succeeded)
            {
                return(this.BadRequest(respose.Errors.FirstOrDefault()?.Description));
            }

            var updatedUser = await this.userHelper.GetUserByEmailAsync(user.Email);

            return(Ok(updatedUser));
        }
Exemplo n.º 11
0
 private string HashPassword(Common.Models.User user, string password)
 {
     return(_passwordHasher.HashPassword(user, password));
 }
Exemplo n.º 12
0
 private PasswordVerificationResult ValidatePassword(Common.Models.User user, string hashedPassword, string providedPassword)
 {
     return(_passwordHasher.VerifyHashedPassword(user, hashedPassword, providedPassword));
 }
Exemplo n.º 13
0
        /// <summary>
        /// Processes the image given in the <see cref="HttpContent"/> into a <see cref="UserImage"/> object.
        /// Resizes the image according to the settings given upon instantiation.
        /// </summary>
        /// <param name="user">The user who initiated the procedure</param>
        /// <returns>A processed image file</returns>
        public async Task<Image> ProcessUserImage(User user, HttpContent fileContent, string description)
        {
            using(fileContent)
            {
                // Get filename
                var fullname = Helpers.GetFilename(fileContent.Headers.ContentDisposition.FileName);
                var filename = fullname.Item1.Replace("\"", string.Empty);
                var extension = fullname.Item2.Replace("\"", string.Empty);
                var mime = fileContent.Headers.ContentType.MediaType;

                using (var fileStream = await fileContent.ReadAsStreamAsync())
                {
                    // Retrieve image
                    var originalImage = d.Image.FromStream(fileStream);
                    var format = originalImage.RawFormat;

                    // Convert image to byte array and set file path
                    var originalData = ConvertToByte(originalImage, format);
                    var origData = new Lazy<byte[]>(() => originalData);
                    var origPath = GetPath(user.Username, originalData, extension);

                    // Calculate medium size
                    var mediumWidth = (int)(originalImage.Width * mediumScaleFactor);
                    var mediumHeight = (int)(originalImage.Height * mediumScaleFactor);

                    // Resize image and set file path
                    var previewImage = ResizeImage(originalImage, mediumWidth, mediumHeight);
                    var previewData = ConvertToByte(previewImage, format);
                    var prevData = new Lazy<byte[]>(() => previewData);
                    var prevPath = GetPath(user.Username, previewData, extension);

                    // Calculate height factor & thumbnail height
                    var thumbnailHeightFactor = ((double)(originalImage.Height) / (double)(originalImage.Width));
                    var thumbnailHeight = (int)(thumbnailWidth * thumbnailHeightFactor);

                    // Resize thumbnail and set file path
                    var thumbnailImage = ResizeImage(originalImage, thumbnailWidth, thumbnailHeight);
                    var thumbnailData = ConvertToByte(thumbnailImage, format);
                    var thumbData = new Lazy<byte[]>(() => thumbnailData);
                    var thumbPath = GetPath(user.Username, thumbnailData, extension);

                    // FileInfos
                    var original = new FileInfo { Data = origData, Path = origPath };
                    var preview = new FileInfo { Data = prevData, Path = prevPath };
                    var thumbnail = new FileInfo { Data = thumbData, Path = thumbPath };

                    // Return the processed image file. Note it has not been saved to the database yet!
                    return new Image
                    {
                        Filename = filename,
                        Extension = extension,
                        MimeType = mime,
                        Description = description,
                        Original = original,
                        Preview = preview,
                        Thumbnail = thumbnail,
                        Owner = user,
                        Uploaded = DateTime.Now,
                    };
                }
            }
        }