public MembershipSettingsBag(LoginSettings login, PasswordSettings password, RegistrationSettings registration, PasswordResetRetrievalSettings passwordResetRetrievalSettings)
 {
     Login = login;
     Password = password;
     Registration = registration;
     PasswordResetRetrievalSettings = passwordResetRetrievalSettings;
 }
		public EmailPassword(IPortalApplication portalApplication, IAuthenticationRepository authenticationRepository,
		                     PasswordSettings settings, IAuthenticationModule authenticationModule) : base(portalApplication)
		{
			AuthenticationRepository = authenticationRepository;
			Settings = settings;
			AuthenticationModule = authenticationModule;
		}
        public Rfc2988Benchmark()
        {
            var passwordService = new PasswordService();
            var settings = new PasswordSettings() {Length = 12, MinimumDigits = 2, MaximumDigits = 4, MaximumUpperCase = 4, MinimumUpperCase = 2, MinimumNonAlphaChars = 2, MaximumNonAlphaChars = 4};

            while(passwords.Count < 100)
                passwords.Add(passwordService.GeneratePassword(settings));
        }
        public void Test()
        {
            var fallback = new PasswordRequirement(0, PasswordService.AlphaChars);
            var settings = new PasswordSettings();
            var passwordLength = 20;
            var reqs = new[]
                           {
                               new PasswordRequirement(settings.MinimumNonAlphaChars, settings.MaximumNonAlphaChars, settings.IsUsKeyboard ? PasswordService.UsKeyboardNonAlphas : PasswordService.NonAlphas),
                               new PasswordRequirement(settings.MinimumUpperCase, settings.MaximumUpperCase, PasswordService.UpperAlphaChars),
                               new PasswordRequirement(settings.MinimumDigits, settings.MaximumDigits, PasswordService.DigitChars)
                           };
            var passwordService = new PasswordService();
            byte[] password = passwordService.GeneratePassword(passwordLength, fallback, reqs);

            Assert.NotNull(password);
            Assert.Equal(passwordLength, password.Length);

            foreach (PasswordRequirement req in reqs)
            {
                Assert.Equal(req.Required, req.Used);
            }
        }
        public static string GetPasswordHelpMessage()
        {
            var info             = new StringBuilder();
            var passwordSettings = PasswordSettings.Load();

            info.AppendFormat("{0} ", Resource.ErrorPasswordMessageStart);
            info.AppendFormat(Resource.ErrorPasswordLength, passwordSettings.MinLength, PasswordSettings.MaxLength);
            if (passwordSettings.UpperCase)
            {
                info.AppendFormat(", {0}", Resource.ErrorPasswordNoUpperCase);
            }
            if (passwordSettings.Digits)
            {
                info.AppendFormat(", {0}", Resource.ErrorPasswordNoDigits);
            }
            if (passwordSettings.SpecSymbols)
            {
                info.AppendFormat(", {0}", Resource.ErrorPasswordNoSpecialSymbols);
            }

            return(info.ToString());
        }
Exemple #6
0
 public AuthService(
     IOptions <JWTTokenSettings> jwtTokenSettings,
     IOptions <PasswordSettings> passwordSettings,
     IOptions <UserSettings> userSettings,
     DataContext context,
     IUserService userService,
     IEmailService emailService,
     IOptions <ApplicationSettings> applicationSettings,
     IHostingEnvironment environment,
     IConfiguration configuration,
     IAccountManagerService accountManager)
 {
     this.jwtTokenSettings    = jwtTokenSettings.Value;
     this.passwordSettings    = passwordSettings.Value;
     this.userSettings        = userSettings.Value;
     this.Context             = context;
     this.UserService         = userService;
     this.EmailService        = emailService;
     this.ApplicationSettings = applicationSettings.Value;
     this.Environment         = environment;
     this.Configuration       = configuration;
     this.AcoountManager      = accountManager;
 }
Exemple #7
0
        /// <summary>
        /// Verifies the otp.
        /// </summary>
        /// <param name="user">The user.</param>
        /// <returns></returns>
        /// <exception cref="Exception">
        /// User is not exists.,
        /// or
        /// OTP does not match.,
        /// </exception>
        public User VerifyOTP(User user)
        {
            var passSettings = new PasswordSettings();
            var newOTP       = user.OTP;

            user = _repositoryFactory.GetUserRepository.IsUserExist(user.Email, user.MobileNo);

            if (user == null)
            {
                throw new Exception("User is not exists.,");
            }

            if (user.OTP == newOTP)
            {
                user.IsOTP = true;
                _repositoryFactory.GetUserRepository.InsertOrUpdateUser(user);
            }
            else
            {
                throw new Exception("OTP does not match.,");
            }
            return(user);
        }
