Ejemplo n.º 1
0
        public SecurityUser GetByLogin(string username, string password)
        {
            SecurityUser securityUser;

            if (string.IsNullOrWhiteSpace(username) || string.IsNullOrWhiteSpace(password))
            {
                securityUser = null;
            }
            else
            {
                securityUser = GetQueryable()
                               .Where(u => u.UserName == username)
                               //.Where(u => u.UserStatusId == (int)UserStatusEnum.ACTIVE)
                               .SingleOrDefault();
                if (securityUser != null)
                {
                    bool passwordMatched = PasswordStorage.VerifyPassword(password, securityUser.PasswordHash);
                    if (!passwordMatched)
                    {
                        securityUser = null;
                    }
                }
            }

            if (securityUser == null)
            {
                _log.Warn("Failed to retrieve user with login credentials");
            }
            return(securityUser);
        }
Ejemplo n.º 2
0
        public Trabajador validarCredenciales(String usuario, String contrasena)
        {
            Trabajador trabajador = new Trabajador();

            trabajador.NombreUsuario = usuario;
            DAOTrabajador daoTrabajador = new DAOTrabajador();

            trabajador = daoTrabajador.validarTrabajador(trabajador);
            if (trabajador != null)
            {
                //Devuelve el perfil del trabajador para la validacion del
                //LoginWindows.xaml.cs
                if (PasswordStorage.VerifyPassword(contrasena, trabajador.Contrasena))
                {
                    try
                    {
                        //long idPerfil = trabajador.Perfil.IdPerfil;
                        //return idPerfil;
                        return(trabajador);
                    }
                    catch
                    {
                        return(null);
                    }
                }
                else
                {
                    return(null);
                }
            }
            else
            {
                return(null);
            }
        }
Ejemplo n.º 3
0
    // Make sure truncated hashes don't validate.
    private static void truncatedHashTest()
    {
        string userString = "test_password";
        string goodHash   = PasswordStorage.CreateHash(userString);
        string badHash    = "";

        int badHashLength = goodHash.Length;

        do
        {
            badHashLength -= 1;
            badHash        = goodHash.Substring(0, badHashLength);
            bool raised = false;
            try {
                PasswordStorage.VerifyPassword(userString, badHash);
            } catch (InvalidHashException) {
                raised = true;
            }

            if (!raised)
            {
                Console.WriteLine("Truncated hash test: FAIL " +
                                  "(At hash length of " + badHashLength + ")");
                System.Environment.Exit(1);
            }

            // The loop goes on until it is two characters away from the last : it
            // finds. This is because the PBKDF2 function requires a hash that's at
            // least 2 characters long. This will be changed once exceptions are
            // implemented.
        } while (badHash[badHashLength - 3] != ':');

        Console.WriteLine("Truncated hash test: pass");
    }
Ejemplo n.º 4
0
        public async Task <ModificarPasswordResponse> Handle(ModificarPasswordCommand request, CancellationToken cancellationToken)
        {
            var entity = await db
                         .User
                         .SingleOrDefaultAsync(el => el.Id == currentUser.UserId);

            if (entity == null)
            {
                throw new NotFoundException(nameof(User), currentUser.UserId);
            }

            if (PasswordStorage.VerifyPassword(request.PasswordActual, entity.HashedPassword))
            {
                string pass = PasswordStorage.CreateHash(request.PasswordNuevo);

                entity.HashedPassword = pass;

                var tokens = await db
                             .UserToken
                             .Where(el => el.IdUser == currentUser.UserId).
                             ToListAsync();

                db.UserToken.RemoveRange(tokens);

                await db.SaveChangesAsync(cancellationToken);

                return(new ModificarPasswordResponse
                {
                });
            }
            else
            {
                throw new BadRequestException("La contraseña es Incorrecta");
            }
        }
