Beispiel #1
0
        public ValidateUserDTO Update(UserUpdateDTO user)
        {
            var result = new ValidateUserDTO()
            {
            };

            if (this.userRepository.Exists(user.Login, user.Id))
            {
                var errors = new List <string>()
                {
                    "The given login '" + user.Login + "' is already in use."
                };
                result.OverallErrors = errors;
                return(result);
            }

            var applicationUser = this.userRepository.Get(user.Id);

            applicationUser.Name     = user.Name;
            applicationUser.Login    = user.Login;
            applicationUser.Password = PasswordEncryptor.Encrypt(user.Password);
            this.userRepository.Update(applicationUser);
            result.ValidatedUser = this.Get(user.Id);
            return(result);
        }
Beispiel #2
0
        public static void UpdateAdminUsername(string newuser, string password)
        {
            SqlConnection con = new DBConnection().getConnection();

            con.Open();
            try
            {
                //check if user  already exist
                AdminLog.CheckUserName(newuser);
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = con;
                cmd.Parameters.Clear();
                cmd.Parameters.AddWithValue("@UserName", newuser);
                cmd.Parameters.AddWithValue("@Password", PasswordEncryptor.Encrypt(password));
                cmd.Parameters.AddWithValue("@ID", Resetuserid);
                cmd.CommandText = "UPDATE Admin SET UserName =@UserName, Password=@Password WHERE ID=@ID";
                cmd.ExecuteNonQuery();
                con.Close();
                AdminLog.Admin     = newuser;
                AdminLog.AdminPass = PasswordEncryptor.Encrypt(password);
            }
            catch (Exception Ex)
            {
                con.Close();
                throw new Exception(Ex.Message + "\nUpdate Not Successful");
            }
        }
Beispiel #3
0
        public ValidateUserDTO Save(UserSaveDTO user)
        {
            var result = new ValidateUserDTO()
            {
            };

            if (this.userRepository.Exists(user.Login, null))
            {
                var errors = new List <string>()
                {
                    "The given login '" + user.Login + "' is already in use."
                };
                result.OverallErrors = errors;
                return(result);
            }

            var applicationUser = Mapper.Map <ApplicationUser>(user);

            applicationUser.Password = PasswordEncryptor.Encrypt(user.Password);
            applicationUser.Roles    = new ApplicationUserRole[] { new ApplicationUserRole()
                                                                   {
                                                                       Name = "User"
                                                                   } };

            result.ValidatedUser = Mapper.Map <UserDTO>(this.userRepository.Create(applicationUser));
            return(result);
        }
Beispiel #4
0
 private void txtPassword_KeyDown(object sender, KeyEventArgs e)
 {
     if (e.KeyValue == (char)Keys.Enter)
     {
         try
         {
             AdminLog.LogIn(txtUsername.Text, txtPassword.Text);
             if (txtUsername.Text == AdminLog.Admin && PasswordEncryptor.Encrypt(txtPassword.Text) == AdminLog.AdminPass)
             {
                 //USE ASYNC HERE
                 new Thread(() => { AdminLog.AdminLogs(AdminLog.Admin, btnLogin.Text); }).Start();
                 this.Close();
             }
             else
             {
                 throw new Exception("Incorrect Username or Password");
             }
         }
         catch (Exception Ex)
         {
             MessageBox.Show(Ex.Message, "Admin Login error", MessageBoxButtons.OK,
                             MessageBoxIcon.Information);
         }
     }
 }
