Exemple #1
0
        public void TestValidInput()
        {
            IHashManager hashManager = new HashManager();

            string hash1 = hashManager.GetHash("saltStr", "passwordStr", 0);

            Assert.True(hash1 != null);
            Assert.True(hash1 != "");

            string hash2 = hashManager.GetHash("saltStr2", "passwordStr2", 0);

            Assert.False(hash1 == hash2);
        }
Exemple #2
0
        public void TestErroneousInput()
        {
            IHashManager hashManager = new HashManager();

            string hash = hashManager.GetHash("", "", 0);

            Assert.True(hash != null);
            Assert.True(hash != "");

            hash = hashManager.GetHash("!(&#E%&)&", "!)(*E^(~`?", 0);

            Assert.True(hash != null);
            Assert.True(hash != "");
        }
        public void Test_IsValidUser_InvalidPassword()
        {
            HashManager manager = new HashManager();

            string      email    = "*****@*****.**";
            string      password = "******";
            Guid        pwdSalt  = new Guid();
            List <User> users    = new List <User>
            {
                new User {
                    Id          = new Guid(),
                    Credentials = new UserCredentials
                    {
                        PwdHash = manager.GetHash(pwdSalt.ToString(), "Dope123", 0),
                        PwdSalt = pwdSalt
                    },
                    Email    = email,
                    Username = "******",
                    Projects = new List <Guid>()
                }
            };

            var mockDbClient = new MockDBClient()
                               .MockContains <User, string>("users", "Email", email, true)
                               .MockFindByField <User, string>("users", "Email", email, users);

            var mockResource = new MockResource().GetDefaultConfig();

            AuthService authService = new AuthService(mockDbClient.Object, mockResource.Object);
            bool        result      = authService.IsValidUser(email, password);

            Assert.True(result == false);
        }
        public void Test_IsValidUser_MultipleUsers()
        {
            IHashManager manager  = new HashManager();
            string       email    = "*****@*****.**";
            string       password = "******";
            Guid         pwdSalt  = new Guid();
            User         user     = new User
            {
                Id          = new Guid(),
                Credentials = new UserCredentials
                {
                    PwdHash = manager.GetHash(pwdSalt.ToString(), password, 0),
                    PwdSalt = pwdSalt
                },
                Email    = email,
                Username = "******",
                Projects = new List <Guid>()
            };
            List <User> users = new List <User>();

            users.Add(user);
            users.Add(user);

            var mockDbClient = new MockDBClient()
                               .MockContains <User, string>("users", "Email", email, true)
                               .MockFindByField <User, string>("users", "Email", email, users);

            var mockResource = new MockResource().GetDefaultConfig();

            AuthService authService = new AuthService(mockDbClient.Object, mockResource.Object);

            Assert.Throws <InvalidDataException>(() =>
                                                 authService.IsValidUser(email, password)
                                                 );
        }
Exemple #5
0
        public async Task <BaseResponse> Login(LoginInfo loginInfo)
        {
            var userResult = await _userRepository.Get(x => x.Username == loginInfo.Username);

            if (userResult.State != State.Success)
            {
                return(userResult);
            }

            var users = (List <User>)userResult.Result;

            if (!users.Any())
            {
                return(new ErrorResponse(State.NotFound, "Not Found", "Invalid username"));
            }

            var user = users.First();

            if (user.Password != HashManager.GetHash(loginInfo.Password))
            {
                return(new ErrorResponse(State.ProcessError, "Password Error", "Password is incorrect"));
            }

            var loginResponse = new LoginResponse();

            loginResponse.Token = BuildToken(user.Id);
            return(new SuccessResponse(loginResponse));
        }
Exemple #6
0
        /// <summary>
        /// Create a Login resource.
        /// </summary>
        /// <param name="user">the user to log in</param>
        /// <param name="baseAddress">the host to log into</param>
        /// <param name="lang">the culture to retrieve login info into (fr-FR or en-US)</param>
        /// <returns>a login object with credential headers and a User with its Clients</returns>
        public async static Task <object> Login(User user, string baseAddress, string lang)
        {
            if (user == null || user.Password == null)
            {
                throw new HttpResponseException(HttpStatusCode.BadRequest);
            }

            CulturalEnumStringConverter.Culture = new CultureInfo(lang);

            string hashedPassword = HashManager.GetHash(user.Password);

            user.Password = hashedPassword;
            User seekedUser = await _findUser(user.Login);

            if (seekedUser == null || hashedPassword != seekedUser.Password)
            {
                throw new HttpResponseException(HttpStatusCode.Unauthorized);
            }

            await _removeLogout(seekedUser.Login);

            Random r1 = new Random(159736545);
            Random r2 = new Random(1892344171);

            seekedUser.Password = null;
            return(new
            {
                a2un = string.Format("{0}.{1}.{2}", string.Format("{0:X12}", r1.Next(0x5F4A2C3)), string.Format("{0:X18}", r1.Next(0x5FDA6C1)), string.Format("{0:X22}", r1.Next(0x5F1C2C3))),
                az4s = JsonWebTokenManager.CreateToken(user.Login, "user", baseAddress),
                e7gu = string.Format("{0}.{1}.{2}", string.Format("{0:X12}", r2.Next(0x5F4A2C3)), string.Format("{0:X18}", r2.Next(0x5FDA6C1)), string.Format("{0:X22}", r2.Next(0x5F1C2C3))),
                user = seekedUser,
                ranges = await RangeService.GetAllRanges(lang)
            });
        }
