public ActionResult Edit([Bind(Include = "Id,FirstName,LastName,Email,Password,ConfirmPassword")] UserEditViewModel viewModel)
        {
            if (!ModelState.IsValid)
            {
                return(View(viewModel));
            }

            var user = _db.Users.AsNoTracking().FirstOrDefault(x => x.Id == viewModel.Id);

            if (user == null)
            {
                this.Flash("warning", "Oops! Something when wrong. Please logout, log back in, and then try again.");
                return(View(viewModel));
            }

            user.FirstName = viewModel.FirstName;
            user.LastName  = viewModel.LastName;
            user.Email     = viewModel.Email;

            if (!string.IsNullOrEmpty(viewModel.Password))
            {
                user.Password = SHA256Hasher.Create(viewModel.Password);
            }

            if (!string.IsNullOrEmpty(viewModel.Role))
            {
                user.Role = viewModel.Role;
            }

            _db.Entry(user).State = EntityState.Modified;
            _db.SaveChanges();

            this.Flash("success", "Account Updated!");
            return(RedirectToAction("Index"));
        }
示例#2
0
        public static bool registroUsuario(String cadenausuario, String email, String passwordTextoPlano, String usuarioCreo, Int32 sistemaUsuario)
        {
            bool ret = false;

            try
            {
                using (DbConnection db = new OracleContext().getConnection())
                {
                    Usuario usuario = new Usuario();
                    usuario.usuario = cadenausuario;
                    usuario.email   = email;
                    string[] hashedData = SHA256Hasher.ComputeHash(passwordTextoPlano);
                    usuario.password       = hashedData[0];
                    usuario.salt           = hashedData[1];
                    usuario.fechaCreacion  = DateTime.Now;
                    usuario.usuarioCreo    = usuarioCreo;
                    usuario.estado         = 1;
                    usuario.sistemaUsuario = sistemaUsuario;
                    db.Query <Usuario>("INSERT INTO USUARIO VALUES (:usuario, :password, :salt, :email, :usuarioCreo, :usuarioActualizo, :fechaCreacion, :fechaActualizacion, :estado, :sistemaUsuario)", usuario);
                    ret = true;
                }
            }
            catch (Exception e)
            {
                CLogger.write("4", "UsuarioDAO", e);
            }

            return(ret);
        }
示例#3
0
        public void Hashers_HMAC_SHA256()
        {
            byte[] data = new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
            byte[] key;
            byte[] digest;

            key    = new byte[] { 0, 1, 2, 3, 4, 5 };
            digest = SHA256Hasher.Compute(key, data);
            Assert.AreEqual(SHA256Hasher.DigestSize, digest.Length);

            key = new byte[128];
            for (int i = 0; i < key.Length; i++)
            {
                key[i] = (byte)i;
            }

            digest = SHA256Hasher.Compute(key, data);
            Assert.AreEqual(SHA256Hasher.DigestSize, digest.Length);

            // $todo(jeff.lill):
            //
            // At some point I'd like to verify this
            // against a hash produced by another
            // codebase.
        }
示例#4
0
        private static Hasher CreateHasher(int crypto)
        {
            Hasher hasher = null;

            switch (crypto)
            {
            case (int)HashName.MD5:
                hasher = new MD5Hasher();
                break;

            case (int)HashName.SHA1:
                hasher = new SHA1Hasher();
                break;

            case (int)HashName.SHA256:
                hasher = new SHA256Hasher();
                break;

            case (int)HashName.SHA384:
                hasher = new SHA384Hasher();
                break;

            case (int)HashName.SHA512:
                hasher = new SHA512Hasher();
                break;
            }
            return(hasher);
        }
示例#5
0
        public void InitAdmin(string login, string password)
        {
            //-----------------------

            //-----------------------
            var hasher = new SHA256Hasher();

            CheckAdmin(login);
            Data.UserRepository.Add(new DAL.Entities.User
            {
                Login    = login,
                Password = hasher.Get(password),
                Info     = new DAL.Entities.UserInfo
                {
                    FullName = ""
                },
                Level = 2,
                Email = new Contact
                {
                    Value     = "*****@*****.**",
                    Confirmed = true
                },
                Phone = new Contact
                {
                    Value     = "+79995701322",
                    Confirmed = true
                },
                authType = AuthType.Phone
            });
        }