Beispiel #5
0
        public static void UpdateAdminPass(string password)
        {
            try
            {
                //PASS IN THE USER NAME AND THE NEW PASSWORD
                UserResetPassword.ResetUserPassword(AdminLog.Admin);
                SqlConnection con = new DBConnection().getConnection();
                con.Open();
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = con;
                cmd.Parameters.Clear();
                cmd.Parameters.AddWithValue("@ID", UserResetPassword.Resetuserid);

                cmd.Parameters.AddWithValue("@Password", PasswordEncryptor.Encrypt(password));
                cmd.CommandText = "UPDATE Admin SET Password =@Password WHERE ID= @ID ";
                cmd.ExecuteNonQuery();
                con.Close();
                dataAccess.Description = Admin + " updated password";
                dataAccess.Activities();
                AdminPass = PasswordEncryptor.Encrypt(password);
            }
            catch (Exception Ex)
            {
                throw new Exception(Ex.Message + "\nUpdate Not Successful");
            }
        }
        public async Task <IActionResult> PutUserDetail(int id, UserDetail userDetail)
        {
            if (id != userDetail.UserId)
            {
                return(BadRequest());
            }

            userDetail.Email = userDetail.Email.ToLower().Trim();
            if (!string.IsNullOrEmpty(userDetail.Password))
            {
                userDetail.Password = PasswordEncryptor.Encrypt(userDetail.Password);
            }

            _context.Entry(userDetail).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!UserDetailExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(NoContent());
        }
Beispiel #7
0
        public long RegisterUser(UserVM userVM)
        {
            var  encryptedPass = PasswordEncryptor.Encrypt(userVM.Password);
            User user          = new User
            {
                Address     = userVM.Address,
                CompanyName = userVM.CompanyName,
                Email       = userVM.Email,
                Liecnse     = userVM.Liecnse,
                Name        = userVM.Name,
                NID         = userVM.NID,
                Password    = encryptedPass,
                Phone       = userVM.Phone,
                RoleID      = userVM.RoleID
            };

            var addedUser = _dbContext.Users.Add(user);

            _dbContext.SaveChanges();

            if (addedUser.ID > 0)
            {
                return(addedUser.ID);
            }

            return(-1);
        }
Beispiel #8
0
        public HttpResponseMessage CreateOrUpdate(UserRequest userRequest)
        {
            string apiName = "CreateOrUpdate(UserRequest userRequest=\n{" + userRequest + "})";
            var    guid    = Guid.NewGuid();

            logger.Info("Guid: \"{0}\" api/{1}/{2} was invoked", guid, controllerName, apiName);

            IUsersRepository usersRepository = new UsersRepository();

            try
            {
                if (!ModelState.IsValidField("userRequest.Email"))
                {
                    ;//  return CreateGeneralResultMessage("Invalid Email Address", false, ApiStatusCodes.InvalidEmail);
                }

                var userToUpdate = usersRepository.GetUserByEmail(userRequest.Email);

                if (userToUpdate == null)
                {//Create
                    logger.Info("Guid: \"{0}\" Start Creating new User", guid);

                    var token   = TokenGenerator.GenerateToken(userRequest.Email);
                    var newUser = new Users
                    {
                        Name      = userRequest.Name,
                        Email     = userRequest.Email,
                        CompanyId = userRequest.CompanyId,
                        Type      = userRequest.Type,
                        Token     = token
                    };
                    usersRepository.Create(newUser);

                    var createdUser = usersRepository.GetUserByToken(token);
                    usersRepository.AddNewAuthUser(createdUser.Id, PasswordEncryptor.Encrypt(userRequest.Password));

                    logger.Info("Guid: \"{0}\" completed Creating new User", guid);
                    return(CreateResponseMessage(newUser));
                }
                else
                {//Update
                    logger.Info("Guid: \"{0}\" Start Updating User", guid);

                    userToUpdate.Name = userRequest.Name;
                    // userToUpdate.Email = userRequest.Email;
                    userToUpdate.CompanyId = userRequest.CompanyId;
                    userToUpdate.Type      = userRequest.Type;

                    logger.Info("Guid: \"{0}\" completed Updating User", guid);
                    usersRepository.SaveChanges();
                    return(CreateResponseMessage(userToUpdate));
                }
            }
            catch (Exception ex)
            {
                logger.Error("Guid: \"{0}\" General Error: {1}", guid, ex);
                return(CreateGeneralResultMessage(ex.ToString(), false, ApiStatusCodes.InternalServerError));
            }
        }
Beispiel #9
0
        public void PasswordEncrpt_Test()
        {
            PasswordEncryptor pe = new PasswordEncryptor();
            long   time          = Convert.ToInt64((new DateTime(2014, 8, 20) - new DateTime(1970, 1, 1)).TotalSeconds);
            string en_pwd        = pe.Encrypt("cjr0912", time);

            Console.WriteLine(en_pwd);
        }