Exemple #7
0
        public ActionResult Register(PostRegIn regInfo)
        {
            if (regInfo.Email == null || regInfo.Email == "" ||
                regInfo.Password == null || regInfo.Password == "" ||
                regInfo.Username == null || regInfo.Username == "")
            {
                return(BadRequest());
            }

            IResource resource = new Resource();
            IDbClient db       = new DbClient(resource.GetString("db_base_path"));

            if (db.Contains <User, string>(resource.GetString("db_users_path"), "Email", regInfo.Email))
            {
                return(Conflict());
            }

            // validate email and password
            try
            {
                new MailAddress(regInfo.Email);
            } catch
            {
                return(UnprocessableEntity());
            }

            PasswordValidator pv = new PasswordValidator();

            if (!pv.IsValid(regInfo.Password))
            {
                return(UnprocessableEntity());
            }


            IHashManager    hashManager = new HashManager();
            Guid            salt        = Guid.NewGuid();
            string          hash        = hashManager.GetHash(salt.ToString(), regInfo.Password, 0);
            UserCredentials credentials = new UserCredentials()
            {
                PwdSalt = salt,
                PwdHash = hash
            };

            User newUser = new User()
            {
                Id          = Guid.NewGuid(),
                Email       = regInfo.Email,
                Credentials = credentials,
                Username    = regInfo.Username,
                Projects    = new List <Guid>()
            };

            db.InsertRecord(resource.GetString("db_users_path"), newUser);
            return(CreatedAtAction("Register", regInfo));
        }
Exemple #8
0
        public void TestInvalidInput()
        {
            IHashManager hashManager = new HashManager();

            Assert.Throws <ArgumentNullException>(() =>
                                                  hashManager.GetHash(null, null, 0)
                                                  );

            Assert.Throws <ArgumentNullException>(() =>
                                                  hashManager.GetHash("teststring", null, 0)
                                                  );

            Assert.Throws <ArgumentNullException>(() =>
                                                  hashManager.GetHash(null, "teststring", 0)
                                                  );

            Assert.Throws <ArgumentOutOfRangeException>(() =>
                                                        hashManager.GetHash("teststring", "teststring", -1)
                                                        );
        }
Exemple #9
0
        public async Task <BaseResponse> AddUser(AddUserRequest model)
        {
            var user = new User();

            user.Username = model.Username;
            user.Password = HashManager.GetHash(model.Password);
            var result = await _userRepository.Add(user);

            if (result.State == State.Success)
            {
                var loginResponse = new LoginResponse();
                loginResponse.Token = BuildToken(user.Id);
                return(new SuccessResponse(loginResponse));
            }
            return(result);
        }
Exemple #10
0
        /// <summary>
        /// Create an <see cref="ConceptionDevisWS.Models.User"/>.
        /// </summary>
        /// <param name="user">the user to store</param>
        /// <returns>the created user</returns>
        public async static Task <User> Register(User user)
        {
            using (ModelsDBContext ctx = new ModelsDBContext())
            {
                if (user == null || user.Login == null || user.Password == null)
                {
                    throw new HttpResponseException(HttpStatusCode.BadRequest);
                }
                ctx.Users.Add(user);
                user.Rights   = ERights.ConceptionDevis;
                user.Password = HashManager.GetHash(user.Password);
                await ctx.SaveChangesAsync();

                user.Password = null;
                return(user);
            }
        }