Exemple #8
0
        public IActionResult SpremiNovogZaposlenika(ZaposleniciDodajVM model)
        {
            if (ModelState.IsValid)
            {
                byte[] lozinkaSalt = PasswordSettings.GetSalt();
                string lozinkaHash = PasswordSettings.GetHash(model.Lozinka, lozinkaSalt);

                Korisnik k = new Korisnik
                {
                    KorisnickoIme = model.KorisnickoIme,
                    LozinkaHash   = lozinkaHash,
                    LozinkaSalt   = Convert.ToBase64String(lozinkaSalt),
                    OpstinaId     = model.OpstinaId,
                    UlogaId       = model.UlogaId
                };
                ctx.Korisnik.Add(k);
                ctx.SaveChanges();

                Zaposlenik z = new Zaposlenik
                {
                    Ime        = model.Ime,
                    Prezime    = model.Prezime,
                    Email      = model.Email,
                    Adresa     = model.Adresa,
                    Telefon    = model.Telefon,
                    KorisnikId = k.Id
                };
                ctx.Zaposlenik.Add(z);
                ctx.SaveChanges();

                return(Redirect("/ModulAdministrator/Korisnici/IndexZaposlenici"));
            }
            else
            {
                return(BadRequest(ModelState));
            }
        }
Exemple #9
0
        public static string GetPasswordHelpMessage(PasswordSettings passwordSettings)
        {
            var text = new StringBuilder();

            text.AppendFormat("{0} ", Resource.ErrorPasswordMessage);
            text.AppendFormat(Resource.ErrorPasswordLength, passwordSettings.MinLength, PasswordSettings.MaxLength);
            text.AppendFormat(", {0}", Resource.ErrorPasswordOnlyLatinLetters);
            text.AppendFormat(", {0}", Resource.ErrorPasswordNoSpaces);

            if (passwordSettings.UpperCase)
            {
                text.AppendFormat(", {0}", Resource.ErrorPasswordNoUpperCase);
            }
            if (passwordSettings.Digits)
            {
                text.AppendFormat(", {0}", Resource.ErrorPasswordNoDigits);
            }
            if (passwordSettings.SpecSymbols)
            {
                text.AppendFormat(", {0}", Resource.ErrorPasswordNoSpecialSymbols);
            }

            return(text.ToString());
        }