示例#6
0
        public static bool cambiarPassword(String usuario, String password, String usuarioActualizo)
        {
            bool ret = false;

            try
            {
                using (DbConnection db = new OracleContext().getConnection())
                {
                    Usuario usuarioCambio = getUsuario(usuario);
                    if (usuarioCambio != null)
                    {
                        string[] hashedData = SHA256Hasher.ComputeHash(password);
                        usuarioCambio.password           = hashedData[0];
                        usuarioCambio.salt               = hashedData[1];
                        usuarioCambio.usuarioActualizo   = usuarioActualizo;
                        usuarioCambio.fechaActualizacion = DateTime.Now;

                        db.Query <Usuario>("UPDATE USUARIO SET password=:password, salt=:salt, email=:email, usuario_creo=:usuarioCreo, usuario_actualizo=:usuarioActualizo, fecha_creacion=:fechaCreacion, fecha_actualizacion=:fechaActualizacion, estado=:estado, sistema_usuario=:sistemaUsuario WHERE usuario=:usuario", usuarioCambio);
                        ret = true;
                    }
                }
            } catch (Exception e) {
                CLogger.write("6", "UsuarioDAO", e);
            }

            return(ret);
        }
示例#7
0
        public void TestBHasher()
        {
            SHA256Hasher hasher = SingletonObjects.Hasher;
            string       hash1  = hasher.GenerateHash(Encoding.UTF8.GetBytes("password"));
            string       hash2  = hasher.GenerateHash(Encoding.UTF8.GetBytes("password"));

            Assert.IsTrue(hasher.CompareHash(hash1, hash2));
        }
示例#8
0
 public override Task <bool> CheckPasswordAsync(User user, string password)
 {
     if (user != null)
     {
         string hash = SHA256Hasher.ComputeHash(password, user.Salt);
         return(Task.FromResult(hash.Equals(user.PasswordHash)));
     }
     return(Task.FromResult(false));
 }
示例#9
0
        public void Hashers_SHA256()
        {
            EnhancedMemoryStream ms;

            byte[] data;
            byte[] digest1, digest2;

            digest1 = SHA256Hasher.Compute(new byte[] { 0, 1, 2, 3 }, 0, 4);
            Assert.AreEqual(32, digest1.Length);
            Assert.AreEqual(32, SHA256Hasher.DigestSize);

            digest2 = SHA256Hasher.Compute(new byte[] { 1, 1, 2, 3 }, 0, 4);
            CollectionAssert.AreNotEqual(digest1, digest2);

            digest1 = SHA256Hasher.Compute(new byte[0]);
            Assert.AreEqual(32, digest1.Length);
            Assert.AreEqual(32, SHA256Hasher.DigestSize);

            digest1 = SHA256Hasher.Compute(new byte[] { 0, 1, 2, 3 });
            ms      = new EnhancedMemoryStream();

            ms.Seek(0, SeekOrigin.Begin);
            ms.Write(new byte[] { 0, 1, 2, 3 }, 0, 4);
            ms.Seek(0, SeekOrigin.Begin);
            digest2 = SHA256Hasher.Compute(ms, 4);
            CollectionAssert.AreEqual(digest1, digest2);
            Assert.AreEqual(32, digest2.Length);
            Assert.AreEqual(0, ms.Position);

            data = new byte[2048];
            for (int i = 0; i < data.Length; i++)
            {
                data[i] = (byte)i;
            }

            digest1 = SHA256Hasher.Compute(data);

            ms.Seek(0, SeekOrigin.Begin);
            ms.Write(data, 0, data.Length);
            ms.Seek(0, SeekOrigin.Begin);

            digest2 = SHA256Hasher.Compute(ms, data.Length);
            CollectionAssert.AreEqual(digest1, digest2);
            Assert.AreEqual(32, digest2.Length);
            Assert.AreEqual(0, ms.Position);

            digest1 = SHA256Hasher.Compute("hello");
            digest2 = SHA256Hasher.Compute("world");
            CollectionAssert.AreNotEqual(digest1, digest2);
            CollectionAssert.AreEqual(digest1, SHA256Hasher.Compute("hello"));
        }
