public ActionResult Edit(EditEmployeeVM model)
        {
            if (!this.ModelState.IsValid)
            {
                return(View(model));
            }

            EmployeeService service  = new EmployeeService();
            Employee        employee = new Employee();

            employee.Id          = model.Id;
            employee.Email       = model.Email;
            employee.Password    = model.Password;
            employee.FirstName   = model.FirstName;
            employee.SecondName  = model.SecondName;
            employee.LastName    = model.LastName;
            employee.Phone       = model.Phone;
            employee.ManagerId   = model.ManagerId;
            employee.PositionId  = model.PositionId;
            employee.TeamId      = model.TeamId;
            employee.Adress      = model.Adress;
            employee.DateofBirth = model.DateOfBirth;
            employee.AdminRole   = AuthenticationManager.LoggedEmployee.AdminRole;

            service.Edit(employee);

            AuthenticationManager.Authenticate(AuthenticationManager.LoggedEmployee.Email, AuthenticationManager.LoggedEmployee.Password);
            return(RedirectToAction("Details", "Home"));
        }
        public ActionResult Login(LoginVM model)
        {
            if (this.ModelState.IsValid)
            {
                AuthenticationManager.Authenticate(model.Username, model.Password);

                if (AuthenticationManager.LoggedUser == null)
                {
                    ModelState.AddModelError("authenticationFailed", "Wrong username or password!");
                }
            }

            if (!this.ModelState.IsValid)
            {
                return(View(model));
            }
            if (AuthenticationManager.LoggedUser.UserName == "admin")
            {
                return(RedirectToAction("AdminIndex", "Users"));
            }
            else if (AuthenticationManager.LoggedUser.IsActiveAccount == false)
            {
                return(RedirectToAction("PermissionDenied", "Home"));
            }
            else
            {
                return(RedirectToAction("RoomIndex", "Rooms"));
            }
        }
        public void CheckTokenFail()
        {
            var authRepo      = new AuthenticationManager(token, auditManagementSystemContext.Object);
            var authrepotoken = authRepo.Authenticate("aaa", "1111");

            Assert.IsNull(authrepotoken);
        }
Exemplo n.º 4
0
        protected void btnAuthenticate_Click(object sender, EventArgs e)
        {
            //pass the credentials to the authentication manager which is class in data project working with context
            var customer = AuthenticationManager.Authenticate(txtFName.Text, txtLName.Text);

            if (customer == null)
            {
                //the customer is not authenticated so send message and return
                lblError.Text = "Invalid login";
                txtFName.Text = string.Empty;
                txtLName.Text = string.Empty;
                txtFName.Focus();

                return;
            }

            //at this point, customer is not null meaning we have a valid authentication
            //so add customer id to session
            Session.Add("customerID", customer.ID);
            string custFullName = customer.FullName;

            Session.Add("CustName", custFullName);
            // redirect - false means no persistent cookie
            FormsAuthentication.RedirectFromLoginPage(customer.FullName, false);
        }
Exemplo n.º 5
0
        public async Task LoginHandler()
        {
            AlertDialog.Builder alertBuilder = new AlertDialog.Builder(this);
            alertBuilder.SetTitle("Login")
            .SetMessage("Please wait while logging in...")
            .SetCancelable(false);

            AlertDialog dialog = null;

            RunOnUiThread(() => { dialog = alertBuilder.Show(); });
            try
            {
                azureResourceManager = await AuthenticationManager.Authenticate(platformParam);
            }
            catch (Exception e)
            {
            }
            finally
            {
                if (dialog != null)
                {
                    dialog.Dismiss();
                    dialog.Dispose();
                }
                if (alertBuilder != null)
                {
                    alertBuilder.Dispose();
                }
            }
        }