Beispiel #10
0
        public new async Task <User> AddAsync(User quotation)
        {
            quotation.Password = PasswordEncryptor.Encrypt(quotation.Password);
            await _repository.AddAsync(quotation);

            await _repository.SaveChangesAsync();

            return(quotation);
        }
Beispiel #11
0
        public static void ResetUserPassword(string username)
        {
            SqlConnection con = new DBConnection().getConnection();

            try
            {
                con.Open();
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = con;
                cmd.Parameters.Clear();
                cmd.Parameters.AddWithValue("@UserName", username);
                cmd.CommandText = "SELECT * FROM Admin WHERE UserName =@UserName  ";
                SqlDataReader reader = cmd.ExecuteReader();
                if (reader.HasRows)
                {
                    while (reader.Read())
                    {
                        Resetuserid        = Int32.Parse(reader["ID"].ToString());
                        AdminLog.Admin     = reader["UserName"].ToString();
                        AdminLog.AdminPass = reader["Password"].ToString();
                    }
                }
                else
                {
                    reader.Close();
                    SqlCommand cmd2 = new SqlCommand();
                    cmd2.Connection = con;
                    cmd2.Parameters.Clear();
                    cmd2.Parameters.AddWithValue("@Password", PasswordEncryptor.Encrypt(username));
                    cmd2.CommandText = "SELECT * FROM Admin WHERE Password=@Password  ";
                    SqlDataReader reader2 = cmd2.ExecuteReader();
                    if (reader2.HasRows)
                    {
                        while (reader2.Read())
                        {
                            Resetuserid        = Int32.Parse(reader2["ID"].ToString());
                            AdminLog.Admin     = reader2["UserName"].ToString();
                            AdminLog.AdminPass = reader2["Password"].ToString();
                        }
                    }
                    else
                    {
                        reader2.Close();
                        throw new Exception("Username NOT found");
                    }
                    reader2.Close();
                }
                reader.Close();
                con.Close();
            }
            catch (Exception Ex)
            {
                con.Close();
                throw new Exception(Ex.Message);
            }
        }
Beispiel #12
0
        public ActionResult Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var encryptedPassword = PasswordEncryptor.Encrypt(model.Password);
                var user = new User {
                    Name = model.Name, Password = encryptedPassword
                };

                _userRepository.Create(user);
            }
            return(RedirectToAction("Login", "Account"));
        }
Beispiel #13
0
        private void btnAdd_Click(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(textBox1.Text))
                {
                    throw new Exception("Enter Username");
                }

                else if (string.IsNullOrEmpty(textBox2.Text))
                {
                    throw new Exception("Enter Password");
                }

                else if (string.IsNullOrEmpty(textBox3.Text))
                {
                    throw new Exception("Confrim Password");
                }
                else if (textBox2.Text == textBox3.Text)
                {
                    if (PasswordEncryptor.Encrypt(txtcreateUserAdmin.Text) == AdminLog.AdminPass)
                    {
                        //call the insert class
                        AdminLog.CreateAdmin(textBox1.Text, textBox2.Text);
                        textBox1.Clear();
                        textBox2.Clear();
                        textBox3.Clear();
                        txtcreateUserAdmin.Text = "";
                        MessageBox.Show("Admin Created Succesfully\n\nPlease set security questions\n" +
                                        "after now, to enable password reset\n" +
                                        "in case password is forgotten", "Create Admin", MessageBoxButtons.OK,
                                        MessageBoxIcon.Information);
                        dataAccess.Description = "Added a new user";
                        dataAccess.Activities();
                    }
                    else
                    {
                        throw new Exception("Enter Currently Logged in admin Password");
                    }
                }
                else
                {
                    throw new Exception("Password Mismatch");
                }
            }
            catch (Exception Ex)
            {
                MessageBox.Show(Ex.Message, "Cash Desk", MessageBoxButtons.OK,
                                MessageBoxIcon.Information);
            }
        }