示例#10
0
    public string AuthenticateGetUseridDL(string LoginId, string SaltedPasswordHash, string Salt)
    {
        DataTable    dt                   = new DataTable();
        string       dbPasswordHash       = string.Empty;
        SHA256Hasher objhash              = new SHA256Hasher();
        string       saltedDbPasswordHash = string.Empty;

        try
        {
            sCon = new Connection();
            con  = new SqlConnection();
            cmd  = new SqlCommand();
            using (con = sCon.getConnection())
            {
                using (cmd = con.CreateCommand())
                {
                    cmd.CommandText = "usp_getLoginIdDetails";
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.Add(new SqlParameter {
                        ParameterName = "@LoginId", DbType = DbType.String, Size = 50, Value = LoginId
                    });
                    using (SqlDataAdapter da = new SqlDataAdapter(cmd))
                    {
                        da.Fill(dt);
                    }
                }
            }
        }
        catch (Exception e)
        {
            throw e;
        }
        finally
        {
            if (con.State == ConnectionState.Open)
            {
                cmd.Dispose();
                sCon = null;
            }
        }
        if (dt.Rows.Count > 0)
        {
            dbPasswordHash       = dt.Rows[0]["Password"].ToString();
            saltedDbPasswordHash = objhash.Hash(Salt + dbPasswordHash);
            if (saltedDbPasswordHash.Equals(saltedDbPasswordHash))
            {
                return(dt.Rows[0]["UserId"].ToString() + ";" + dt.Rows[0]["N_Name"].ToString() + ";" + dt.Rows[0]["DesignationName"].ToString());
            }
        }
        return("NOTAUTHENTICATED");
    }
示例#11
0
        public async Task CreateUserAsync(User user)
        {
            if (user == null)
            {
                throw new ArgumentNullException(nameof(user));
            }

            SHA256Hasher hasher = new SHA256Hasher();
            string       salt   = await hasher.GenerateSaltAsync(10);

            user.Salt     = salt;
            user.Password = await hasher.EncryptStringSHA256Async(user.Password, salt);

            await _context.AddAsync(user);
        }
        public ActionResult Register([Bind(Include = "Id,FirstName,LastName,Email,Password,Role,ConfirmPassword")] UserCreateViewModel tempUser)
        {
            if (!ModelState.IsValid)
            {
                return(View(tempUser));
            }

            var hashedPassword   = SHA256Hasher.Create(tempUser.Password);
            var existingCustomer = _db.Users.FirstOrDefault(x => x.Email == tempUser.Email &&
                                                            x.Password.Equals(hashedPassword));

            if (existingCustomer != null)
            {
                ModelState.AddModelError(string.Empty, "That email is already being used with another account.");
                return(View(tempUser));
            }

            var role = (!string.IsNullOrEmpty(tempUser.Role)) ? tempUser.Role : "Customer";

            if (role.Equals("Customer"))
            {
                _db.Users.Add(new Customer
                {
                    FirstName = tempUser.FirstName,
                    LastName  = tempUser.LastName,
                    Email     = tempUser.Email,
                    Password  = SHA256Hasher.Create(tempUser.Password),
                    Role      = (!string.IsNullOrEmpty(tempUser.Role)) ? tempUser.Role : "Customer"
                });
            }
            else
            {
                _db.Users.Add(new User
                {
                    FirstName = tempUser.FirstName,
                    LastName  = tempUser.LastName,
                    Email     = tempUser.Email,
                    Password  = hashedPassword,
                    Role      = (!string.IsNullOrEmpty(tempUser.Role)) ? tempUser.Role : "Customer"
                });
            }

            _db.SaveChanges();

            this.Flash("success", "Registration complete!");
            return(RedirectToAction("Login", "Authentication"));
        }
示例#13
0
        public async Task <User> GetUserWithEmailAndPasswordAsync(string email, string password)
        {
            User         user   = null;
            SHA256Hasher hasher = new SHA256Hasher();

            await Task.Run(() => {
                user = _context.Users?.Where(user =>
                                             user.Email == email
                                             ).FirstOrDefault();
            });

            if (
                user != null &&
                user.Password == await hasher.EncryptStringSHA256Async(password, user.Salt)
                )
            {
                return(user);
            }
            return(null);
        }