Exemple #11
0
        /// <summary>
        /// Fill the database with test data.
        /// </summary>
        /// <param name="context"></param>
        protected override void Seed(ConceptionDevisWS.Models.ModelsDBContext context)
        {
            Component sectionDroite = new Component {
                Id = 1, Name = "Section droite", Length = 4.0, Angle = EAngle.Straight
            };
            Component sectionFinale = new Component {
                Id = 2, Name = "Section finale", Length = 4.0, Angle = EAngle.Straight
            };
            Component sectionPaloise = new Component {
                Id = 3, Name = "Section paloise", Length = 4.0, Angle = EAngle.Straight
            };
            Module murN1 = new Module {
                Id = 1, Name = "Mur Nord 1", Components = new List <Component> {
                    sectionDroite, sectionFinale
                }
            };
            Module murS1 = new Module {
                Id = 2, Name = "Mur Sud 1", Components = new List <Component> {
                    sectionFinale, sectionPaloise
                }
            };

            context.Modules.AddRange(new List <Module> {
                murN1, murS1
            });

            User tutuUser = new User
            {
                Id       = 1,
                Login    = "******",
                Password = HashManager.GetHash("ah$34!"),
                Rights   = ERights.ConceptionDevis
            };



            context.Users.AddOrUpdate(new User[] { tutuUser });



            Client client = new Client {
                Id         = 2,
                FirstName  = "Test",
                LastName   = "Tartampion",
                Address    = "10 rue Lagrange",
                City       = "Pau",
                ZipCode    = 64000,
                Email      = "*****@*****.**",
                Birdthdate = new DateTime(1984, 11, 16, 0, 0, 0, DateTimeKind.Utc),
                Phone      = "0200094524",
                User       = tutuUser
            };

            Client client2 = new Client
            {
                Id         = 3,
                FirstName  = "Test2",
                LastName   = "LaTruffe",
                Address    = "12 rue Lagrange",
                City       = "Pau",
                ZipCode    = 64000,
                Email      = "*****@*****.**",
                Birdthdate = new DateTime(1984, 11, 14, 0, 0, 0, DateTimeKind.Utc),
                Phone      = "0100094524",
                User       = tutuUser
            };

            Client maderaClient = new Client
            {
                Id         = 1,
                FirstName  = "Madera",
                LastName   = "",
                Birdthdate = DateTime.ParseExact("16/02/1988", "dd/MM/yyyy", null),
                ZipCode    = -1
            };

            context.Clients.AddOrUpdate(new Client[] { maderaClient, client, client2 });



            Project firstProj = new Project
            {
                Id                 = 1,
                Name               = "SuperProjet1",
                CreationDate       = DateTime.UtcNow,
                State              = EProjectState.Signed,
                Client             = client,
                TechnicalSheetPath = @"/techSheets/techSheet_1.pdf"
            };


            context.Projects.AddOrUpdate(new Project[] {
                firstProj
            });

            Range nature = new Range
            {
                Id             = 1,
                Name           = "Nature",
                ExtFinishings  = EExtFinishing.Wood,
                FrameQualities = EFrameQuality.Wood,
                Insulators     = EInsulatorKind.RockWool,
                FrameStructure = EFrameStructure.Angleless
            };

            Range bois = new Range
            {
                Id             = 2,
                Name           = "Bois",
                ExtFinishings  = EExtFinishing.Wood | EExtFinishing.Roughcast,
                FrameQualities = EFrameQuality.Wood | EFrameQuality.PVC,
                Insulators     = EInsulatorKind.Styrofoam,
                FrameStructure = EFrameStructure.OpenAngle
            };

            Range couleur = new Range
            {
                Id             = 3,
                Name           = "Couleurs",
                ExtFinishings  = EExtFinishing.Roughcast | EExtFinishing.Paint,
                FrameQualities = EFrameQuality.Wood | EFrameQuality.PVC,
                Insulators     = EInsulatorKind.GlassWool,
                FrameStructure = EFrameStructure.ClosedAngle
            };

            context.Ranges.AddOrUpdate(nature, bois, couleur);

            Model maison3ChSdb = new Model
            {
                Name = "Maison 3 Chambres",
                BasePricePercentage = 15.00,
                Filling             = EFillingKind.NaturalWool,
                IntFinishing        = EIntFinishing.Plasterboard,
                ExtFinishing        = EExtFinishing.Roughcast,
                FrameQuality        = EFrameQuality.Wood,
                Range = bois
            };

            Model villaAvecTerrasse = new Model
            {
                Name = "Maison a étage",
                BasePricePercentage = 25.00,
                Filling             = EFillingKind.NaturalWool,
                IntFinishing        = EIntFinishing.Plasterboard,
                ExtFinishing        = EExtFinishing.Roughcast,
                FrameQuality        = EFrameQuality.PVC,
                Range = bois
            };

            Model maison2ChJardin = new Model
            {
                Name = "Maison 2 Chambres avec jardin",
                BasePricePercentage = 18.00,
                Filling             = EFillingKind.NaturalWool,
                IntFinishing        = EIntFinishing.Styrofoam,
                ExtFinishing        = EExtFinishing.Wood,
                FrameQuality        = EFrameQuality.Wood,
                Range = bois
            };

            Model chalet2Ch = new Model
            {
                Name = "Chalet 2 Chambres",
                BasePricePercentage = 35.00,
                Filling             = EFillingKind.NaturalWool,
                IntFinishing        = EIntFinishing.Plasterboard,
                ExtFinishing        = EExtFinishing.Wood,
                FrameQuality        = EFrameQuality.Wood,
                Range = nature
            };

            Model abrisMontagnard = new Model
            {
                Name = "Abris Montagnard",
                BasePricePercentage = 28.00,
                Filling             = EFillingKind.Hemp,
                IntFinishing        = EIntFinishing.Styrofoam,
                ExtFinishing        = EExtFinishing.Wood,
                FrameQuality        = EFrameQuality.Wood,
                Range = nature
            };

            Model villaAvecPiscine = new Model
            {
                Name = "Villa avec piscine",
                BasePricePercentage = 40.00,
                Filling             = EFillingKind.NaturalWool,
                IntFinishing        = EIntFinishing.Wood,
                ExtFinishing        = EExtFinishing.Wood,
                FrameQuality        = EFrameQuality.Wood,
                Range = nature
            };

            Model creche = new Model
            {
                Name = "Creche",
                BasePricePercentage = 8.00,
                Filling             = EFillingKind.WoodenWool,
                IntFinishing        = EIntFinishing.Plasterboard,
                ExtFinishing        = EExtFinishing.Roughcast,
                FrameQuality        = EFrameQuality.PVC,
                Range = couleur
            };

            Model localProCrea = new Model
            {
                Name = "Local Professionnel (Créatif)",
                BasePricePercentage = 12.00,
                Filling             = EFillingKind.WoodenWool,
                IntFinishing        = EIntFinishing.Wood,
                ExtFinishing        = EExtFinishing.Paint,
                FrameQuality        = EFrameQuality.PVC,
                Range = couleur
            };

            Model localProDesign = new Model
            {
                Name = "Local Professionnel (Design)",
                BasePricePercentage = 15.00,
                Filling             = EFillingKind.Hemp,
                IntFinishing        = EIntFinishing.Wood,
                ExtFinishing        = EExtFinishing.Roughcast,
                FrameQuality        = EFrameQuality.PVC,
                Range = couleur
            };

            context.Models.AddOrUpdate(maison3ChSdb, villaAvecTerrasse, maison2ChJardin, chalet2Ch, abrisMontagnard, villaAvecPiscine, creche, localProCrea, localProDesign);

            Module porteRenforcee = new Module {
                Id = 1, Name = "Porte Renforcee", Price = 4, Components = new List <Component> {
                    sectionDroite
                }
            };
            Module fenetreRonde = new Module {
                Id = 2, Name = "Fenêtre Ronde", Price = 4, Components = new List <Component> {
                    sectionDroite
                }
            };
            Module fenetreOuverte = new Module {
                Id = 3, Name = "Fenêtre Ouverte", Price = 4, Components = new List <Component> {
                    sectionDroite
                }
            };
            Module palissade = new Module {
                Id = 4, Name = "Palissade", Price = 4, Components = new List <Component> {
                    sectionDroite
                }
            };
            Module decorationInt = new Module {
                Id = 5, Name = "Decoration Int 1", Price = 4, Components = new List <Component> {
                    sectionDroite
                }
            };
            Module archeVoute = new Module {
                Id = 6, Name = "Arche Voute", Price = 4, Components = new List <Component> {
                    sectionDroite
                }
            };

            context.Modules.AddRange(new List <Module> {
                porteRenforcee, fenetreRonde, fenetreOuverte, palissade, decorationInt, archeVoute
            });

            maison3ChSdb.Modules      = new List <Module>();
            maison2ChJardin.Modules   = new List <Module>();
            villaAvecTerrasse.Modules = new List <Module>();

            maison3ChSdb.Modules.AddRange(new Module[] { fenetreRonde, fenetreOuverte, palissade });
            maison2ChJardin.Modules.AddRange(new Module[] { decorationInt, archeVoute });
            villaAvecTerrasse.Modules.AddRange(new Module[] { porteRenforcee });
        }
Exemple #12
0
        public User GetUser(string login, string password)
        {
            var passwordHash = HashManager.GetHash(password);

            return(_context.Users.FirstOrDefault(m => m.Login == login && m.PasswordHash == passwordHash));
        }