Beispiel #14
0
        /// <summary>
        /// Login
        /// </summary>
        /// <param name="url"></param>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public LoginResponseResult Login(string url, string username, string password)
        {
            PasswordEncryptor pe = new PasswordEncryptor();
            long   ts            = CommonService.BuildTimestamp(Config.TimestampOffset);
            string enc_pwd       = pe.Encrypt(password, ts);
            Dictionary <string, string> paramList = CommonService.BuildForm(username, enc_pwd);
            string attempt = WebRequestHelper.CreateRequest(url, "POST", paramList);

            LoginResponseResult result = new LoginResponseResult(attempt);

            // There are several kinds of error, but only "password_error" should be retried with the responsed timestamp.
            if (result.Status == ResponseStatus.Error && result.Message == "password_error")
            {
                long correctTime = result.Timestamp;
                enc_pwd = pe.Encrypt(password, Convert.ToInt64(correctTime));
                paramList["password"] = enc_pwd;
                string response = WebRequestHelper.CreateRequest(url, "POST", paramList);
                result            = new LoginResponseResult(response);
                result.Timestamp  = correctTime;
                result.TimeOffset = result.Timestamp - ts;
            }
            return(result);
        }
Beispiel #15
0
 public bool UpdatePassword()
 {
     try
     {
         Data.USER_INFO usr = Connection.ProcessSA_DB.USER_INFO.First(user => Email.Equals(user.EMAIL, StringComparison.InvariantCultureIgnoreCase));
         usr.PASSWORD = PasswordEncryptor.Encrypt(Password);
         Connection.ProcessSA_DB.SaveChanges();
         return(true);
     }
     catch (Exception e)
     {
         log.Error("Error al actualizar la contraseña de usuario de email " + Email, e);
         return(false);
     }
 }
 public ActionResult Login(string Email, string Password)
 {
     if (ModelState.IsValid)
     {
         var encryptedPass = PasswordEncryptor.Encrypt(Password);
         var user          = _dbContext.Users.Where(x => x.Email == Email && x.Password == encryptedPass).FirstOrDefault();
         if (user != null)
         {
             Session["currentUser"] = user;
             return(RedirectToAction("Index", "Home"));
         }
     }
     ViewBag.ErrorMsg = "Email or Password is Incorrect";
     return(View());
 }
Beispiel #17
0
 public bool Authenticate()
 {
     try
     {
         string         encryptedPassword = PasswordEncryptor.Encrypt(Password);
         Data.USER_INFO usr = Connection.ProcessSA_DB.USER_INFO.First(user => Email.Equals(user.EMAIL, StringComparison.InvariantCultureIgnoreCase) && encryptedPassword == user.PASSWORD);
         ReadByEmail();
         return(true);
     }
     catch (Exception e)
     {
         log.Warn("Error al autenticar el usuario, verifique que usuario y contraseña corresponda", e);
         return(false);
     }
 }
        public void EncryptDecryptByPassword_different_instance_default_AesCryptoServiceProvider()
        {
            //ARRANGE
            var encryptor       = new PasswordEncryptor();
            var decryptor       = new PasswordEncryptor();
            var plainTextSource = "Test data to encrypt";
            var result          = String.Empty;

            byte[] salt;
            //ACT
            var encrypted = encryptor.Encrypt("Password1", plainTextSource, out salt);

            result = decryptor.Decrypt("Password1", salt, encrypted);
            //ASSERT
            Assert.AreEqual(plainTextSource, result);
        }
        public async Task <ActionResult <UserDetail> > PostUserDetail(UserDetail userDetail)
        {
            userDetail.Email = userDetail.Email.ToLower().Trim();

            if (!string.IsNullOrEmpty(userDetail.Password))
            {
                userDetail.Password = PasswordEncryptor.Encrypt(userDetail.Password);
            }

            if (await _context.UserDetails.AnyAsync(u => u.Email == userDetail.Email))
            {
                return(BadRequest($"User with {userDetail.Email} already exist."));
            }

            _context.UserDetails.Add(userDetail);
            await _context.SaveChangesAsync();

            return(CreatedAtAction("GetUserDetail", new { id = userDetail.UserId }, userDetail));
        }