示例#14
0
        public static Usuario setNuevoPassword(Usuario usuario, String password)
        {
            try
            {
                if (usuario != null)
                {
                    using (DbConnection db = new OracleContext().getConnection())
                    {
                        string[] hashedData = SHA256Hasher.ComputeHash(password);
                        usuario.password      = hashedData[0];
                        usuario.salt          = hashedData[1];
                        usuario.fechaCreacion = DateTime.Now;

                        db.Query <Usuario>("UPDATE USUARIO SET password=:password, salt=:salt, email=:email, usuario_creo=:usuarioCreo, usuario_actualizo=:usuarioActualizo, fecha_creacion=:fechaCreacion, fecha_actualizacion=:fechaActualizacion, estado=:estado, sistema_usuario=:sistemaUsuario WHERE usuario=:usuario", usuario);
                    }
                }
            }
            catch (Exception e)
            {
                CLogger.write("35", "UsuarioDAO", e);
            }
            return(usuario);
        }
示例#15
0
        /// <summary>
        /// Authenticates the account credentials against the authentication extension.
        /// </summary>
        /// <param name="realm">The authentication realm.</param>
        /// <param name="account">The account ID.</param>
        /// <param name="password">The password.</param>
        /// <returns>A <see cref="AuthenticationResult" /> instance with the result of the operation.</returns>
        /// <remarks>
        /// <para>
        /// The <see cref="AuthenticationResult.Status" /> property indicates the disposition
        /// of the authentication operation.  Extensions will return <see cref="AuthenticationStatus.Authenticated" />
        /// if the operation was successful.  Authentication failures due to the
        /// sumbission of invalid credentials will be indicated by returning one of
        /// the error codes.  Extensions may return specific error codes such as
        /// <see cref="AuthenticationStatus.BadPassword" /> and <see cref="AuthenticationStatus.BadAccount" />
        /// or the generic error code <see cref="AuthenticationStatus.AccessDenied" />.
        /// </para>
        /// <para>
        /// The <see cref="AuthenticationResult.MaxCacheTime" /> returns as the maximum time the
        /// results of the authentication operation should be cached.
        /// </para>
        /// </remarks>
        /// <exception cref="AuthenticationException">Thrown for authentication related exception.</exception>
        public AuthenticationResult Authenticate(string realm, string account, string password)
        {
            OdbcConnection dbCon;
            OdbcCommand    cmd;
            OdbcDataReader reader = null;
            MacroProcessor processor;
            string         _conString;
            string         query;
            int            authCode;

            using (TimedLock.Lock(this))
            {
                if (!IsOpen)
                {
                    throw new AuthenticationException("Authentication extension is closed.");
                }

                cAuthentications++;
                _conString = conString;

                // Substitute the credentials into the query template.

                processor = new MacroProcessor();
                processor.Add("realm", SqlHelper.Literal(realm));
                processor.Add("account", SqlHelper.Literal(account));
                processor.Add("password", SqlHelper.Literal(password));
                processor.Add("md5-password", SqlHelper.Literal(MD5Hasher.Compute(password)));
                processor.Add("sha1-password", SqlHelper.Literal(SHA1Hasher.Compute(password)));
                processor.Add("sha256-password", SqlHelper.Literal(SHA256Hasher.Compute(password)));
                processor.Add("sha512-password", SqlHelper.Literal(SHA512Hasher.Compute(password)));
                query = processor.Expand(queryTemplate);
            }

            // Perform the query.

            dbCon = new OdbcConnection(_conString);
            dbCon.Open();

            try
            {
                cmd             = dbCon.CreateCommand();
                cmd.CommandText = query;
                cmd.CommandType = CommandType.Text;

                perf.Queries.Increment();
                reader = cmd.ExecuteReader();
                if (!reader.Read())
                {
                    authCode = (int)AuthenticationStatus.AccessDenied; // Empty result set
                }
                else
                {
                    object o    = reader[0];
                    Type   type = o.GetType();

                    if (type == typeof(byte))
                    {
                        authCode = (int)(byte)o;
                    }
                    else if (type == typeof(int))
                    {
                        authCode = (int)o;
                    }
                    else if (type == typeof(long))
                    {
                        authCode = (int)(long)o;
                    }
                    else
                    {
                        throw new AuthenticationException("ODBC authenticate query returned a [{0}] instead of the expected [integer].", type.Name);
                    }

                    if (authCode < 0 || authCode > 5)
                    {
                        throw new AuthenticationException("ODBC authenticate query returned the invalid return code [{0}]. Valid codes range from 0..5", authCode);
                    }
                }
            }
            catch (Exception e)
            {
                perf.Exceptions.Increment();
                throw new AuthenticationException(e);
            }
            finally
            {
                if (reader != null)
                {
                    reader.Close();
                }

                dbCon.Close();
            }

            return(new AuthenticationResult((AuthenticationStatus)authCode, maxCacheTime));
        }