Exemple #10
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.InitializeServices();
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            services.AddDbContext <ApplicationDbContext>(options =>
                                                         options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

            services.AddIdentityCore <ApplicationUser>(options =>
            {
                // Temporary mild password policy: to be strictened
                options.Password = PasswordSettings.GetPasswordSettings().Password;

                options.User.AllowedUserNameCharacters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzАБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЬЮЯҐЄІЇабвгдеёжзийклмнопрстуфхцчшщьюяґєії'0123456789 -_";//A-Za-zА-ЩЬЮЯҐЄІЇа-щьюяґєії'0-9 -_
                options.User.RequireUniqueEmail        = true;
            }).AddRoles <IdentityRole>()
            .AddEntityFrameworkStores <ApplicationDbContext>()
            .AddDefaultTokenProviders();

            services.AddAuthorization(options =>
            {
                options.AddPolicy(PolicyTypes.NotBanned, policy =>
                                  policy.AddRequirements(new NotBannedRequirement()));
            });

            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters()
                {
                    ValidateIssuer           = true,
                    ValidateAudience         = true,
                    ValidateLifetime         = true,
                    ValidateIssuerSigningKey = true,
                    ValidIssuer      = Configuration["Jwt:Issuer"],
                    ValidAudience    = Configuration["Jwt:Audience"],
                    IssuerSigningKey = new SymmetricSecurityKey(
                        Encoding.UTF8.GetBytes(Configuration["Jwt:Key"]))
                };
            });

            // In production, the Angular files will be served from this directory
            services.AddSpaStaticFiles(configuration =>
            {
                configuration.RootPath = "ClientApp/dist";
            });

            services.AddScoped <DbInitializer>();

            // Register the Swagger generator, defining 1 or more Swagger documents
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info {
                    Title = "Booking API", Version = "v1"
                });
                c.AddSecurityDefinition("Bearer", new ApiKeyScheme {
                    In = "header", Description = "Please enter JWT with Bearer into field", Name = "Authorization", Type = "apiKey"
                });
                c.AddSecurityRequirement(new Dictionary <string, IEnumerable <string> > {
                    { "Bearer", Enumerable.Empty <string>() },
                });
            });
        }
 public PasswordHelper(PasswordSettings settings)
 {
     Settings = settings;
 }
        public IActionResult Registracija(RegistracijaViewModel model)
        {
            if (!ModelState.IsValid)
            {
                model.Gradovi = _context.Grads.Select
                                    (i => new SelectListItem {
                    Text = i.Naziv, Value = i.GradId.ToString()
                }).ToList();
                return(View("Registracija", model));
            }


            if (_context.KorisnickiNalogs.Any(i => i.Email == model.Email))
            {
                TempData["errorMessage"] = "Email adresa se koristi.";
                model.Gradovi            = _context.Grads.Select
                                               (i => new SelectListItem {
                    Text = i.Naziv, Value = i.GradId.ToString()
                }).ToList();
                return(View("Registracija", model));
            }

            byte[] lozinkaSalt = PasswordSettings.GetSalt();
            string lozinkaHash = PasswordSettings.GetHash(model.Lozinka, lozinkaSalt);

            //implementiraj izmjenu lozinke ako je 0 na pocetku, prebaci u 387
            string uniqueFileName = UploadedFile(model);

            KorisnickiNalog korisnickiNalog = new KorisnickiNalog
            {
                Ime           = model.Ime,
                Prezime       = model.Prezime,
                Email         = model.Email,
                LozinkaHash   = lozinkaHash,
                LozinkaSalt   = Convert.ToBase64String(lozinkaSalt),
                Permisije     = 3,
                Kreirano      = DateTime.Now,
                Mobitel       = model.Mobitel,
                GradId        = model.GradID,
                Adresa        = model.Adresa,
                JMBG          = model.JMBG,
                DatumRodjenja = model.DatumRodjenja,
                Spol          = model.Spol,
                Slika         = uniqueFileName
            };
            Pacijent pacijent = new Pacijent
            {
                KorisnickiNalog = korisnickiNalog,
                AlergijaNaLijek = model.AlergijaNaLijek,
                Aparatic        = model.Aparatic,
                Navlake         = model.Navlake,
                Proteza         = model.Proteza,
                Terapija        = model.Terapija
            };

            _context.KorisnickiNalogs.Add(korisnickiNalog);
            _context.Pacijents.Add(pacijent);

            _context.SaveChanges();

            TempData["successMessage"] = "Uspješno ste se registrovali.";
            return(RedirectToAction("Prijava"));
        }
        public IActionResult Prijava()
        {
            if (!_context.Administrators.Any())
            {
                byte[] lozinkaSalt = PasswordSettings.GetSalt();
                string lozinkaHash = PasswordSettings.GetHash("Admin24!", lozinkaSalt);
                if (!_context.Grads.Any())
                {
                    if (!_context.Drzavas.Any())
                    {
                        var novaDrzava = new Drzava
                        {
                            Naziv = "Bosna i Hercegovina"
                        };
                        _context.Add(novaDrzava);
                        _context.SaveChanges();
                    }

                    var noviGrad = new Grad
                    {
                        DrzavaId      = 1,
                        Naziv         = "Jablanica",
                        PostanskiBroj = "88420"
                    };
                    _context.Add(noviGrad);
                    _context.SaveChanges();
                }
                var AdminKorisnik = new KorisnickiNalog
                {
                    Ime           = "Dino",
                    Prezime       = "Nanić",
                    Email         = "*****@*****.**",
                    LozinkaHash   = lozinkaHash,
                    LozinkaSalt   = Convert.ToBase64String(lozinkaSalt),
                    Permisije     = 0,
                    Kreirano      = DateTime.Now,
                    JMBG          = "0101990150023",
                    DatumRodjenja = new DateTime(1990, 1, 1),
                    Mobitel       = "38762516238",
                    Adresa        = "San BB",
                    GradId        = 1,
                    Spol          = "Muško",
                    Slika         = "blank-profile.jpg"
                };
                _context.Add(AdminKorisnik);
                _context.SaveChanges();
                var NoviAdministrator = new Administrator
                {
                    KorisnickiNalog = _context.KorisnickiNalogs.SingleOrDefault(i => i.Email == AdminKorisnik.Email),
                    DatumZaposlenja = DateTime.Now,
                    OpisPosla       = "Administracija stranice",
                    BrojZiroRacuna  = "4343000022225555",
                    Aktivan         = true
                };
                _context.Add(NoviAdministrator);
                _context.SaveChanges();

                var novaTitula = new Titula
                {
                    Naziv = "dr."
                };
                _context.Add(novaTitula);
                _context.SaveChanges();
            }


            if (HttpContext.GetLogiraniKorisnik() != null)
            {
                return(RedirectToAction("Pocetna", "Profil"));
            }

            return(View());
        }
 public LoginService(EFDbContext context, IOptions <PasswordSettings> settings, ILoggerService loggerService)
 {
     _unitOfWork    = new UnitOfWork(context);
     _settings      = settings.Value;
     _loggerService = loggerService;
 }
        public IActionResult Prijava(PrijavaViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }


            var korisnickiNalog = _context.KorisnickiNalogs
                                  .Where(i => i.Email == model.Email)
                                  .AsEnumerable()
                                  .Where(i => i.LozinkaHash ==
                                         PasswordSettings.GetHash(model.Lozinka, Convert.FromBase64String(i.LozinkaSalt)));

            if (korisnickiNalog == null || !korisnickiNalog.Any())
            {
                TempData["errorMessage"] = "Niste unijeli ispravne podatke za prijavu.";
                return(View(model));
            }


            if ((korisnickiNalog.First().Permisije == 0 &&
                 _context.Administrators
                 .Where(i => i.KorisnickiNalogId == korisnickiNalog.First().KorisnickiNalogId).First().Aktivan) ||
                (korisnickiNalog.First().Permisije == 1 &&
                 _context.Stomatologs
                 .Where(i => i.KorisnickiNalogId == korisnickiNalog.First().KorisnickiNalogId).First().Aktivan) ||
                (korisnickiNalog.First().Permisije == 2 &&
                 _context.MedicinskoOsobljes
                 .Where(i => i.KorisnickiNalogId == korisnickiNalog.First().KorisnickiNalogId).First().Aktivan) ||
                korisnickiNalog.First().Permisije == 3)
            {
                HttpContext.SetLogiraniKorisnik(korisnickiNalog.First(), true);                               //setuje logiranog korisnika

                var prijavaLokacijaMail    = GetLoginLocation(model.Email, "mail");                           //dobavlja informacije o lokaciji prijave
                var prijavaLokacijaMobitel = GetLoginLocation(model.Email, "mobitel");                        //dobavlja informacije o lokaciji prijave

                var trenutnoVrijeme    = DateTime.Now.ToString(new CultureInfo("de-DE"));                     //trenutno vrijeme prebacuje na njemacki format datum 19.03.2020 15:35:43
                var primalacPoruke     = korisnickiNalog.First().Ime + " " + korisnickiNalog.First().Prezime; //ime i prezime za email
                var primalacEmail      = korisnickiNalog.First().Email;                                       //primalac email-a
                var prijavaEmailPoruka = "Poštovani " + primalacPoruke +
                                         ",\nDetektovana je prijava na vaš račun" +
                                         "\n-----------------------------------------------\n\n" + prijavaLokacijaMail +
                                         "\nDatum i vrijeme: " + trenutnoVrijeme +
                                         "\n!!!AKO OVO NISTE BILI VI, MOLIMO VAS DA PROMJENITE VAŠU LOZINKU!!!" +
                                         "\nIli nas kontaktirajte na naš mail: [email protected]"; //generisanje email poruke

                var primalacPorukeTelefon = korisnickiNalog.First().Mobitel;



                //VAZNO!!! UKLONI KOMENTARE DA BI PRORADILO SLANJE PORUKA

                var client = new Client(creds: new Nexmo.Api.Request.Credentials
                {
                    ApiKey    = _configuration.GetValue <string>("NexmoSmsGateway:ApiKey"),
                    ApiSecret = _configuration.GetValue <string>("NexmoSmsGateway:ApiSecret")
                });
                var results = client.SMS.Send(request: new SMS.SMSRequest
                {
                    from = "Ordinacija",
                    to   = primalacPorukeTelefon,
                    text = prijavaLokacijaMobitel
                });


                EmailSettings.SendEmail(_configuration, primalacPoruke, primalacEmail, "Nova prijava detektovana", prijavaEmailPoruka);//šalje email

                return(RedirectToAction("Pocetna", "Profil"));
            }

            TempData["errorMessage"] = "Niste unijeli ispravne podatke za prijavu.";
            return(View(model));
        }