Ejemplo n.º 5
0
        public FE_Nutzer Login(string user, string password)
        {
            MySqlConnection logincon = new MySqlConnection(ConfigurationManager.ConnectionStrings["webapp"].ConnectionString);

            logincon.Open();
            MySqlCommand logincmd = new MySqlCommand("LoginProcedure", logincon);

            logincmd.CommandType = System.Data.CommandType.StoredProcedure;
            logincmd.Parameters.AddWithValue("@Lname", user);
            MySqlDataReader loginresult = logincmd.ExecuteReader();
            FE_Nutzer       fE_Nutzer   = new FE_Nutzer();

            if (loginresult.Read() && !string.IsNullOrEmpty(loginresult["loginname"] as string))
            {
                string dbhash = String.Format("{0}:{1}:{2}:{3}:{4}",
                                              loginresult["algorithmus"],
                                              loginresult["stretch"],
                                              Convert.ToString(18),
                                              loginresult["salt"],
                                              loginresult["hash"]);
                if (PasswordStorage.VerifyPassword(password, dbhash))
                {
                    fE_Nutzer.loginname    = loginresult["loginname"].ToString();
                    fE_Nutzer.role         = loginresult["role"].ToString();
                    fE_Nutzer.email        = loginresult["email"].ToString();
                    fE_Nutzer.aktiv        = Convert.ToBoolean(loginresult["activ"]);
                    fE_Nutzer.letzterlogin = Convert.ToDateTime(loginresult["LetzterLogin"]);
                    fE_Nutzer.ID           = Convert.ToInt32(loginresult["ID"]);
                    logincon.Close();
                    return(fE_Nutzer);
                }
            }
            logincon.Close();
            return(null);
        }
Ejemplo n.º 6
0
        public async Task <ModificarEmailResponse> Handle(ModificarEmailCommand request, CancellationToken cancellationToken)
        {
            var entity = await db
                         .Usuario
                         .SingleOrDefaultAsync(el => el.Id == currentUser.UserId);

            if (entity == null)
            {
                throw new NotFoundException(nameof(Usuario), currentUser.UserId);
            }

            if (PasswordStorage.VerifyPassword(request.Password, entity.HashedPassword))
            {
                entity.Email           = request.NuevoEmail;
                entity.NormalizedEmail = request.NuevoEmail.ToUpper();

                await db.SaveChangesAsync(cancellationToken);

                return(new ModificarEmailResponse
                {
                    Email = entity.Email
                });
            }
            else
            {
                throw new BadRequestException("La contrase�a es Incorrecta");
            }
        }
        public async Task <IActionResult> Login(LoginViewModel model, string returnUrl)
        {
            var login = EntitiesContext.Logins.SingleOrDefault(l => l.Identity == model.Identity);

            if (login == null)
            {
                ModelState.AddModelError(string.Empty, GenericLoginError);
                return(View(model));
            }

            if (!PasswordStorage.VerifyPassword(model.Password, login.PasswordHash))
            {
                ModelState.AddModelError(string.Empty, GenericLoginError);
                return(View(model));
            }

            var claims = new List <Claim>
            {
                new Claim("http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider", "ASP.NET Identity", "http://www.w3.org/2001/XMLSchema#string"),
                new Claim(ClaimTypes.Name, login.Identity),
                new Claim(ClaimTypes.NameIdentifier, login.Identity),
                new Claim(ClaimTypes.Role, login.Role.ToString()),
                new Claim(ClaimTypes.Sid, login.Id.ToString()),
            };

            var claimsIdentity  = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
            var claimsPrincipal = new ClaimsPrincipal(claimsIdentity);

            await HttpContext.SignInAsync(claimsPrincipal);

            return(RedirectToUrl(returnUrl));
        }