示例#16
0
        private void ProcessRequest(Options commandLineOptions)
        {
            StreamHasher fileHashMaker;

            switch (commandLineOptions.HashAgorithm.ToUpper())
            {
            case "MD160":
                fileHashMaker = new MD160Hasher();
                break;

            case "SHA1":
                fileHashMaker = new SHA1Hasher();
                break;

            case "SHA256":
                fileHashMaker = new SHA256Hasher();
                break;

            case "SHA384":
                fileHashMaker = new SHA384Hasher();
                break;

            case "SHA512":
                fileHashMaker = new SHA512Hasher();
                break;

            case "MD5":
            default:
                fileHashMaker = new MD5Hasher();
                break;
            }

            fileHashMaker.HashBlockProcessed += fileHashMaker_HashBlockProcessed;

            List <String[]> inputFiles = new List <String[]>();

            if (commandLineOptions.Concatenate)
            {
                // Files will be treated as a single stream -
                // copy all filenames into a string array,
                // then add the array to the List
                String[] files = new String[commandLineOptions.Items.Count];
                for (int loop = 0; loop < commandLineOptions.Items.Count; loop++)
                {
                    files[loop] = commandLineOptions.Items[loop];
                }
                inputFiles.Add(files);
            }
            else
            {
                // Each file treated as a separate entity -
                // copy each filename into a separate string array,
                // then add each array to the List
                foreach (String fileToProcess in commandLineOptions.Items)
                {
                    String[] file = new String[] { fileToProcess };
                    inputFiles.Add(file);
                }
            }
            foreach (String[] fileEntry in inputFiles)
            {
                byte[] fileHash = fileHashMaker.ComputeFileHash(fileEntry, (int)commandLineOptions.BlockSize);
                Console.WriteLine(commandLineOptions.HashAgorithm.ToUpper() + ": " + BitConverter.ToString(fileHash));

                if (!string.IsNullOrWhiteSpace(commandLineOptions.AppendToHashFile))
                {
                    var settings = HashFile.OpenFile(commandLineOptions.AppendToHashFile);
                    settings.Add(fileEntry[0], BitConverter.ToString(fileHash).Replace("-", string.Empty), commandLineOptions.HashAgorithm.ToUpper());
                    settings.Save();
                }
            }
        }
 private void LoginPage_Loaded(object sender, RoutedEventArgs e)
 {
     this.hasher    = new SHA256Hasher();
     this.validator = new Validator();
 }
        /// <summary>
        /// Seed the default data.
        /// </summary>
        /// <param name="db">DbContext object</param>
        protected override void Seed(OrderingSystemDbContext db)
        {
            //Import default users
            var users = new List <User>()
            {
                new User()
                {
                    FirstName = "John",
                    LastName  = "Doe",
                    Email     = "*****@*****.**",
                    Password  = SHA256Hasher.Create("test123"),
                    Role      = "Admin"
                },
                new Customer()
                {
                    FirstName = "Jane",
                    LastName  = "Doe",
                    Email     = "*****@*****.**",
                    Password  = SHA256Hasher.Create("test123"),
                    Role      = "Customer"
                }
            };

            db.Users.AddRange(users);


            //Add default categories
            var categories = new List <Category>()
            {
                new Category()
                {
                    Name = "Pizza",
                    Url  = "pizza"
                },
                new Category()
                {
                    Name = "Sides",
                    Url  = "sides"
                },
                new Category()
                {
                    Name = "drinks",
                    Url  = "drinks"
                },
                new Category()
                {
                    Name = "Desserts",
                    Url  = "desserts"
                }
            };

            db.Categories.AddRange(categories);


            //Add menu items
            var menuItems = new List <MenuItem>()
            {
                new MenuItem()
                {
                    Name       = "Cheese Pizza",
                    Price      = 5.00M,
                    CategoryId = 1
                },
                new MenuItem()
                {
                    Name       = "Sausage Pizza",
                    Price      = 5.00M,
                    CategoryId = 1
                },
                new MenuItem()
                {
                    Name       = "Pepperoni Pizza",
                    Price      = 5.00M,
                    CategoryId = 1
                },
                new MenuItem()
                {
                    Name       = "Breadsticks (6 pack)",
                    Price      = 4.00M,
                    CategoryId = 2
                },
                new MenuItem()
                {
                    Name       = "Marinara Sauce",
                    Price      = .50M,
                    CategoryId = 2
                },
                new MenuItem()
                {
                    Name       = "Garlic Sauce",
                    Price      = .50M,
                    CategoryId = 2
                },
                new MenuItem()
                {
                    Name       = "Coca-Cola 2L",
                    Price      = 2.00M,
                    CategoryId = 3
                },
                new MenuItem()
                {
                    Name       = "Pepsi 2L",
                    Price      = 2.00M,
                    CategoryId = 3
                },
                new MenuItem()
                {
                    Name       = "Cinnamon Rolls",
                    Price      = 6.00M,
                    CategoryId = 4
                }
            };

            db.MenuItems.AddRange(menuItems);

            //Complete seeding process
            base.Seed(db);
        }