Exemple #16
0
 public PasswordValidator(PasswordSettings passwordSettings)
 {
     _passwordSettings = passwordSettings;
 }
Exemple #17
0
        public IActionResult LoginTwoFactor(LoginTwoFactorVM model)
        {
            if (!ModelState.IsValid)
            {
                return(RedirectToAction("Login"));
            }

            Korisnik korisnik = ctx.Korisnik
                                .SingleOrDefault(x => x.KorisnickoIme == model.username && x.LozinkaHash == PasswordSettings.GetHash(model.password, Convert.FromBase64String(x.LozinkaSalt)));

            if (korisnik == null)
            {
                ViewData["poruka"] = "Pogrešan username ili password";
                return(View("Login"));
            }


            TwoFactorAuthenticator TwoFacAuth = new TwoFactorAuthenticator();
            string current = TwoFacAuth.GetCurrentPIN(korisnik.TwoFactorUniqueKey);
            bool   isValid = current.Equals(model.TwoFactorPin);

            //bool isValid = true;
            if (isValid)
            {
                HttpContext.SetLogiraniKorisnik(korisnik, snimiUCookie: model.ZapamtiLozinku);
                return(RedirectToAction("Index", "Home"));
            }
            else
            {
                ViewData["poruka"] = "Pogrešan kod";
                return(View("LoginTwoFactor", model));
            }
        }
        public bool TryAddLDAPUser(UserInfo ldapUserInfo, bool onlyGetChanges, out UserInfo portalUserInfo)
        {
            portalUserInfo = Constants.LostUser;

            try
            {
                if (ldapUserInfo == null)
                {
                    throw new ArgumentNullException("ldapUserInfo");
                }

                _log.DebugFormat("TryAddLDAPUser(SID: {0}): Email '{1}' UserName: {2}", ldapUserInfo.Sid,
                                 ldapUserInfo.Email, ldapUserInfo.UserName);

                if (!CheckUniqueEmail(ldapUserInfo.ID, ldapUserInfo.Email))
                {
                    _log.DebugFormat("TryAddLDAPUser(SID: {0}): Email '{1}' already exists.",
                                     ldapUserInfo.Sid, ldapUserInfo.Email);

                    return(false);
                }

                if (!TryChangeExistingUserName(ldapUserInfo.UserName, onlyGetChanges))
                {
                    _log.DebugFormat("TryAddLDAPUser(SID: {0}): Username '{1}' already exists.",
                                     ldapUserInfo.Sid, ldapUserInfo.UserName);

                    return(false);
                }

                if (!ldapUserInfo.WorkFromDate.HasValue)
                {
                    ldapUserInfo.WorkFromDate = TenantUtil.DateTimeNow();
                }

                if (onlyGetChanges)
                {
                    portalUserInfo = ldapUserInfo;
                    return(true);
                }

                _log.DebugFormat("CoreContext.UserManager.SaveUserInfo({0})", ldapUserInfo.GetUserInfoString());

                portalUserInfo = CoreContext.UserManager.SaveUserInfo(ldapUserInfo);

                if (PasswordSettings == null)
                {
                    _log.DebugFormat("PasswordSettings.Load()");

                    PasswordSettings = PasswordSettings.Load();
                }

                var password = LdapUtils.GeneratePassword(PasswordSettings);

                _log.DebugFormat("SecurityContext.SetUserPassword(ID:{0})", portalUserInfo.ID);

                SecurityContext.SetUserPassword(portalUserInfo.ID, password);

                return(true);
            }
            catch (Exception ex)
            {
                if (ldapUserInfo != null)
                {
                    _log.ErrorFormat("TryAddLDAPUser(UserName='******' Sid='{1}') failed: Error: {2}", ldapUserInfo.UserName,
                                     ldapUserInfo.Sid, ex);
                }
            }

            return(false);
        }
