Esempio n. 1
0
        public override void Execute()
        {
            string username = Helpers.IsNullOrEmptyValidator("Username: "******"Password: "******"Welcome Dr. {doctor.Name} ({doctor.Specialty})!");
        }
Esempio n. 2
0
        public async Task <OperationResult> PasswordRecover(UserDTO userDto)
        {
            var user = Db.UserRepository.Get(userDto.Id);

            if (user == null)
            {
                return(new OperationResult(false, "Not found", ""));
            }

            var newPassword = Guid.NewGuid().ToString();

            user.PasswordHash = PasswordHasher.GenerateHash(newPassword);

            try
            {
                await Db.SaveAsync();

                await _emailService.SendEmailAsync(new EmailDTO
                {
                    Subject        = "EventsExpress password recovery",
                    RecepientEmail = user.Email,
                    MessageText    = $"Hello, {user.Email}.\nYour new Password is: {newPassword}"
                });

                return(new OperationResult(true, "Password Changed", ""));
            }
            catch (Exception)
            {
                return(new OperationResult(false, "Something is wrong", ""));
            }
        }
Esempio n. 3
0
        public override string Execute(string[] data, PhotoShareContext context)
        {
            string username = data[0];
            string password = data[1];

            User currentUser = context.Users
                               .SingleOrDefault(u => u.Username.Equals(username));

            if (currentUser == null)
            {
                throw new ArgumentException("Invalid username or password!");
            }

            string hashedPassword = PasswordHasher.GenerateHash(password + currentUser.Salt);

            if (!currentUser.Password.Equals(hashedPassword))
            {
                throw new ArgumentException("Invalid username or password!");
            }

            if (currentUser.IsDeleted != null && currentUser.IsDeleted.Value)
            {
                throw new InvalidOperationException("Invalid credentials!");
            }

            if (Session.User != null)
            {
                throw new ArgumentException("You should logout first!");
            }

            currentUser.LastTimeLoggedIn = DateTime.Now;
            context.SaveChanges();
            Session.User = currentUser;
            return($"User {currentUser.Username} successfully logged in!");
        }
        public AutoMapperProfile()
        {
            CreateMap <Map, MapDto>().ForMember(dest => dest.WallIcon,
                                                opts => opts.MapFrom(src => src.WallIcon.Img.ToRenderablePictureString()));

            CreateMap <Tank, TankDto>().ForMember(dest => dest.PhotoUrl,
                                                  opts => opts.MapFrom(src => src.Icon.Img.ToRenderablePictureString()));


            CreateMap <User, UserDto>().ReverseMap();

            CreateMap <User, UserInfo>()
            .ForMember(dest => dest.Nickname, opts => opts.MapFrom(src => src.Nickname ?? src.Email.Substring(0, src.Email.IndexOf("@", StringComparison.Ordinal))))
            .ForMember(dest => dest.Role, opts => opts.MapFrom(src => src.Role.Name))
            .ForMember(dest => dest.PhotoUrl,
                       opts => opts.MapFrom(src => src.Photo.Img.ToRenderablePictureString()))
            .ForMember(dest => dest.Gender, opts => opts.MapFrom(src => src.Gender));


            CreateMap <UserDto, UserInfo>()
            .ForMember(dest => dest.Nickname, opts => opts.MapFrom(src => src.Nickname ?? src.Email.Substring(0, src.Email.IndexOf("@", StringComparison.Ordinal))))
            .ForMember(dest => dest.Role, opts => opts.MapFrom(src => src.Role.Name))
            .ForMember(dest => dest.PhotoUrl,
                       opts => opts.MapFrom(src => src.Photo.Img.ToRenderablePictureString()))
            .ForMember(dest => dest.Gender, opts => opts.MapFrom(src => src.Gender));

            CreateMap <LoginDto, UserDto>();

            CreateMap <RegisterDto, UserDto>()
            .ForMember(dest => dest.PasswordHash,
                       opts => opts.MapFrom(src => PasswordHasher.GenerateHash(src.Password)));
        }