示例#19
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            //----------------------------------------------------
            IConfigService configService     = new XMLConfigService("Config.xml");
            IMessenger     messenger_sms     = new SmsMessenger();
            IMessenger     messenger_email   = new EmailMessenger();
            IPassHasher    passHasher        = new SHA256Hasher();
            IKeyGenerator  smallKeyGenerator = new SmallKeyGenerator();
            IKeyGenerator  bigKeyGenerator   = new BigKeyGenerator();
            IRegValidator  regValidator      = new RegValidator();
            IUOWFactory    UOWFactory        = new EFUOWFactory(configService.ConnectionString);
            IGetUserDTO    getUserDTO        = new GetUserDTO();

            //----------------------------------------------------
            IClaimService claimService = new ClaimService(UOWFactory);

            //----------------------------------------------------
            services.AddSingleton <IConfigService, IConfigService>(
                serviceProvider =>
            {
                return(configService);
            }
                );
            //----------------------------------------------------
            services.AddSingleton <IGetUserDTO, IGetUserDTO>(
                serviceProvider =>
            {
                return(getUserDTO);
            }
                );
            //----------------------------------------------------
            services.AddSingleton <IUOWFactory, IUOWFactory>(
                serviceProvider =>
            {
                return(UOWFactory);
            }
                );

            services.AddSingleton <IClaimService, ClaimService>();
            //-----------------------------------------------------

            services.AddSingleton <IUserService, UserAuthService>(
                serviceProvider =>
            {
                return(new UserAuthService(
                           UOWFactory,
                           new AuthKeyService(smallKeyGenerator, messenger_sms),
                           new AuthKeyService(smallKeyGenerator, messenger_email),
                           passHasher,
                           regValidator,
                           claimService,
                           bigKeyGenerator,
                           getUserDTO
                           ));
            }
                );

            services.AddSingleton <IProfileService, ProfileService>(
                serviceProvider =>
            {
                IConfirmService emailCS = new ConfirmService(
                    new ConfirmKeyService(bigKeyGenerator, messenger_email)
                    );
                IConfirmService phoneCS = new ConfirmService(
                    new ConfirmKeyService(smallKeyGenerator, messenger_sms)
                    );
                return(new ProfileService(
                           UOWFactory,
                           regValidator,
                           emailCS,
                           phoneCS,
                           passHasher,
                           claimService,
                           getUserDTO
                           ));
            }
                );

            services.AddSingleton <IRestorePasswordService, RestorePasswordService>(
                serviceProvider =>
            {
                var emaiCKS  = new ConfirmKeyService(bigKeyGenerator, messenger_email);
                var phoneCKS = new ConfirmKeyService(smallKeyGenerator, messenger_sms);
                return(new RestorePasswordService(UOWFactory, emaiCKS, phoneCKS, new RegValidator(), passHasher));
            }
                );
            //---------Forum Services--------------------------------
            IGroupRules     groupRules     = new GroupRules();
            ISectionRules   sectionRules   = new SectionRules(groupRules);
            IThemeRules     themeRules     = new ThemeRules(sectionRules);
            IMessageRules   messageRules   = new MessageRules(themeRules, sectionRules);
            IDTOHelper      dtoHelper      = new DTOHelper();
            IForumDTOHelper forumDTOHelper = new ForumDTOHelper(messageRules, themeRules, sectionRules, groupRules, dtoHelper);

            services.AddSingleton <IGroupService, GroupService>(
                serviceProvider =>
            {
                return(new GroupService(groupRules, getUserDTO, UOWFactory, forumDTOHelper));
            }
                );

            services.AddSingleton <ISectionService, SectionService>(
                serviceProvider =>
            {
                return(new SectionService(sectionRules, getUserDTO, UOWFactory, forumDTOHelper));
            }
                );

            services.AddSingleton <IThemeService, ThemeService>(
                serviceProvider =>
            {
                return(new ThemeService(themeRules, getUserDTO, UOWFactory, forumDTOHelper));
            }
                );

            services.AddSingleton <IMessageService, MessageService>(
                serviceProvider =>
            {
                return(new MessageService(messageRules, getUserDTO, UOWFactory, forumDTOHelper));
            }
                );

            services.AddSingleton <IForumService, ForumService>(
                serviceProvider =>
            {
                return(new ForumService(getUserDTO, UOWFactory, forumDTOHelper, groupRules));
            }
                );
            //--------------------Page Services--------------------
            IPageRules pageRules = new PageRules();
            INoteRules noteRules = new NoteRules();

            services.AddSingleton <IPageService, PageService>(
                serviceProvider =>
            {
                return(new PageService(pageRules, UOWFactory, getUserDTO, dtoHelper));
            }
                );

            services.AddSingleton <IBlogService, BlogService>(
                serviceProvider =>
            {
                return(new BlogService(noteRules, UOWFactory, getUserDTO, dtoHelper));
            }
                );

            //-------------------------------------------------------
            services.AddSingleton <IImageService, ImageService>(
                serviceProvider =>
            {
                return(new ImageService(UOWFactory, getUserDTO));
            }
                );
            //-------------------------------------------
            services.AddSingleton <IAdminService, AdminService>(
                serviceProvider =>
            {
                return(new AdminService(getUserDTO, UOWFactory));
            }
                );

            services.Configure <FormOptions>(x =>
            {
                x.ValueCountLimit          = int.MaxValue;
                x.MemoryBufferThreshold    = int.MaxValue;
                x.ValueLengthLimit         = int.MaxValue;
                x.MultipartBodyLengthLimit = int.MaxValue; // In case of multipart
            });
            //------------------------------------------------------
            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
            .AddCookie(options =>
            {
                options.LoginPath  = new Microsoft.AspNetCore.Http.PathString("/Account/Login");
                options.LogoutPath = new Microsoft.AspNetCore.Http.PathString("/Account/Logout");
                options.Events.OnValidatePrincipal = PrincipalValidator.ValidateAsync;
            });

            services.AddMvc();
        }