Exemple #19
0
        /// <summary>
        /// Page_Load runs when the control is loaded
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <history>
        ///     [cnurse]	03/02/2006  Created
        /// </history>
        protected void Page_Load(Object sender, EventArgs e)
        {
            //Bind User Controller to PropertySettings
            MembershipProviderConfig config = new MembershipProviderConfig();

            if (MembershipProviderConfig.CanEditProviderProperties)
            {
                ProviderSettings.EditMode = PropertyEditorMode.Edit;
            }
            else
            {
                ProviderSettings.EditMode = PropertyEditorMode.View;
            }
            ProviderSettings.LocalResourceFile = this.LocalResourceFile;
            ProviderSettings.DataSource        = config;
            ProviderSettings.DataBind();

            if (UserInfo.IsSuperUser)
            {
                PasswordSettings.EditMode = PropertyEditorMode.Edit;
            }
            else
            {
                PasswordSettings.EditMode = PropertyEditorMode.View;
            }
            PasswordSettings.LocalResourceFile = this.LocalResourceFile;
            PasswordSettings.DataSource        = new PasswordConfig();
            PasswordSettings.DataBind();

            //Create a hashtable for the custom editors being used, using the same keys
            //as in the settings hashtable
            Hashtable editors = new Hashtable();

            editors["Redirect_AfterLogin"]        = EditorInfo.GetEditor("Page");
            editors["Redirect_AfterLogout"]       = EditorInfo.GetEditor("Page");
            editors["Redirect_AfterRegistration"] = EditorInfo.GetEditor("Page");

            //Create a Hashtable for the custom Visibility options
            Hashtable visibility = new Hashtable();

            if (PortalSettings.ActiveTab.ParentId == PortalSettings.SuperTabId)
            {
                visibility["Profile_DefaultVisibility"]           = false;
                visibility["Profile_DisplayVisibility"]           = false;
                visibility["Profile_ManageServices"]              = false;
                visibility["Redirect_AfterLogin"]                 = false;
                visibility["Redirect_AfterRegistration"]          = false;
                visibility["Redirect_AfterLogout"]                = false;
                visibility["Security_CaptchaLogin"]               = false;
                visibility["Security_CaptchaRegister"]            = false;
                visibility["Security_RequireValidProfile"]        = false;
                visibility["Security_RequireValidProfileAtLogin"] = false;
                visibility["Security_UsersControl"]               = false;
            }


            UserSettingsControl.LocalResourceFile = this.LocalResourceFile;
            Hashtable ht = this.Settings;

            UserSettingsControl.DataSource    = UserModuleBase.GetSettings(ht);
            UserSettingsControl.CustomEditors = editors;
            UserSettingsControl.Visibility    = visibility;
            UserSettingsControl.DataBind();
        }