Esempio n. 5
0
        ///<summary>
        /// Create an InMemory Store that uses Microsoft.Extensions.DependencyInjection for a MemoryStore Instance
        ///</summary>
        public static IServiceCollection InMemoryStore(this IServiceCollection services, string initialAdminName, string pw, string appName = "testAdmin")
        {
            string hash  = PasswordHasher.GenerateHash(pw);
            var    store = new InMemoryStore(initialAdminName, hash, appName);

            services.AddSingleton <IStorageModel>(store);
            services.AddSingleton <IAuthStorageModel>(store);
            return(services);
        }
Esempio n. 6
0
 public Doctor(string name, string specialty, string username, string password)
 {
     this.Name        = name;
     this.Specialty   = specialty;
     this.Username    = username;
     this.Salt        = PasswordHasher.GenerateSalt();
     this.Password    = PasswordHasher.GenerateHash(password + this.Salt);
     this.Visitations = new List <Visitation>();
 }
Esempio n. 7
0
        public async Task <OperationResult> ChangePasswordAsync(UserDTO userDto, string oldPassword, string newPassword)
        {
            if (VerifyPassword(userDto, oldPassword))
            {
                userDto.PasswordHash = PasswordHasher.GenerateHash(newPassword);

                return(await _userService.Update(userDto));
            }
            return(new OperationResult(false, "Invalid password", ""));
        }
Esempio n. 8
0
        public static void Seed(AppDbContext dbContext)
        {
            dbContext.Database.EnsureCreated();

            //Look for any users
            if (dbContext.Users.Any())
            {
                return; // DB has been seeded
            }


            Role adminRole = new Role {
                Name = "Admin"
            };
            Role userRole = new Role {
                Name = "User"
            };

            dbContext.Role.AddRange(new Role[] { adminRole, userRole });

            var users = new User[] {
                new User {
                    Name           = "Admin",
                    PasswordHash   = PasswordHasher.GenerateHash("1qaz1qaz"),
                    Email          = "*****@*****.**",
                    EmailConfirmed = true,
                    Phone          = "+380974293583",
                    Birthday       = DateTime.Parse("2000-01-01"),
                    Gender         = Gender.Male,
                    Role           = adminRole
                },

                new User {
                    Name           = "UserTest",
                    PasswordHash   = PasswordHasher.GenerateHash("1qaz1qaz"),
                    Email          = "*****@*****.**",
                    EmailConfirmed = true,
                    Phone          = "+380970101013",
                    Birthday       = DateTime.Parse("2000-01-01"),
                    Gender         = Gender.Male,
                    Role           = userRole
                }
            };

            dbContext.Users.AddRange(users);



            dbContext.SaveChanges();
        }
        public Registration Register(RegisterDto registerDto)
        {
            // Generate jwt.
            string token = tokenHandler.GenerateToken(registerDto.Name);

            PasswordHasher hasher = new PasswordHasher();

            registerDto.Password = hasher.GenerateHash(registerDto.Password); // Hash password before registration.

            // Save to storage.
            Account account = mapper.Map <Account>(registerDto);

            repository.InsertEntity(account);
            repository.Save();

            return(new Registration(registerDto.Email, registerDto.Name, token));
        }