Ejemplo n.º 8
0
    private void LoginWithPasswordHashFunction()
    {
        List <String> salthashList = null;
        List <String> namesList    = null;

        try
        {
            connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["WebAppConnString"].ToString();

            conn = new MySql.Data.MySqlClient.MySqlConnection(connectionString);
            conn.Open();
            String query = "SELECT slowHashSalt, firstname, middlename, lastname FROM webAppPersonalFit.userregistration WHERE username=?uname";

            cmd = new MySql.Data.MySqlClient.MySqlCommand(query, conn);
            cmd.Parameters.AddWithValue("?uname", usernameTextBox.Text);

            reader = cmd.ExecuteReader();

            while (reader.HasRows && reader.Read())
            {
                if (salthashList == null)
                {
                    salthashList = new List <String>();
                    namesList    = new List <String>();
                }

                String saltHashes = reader.GetString(reader.GetOrdinal("slowHashSalt"));
                //Console.WriteLine(saltHashes);
                salthashList.Add(saltHashes);

                String fullname = reader.GetString(reader.GetOrdinal("firstname")) + " " + reader.GetString(reader.GetOrdinal("lastname"));
                namesList.Add(fullname);
            }

            if (salthashList != null)
            {
                for (int i = 0; i < salthashList.Count; i++)
                {
                    bool validUser = PasswordStorage.VerifyPassword(passwordTextBox.Text, salthashList[i]);

                    if (validUser == true)
                    {
                        Session["UserName"]   = namesList[i];
                        Response.BufferOutput = true;
                        Response.Redirect("LoggedIn.aspx", false);
                    }
                    else
                    {
                        passwordTextBox.Text = "User not authenticated";
                    }
                }
            }
            reader.Close();
            conn.Close();
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
        }
    }
Ejemplo n.º 9
0
        static void Main(string[] args)
        {
            Console.Write("Create/Verify (1/2) ");
            String auswahl = Console.ReadLine();

            if (auswahl.Contains("1"))
            {
                Console.Write("Geben Sie Ihr gewünschtes Passwort ein: ");
                String passwordPlain   = Console.ReadLine();
                String passwordEncrypt = PasswordStorage.CreateHash(passwordPlain);
                Console.WriteLine("Ihr verschlüsseltes Passwort lautet: " + passwordEncrypt);
            }
            else if (auswahl.Contains("2"))
            {
                Console.Write("Hash: ");
                string goodhash = Console.ReadLine();
                Console.Write("Passwort: ");
                string password = Console.ReadLine();
                if (PasswordStorage.VerifyPassword(password, goodhash))
                {
                    Console.WriteLine("Passwort ist korrekt.");
                }
            }

            Console.WriteLine("Zum beenden eine Taste drücken.");
            Console.ReadKey();
        }