Exemple #20
0
 public static string GetPasswordHelpMessage()
 {
     return(GetPasswordHelpMessage(PasswordSettings.Load()));
 }
        public static String GeneratePassword(int length, int randomChars, PasswordSettings settings)
        {
            //Get Words
            //Replace Vowels
            //Random Caps
            //  insert random chars
            //  add random chars
            //Last two steps use the same number of random chars.


            string[] words = ReadAllWords();
            Random   ran   = new Random();

            string pass  = "";
            int    tries = 1000;

            while (tries > 0)             //There has got to be a better way to do this, right?
            {
                string word = words[ran.Next(words.Length)];
                if (word.Length + pass.Length <= length)
                {
                    pass += word;
                    tries = 1000;
                }
                else
                {
                    tries--;
                }
            }

            if (settings.HasFlag(PasswordSettings.replaceVowels) && settings.HasFlag(PasswordSettings.useNumbers))
            {
                for (int i = 0; i < pass.Length; i++)
                {
                    char c = pass[i];
                    if ("aeio".IndexOf(c) >= 0 && ran.NextDouble() > .5f)
                    {
                        //a->4 or @, e -> 3, i -> 1 or !, o -> 0

                        char replacedChar = c;

                        if (c == 'a')
                        {
                            replacedChar = (settings.HasFlag(PasswordSettings.useSpecialChars) && ran.NextDouble() > .5f) ? '@' : '4';
                        }
                        else if (c == 'e')
                        {
                            replacedChar = '3';
                        }
                        else if (c == 'i')
                        {
                            replacedChar = (settings.HasFlag(PasswordSettings.useSpecialChars) && ran.NextDouble() > .5f) ? '!' : '1';
                        }
                        else if (c == 'o')
                        {
                            replacedChar = '0';
                        }

                        pass = pass.Remove(i, 1);
                        pass = pass.Insert(i, replacedChar + "");
                    }
                }
            }

            if (settings.HasFlag(PasswordSettings.randomCaps))
            {
                for (int i = 0; i < pass.Length; i++)
                {
                    char c = pass[i];
                    if ("abcdefghijklmnopqrstuvwxyz".IndexOf(c) >= 0 && ran.NextDouble() > .5f)
                    {
                        pass = pass.Remove(i, 1);
                        pass = pass.Insert(i, (c + "").ToUpper());
                    }
                }
            }

            string charPool = "";

            charPool += (settings.HasFlag(PasswordSettings.useLowercase)) ? "abcdefghijklmnopqrstuvwxyz" : "";
            charPool += (settings.HasFlag(PasswordSettings.useUppercase)) ? "ABCDEFGHIJKLMNOPQRSTUVWXYZ" : "";
            charPool += (settings.HasFlag(PasswordSettings.useNumbers)) ? "1234567890" : "";
            charPool += (settings.HasFlag(PasswordSettings.useSpecialChars)) ? "!@#$%^&*()" : "";

            for (int i = 0; i < randomChars; i++)
            {
                if (settings.HasFlag(PasswordSettings.insertRandom) && ran.NextDouble() > .6f)                  //.6 because we want random inserts less likley
                {
                    pass = pass.Insert(ran.Next(pass.Length), charPool[ran.Next(charPool.Length)] + "");
                }
                else
                {
                    pass = pass.Insert(((ran.NextDouble() > .5f) ? 0 : pass.Length), charPool[ran.Next(charPool.Length)] + "");
                }
            }

            return(pass);
        }
        public object GetPasswordSettings()
        {
            var UserPasswordSettings = PasswordSettings.Load();

            return(UserPasswordSettings);
        }
Exemple #23
0
        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Page_Load runs when the control is loaded
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <history>
        ///     [cnurse]	03/02/2006  Created
        /// </history>
        /// -----------------------------------------------------------------------------
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            jQuery.RequestDnnPluginsRegistration();

            cmdCancel.Click += cmdCancel_Click;
            cmdUpdate.Click += cmdUpdate_Click;

            var config = new MembershipProviderConfig();

            if (MembershipProviderConfig.CanEditProviderProperties)
            {
                ProviderSettings.EditMode = PropertyEditorMode.Edit;
            }
            else
            {
                ProviderSettings.EditMode = PropertyEditorMode.View;
            }
            ProviderSettings.LocalResourceFile = LocalResourceFile;
            ProviderSettings.DataSource        = config;
            ProviderSettings.DataBind();

            if (UserInfo.IsSuperUser)
            {
                PasswordSettings.EditMode = PropertyEditorMode.Edit;
            }
            else
            {
                PasswordSettings.EditMode = PropertyEditorMode.View;
            }
            PasswordSettings.LocalResourceFile = LocalResourceFile;
            PasswordSettings.DataSource        = new PasswordConfig();
            PasswordSettings.DataBind();

            //Create a hashtable for the custom editors being used, using the same keys
            //as in the settings hashtable
            var editors = new Hashtable();

            editors["Redirect_AfterLogin"]        = EditorInfo.GetEditor("Page");
            editors["Redirect_AfterLogout"]       = EditorInfo.GetEditor("Page");
            editors["Redirect_AfterRegistration"] = EditorInfo.GetEditor("Page");

            //Create a Hashtable for the custom Visibility options
            var visibility = new Hashtable();

            if (IsHostMenu)
            {
                visibility["Profile_DefaultVisibility"]           = false;
                visibility["Profile_DisplayVisibility"]           = false;
                visibility["Profile_ManageServices"]              = false;
                visibility["Redirect_AfterLogin"]                 = false;
                visibility["Redirect_AfterRegistration"]          = false;
                visibility["Redirect_AfterLogout"]                = false;
                visibility["Security_CaptchaLogin"]               = false;
                visibility["Security_CaptchaRegister"]            = false;
                visibility["Security_EmailValidation"]            = false;
                visibility["Security_RequireValidProfile"]        = false;
                visibility["Security_RequireValidProfileAtLogin"] = false;
                visibility["Security_UsersControl"]               = false;
            }
            UserSettingsEditor.LocalResourceFile = LocalResourceFile;
            UserSettingsEditor.DataSource        = UserController.GetUserSettings(UserPortalID);
            UserSettingsEditor.CustomEditors     = editors;
            UserSettingsEditor.Visibility        = visibility;
            UserSettingsEditor.DataBind();
        }