Exemplo n.º 6
0
        public void Authenticate_NotSupported()
        {
#pragma warning disable SYSLIB0009 // The methods are obsolete
            Assert.Throws <PlatformNotSupportedException>(() => AuthenticationManager.Authenticate(null, null, null));
            Assert.Throws <PlatformNotSupportedException>(() => AuthenticationManager.PreAuthenticate(null, null));
#pragma warning restore SYSLIB0009
        }
        /// <summary>
        /// Performs the login async
        ///
        /// Note: You may have to update your iOS/Android/UWP projects to use the
        /// latest version of TLS and HttpClient if login seems to fail.
        ///
        /// More details can be found here:
        /// https://docs.microsoft.com/en-us/xamarin/cross-platform/app-fundamentals/transport-layer-security
        /// </summary>
        ///
        public async Task <AuthenticationResult> PerformLoginAsync(string username, string password)
        {
            // Creates an authentication manager configuration configured for your UAA instance.
            // The baseURL, clientId and clientSecret can also be defined in your info.plist
            // if you wish but for simplicity they're added here.
            AuthenticationConfiguration authConfig = new AuthenticationConfiguration(Constants.UaaServer, Constants.ClientID, Constants.ClientSecret);

            // Give the username and password to the credential provider
            IClientCredentialProvider credentialProvider = new PredixCredentialProvider(username, password);

            // Create an online handler so that we can tell the authentication manager we want to authenticate online
            IAuthenticationHandler onlineAuthHandler = new UaaPasswordGrantAuthenticationHandler(credentialProvider);

            // Create an authentication manager with our UAA configuration, set UAA as our authorization source,
            // set the online handler so that the manager knows we want to autenticate online
            AuthenticationManager authenticationManager = new AuthenticationManager(authConfig, onlineAuthHandler)
            {
                AuthorizationHandler = new UaaAuthorizationHandler(),
                Reachability         = new Reachability()
            };

            // Tell authentication manager we are ready to authenticate,
            // once we call authenticate it will call the authentication handler with the credential provider
            return(await authenticationManager.Authenticate());
        }
Exemplo n.º 8
0
        public ActionResult Login(FormCollection collection)
        {
            var model = new HomeLoginVM();

            this.TryUpdateModel(model);

            AuthenticationManager.Authenticate(model.Email, model.Password);

            if (AuthenticationManager.LoggedUser == null)
            {
                this.ModelState.AddModelError("AuthenticationFailed", "* invalid or empty email or password");
                return(View("Index"));
            }
            else
            {
                Session["LoggedUser"] = model.Email;
                if (!string.IsNullOrEmpty(model.RedirectUrl))
                {
                    Response.Redirect(model.RedirectUrl);
                    return(new EmptyResult());
                }
            }

            return(RedirectToAction("Index", "Home"));
        }