Ejemplo n.º 10
0
        public void Identify(string password)
        {
            Rule("Disabled", x => x.Disabled, "user disabled");
            Rule("Password", x => !PasswordStorage.VerifyPassword(password, x.HashedPassword), "invalid password");

            Apply <Events.Identified>(x => { x.UserName = Id; });
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Bizs the function login.
        /// </summary>
        /// <param name="Email">The email.</param>
        /// <param name="PassWord">The pass word.</param>
        /// <returns>BizUser.</returns>
        public BizUser BizFuncLogin(string Email, string PassWord)
        {
            BizUser bizUser = new BizUser();

            string Result = BizCall(
                new Action(() =>
            {
                bizUser = baseFuntion.DataFuncLogin(Email);
            }
                           )
                );

            if (Result.Equals("EXITO"))
            {
                if (PasswordStorage.VerifyPassword(PassWord, bizUser.PassWord))
                {
                    return(bizUser);
                }
                else
                {
                    return(null);
                }
            }
            else
            {
                return(null);
            }
        }
Ejemplo n.º 12
0
        public ActionResult Put([FromBody] Users credentials)
        {
            var user = context.Users.SingleOrDefault(u => u.Email == credentials.Email);

            if (user == null)
            {
                return(BadRequest("No user with this email"));
            }
            else
            {
                var verifyPassword = PasswordStorage.VerifyPassword(credentials.Password, user.Password);
                if (verifyPassword)
                {
                    if (credentials.Username == "ADMIN")
                    {
                        return(Ok(PasswordStorage.CreateHash(credentials.Username + "/" + credentials.Password)));
                    }
                    return(Ok(user));
                }
                else
                {
                    return(BadRequest("Invalid password"));
                }
            }
        }
Ejemplo n.º 13
0
        public async Task <Response> LoginUser(string emailAddress, string password)
        {
            var response = new Response();

            try
            {
                var user = await _userRepository.GetByEmailAddressAsync(emailAddress);

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

                var saltedPassword = user.Salt + password;
                if (PasswordStorage.VerifyPassword(saltedPassword, user.Password))
                {
                    response.Success = true;
                    return(response);
                }

                response.Success = false;
                response.Errors.Add("Invalid password.");
                return(response);
            }
            catch (Exception e)
            {
                response.Success = false;
                response.Errors.Add(e.Message);
                return(response);
            }
        }
Ejemplo n.º 14
0
        public Token Login(Credentials credentials)
        {
            var user = _userService.FindUserByEmail(credentials.Email);

            if (user == null)
            {
                return(null);
            }

            if (!PasswordStorage.VerifyPassword(credentials.Password, user.Password))
            {
                return(null);
            }

            var token = _db.Tokens.FirstOrDefault(t => t.User.UserId == user.UserId);

            if (token != null)
            {
                _db.Tokens.Remove(token);
            }

            var newToken = new Token(user);

            _db.Tokens.Add(newToken);
            _db.SaveChanges();
            return(newToken);
        }
Ejemplo n.º 15
0
    private static void basicTests()
    {
        // Test password validation
        bool failure = false;

        for (int i = 0; i < 10; i++)
        {
            string password   = "" + i;
            string hash       = PasswordStorage.CreateHash(password);
            string secondHash = PasswordStorage.CreateHash(password);
            if (hash == secondHash)
            {
                Console.WriteLine("Hashes of same password differ: FAIL");
                failure = true;
            }
            String wrongPassword = "" + (i + 1);
            if (PasswordStorage.VerifyPassword(wrongPassword, hash))
            {
                Console.WriteLine("Validate wrong password: FAIL");
                failure = true;
            }
            if (!PasswordStorage.VerifyPassword(password, hash))
            {
                Console.WriteLine("Correct password: FAIL");
                failure = true;
            }
        }
        if (failure)
        {
            System.Environment.Exit(1);
        }
    }
Ejemplo n.º 16
0
        public ActionResult Index([Bind(Include = "authorized_person_email, authorized_person_password")] Authorized_Persons form_datas)
        {
            Authorized_Persons check_authorized_person = db.Authorized_Persons.Where(a => a.authorized_person_email == form_datas.authorized_person_email).FirstOrDefault();

            if (check_authorized_person == null)
            {
                ViewBag.LoginError = "Email düzgün daxil edilməyib!";
                return(View());
            }

            //Input'dan daxil edilən şifrəni VerifyPassword methodu ilə check edir. (Ətraflı: BaseController-Abstract.cs)
            if (!PasswordStorage.VerifyPassword(form_datas.authorized_person_password, check_authorized_person.authorized_person_password))
            {
                ViewBag.LoginError = "Şifrə düzgün daxil edilməyib!";
                return(View());
            }

            User_Roles role = db.User_Roles.Where(r => r.user_role_id == check_authorized_person.authorized_person_role_id).FirstOrDefault();

            //Normalda bu üsulla user authorization etmək düzgün deyil.
            //Lakin layihə üçün verilən vaxt müddəti az olduğundan dərinliyinə getmirəm.
            if (role.user_role_name == "Rektor" || role.user_role_name == "Prorektor" || role.user_role_name == "Rektor Müşaviri" || role.user_role_name == "Dekan" || role.user_role_name == "Kafedra Müdiri" || role.user_role_name == "Mərkəz Rəhbəri" || role.user_role_name == "Muzey Rəhbəri")
            {
                Session["Authorized_Person_Id"]       = check_authorized_person.authorized_person_id;
                Session["Authorized_Person_Email"]    = check_authorized_person.authorized_person_email;
                Session["Authorized_Person_Password"] = check_authorized_person.authorized_person_password;
                AreaName = "Admin";
            }

            return(RedirectToAction("Index", "Dashboard", new { Area = AreaName }));
        }
        public Model.Usuario Find(string nome, string senha)
        {
            var user = this.Find(nome);

            if (!PasswordStorage.VerifyPassword(senha, user.SenhaHashed))
            {
                return(null);
            }

            return(user);
        }
Ejemplo n.º 18
0
    private void LoginWithPasswordHashFunction()
    {
        String saltHash = null;

        try
        {
            connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["WebAppConnString"].ToString();

            conn = new MySql.Data.MySqlClient.MySqlConnection(connectionString);
            conn.Open();
            String query = "SELECT userID, slowHashSalt, firstname, middlename, lastname, isPT FROM webAppPersonalFit.userregistration WHERE username=?uname";

            cmd = new MySql.Data.MySqlClient.MySqlCommand(query, conn);
            cmd.Parameters.AddWithValue("?uname", usernameTextBox.Value);

            reader = cmd.ExecuteReader();

            if (reader.HasRows && reader.Read())
            {
                String saltHashes = reader.GetString(reader.GetOrdinal("slowHashSalt"));
                //Console.WriteLine(saltHashes);
                saltHash = saltHashes;

                userID = "" + reader.GetInt16(reader.GetOrdinal("userID"));
                isPT   = Convert.ToInt32(reader.GetByte(reader.GetOrdinal("isPT")));
            }
            else
            {
                ValidationTextBoxLabel.Text = "Invalid Username or Password.";
            }
            if (saltHash != null)
            {
                bool validUser = PasswordStorage.VerifyPassword(passwordTextBox.Value, saltHash);

                if (validUser == true)
                {
                    Session[userID]       = userID;
                    Response.BufferOutput = true;
                    Server.Transfer("TrainerCatalog.aspx", true);
                }
                else
                {
                    ValidationTextBoxLabel.Text = "Invalid Username or Password.";
                }
            }
            ValidationTextBoxLabel.Text = "Invalid Username or Password.";
            reader.Close();
            conn.Close();
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
        }
    }
Ejemplo n.º 19
0
        public Task <User> Authenticate(string username, string password)
        {
            var user = _users.GetByPredicate(u => u.Username == username);

            if (user != null && PasswordStorage.VerifyPassword(password, user.Password))
            {
                user.Password = null;
                return(Task.FromResult(user));
            }

            return(null);
        }
Ejemplo n.º 20
0
 public Boolean verifyPassword(string password)
 {
     lock (this)
     {
         return(PasswordStorage.VerifyPassword(password, String.Format("{0}:{1}:{2}:{3}:{4}",
                                                                       "sha1",
                                                                       "64000",
                                                                       Convert.ToString(18),
                                                                       this.Salt,
                                                                       this.Hash)));
     }
 }
Ejemplo n.º 21
0
        public void ChangePassword(string currentPassword, string newPassword)
        {
            Rule("Password", x => !PasswordStorage.VerifyPassword(currentPassword, x.HashedPassword), "invalid current password");

            var hashed = PasswordStorage.CreateHash(newPassword);

            Apply <Events.PasswordChanged>(x =>
            {
                x.UserName = Id;
                x.Password = hashed;
            });
        }
Ejemplo n.º 22
0
        public ActionResult Login(UserMaster data)

        {
            bool   isPasswordCorrect = false;
            string un       = data.UserName;
            string Password = data.Password;

            {
                var user = entity.UserMasters.Where(u => u.UserName == un && u.OTPVerify == 1 && u.Deleted == 0).FirstOrDefault();
                if (user != null && Password != null)
                {
                    bool result = PasswordStorage.VerifyPassword(Password, user.Password);

                    if (result == true)
                    {
                        //if (Count == "1")
                        //{
                        //}
                        //User loggedInUser = new User();
                        //loggedInUser.setId(user.userID);
                        //loggedInUser.setFullName(user.firstName);
                        //loggedInUser.setUserName(user.email);
                        //loggedInUser.setCompany(Convert.ToSingle(user.companyID));
                        //loggedInUser.setAdmin(Convert.ToSingle(user.adminStatus));
                        //Session[Constants.LOGGEDIN_USER] = loggedInUser;
                        //GetBranchCount();
                        //if (BCount == "1")
                        //{
                        //    loggedInUser.setBranch(BranchID);
                        //    Session[Constants.LOGGEDIN_USER] = loggedInUser;
                        //    return "1";
                        //}
                        //else
                        //{
                        //    loggedInUser.setBranch(BranchID);
                        //    Session[Constants.LOGGEDIN_USER] = loggedInUser;
                        //    return "1";
                        //}
                        return(RedirectToAction("Dashboard", "Home"));
                    }
                    else
                    {
                        ViewBag.Message = String.Format("Wrong Password");
                        return(View());
                    }
                }
                else
                {
                    ViewBag.Message = String.Format("UserName not Valid", data.UserName);
                    return(View());
                }
            }
        }
Ejemplo n.º 23
0
        public bool CheckPassword(User userToEdit)
        {
            var user = context.Users.FirstOrDefault(u => u.Id == userToEdit.Id);

            if (PasswordStorage.VerifyPassword(userToEdit.Username, user.Password))
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
Ejemplo n.º 24
0
        public async Task <GetUsuarioLoginResponse> Handle(GetUsuarioLoginQuery request, CancellationToken cancellationToken)
        {
            var entity = await db
                         .Usuario
                         .SingleOrDefaultAsync(el => el.NombreUsuario == request.NombreUsuario || el.Email == request.NombreUsuario);

            if (entity == null)
            {
                throw new NotFoundException(nameof(Usuario), request.NombreUsuario);
            }

            if (PasswordStorage.VerifyPassword(request.Password, entity.HashedPassword))
            {
                if (!entity.Confirmado)
                {
                    throw new ForbiddenException("La cuenta no ha sido aprobada por el administrador");
                }

                string randomToken = randomGenerator.SecureRandomString(32);

                db.UsuarioToken.Add(new UsuarioToken
                {
                    IdUsuario    = entity.Id,
                    RefreshToken = randomToken
                });
                entity.AccessFailedCount = 0;

                await db.SaveChangesAsync(cancellationToken);

                return(new GetUsuarioLoginResponse
                {
                    Email = entity.Email,
                    NombreUsuario = entity.NombreUsuario,
                    IdUsuario = entity.Id,
                    TipoUsuario = entity.TipoUsuario,
                    RefreshToken = randomToken
                });
            }
            else
            {
                entity.AccessFailedCount++;
                if (entity.AccessFailedCount >= 5)
                {
                    entity.LockoutEnd = dateTime.Now.AddMinutes(1);
                }
                await db.SaveChangesAsync(cancellationToken);

                throw new NotFoundException(nameof(Usuario), request.NombreUsuario);
            }
        }
Ejemplo n.º 25
0
 public Task <string> auth(UserAuthRequest request)
 {
     if (request?.Email == null || request?.Password == null)
     {
         return(null);
     }
     return(Services.DoWithDB(async db =>
     {
         var user = await UserLookup(db, request.Email).FirstOrDefaultAsync();
         if (user == null || !PasswordStorage.VerifyPassword(request.Password, user.Hash))
         {
             throw new HTTPError("Invalid user/pass", 401);
         }
         return Auth.GenerateToken(user);
     }));
 }
Ejemplo n.º 26
0
    private static void testPHPHashes()
    {
        string[] testData     = null;
        char[]   useDelimiter = { ' ' };

        // Good password.
        CommandExecResult goodHashExecution = RunCommand("php", "tests/phpHashMaker.php");

        testData = goodHashExecution.stdOut.Split(useDelimiter);

        if (testData[1].Length != Int32.Parse(testData[0]))
        {
            Console.WriteLine("Unicode test is invalid.");
            System.Environment.Exit(1);
        }

        if (PasswordStorage.VerifyPassword(testData[1], testData[2]))
        {
            Console.WriteLine("PHP hash validating in C#: pass");
        }
        else
        {
            Console.WriteLine("PHP hash validating in C#: FAIL");
            System.Environment.Exit(1);
        }

        // Bad password.
        CommandExecResult badHashExecution = RunCommand("php", "tests/phpHashMaker.php");

        testData = badHashExecution.stdOut.Split(useDelimiter);

        if (testData[1].Length != Int32.Parse(testData[0]))
        {
            Console.WriteLine("Unicode test is invalid.");
            System.Environment.Exit(1);
        }

        if (PasswordStorage.VerifyPassword("wrongPassword", testData[2]))
        {
            Console.WriteLine("The C# implementation accepts BAD PHP hashes: FAIL");
            System.Environment.Exit(1);
        }
        else
        {
            Console.WriteLine("The C# implementation will not accept bad PHP hashes: pass");
        }
    }
        public ActionResult Index([Bind(Include = "teacher_email, teacher_password")] Teachers teacher_login_form)
        {
            Teachers check_teacher_email = db.Teachers.Where(t => t.teacher_email == teacher_login_form.teacher_email).FirstOrDefault();

            if (check_teacher_email == null)
            {
                ViewBag.LoginError = "Email düzgün daxil edilməyib!";
                return(View());
            }

            if (!PasswordStorage.VerifyPassword(teacher_login_form.teacher_password, check_teacher_email.teacher_password))
            {
                ViewBag.LoginError = "Şifrə düzgün daxil edilməyib!";
                return(View());
            }

            if (Convert.ToBoolean(check_teacher_email.teacher_first_login))
            {
                Session["FirstLogin_Email"] = check_teacher_email.teacher_email;
                Session["FirstLogin_Id"]    = check_teacher_email.teacher_id.ToString();
                return(RedirectToAction("SetNewPassword", "Login"));
            }

            Role_Types teacher_role = db.Role_Types.Where(r => r.role_types_id == check_teacher_email.teacher_role_types_id).FirstOrDefault();

            if (teacher_role.role_types_name == "Admin")
            {
                Session["LoggedAdminId"]       = check_teacher_email.teacher_id;
                Session["LoggedAdminEmail"]    = check_teacher_email.teacher_email;
                Session["LoggedAdminPassword"] = check_teacher_email.teacher_password;
                AreaName = "Adminpanel";
            }
            else if (teacher_role.role_types_name == "Müəllim")
            {
                Session["LoggedTeacherId"]       = check_teacher_email.teacher_id;
                Session["LoggedTeacherEmail"]    = check_teacher_email.teacher_email;
                Session["LoggedTeacherPassword"] = check_teacher_email.teacher_password;
                AreaName = "Teacher";
            }

            //Class'ın hansı məqsədlə istifadə olunduğunu SetGroupsStatusByDate.cs faylında yazmışam.
            SetGroupsStatusByDate test = new SetGroupsStatusByDate();

            test.Run();

            return(RedirectToAction("Index", "Dashboard", new { Area = AreaName }));
        }
Ejemplo n.º 28
0
 public ActionResult Login(string userName, string password)
 {
     if (userName != null && password != null)
     {
         var model = db.Users.Where(x => x.UserName == userName).SingleOrDefault();
         if (model == null)
         {
             return(Content("User Name or Password is not Valid"));
         }
         bool result = PasswordStorage.VerifyPassword(password, model.Password);
         if (result)
         {
             return(RedirectToAction("Index", "Users"));
         }
     }
     return(View());
 }
Ejemplo n.º 29
0
        public async Task <User> Authenticate(string username, string password)
        {
            var user = await Task.Run(() => _storage.GetByPredicate(x => x.Username == username));

            if (user is null)
            {
                return(null);
            }

            if (!PasswordStorage.VerifyPassword(password, user.Password))
            {
                return(null);
            }

            user.Password = null;
            return(user);
        }
Ejemplo n.º 30
0
        public ActionResult Password(ChangePassword changePwd)
        {
            if (ModelState.IsValid)
            {
                string userid = Session["userid"].ToString();
                if (userid != null)
                {
                    customer_profile_table existing = ags.customer_profile_table.Where(x => x.id.ToString() == userid).FirstOrDefault();

                    var  password       = existing.password.ToString();
                    var  oldPassword    = changePwd.password;
                    var  newPassword    = changePwd.newpassword;
                    var  retypePassword = changePwd.retypepassword;
                    bool result         = PasswordStorage.VerifyPassword(oldPassword, password);
                    if (result)
                    {
                        if (newPassword == retypePassword)
                        {
                            existing.password = PasswordStorage.CreateHash(newPassword);
                        }
                        else
                        {
                            TempData["NotEqual"] = "<script>alert('password dosen't match');</script>";
                            return(RedirectToAction("Index", "Clientele"));
                        }
                    }
                    else
                    {
                        TempData["logAgain"] = "Oops.! Please Provide Valid Credentials.";
                        return(RedirectToAction("ClientLogout", "Account"));
                    }
                    ags.SaveChanges();



                    return(RedirectToAction("Index", "Clientele"));
                }
                else
                {
                    TempData["logAgain"] = "Oops.! Something Went Wrong.";
                    return(RedirectToAction("ClientLogout", "Account"));
                }
            }
            return(RedirectToAction("Index", "Clientele"));
        }