Exemple #24
0
        public IActionResult DodajPacijenta(KorisnikDodajPacijentaViewModel model)
        {
            if (!ModelState.IsValid)
            {
                model.Gradovi = _context.Grads.Select
                                    (i => new SelectListItem {
                    Text = i.Naziv, Value = i.GradId.ToString()
                }).ToList();
                return(View("DodajPacijenta", model));
            }

            if (_context.KorisnickiNalogs.Any(i => i.Email == model.Email))
            {
                TempData["errorMessage"] = "Email adresa se koristi.";
                model.Gradovi            = _context.Grads.Select
                                               (i => new SelectListItem {
                    Text = i.Naziv, Value = i.GradId.ToString()
                }).ToList();
                return(View("DodajPacijenta", model));
            }

            byte[] lozinkaSalt = PasswordSettings.GetSalt();
            var    templozinka = GenerateRandomPassword();
            string lozinkaHash = PasswordSettings.GetHash(templozinka, lozinkaSalt);

            string uniqueFileName = UploadedFile(model);

            KorisnickiNalog korisnickiNalog = new KorisnickiNalog
            {
                Ime           = model.Ime,
                Prezime       = model.Prezime,
                Email         = model.Email,
                LozinkaHash   = lozinkaHash,
                LozinkaSalt   = Convert.ToBase64String(lozinkaSalt),
                Permisije     = 3,
                Kreirano      = DateTime.Now,
                Mobitel       = model.Mobitel,
                GradId        = model.GradID,
                Adresa        = model.Adresa,
                JMBG          = model.JMBG,
                DatumRodjenja = model.DatumRodjenja,
                Spol          = model.Spol,
                Slika         = uniqueFileName
            };
            Pacijent pacijent = new Pacijent
            {
                KorisnickiNalog = korisnickiNalog,
                AlergijaNaLijek = model.AlergijaNaLijek,
                Aparatic        = model.Aparatic,
                Navlake         = model.Navlake,
                Proteza         = model.Proteza,
                Terapija        = model.Terapija
            };

            _context.KorisnickiNalogs.Add(korisnickiNalog);
            _context.Pacijents.Add(pacijent);

            _context.SaveChanges();

            string primalacPoruke = korisnickiNalog.Ime + " " + korisnickiNalog.Prezime;
            string poruka         = primalacPoruke + " vaši pristupni podaci su: \nEmail: " + korisnickiNalog.Email +
                                    "\nPassword: "******"Nalog napravljen", poruka);

            TempData["successMessage"] = "Uspješno ste dodali novog pacijenta.";

            return(RedirectToAction("uredi-pacijent"));
        }
        private static ActiveDirectoryObject GetActiveDirectoryObject(SearchResult searchResult)
        {
            ActiveDirectoryObject     activeDirectoryObject;
            ActiveDirectoryObjectType activeDirectoryObjectType = GetActiveDirectoryObjectType(searchResult);

            switch (activeDirectoryObjectType)
            {
            case ActiveDirectoryObjectType.User:
                activeDirectoryObject = new User(searchResult.GetDirectoryEntry());
                break;

            case ActiveDirectoryObjectType.Contact:
                activeDirectoryObject = new Contact(searchResult.GetDirectoryEntry());
                break;

            case ActiveDirectoryObjectType.Computer:
                activeDirectoryObject = new Computer(searchResult.GetDirectoryEntry());
                break;

            case ActiveDirectoryObjectType.Container:
                activeDirectoryObject = new Container(searchResult.GetDirectoryEntry());
                break;

            case ActiveDirectoryObjectType.Group:
                activeDirectoryObject = new Group(searchResult.GetDirectoryEntry());
                break;

            case ActiveDirectoryObjectType.InetOrgPerson:
                activeDirectoryObject = new InetOrgPerson(searchResult.GetDirectoryEntry());
                break;

            case ActiveDirectoryObjectType.MSMQQueueAlias:
                activeDirectoryObject = new MSMQQueueAlias(searchResult.GetDirectoryEntry());
                break;

            case ActiveDirectoryObjectType.MsImaging_PSPs:
                activeDirectoryObject = new MsImaging_PSPs(searchResult.GetDirectoryEntry());
                break;

            case ActiveDirectoryObjectType.OrganizationalUnit:
                activeDirectoryObject = new OrganizationalUnit(searchResult.GetDirectoryEntry());
                break;

            case ActiveDirectoryObjectType.Printer:
                activeDirectoryObject = new Printer(searchResult.GetDirectoryEntry());
                break;

            case ActiveDirectoryObjectType.SharedFolder:
                activeDirectoryObject = new SharedFolder(searchResult.GetDirectoryEntry());
                break;

            case ActiveDirectoryObjectType.DomainController:
                activeDirectoryObject = new DomainController(searchResult.GetDirectoryEntry());
                break;

            case ActiveDirectoryObjectType.PasswordSettings:
                activeDirectoryObject = new PasswordSettings(searchResult.GetDirectoryEntry());
                break;

            default:
                activeDirectoryObject = new UnknownObject(searchResult.GetDirectoryEntry());
                break;
            }
            return(activeDirectoryObject);
        }