Beispiel #20
0
        public SignupResponse Signup(SignupRequest request, dbDataContext db)
        {
            var result = db.sp_GetUserStatusByEmail(request.Email).FirstOrDefault();

            if (result != null)
            {
                if (ConfigHelper.Config.SignupActivationRequired)
                {
                    if (!result.IsEmailVerified == true)
                    {
                        throw new HappyHourException(ErrorCode.EmailNotVerified);
                    }
                }

                throw new HappyHourException(ErrorCode.EmailAlreadyExist);
            }

            var md5Password = Md5SecurityHelper.GetMd5Hash(request.Password);

            var encyptedSystemPassword = PasswordEncryptor.Encrypt(request.SystemPassword);
            var encryptedSystemNumber  = PasswordEncryptor.Encrypt(request.SystemNumber);

            var signupResult = db.sp_Signup(request.FirstName, request.LastName, request.Email,
                                            md5Password, request.SystemEmail, encyptedSystemPassword, encryptedSystemNumber, ConfigHelper.Config.SignupActivationRequired).FirstOrDefault();

            if (signupResult.EmailExist == true)
            {
                throw new HappyHourException(ErrorCode.EmailAlreadyExist);
            }

            if (ConfigHelper.Config.SignupActivationRequired)
            {
                var    activationLink = CreateActivationLink(signupResult.ActivationToken.Value.ToString());
                string fullName       = string.Format("{0} {1}", request.FirstName, request.LastName);
                SendActivationEmail(request.Email, fullName, activationLink);
            }

            return(new SignupResponse()
            {
                IsEmailVerificationRequired = ConfigHelper.Config.SignupActivationRequired
            });
        }
        public async Task <ActionResult <UserDetail> > Login(string email, string password)
        {
            var user = await _context.UserDetails.FirstOrDefaultAsync(u => u.Email.Equals(email.Trim()));

            if (user == null)
            {
                return(BadRequest($"User with {email} not found."));
            }

            string passwordHash = PasswordEncryptor.Encrypt(password);

            if (user.Password != passwordHash)
            {
                return(BadRequest($"Password isn't correct."));
            }

            user.Password = "";

            return(user);
        }