示例#20
0
        public void Initialize()
        {
            Helper.InitializeApp(Assembly.GetExecutingAssembly());

            this.ADSettings   = new ADTestSettings();
            this.DB           = SqlTestDatabase.Create();
            this.AuthFilePath = Path.GetTempFileName();

            //-------------------------------------------------------------
            // Initialize file authentication

            Helper.WriteToFile(this.AuthFilePath, @"

file.com;file1;file-password1
file.com;file2;file-password2
");
            this.Accounts.Add(new AuthTestAccount(AuthTestExtensionType.File, "file.com", "file1", "file-password1"));
            this.Accounts.Add(new AuthTestAccount(AuthTestExtensionType.File, "file.com", "file2", "file-password2"));

            //-------------------------------------------------------------
            // Initialize RADIUS authentication

            RadiusServerSettings radiusSettings = new RadiusServerSettings();

            radiusSettings.NetworkBinding = NetworkBinding.Parse("ANY:52111");
            radiusSettings.Devices.Add(new RadiusNasInfo(IPAddress.Loopback, this.RadiusSecret));
            radiusSettings.Devices.Add(new RadiusNasInfo(NetHelper.GetActiveAdapter(), this.RadiusSecret));

            this.RadiusServer = new RadiusServer();
            this.RadiusServer.Start(radiusSettings);
            this.RadiusServer.LoadAccountsFromString(@"

radius.com;radius1;radius-password1
radius.com;radius2;radius-password2
");
            this.Accounts.Add(new AuthTestAccount(AuthTestExtensionType.Radius, "radius.com", "radius1", "radius-password1"));
            this.Accounts.Add(new AuthTestAccount(AuthTestExtensionType.Radius, "radius.com", "radius2", "radius-password2"));

            //-------------------------------------------------------------
            // Initialize config authentication

            Config.SetConfig(@"

Accounts[0] = config.com;config1;config-password1
Accounts[1] = config.com;config2;config-password2
");
            this.Accounts.Add(new AuthTestAccount(AuthTestExtensionType.Config, "config.com", "config1", "config-password1"));
            this.Accounts.Add(new AuthTestAccount(AuthTestExtensionType.Config, "config.com", "config2", "config-password2"));

#if TEST_AD
            //-------------------------------------------------------------
            // Initialize active directory authentication

#if !TEST_AD_LDAP
            if (ADSettings.NasSecret != string.Empty)   // Disable the test if the NAS secret is blank
#endif
            this.Accounts.Add(new AuthTestAccount(AuthTestExtensionType.Ldap, ADSettings.Domain, ADSettings.Account, ADSettings.Password));
#endif

            //-------------------------------------------------------------
            // Initalize ODBC authentication

            SqlConnection   sqlCon = null;
            SqlScriptRunner scriptRunner;
            MacroProcessor  processor;
            string          initScript =
                @"
create table Accounts (

Realm           varchar(64),
Account         varchar(64),
Password        varchar(64),
MD5             varbinary(128),
SHA1            varbinary(128),
SHA256          varbinary(128),
SHA512          varbinary(128)
)
go

insert into Accounts(Realm,Account,Password,MD5,SHA1,SHA256,SHA512)
values ('odbc.com','odbc1','odbc-password1',$(md5-1),$(sha1-1),$(sha256-1),$(sha512-1))

insert into Accounts(Realm,Account,Password,MD5,SHA1,SHA256,SHA512)
values ('odbc.com','odbc2','odbc-password2',$(md5-2),$(sha1-2),$(sha256-2),$(sha512-2))

go
";
            try
            {
                processor = new MacroProcessor();
                processor.Add("md5-1", SqlHelper.Literal(MD5Hasher.Compute("odbc-password1")));
                processor.Add("sha1-1", SqlHelper.Literal(SHA1Hasher.Compute("odbc-password1")));
                processor.Add("sha256-1", SqlHelper.Literal(SHA256Hasher.Compute("odbc-password1")));
                processor.Add("sha512-1", SqlHelper.Literal(SHA512Hasher.Compute("odbc-password1")));

                processor.Add("md5-2", SqlHelper.Literal(MD5Hasher.Compute("odbc-password2")));
                processor.Add("sha1-2", SqlHelper.Literal(SHA1Hasher.Compute("odbc-password2")));
                processor.Add("sha256-2", SqlHelper.Literal(SHA256Hasher.Compute("odbc-password2")));
                processor.Add("sha512-2", SqlHelper.Literal(SHA512Hasher.Compute("odbc-password2")));

                initScript = processor.Expand(initScript);

                sqlCon       = DB.OpenConnection();
                scriptRunner = new SqlScriptRunner(initScript);
                scriptRunner.Run(sqlCon);

                this.Accounts.Add(new AuthTestAccount(AuthTestExtensionType.Odbc, "odbc.com", "odbc1", "odbc-password1"));
                this.Accounts.Add(new AuthTestAccount(AuthTestExtensionType.Odbc, "odbc.com", "odbc2", "odbc-password2"));
            }
            finally
            {
                if (sqlCon != null)
                {
                    sqlCon.Close();
                }
            }
        }