Exemple #26
0
        public IActionResult Login(LoginVM input)
        {
            if (!ModelState.IsValid)
            {
                ViewData["poruka"] = "Niste unijeli ispravne podatke";
                return(View("Index", input));
            }
            Korisnik korisnik = ctx.Korisnik
                                .SingleOrDefault(x => x.KorisnickoIme == input.username && x.LozinkaHash == PasswordSettings.GetHash(input.password, Convert.FromBase64String(x.LozinkaSalt)));

            if (korisnik == null)
            {
                ViewData["poruka"] = "Pogrešan username ili password";
                return(View("Index", input));
            }

            if (!String.IsNullOrEmpty(korisnik.TwoFactorUniqueKey))
            {
                var twoFactorModel = new LoginTwoFactorVM
                {
                    username       = korisnik.KorisnickoIme,
                    password       = input.password,
                    ZapamtiLozinku = input.ZapamtiPassword
                };

                return(View("LoginTwoFactor", twoFactorModel));
            }
            else
            {
                HttpContext.SetLogiraniKorisnik(korisnik, snimiUCookie: input.ZapamtiPassword);
                return(RedirectToAction("Index", "Home"));
            }
        }
Exemple #27
0
        public bool CheckPasswordRegex(PasswordSettings passwordSettings, string password)
        {
            var passwordRegex = GetPasswordRegex(passwordSettings);

            return(new Regex(passwordRegex).IsMatch(password));
        }
Exemple #28
0
        public IActionResult DodajOsoblje(KorisnikDodajOsobljeViewModel model)
        {
            if (!ModelState.IsValid)
            {
                model.Gradovi = _context.Grads.Select
                                    (i => new SelectListItem {
                    Text = i.Naziv, Value = i.GradId.ToString()
                }).ToList();
                model.Titule = _context.Titulas.Select
                                   (i => new SelectListItem {
                    Text = i.Naziv, Value = i.TitulaId.ToString()
                }).ToList();
                return(View("DodajOsoblje", model));
            }


            if (_context.KorisnickiNalogs.Any(i => i.Email == model.Email))
            {
                TempData["errorMessage"] = "Email adresa se koristi.";
                model.Gradovi            = _context.Grads.Select
                                               (i => new SelectListItem {
                    Text = i.Naziv, Value = i.GradId.ToString()
                }).ToList();
                model.Titule = _context.Titulas.Select
                                   (i => new SelectListItem {
                    Text = i.Naziv, Value = i.TitulaId.ToString()
                }).ToList();
                return(View("DodajOsoblje", model));
            }

            byte[] lozinkaSalt = PasswordSettings.GetSalt();
            var    templozinka = GenerateRandomPassword();
            string lozinkaHash = PasswordSettings.GetHash(templozinka, lozinkaSalt);


            string uniqueFileName = UploadedFile(model);

            KorisnickiNalog korisnickiNalog = new KorisnickiNalog
            {
                Ime           = model.Ime,
                Prezime       = model.Prezime,
                Email         = model.Email,
                LozinkaHash   = lozinkaHash,
                LozinkaSalt   = Convert.ToBase64String(lozinkaSalt),
                Permisije     = 2,
                Kreirano      = DateTime.Now,
                Mobitel       = model.Mobitel,
                GradId        = model.GradID,
                Adresa        = model.Adresa,
                JMBG          = model.JMBG,
                DatumRodjenja = model.DatumRodjenja,
                Spol          = model.Spol,
                Slika         = uniqueFileName
            };
            MedicinskoOsoblje osoblje = new MedicinskoOsoblje
            {
                KorisnickiNalog = korisnickiNalog,
                TitulaID        = model.TitulaID,
                DatumZaposlenja = model.DatumZaposlenja,
                BrojZiroRacuna  = model.BrojZiroRacuna,
                Aktivan         = model.Aktivan,
                OpisPosla       = model.OpisPosla
            };

            _context.KorisnickiNalogs.Add(korisnickiNalog);
            _context.MedicinskoOsobljes.Add(osoblje);

            _context.SaveChanges();

            string primalacPoruke = korisnickiNalog.Ime + " " + korisnickiNalog.Prezime;
            string poruka         = primalacPoruke + " vaši pristupni podaci su: \nEmail: " + korisnickiNalog.Email +
                                    "\nPassword: "******"Nalog napravljen", poruka);

            TempData["successMessage"] = "Uspješno ste dodali novog uposlenika.";
            return(RedirectToAction("uredi-osoblje"));
        }