Esempio n. 10
0
        public static void Seed(AppDbContext dbContext)
        {
            dbContext.Database.EnsureCreated();

            //Look for any users
            if (dbContext.Users.Any())
            {
                return; // DB has been seeded
            }

            Role adminRole = new Role {
                Name = "Admin"
            };
            Role userRole = new Role {
                Name = "User"
            };

            dbContext.Roles.AddRange(new Role[] { adminRole, userRole });

            var users = new User[] {
                new User {
                    Nickname       = "Admin",
                    PasswordHash   = PasswordHasher.GenerateHash("1qaz1qaz"),
                    Email          = "*****@*****.**",
                    EmailConfirmed = true,
                    Gender         = Gender.Male,
                    IsBlocked      = false,
                    Role           = adminRole
                },

                new User {
                    Nickname       = "UserTest",
                    PasswordHash   = PasswordHasher.GenerateHash("1qaz1qaz"),
                    Email          = "*****@*****.**",
                    EmailConfirmed = true,
                    Gender         = Gender.Male,
                    IsBlocked      = false,
                    Role           = userRole
                }
            };

            dbContext.Users.AddRange(users);

            dbContext.SaveChanges();
        }
        public async Task <IActionResult> Register(LoginDto authRequest)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            var user = _mapper.Map <LoginDto, UserDTO>(authRequest);

            user.PasswordHash = PasswordHasher.GenerateHash(authRequest.Password);

            var result = await _userService.Create(user);

            if (!result.Successed)
            {
                return(BadRequest(result.Message));
            }
            return(Ok());
        }
Esempio n. 12
0
        // RegisterUser <username> <password> <repeat-password> <email>
        public override string Execute(string[] data, PhotoShareContext context)
        {
            string username       = data[0];
            string password       = data[1];
            string repeatPassword = data[2];
            string email          = data[3];

            if (context.Users.Any(u => u.Username == username))
            {
                throw new InvalidOperationException($"Username {username} is already taken!");
            }

            if (!password.Any(char.IsLower) || !password.Any(char.IsDigit))
            {
                throw new ArgumentException($"Value {password} not valid. Password must include a lower letter and a digit.{Environment.NewLine}Invalid Password");
            }

            if (password != repeatPassword)
            {
                throw new ArgumentException("Passwords do not match!");
            }

            string salt = PasswordHasher.GenerateSalt();

            User currentUser = new User
            {
                Username     = username,
                Salt         = salt,
                Password     = PasswordHasher.GenerateHash(password + salt),
                Email        = email,
                IsDeleted    = false,
                RegisteredOn = DateTime.Now
            };

            context.Users.Add(currentUser);
            context.SaveChanges();

            return($"User {currentUser.Username} was registered successfully!");
        }
Esempio n. 13
0
        public UserViewModel AuthernticateUser(string userName, string password)
        {
            try
            {
                var passwordHash = PasswordHasher.GenerateHash(password);
                var user         = context.Db.users.FirstOrDefault(t => t.active == 1 && t.mobilenumber == userName && t.userlevel == 5);
                if (user == null)
                {
                    return(null);
                }
                else
                {
                    if (user.password == passwordHash)
                    {
                        var userVm = new UserViewModel()
                        {
                            Email        = user.email,
                            Id           = user.id,
                            MobileNumber = user.mobilenumber,
                            UserName     = user.username,
                            UserLevel    = user.userlevel
                        };

                        return(userVm);
                    }
                    else
                    {
                        return(null);
                    }
                }
            }
            catch (Exception ex)
            {
                return(null);
            }
        }
Esempio n. 14
0
 public AuthModel(string name, string password)
 {
     Name         = name;
     Password     = password;
     passwordHash = PasswordHasher.GenerateHash(password);
 }
Esempio n. 15
0
 private static bool VerifyPassword(UserDto user, string actualPassword) =>
 (user.PasswordHash == PasswordHasher.GenerateHash(actualPassword));