Exemplo n.º 9
0
        public async Task Cookies_Are_Stored_Successfully()
        {
            const string expectedUri = "http://fake.forums.somethingawful.com/";

            var cookieContainer = new CookieContainer();

            cookieContainer.Add(new Uri(expectedUri), new Cookie("Foo", "bar"));
            cookieContainer.Add(new Uri(expectedUri), new Cookie("Bar", "Foo"));
            var webManager = new FakeWebManager
            {
                CookiesToReturn = cookieContainer,
            };

            var localStorage = new FakeLocalStorageManager();
            var am           = new AuthenticationManager(webManager, localStorage);

            await am.Authenticate("foo", "bar");

            Assert.AreEqual(expectedUri, localStorage.SavedUri.AbsoluteUri);
            Assert.AreEqual(2, localStorage.SavedCookies.Count);
            CookieCollection storedCookies = localStorage.SavedCookies.GetCookies(new Uri(expectedUri));

            Assert.IsNotNull(storedCookies["Foo"]);
            Assert.IsNotNull(storedCookies["Bar"]);
        }
        public async Task SetupLogin(IBrowserAuthenticationDelegate browserDelegate)
        {
            AuthenticationStatus = "Authentication Status:\nAuthenticating...";
            IsAuthenticating     = true;

            // We'll use the browserDelegate for handling events.
            //
            // create an AuthenticationManagerConfiguration, and load associated
            // UAA endpoint from our Predix Mobile server endpoint
            AuthenticationConfiguration authConfig = new AuthenticationConfiguration(Constants.UaaServer, Constants.ClientID, Constants.ClientSecret);

            // Create an OnlineAuthenticationHandler object -- in this case our online handler subclass is designed to work with a UAA login web page.
            // The redirectURI is setup in the UAA configuration
            IAuthenticationHandler onlineAuthHandler = new UaaBrowserAuthenticationHandler(Constants.RedirectUri, browserDelegate);

            // Create our AuthenticationManager with our configuration
            AuthenticationManager authenticationManager = new AuthenticationManager(authConfig, onlineAuthHandler)
            {
                //associate an AuthorizationHandler with the AuthenticationManager
                AuthorizationHandler = new UaaAuthorizationHandler(),
                Reachability         = new Reachability()
            };

            var result = await authenticationManager.Authenticate();

            Console.WriteLine("Authentication Completed");

            AuthenticationStatus = $"Authentication Status:\nSuccess - {result.Successful}\nError - {result.Error?.ToString() ?? "None"}";
            IsAuthenticating     = false;
        }
Exemplo n.º 11
0
 public ActionResult Login(DefaultControllerLoginVM model)
 {
     if (!ModelState.IsValid)
     {
         return(View(model));
     }
     else
     {
         TryUpdateModel(model);
         AuthenticationManager.Authenticate(model.UserName, model.Password, model.UserType);
         if (AuthenticationManager.LoggedUser == null)
         {
             return(RedirectToAction("Login", "Default"));
         }
         if (ObjectContext.GetObjectType(AuthenticationManager.LoggedUser.GetType()).Equals(typeof(Administrator)))
         {
             return(RedirectToAction("Home", "Admin"));
         }
         if (ObjectContext.GetObjectType(AuthenticationManager.LoggedUser.GetType()).Equals(typeof(Teacher)))
         {
             return(RedirectToAction("Index", "Teacher"));
         }
         if (ObjectContext.GetObjectType(AuthenticationManager.LoggedUser.GetType()).Equals(typeof(Student)))
         {
             return(RedirectToAction("Index", "Student"));
         }
         return(RedirectToAction("Login", "Default"));
     }
 }
Exemplo n.º 12
0
        public ActionResult Edit(EditDoctorVM edit)
        {
            if (!this.ModelState.IsValid)
            {
                return(View(edit));
            }

            UserService service = new UserService();
            User        user    = new User();

            user.Id        = edit.Id;
            user.Email     = edit.Email;
            user.Password  = edit.Password;
            user.Firstname = edit.Firstname;
            user.Lastname  = edit.Lastname;
            user.Phone     = edit.Phone;
            user.IsAdmin   = AuthenticationManager.LoggedUser.IsAdmin;

            service.Edit(user);

            if (edit.Specialization != null)
            {
                DoctorService serviceDoctor = new DoctorService();
                Doctor        doctor        = new Doctor();

                doctor.Specialization = edit.Specialization;
                doctor.Address        = edit.Address;
                doctor.UserId         = AuthenticationManager.LoggedUser.Id;

                serviceDoctor.Edit(doctor);
            }

            AuthenticationManager.Authenticate(AuthenticationManager.LoggedUser.Email, AuthenticationManager.LoggedUser.Password);
            return(RedirectToAction("Details", "Home"));
        }