Beispiel #22
0
        private void btnSet_Click(object sender, EventArgs e)
        {
            //change username button
            try
            {
                if (string.IsNullOrEmpty(txtUsername.Text))
                {
                    throw new Exception("Enter current username");
                }
                if (txtUsername.Text != AdminLog.Admin)
                {
                    throw new Exception("Current username is not same as the current user");
                }

                if (string.IsNullOrEmpty(txtNewUser.Text))
                {
                    throw new Exception("Enter New username");
                }
                if (string.IsNullOrEmpty(txtCurrentPass.Text))
                {
                    throw new Exception("Enter admin password");
                }

                if (PasswordEncryptor.Encrypt(txtCurrentPass.Text) != AdminLog.AdminPass)
                {
                    throw new Exception("Current user password is incorrect");
                }

                AdminLog.UpdateAdminUsername(txtUsername.Text, txtNewUser.Text);
                MessageBox.Show("Update Successful", "Cash Desk", MessageBoxButtons.OK, MessageBoxIcon.Information);
                txtCurrentPass.Text = "";
                txtUsername.Text    = "";
                txtNewUser.Text     = "";
                var newLogin = new AdminLogOut();
                newLogin.ShowDialog();
            }
            catch (Exception Ex)
            {
                MessageBox.Show(Ex.Message, "Cash Desk", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
Beispiel #23
0
        public static void CreateAdmin(string user, string pass)
        {
            SqlConnection con = new DBConnection().getConnection();

            try
            {
                if (ForgottenPassword == true)
                {
                    UpdateAdminUsername(Admin, user);
                    UpdateAdminPass(pass);
                    ForgottenPassword = false;
                }
                else if (ResetPassword == true)
                {
                    UpdateAdminPass(pass);
                    ResetPassword = false;
                }
                else
                {
                    CheckPrvilege();
                    CheckUserName(user);
                    con.Open();
                    DataTable  dt = new DataTable();
                    DataSet    ds = new DataSet();
                    SqlCommand cmdcreateCommand = new SqlCommand();
                    cmdcreateCommand.Connection = con;
                    cmdcreateCommand.Parameters.Clear();
                    cmdcreateCommand.Parameters.AddWithValue("@UserName", user);
                    cmdcreateCommand.Parameters.AddWithValue("@Password", PasswordEncryptor.Encrypt(pass));
                    cmdcreateCommand.CommandText = "INSERT INTO Admin(UserName,Password) VALUES(@UserName,@Password)";

                    cmdcreateCommand.ExecuteNonQuery();
                    con.Close();
                }
            }
            catch (Exception Ex)
            {
                con.Close();
                throw new Exception(Ex.Message + "\nAdmin Not Created");
            }
        }
Beispiel #24
0
        private void btnChangePassword_Click(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(txtCurrentPassword.Text))
                {
                    throw new Exception("Enter current password");
                }
                if (string.IsNullOrEmpty(txtNewPass.Text))
                {
                    throw new Exception("Enter new password");
                }
                if (string.IsNullOrEmpty(txtConPass.Text))
                {
                    throw new Exception("confirm new password");
                }
                if (PasswordEncryptor.Encrypt(txtCurrentPassword.Text) != AdminLog.AdminPass)
                {
                    throw new Exception("Incorrect current password");
                }
                if (PasswordEncryptor.Encrypt(txtNewPass.Text) != PasswordEncryptor.Encrypt(txtConPass.Text))
                {
                    throw new Exception("new password mismatched");
                }
                else
                {
                    //call update method

                    AdminLog.UpdateAdminPass(txtConPass.Text);
                    MessageBox.Show("Update Successful", "Cash Desk", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    txtCurrentPassword.Text = "";
                    txtNewPass.Text         = "";
                    txtConPass.Text         = "";
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Input Error", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
        public ActionResult ForgotPassword(string Email)
        {
            var user = _dbContext.Users.Where(x => x.Email == Email).FirstOrDefault();

            if (user != null)
            {
                int result = SendForgetPasswordMail(user.Email);
                if (result == 0)
                {
                    var encryptedPass = PasswordEncryptor.Encrypt("1456");
                    user.Password = encryptedPass;
                    _dbContext.SaveChanges();
                    return(RedirectToAction("EmailSent"));
                }

                return(View());
            }
            else
            {
                return(View());
            }
        }
Beispiel #26
0
        public static void LogIn(string admin, string pass)
        {
            SqlConnection con = new DBConnection().getConnection();

            try
            {
                if (string.IsNullOrEmpty(admin))
                {
                    throw new Exception("Enter Username");
                }
                else if (string.IsNullOrEmpty(pass))
                {
                    throw new Exception("Enter Password");
                }
                con.Open();
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = con;
                cmd.Parameters.Clear();
                cmd.Parameters.AddWithValue("@UserName", admin);
                cmd.Parameters.AddWithValue("@Password", PasswordEncryptor.Encrypt(pass));
                cmd.CommandText = "SELECT *FROM Admin WHERE UserName =@UserName AND Password=@Password ";
                SqlDataReader reader = cmd.ExecuteReader();
                if (reader.HasRows)
                {
                    while (reader.Read())
                    {
                        Admin     = reader.GetString(1);
                        AdminPass = reader.GetString(2);
                    }
                }
                reader.Close();
                con.Close();
            }
            catch (Exception Ex)
            {
                con.Close();
                throw new ExceptionHandling("Username or Password was not provided\n Login Not Successful", Ex);
            }
        }
        public HttpResponseMessage Login(LoginRequest loginRequest)
        {
            string apiName = "Login(LoginRequest loginRequest)";
            var    guid    = Guid.NewGuid();

            logger.Info("Guid: \"{0}\" api/{1}/{2} was invoked", guid, controllerName, apiName);

            using (CouponsEntities db = new CouponsEntities())
            {
                try
                {
                    var user = db.Users.FirstOrDefault(u => u.Email.Equals(loginRequest.UserName));
                    if (user == null)
                    {
                        return(CreateGeneralResultMessage("Wrong Password or User Name", false, ApiStatusCodes.BadRequest));
                    }
                    var userEncryptedPassword = db.AuthUsers.FirstOrDefault(a => a.UserId.Equals(user.Id)).EncryptedPassword;
                    //if (loginRequest.Password.Equals(PasswordEncryptor.Decrypt(userEncryptedPassword)))
                    if (PasswordEncryptor.Encrypt(loginRequest.Password).Equals(userEncryptedPassword))
                    {
                        AuthenticationResponse response = new AuthenticationResponse();
                        response.TokenId = user.Token.ToString();

                        return(CreateResponseMessage(response));
                    }
                    else
                    {
                        logger.Error("Guid: \"{0}\" Wrong Password or User Name:", guid);
                        return(CreateGeneralResultMessage("Wrong Password or User Name", false, ApiStatusCodes.BadRequest));
                    }
                }
                catch (Exception ex)
                {
                    logger.Error("Guid: \"{0}\" General Error: {1}", guid, ex);
                    return(CreateGeneralResultMessage(ex.Message, false, ApiStatusCodes.InternalServerError));
                }
            }
        }
Beispiel #28
0
        public ValidateLoginDTO Login(string clientId, string login, string password)
        {
            var result = new ValidateLoginDTO();
            var user   = this.userRepositiory.Authenticate(login, PasswordEncryptor.Encrypt(password));
            var client = this.clientRepository.GetByPublicKey(clientId);

            if (user == null || client == null)
            {
                var errors = new List <string>()
                {
                    "User cannot be authenticated."
                };
                result.OverallErrors = errors;
                return(result);
            }

            this.tokenRepository.Invalidate(client.Id, user.Id, DateTime.UtcNow);

            var expiration = DateTime.UtcNow.AddMinutes(client.TokenExpirationTime);
            var token      = GenerateToken(client, user, expiration);

            this.tokenRepository.Create(new ApplicationToken()
            {
                Token      = token,
                Expiration = expiration,
                ClientId   = client.Id,
                UserId     = user.Id
            });

            result.Auth = new AuthDTO()
            {
                Expiration = expiration,
                Token      = token,
                Roles      = user.Roles.Select(role => role.Name).ToArray()
            };

            return(result);
        }
        public LoginResult Login(string login, string password)
        {
            try
            {
                var autorizedUser = default(IAutorizedUser);

                var encryptedPassword = PasswordEncryptor.Encrypt(password);

                var findUser = context.Users
                               .SingleOrDefault(user => user.Login.Equals(login) && user.Password.Equals(encryptedPassword));

                if (findUser != null)
                {
                    switch (findUser.Role)
                    {
                    case Role.Manager:
                        autorizedUser = context.Managers
                                        .Include(manager => manager.User)
                                        .SingleOrDefault(manager => manager.User.Id == findUser.Id);
                        break;

                    case Role.Customer:
                        autorizedUser = context.Customers
                                        .Include(customer => customer.User)
                                        .SingleOrDefault(customer => customer.User.Id == findUser.Id);
                        break;
                    }
                }

                return(autorizedUser != null
                    ? new LoginResult(true, autorizedUser)
                    : new LoginResult(false, null));
            }
            catch (Exception e)
            {
                return(new LoginResult(false, null));
            }
        }
        public ActionResult ChangePassword(long?id, string Password, string oldPass, string confirmPass)
        {
            try
            {
                string encOldPass = PasswordEncryptor.Encrypt(oldPass);
                User   user       = db.Users.Where(z => z.ID == id && z.Password == encOldPass).FirstOrDefault();
                if (user != null)
                {
                    user.Password = PasswordEncryptor.Encrypt(Password);

                    if (Password == confirmPass)
                    {
                        db.Entry(user).State = EntityState.Modified;
                        db.SaveChanges();
                        return(RedirectToAction("Profile", "Home", new { user.ID }));
                    }
                    else
                    {
                        ViewBag.NotMatching = "confirm password not matching";
                        ViewBag.Id          = id;
                        return(View());
                    }
                }
                else
                {
                    ViewBag.WrongOldPass = "******";
                    ViewBag.Id           = id;
                    return(View());
                }
            }
            catch (Exception)
            {
                ViewBag.somethingwentwrong = "some thing went wrong";
                ViewBag.Id = id;
                return(View());
            }
        }