Esempio n. 16
0
        public static void Seed(AppDbContext dbContext)
        {
            dbContext.Database.EnsureCreated();

            //Look for any users
            if (dbContext.Users.Any())
            {
                return;  // DB has been seeded
            }
            dbContext.Countries.AddRange(LocationParser.GetCountries());

            Role adminRole = new Role {
                Name = "Admin"
            };
            Role userRole = new Role {
                Name = "User"
            };

            dbContext.Roles.AddRange(new Role[] { adminRole, userRole });

            var users = new User[] {
                new User {
                    Name           = "Admin",
                    PasswordHash   = PasswordHasher.GenerateHash("1qaz1qaz"),
                    Email          = "*****@*****.**",
                    EmailConfirmed = true,
                    Phone          = "+380974293583",
                    Birthday       = DateTime.Parse("2000-01-01"),
                    Gender         = Gender.Male,
                    IsBlocked      = false,
                    Role           = adminRole
                },

                new User {
                    Name           = "UserTest",
                    PasswordHash   = PasswordHasher.GenerateHash("1qaz1qaz"),
                    Email          = "*****@*****.**",
                    EmailConfirmed = true,
                    Phone          = "+380970101013",
                    Birthday       = DateTime.Parse("2000-01-01"),
                    Gender         = Gender.Male,
                    IsBlocked      = false,
                    Role           = userRole
                }
            };

            dbContext.Users.AddRange(users);


            var categories = new Category[]
            {
                new Category {
                    Name = "Sea"
                },
                new Category {
                    Name = "Mount"
                },
                new Category {
                    Name = "Summer"
                },
                new Category {
                    Name = "Golf"
                },
                new Category {
                    Name = "Team-Building"
                },
                new Category {
                    Name = "Swimming"
                },
                new Category {
                    Name = "Gaming"
                },
            };

            dbContext.Categories.AddRange(categories);

            dbContext.SaveChanges();
        }
 public override int AuthenticateUser(string username, string password)
 {
     return(base.AuthenticateUser(username, _hasher.GenerateHash(password)));
 }
        // ModifyUser <username> <property> <new value>
        // For example:
        // ModifyUser <username> Password <NewPassword>
        // ModifyUser <username> BornTown <newBornTownName>
        // ModifyUser <username> CurrentTown <newCurrentTownName>
        // !!! Cannot change username
        public override string Execute(string[] data, PhotoShareContext context)
        {
            string username         = data[0];
            string property         = data[1];
            string propertyNewValue = data[2];

            User currentUser = context.Users
                               .SingleOrDefault(u => u.Username.Equals(username));

            if (currentUser == null)
            {
                throw new ArgumentException($"User {username} not found!");
            }

            PropertyInfo[] userProperties = currentUser.GetType()
                                            .GetProperties(BindingFlags.Public | BindingFlags.Instance);

            if (!userProperties.Any(p => p.Name.Equals(property, StringComparison.InvariantCultureIgnoreCase)))
            {
                throw new ArgumentException($"Property {property} not supported!");
            }

            switch (property.ToLower())
            {
            case "password":
                if (!propertyNewValue.Any(char.IsLower) || !propertyNewValue.Any(char.IsDigit))
                {
                    throw new ArgumentException($"Value {propertyNewValue} not valid.{Environment.NewLine}Invalid Password");
                }

                currentUser.Salt     = PasswordHasher.GenerateSalt();
                currentUser.Password = PasswordHasher.GenerateHash(propertyNewValue + currentUser.Salt);
                break;

            case "borntown":
                Town newBornTown = context.Towns.SingleOrDefault(t => t.Name.Equals(propertyNewValue));

                if (newBornTown == null)
                {
                    throw new ArgumentException($"Value {propertyNewValue} not valid.{Environment.NewLine}Town {propertyNewValue} not found!");
                }

                currentUser.BornTown = newBornTown;
                break;

            case "currenttown":
                Town newCurrentTown = context.Towns.SingleOrDefault(t => t.Name.Equals(propertyNewValue));

                if (newCurrentTown == null)
                {
                    throw new ArgumentException($"Value {propertyNewValue} not valid.{Environment.NewLine}Town {propertyNewValue} not found!");
                }

                currentUser.CurrentTown = newCurrentTown;
                break;

            default:
                return($"Property {property} not supported!");
            }

            context.SaveChanges();

            return($"User {username} {property} is {propertyNewValue}.");
        }