Exemplo n.º 13
0
        private async void LoginCommandExecute()
        {
            _loadingService.ShowLoading();

            // Input fields validation
            if (!AreFieldsValid())
            {
                return;
            }

            string authResult = AuthenticationManager.Authenticate(UserName, Password);

            if (authResult == ConstantsHelper.UserNotExistsMessage)
            {
                var userNotExistsMessageLocalized = Resmgr.Value.GetString(ConstantsHelper.UserNotExistsMessage, _cultureInfo);
                _alertService.ShowOkAlert(userNotExistsMessageLocalized, ConstantsHelper.Ok);
                _loadingService.HideLoading();
                return;
            }
            if (authResult == ConstantsHelper.IncorrectPassword)
            {
                var incorrectPasswordMessageLocalized = Resmgr.Value.GetString(ConstantsHelper.IncorrectPassword, _cultureInfo);
                _alertService.ShowOkAlert(incorrectPasswordMessageLocalized, ConstantsHelper.Ok);
                _loadingService.HideLoading();
                return;
            }
            _loadingService.HideLoading();
            Settings.CurrentUserId       = authResult;
            Application.Current.MainPage = new NavigationPage(new NotesPage());
        }
Exemplo n.º 14
0
        private static void Main(string[] args)
        {
            try {
                AuthenticationManager.Authenticate();
            } catch (Exception) {
                MessageBox.Show("Ошибка авторизации!");
                return;
            }

            System.IO.StreamWriter logFile;
            try {
                logFile = new System.IO.StreamWriter(@"D:\log1.txt");
            } catch (Exception) {
                AuthenticationManager.Deauthenticate();
                MessageBox.Show("Ошибка создания файла!");
                return;
            }

            TechDocument doc = TechDocument.Load(@"D:\test.vtp");

            foreach (var child in doc.Objects)
            {
                logFile.WriteLine(child.ToString() + " (" + child.Class.Name + "): " + child.CreatorId);
            }

            doc.Close();

            AuthenticationManager.Deauthenticate();
            logFile.Close();
            MessageBox.Show("Выполнено!");
        }
Exemplo n.º 15
0
        private static void Main(string[] args)
        {
            try {
                AuthenticationManager.Authenticate();
            } catch (Exception) {
                MessageBox.Show("Ошибка авторизации!");
                return;
            }

            OpenFileDialog openFileDialog1 = new OpenFileDialog
            {
                InitialDirectory = @"c:\",
                Title            = "Выбор файла техпроцесса",

                CheckFileExists = true,
                CheckPathExists = true,

                DefaultExt       = "vtp",
                Filter           = "Файлы ТП (*.vtp;*.ttp)|*.vtp;*.ttp",
                FilterIndex      = 4,
                RestoreDirectory = true,

                ReadOnlyChecked = true,
                ShowReadOnly    = true
            };

            if (openFileDialog1.ShowDialog() != DialogResult.OK)
            {
                AuthenticationManager.Deauthenticate();
                return;
            }

            TechDocument doc = null;

            try {
                doc = TechDocument.Load(openFileDialog1.FileName);
            } catch (Exception) {
                doc.Close();
                AuthenticationManager.Deauthenticate();
                MessageBox.Show("Ошибка загрузки техпроцесса!");
                return;
            }

            if (doc.Extensions.EngineeringChangesManager.State
                == TechEngineeringChangesTechnologyState.Approved)
            {
                doc.Extensions.EngineeringChangesManager.CancelLatestApprove();
                doc.Save(openFileDialog1.FileName);
            }
            else
            {
                MessageBox.Show("Техпроцесс не утвержден!");
            }

            doc.Close();
            AuthenticationManager.Deauthenticate();
            MessageBox.Show("Выполнено!");
        }
        protected void Application_PostAuthenticateRequest()
        {
            var principal    = ClaimsPrincipal.Current;
            var transformer  = new AuthenticationManager();
            var newPrincipal = transformer.Authenticate(string.Empty, principal);

            Thread.CurrentPrincipal  = newPrincipal;
            HttpContext.Current.User = newPrincipal;
        }
Exemplo n.º 17
0
 public ActionResult Login(LoginVM loginVM)
 {
     AuthenticationManager.Authenticate(loginVM.Username, loginVM.Password);
     if (AuthenticationManager.LoggedUser == null)
     {
         return(RedirectToAction("Login", "Home"));
     }
     return(RedirectToAction("Index", "Footballers"));
 }
        public static void GetPage(String url, string username, string passwd)
        {
            try
            {
                string         challenge        = null;
                HttpWebRequest myHttpWebRequest = null;
                try
                {
                    // Create a 'HttpWebRequest' object for the above 'url'.
                    myHttpWebRequest = (HttpWebRequest)WebRequest.Create(url);
                    // The following method call throws the 'WebException'.
                    HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
                    // Release resources of response object.
                    myHttpWebResponse.Close();
                }
                catch (WebException e)
                {
                    for (int i = 0; i < e.Response.Headers.Count; ++i)
                    {
                        // Retrieve the challenge string from the header "WWW-Authenticate".
                        if ((String.Compare(e.Response.Headers.Keys[i], "WWW-Authenticate", true) == 0))
                        {
                            challenge = e.Response.Headers[i];
                        }
                    }
                }

                if (challenge != null)
                {
                    // Challenge was raised by the client.Declare your credentials.
                    NetworkCredential myCredentials = new NetworkCredential(username, passwd);
                    // Pass the challenge , 'NetworkCredential' object and the 'HttpWebRequest' object to the
                    //    'Authenticate' method of the  "AuthenticationManager" to retrieve an "Authorization" ;
                    //    instance.
                    Authorization urlAuthorization = AuthenticationManager.Authenticate(challenge, myHttpWebRequest, myCredentials);
                    if (urlAuthorization != null)
                    {
                        Console.WriteLine("\nSuccessfully Created 'Authorization' object with authorization Message:\n \"{0}\"", urlAuthorization.Message);
                        Console.WriteLine("\n\nThis authorization is valid for the following Uri's:");
                        int count = 0;
                        foreach (string uri in urlAuthorization.ProtectionRealm)
                        {
                            ++count;
                            Console.WriteLine("\nUri[{0}]: {1}", count, uri);
                        }
                    }
                    else
                    {
                        Console.WriteLine("\nAuthorization object was returned as null. Please check if site accepts 'CloneBasic' authentication");
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("\n The following exception was raised : {0}", e.Message);
            }
        }
Exemplo n.º 19
0
        private static void Main(string[] args)
        {
            if (args.Count() < 1)
            {
                return;
            }

            string modelName = args[0];

            try {
                AuthenticationManager.Authenticate();
            } catch (Exception) {
                MessageBox.Show("Ошибка авторизации!");
                return;
            }

            TechModel model = null;

            try {
                model = TechModel.Load(modelName);
            } catch (Exception) {
                MessageBox.Show("Ошибка загрузки модели!");
                AuthenticationManager.Deauthenticate();
                return;
            }

            foreach (var cls in model.Classes)
            {
                var missingRoles = cls.Permissions.Where(
                    p => p.Key != Guid.Empty &&
                    AuthenticationManager.Roles.All(r => r.Id != p.Key)
                    ).ToList();

                foreach (var missingRole in missingRoles)
                {
                    cls.Permissions.Clear(missingRole.Key);
                }

                foreach (var member in cls.Members)
                {
                    missingRoles = member.Permissions.Where(
                        p => p.Key != Guid.Empty &&
                        AuthenticationManager.Roles.All(r => r.Id != p.Key)
                        ).ToList();
                    foreach (var missingRole in missingRoles)
                    {
                        member.Permissions.Clear(missingRole.Key);
                    }
                }
            }
            model.Save(modelName);
            model.Close();

            AuthenticationManager.Deauthenticate();
            MessageBox.Show("Выполнено!");
        }
Exemplo n.º 20
0
        private static void Main(string[] args)
        {
            string modelName = @"e:\str.vtp";

            try {
                AuthenticationManager.Authenticate();
            } catch (Exception) {
                MessageBox.Show("Ошибка авторизации!");
                return;
            }

            TechModel model = null;

            try {
                model = TechModel.Load(modelName);
            } catch (Exception) {
                MessageBox.Show("Ошибка загрузки модели!");
                AuthenticationManager.Deauthenticate();
                return;
            }

            var presenations = model.Presentations;
            var prs          = model.Presentations[0];

            if (prs != null)
            {
                var newPrsn = presenations.Add("test");
                foreach (var oldItem in  prs.Items)
                {
                    var filter = model.Filters[oldItem.Name];
                    if (filter != null)
                    {
                        for (int i = 0; i < filter.Count; ++i)
                        {
                            var childCls = filter[i];
                            var newItem  = newPrsn.Items.Add(childCls.Name);
                            newItem.Description = childCls.Name + ": " + childCls.Description;
                            childrenPrsn(oldItem, newItem);
                        }
                    }
                    else
                    {
                        var newItem = newPrsn.Items.Add(oldItem.Name);
                        newItem.Description = oldItem.Description;
                        childrenPrsn(oldItem, newItem);
                    }
                }
            }


            model.Save(modelName);
            model.Close();

            AuthenticationManager.Deauthenticate();
            MessageBox.Show("Выполнено!");
        }
Exemplo n.º 21
0
        private static void Main(string[] args)
        {
            try {
                AuthenticationManager.Authenticate();
            } catch (Exception) {
                MessageBox.Show("Ошибка авторизации!");
                return;
            }

            TechModel model;

            try {
                model = TechModel.Load("d:\\structure.vtp");
            } catch (Exception) {
                AuthenticationManager.Deauthenticate();
                MessageBox.Show("Ошибка загрузки модели!");
                return;
            }

            System.IO.StreamWriter logFile;
            try {
                logFile = new System.IO.StreamWriter(@"D:\attr.txt");
            } catch (Exception) {
                model.Close();
                AuthenticationManager.Deauthenticate();
                MessageBox.Show("Ошибка создания файла!");
                return;
            }

            foreach (TechClass cls in model.Classes)
            {
                foreach (TechClassMember mbr in cls.Members)
                {
                    if (mbr.Type == TechClassMemberType.Property)
                    {
                        var prop         = mbr as TechClassProperty;
                        var mRestriction = prop.ValueRestrictions as TechMeasurandValueRestrictions;
                        if (mRestriction != null && mRestriction.Precision >= 0)
                        {
                            logFile.WriteLine(cls.Name + "." + prop.Name);
                            continue;
                        }
                        var dRestriction = prop.ValueRestrictions as TechDoubleValueRestrictions;
                        if (dRestriction != null && mRestriction.Precision >= 0)
                        {
                            logFile.WriteLine(cls.Name + "." + prop.Name);
                            continue;
                        }
                    }
                }
            }
            model.Close();
            AuthenticationManager.Deauthenticate();
            logFile.Close();
            MessageBox.Show("Выполнено!");
        }
Exemplo n.º 22
0
        public ActionResult Login(LoginViewModel loginViewModel, string returnUrl = "")
        {
            if (!_userManager.VerifyCredentials(loginViewModel.UserName, loginViewModel.Password))
            {
                return(RedirectToAction("Index", "Account"));
            }

            _authenticationManager.Authenticate(loginViewModel.UserName);
            return(RedirectToAction("Index", "Home"));
        }
Exemplo n.º 23
0
        public ActionResult LogIn(LoginVM model)
        {
            AuthenticationManager.Authenticate(model.Username, model.Password);
            if (AuthenticationManager.LoggedUser == null)
            {
                return(RedirectToAction("LogIn", "Home"));
            }

            return(RedirectToAction("Index", "Home"));
        }
Exemplo n.º 24
0
        private static void Main(string[] args)
        {
            string markerName = "ttplock";

            if (args.Count() < 1)
            {
                return;
            }

            string modelName = args[0];

            try {
                AuthenticationManager.Authenticate();
            } catch (Exception) {
                MessageBox.Show("Ошибка авторизации!");
                return;
            }

            TechModel model = null;

            try {
                model = TechModel.Load(modelName);
            } catch (Exception) {
                MessageBox.Show("Ошибка загрузки модели!");
                AuthenticationManager.Deauthenticate();
                return;
            }

            foreach (var cls in model.Classes)
            {
                foreach (var marker in cls.Markers)
                {
                    if (marker.Key.Name == markerName)
                    {
                        MessageBox.Show(cls.Name);
                    }
                }

                foreach (var member in cls.Members)
                {
                    foreach (var marker in member.Markers)
                    {
                        if (marker.Key.Name == markerName)
                        {
                            MessageBox.Show(cls.Name + "." + member.Name);
                        }
                    }
                }
            }
            model.Close();

            AuthenticationManager.Deauthenticate();
            MessageBox.Show("Выполнено!");
        }
Exemplo n.º 25
0
 private void buttonCheckHardwareId_Click(object sender, EventArgs e)
 {
     if (AuthenticationManager.Authenticate(textServerUri.Text, textHardwareId.Text))
     {
         MessageBox.Show("Successfully authenticated!", "hardwarechecker", MessageBoxButtons.OK, MessageBoxIcon.Information);
     }
     else
     {
         MessageBox.Show("Failed to authenticate!", "hardwarechecker", MessageBoxButtons.OK, MessageBoxIcon.Error);
     }
 }
Exemplo n.º 26
0
        public ActionResult Login(string email, string password)
        {
            var token = _authenticationManager.Authenticate(email, password);

            if (token == null)
            {
                return(BadRequest("Username or password incorrect"));
            }

            return(Ok(token));
        }
Exemplo n.º 27
0
        protected void UxAuthenticate_Click(object sender, EventArgs e)
        {
            // pass the credentials to the authenticationmanager
            var customer = AuthenticationManager.Authenticate(uxFirstname.Text, uxLastName.Text);

            // add the customer Id ito session

            Session.Add("CustomerID", customer.ID);

            //redirect
            FormsAuthentication.RedirectFromLoginPage(customer.FullName, false);
        }
Exemplo n.º 28
0
        protected void btnSubmit_click(object sender, EventArgs e)
        {
            if (IsUpdate)
            {
                //updating the record
                //get id out of session
                if (Session["ID"] != null)
                {
                    var id = Convert.ToInt32(Session["ID"]);
                    //get the Authentication object from the manager
                    var auth = AuthenticationManager.Find(id);
                    auth.FirstName = txtFirstname.Text;
                    auth.LastName  = txtLastname.Text;
                    auth.City      = txtCity.Text;
                    auth.Phone     = txtPhone.Text;
                    //pass auth to the manager for updating
                    AuthenticationManager.Update(auth);
                    //remove from auth ticket, clear session and redirect
                    FormsAuthentication.SignOut();
                    Session.Clear();
                    Response.Redirect("~/Registration");
                }
            }
            else
            {
                //inserting the record
                var customer = new Customer
                {
                    FirstName = txtFirstname.Text,
                    LastName  = txtLastname.Text,
                    City      = txtCity.Text,
                    Phone     = txtPhone.Text
                };
                //pass the auth object to the manager for inserting
                AuthenticationManager.Add(customer);
                Response.Redirect("~/Login");
            }
            var user = AuthenticationManager.Authenticate(txtFirstname.Text, txtLastname.Text);

            if (user == null)
            {
                //the customer is not authenticated
                txtFirstname.Text = string.Empty;
                txtLastname.Text  = string.Empty;
                txtFirstname.Focus();
                return;
            }
            //add id to session
            Session.Add("ID", ID);
            //redirect
            FormsAuthentication.RedirectFromLoginPage(user.FullName, false);
        }
Exemplo n.º 29
0
        public ActionResult LogIn(LogInVM login)
        {
            AuthenticationManager.Authenticate(login.Email, login.Password);

            if (AuthenticationManager.LoggedUser == null)
            {
                return(RedirectToAction("LogIn", "Home"));
            }
            else
            {
                return(RedirectToAction("Index", "Appointment"));
            }
        }
Exemplo n.º 30
0
        public ActionResult Login(AccountLoginVM viewModel)
        {
            AuthenticationManager.Authenticate(viewModel.Username, viewModel.Password);

            if (AuthenticationManager.LoggedUser == null)
            {
                ModelState.AddModelError("AuthenticationFailed", "WrongUsernameOrPassword");

                return(View(viewModel));
            }

            return(RedirectToAction("Index", "Home"));
        }
        public async Task Providing_Invalid_Credentials_Returns_False()
        {
            var cookieContainer = new CookieContainer();
            cookieContainer.Add(new Uri("http://foo.com"), new Cookie("Bar", "Foo"));
            var webManager = new FakeWebManager
            {
                CookiesToReturn = cookieContainer
            };

            var localStorage = new FakeLocalStorageManager();
            var am = new AuthenticationManager(webManager, localStorage);
            const bool expected = false;
            bool actual = await am.Authenticate("foo", "bar");
            Assert.AreEqual(expected, actual);
        }
        public async Task Network_Interface_Being_Unavailable_Throws_Exception()
        {
            var cookieContainer = new CookieContainer();
            cookieContainer.Add(new Uri("http://foo.com"), new Cookie("Bar", "Foo"));
            var webManager = new FakeWebManager
            {
                CookiesToReturn = cookieContainer,
                IsNetworkAvailable = false
            };

            var localStorage = new FakeLocalStorageManager();
            var am = new AuthenticationManager(webManager, localStorage);
            try
            {
                await am.Authenticate("foo", "bar");
            }
            catch (Exception)
            {
                return;
            }
            Assert.Fail();
        }
        public async Task Cookies_Are_Stored_Successfully()
        {
            const string expectedUri = "http://fake.forums.somethingawful.com/";

            var cookieContainer = new CookieContainer();
            cookieContainer.Add(new Uri(expectedUri), new Cookie("Foo", "bar"));
            cookieContainer.Add(new Uri(expectedUri), new Cookie("Bar", "Foo"));
            var webManager = new FakeWebManager
            {
                CookiesToReturn = cookieContainer,
            };

            var localStorage = new FakeLocalStorageManager();
            var am = new AuthenticationManager(webManager, localStorage);

            await am.Authenticate("foo", "bar");

            Assert.AreEqual(expectedUri, localStorage.SavedUri.AbsoluteUri);
            Assert.AreEqual(2, localStorage.SavedCookies.Count);
            CookieCollection storedCookies = localStorage.SavedCookies.GetCookies(new Uri(expectedUri));
            Assert.IsNotNull(storedCookies["Foo"]);
            Assert.IsNotNull(storedCookies["Bar"]);
        }
        public async Task Cookies_Are_Retrieved_Successfully()
        {
            const string expectedUri = "http://fake.forums.somethingawful.com/";

            var cookieContainer = new CookieContainer();
            cookieContainer.Add(new Uri(expectedUri), new Cookie("Foo", "bar"));
            cookieContainer.Add(new Uri(expectedUri), new Cookie("Bar", "Foo"));
            var webManager = new FakeWebManager
            {
                CookiesToReturn = cookieContainer,
            };

            var localStorage = new FakeLocalStorageManager();
            var am = new AuthenticationManager(webManager, localStorage);

            await am.Authenticate("foo", "bar");
            localStorage.CookiesToReturn = localStorage.SavedCookies;

            CookieContainer cookies = await localStorage.LoadCookie(Constants.COOKIE_FILE);

            Assert.AreEqual(2, cookies.Count);
        }