Ejemplo n.º 1
1
    protected void LoginButton_Click(object sender, EventArgs e)
    {
        SqlConnection con = new SqlConnection();
        //string hh = "select *from tbuser where uname='" + Login1.UserName + "' and upass='******'";
        con.ConnectionString = ConfigurationManager.ConnectionStrings["forest_depoConnectionString"].ConnectionString;
        con.Open();
        SqlCommand cmd = new SqlCommand();
        cmd.CommandText = "user_log";
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Connection = con;
        cmd.Parameters.Add("@un", SqlDbType.VarChar, 50).Value = LoginUser.UserName.ToString();
        cmd.Parameters.Add("@up", SqlDbType.VarChar, 50).Value = LoginUser.Password.ToString();
        SqlDataReader dr = cmd.ExecuteReader();
        dr.Read();
        if (dr.HasRows)
        {

            FormsAuthenticationTicket tkt = new FormsAuthenticationTicket(1, LoginUser.UserName, DateTime.Now, DateTime.Now.AddHours(2), false, dr[3].ToString(), FormsAuthentication.FormsCookiePath);
            string st1;
            st1 = FormsAuthentication.Encrypt(tkt);
            HttpCookie ck = new HttpCookie(FormsAuthentication.FormsCookieName, st1);
            Response.Cookies.Add(ck);
            string role = dr[3].ToString();

            //if (dr[3].ToString() == "admin".ToString())
            //{
            //    //Response.Redirect("focus1/admin/");
                Session["start_a"] = "start";
                if (dr["role"].ToString() == "admin")
                {
                    Response.Redirect("../admin/speces_size_type.aspx");
                }
                if (dr["role"].ToString() == "admin2")
                {
                    Response.Redirect("../admin2/auc_cal.aspx");
                }
                if (dr["role"].ToString() == "admin3")
                {
                    Response.Redirect("../admin3/gate_pass.aspx");
                }
                if (dr["role"].ToString() == "admin4")
                {
                    Response.Redirect("../admin4/");
                }

            }
        //    else
        //    {
        //        Session["start_u"] = "start";
        //        // Response.Redirect("focus1/user/");
        //        Response.Redirect("user/");
        //    }
        //}

        else
        {
             //LoginUser.FailureText= "Wrong UserName or Password";
             Response.Redirect("error.aspx");
        }
    }
Ejemplo n.º 2
1
 public void RaiseCallbackEvent(string eventArgument)
 {
     //匿名用户登录
     if (String.IsNullOrEmpty(eventArgument)) {
         FormsAuthentication.SetAuthCookie("Anonymous", true);
         callBackResult = FormsAuthentication.DefaultUrl;
         WriteLoginLog("Anonymous");
         return;
     }
     String[] arguments = eventArgument.Split(',');
     String userAccount = arguments[0];
     String password = FormsAuthentication.HashPasswordForStoringInConfigFile(arguments[1], "MD5");
     using (SysUserBusiness user = new SysUserBusiness()) {
         bool passed = user.Authentication(userAccount, password);
         if (passed) {
             FormsAuthentication.SetAuthCookie(userAccount, true);
             HttpCookie authCookie = FormsAuthentication.GetAuthCookie(userAccount, true);
             FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(authCookie.Value);
             FormsAuthenticationTicket newTicket = new FormsAuthenticationTicket(ticket.Version, ticket.Name, ticket.IssueDate, ticket.Expiration, ticket.IsPersistent, "");
             authCookie.Value = FormsAuthentication.Encrypt(newTicket);
             Response.Cookies.Add(authCookie);
             callBackResult = FormsAuthentication.DefaultUrl;
             WriteLoginLog(userAccount);
         }
     }
 }
Ejemplo n.º 3
1
    protected void btnValidar_Click(object sender, EventArgs e)
    {
        ClaseValidacion c = new ClaseValidacion();
        if (c.validarUser(this.txtusuario.Text, this.txtpassword.Text))
        {
            //CREAMOS EL TICKET
            FormsAuthenticationTicket ticket =
                new FormsAuthenticationTicket(1,
                    this.txtusuario.Text
                    , DateTime.Now
                    , DateTime.Now.AddMinutes(30)
                    , true
                    , c.role);
            //ENCRIPTAR LOS DATOS DEL TICKET
            String informacion = FormsAuthentication.Encrypt(ticket);
            //CREAR LA COOKIE
            HttpCookie cookie =
                new HttpCookie(FormsAuthentication.FormsCookieName
                    , informacion);
            //ALMACENAR LA COOKIE
            Response.Cookies.Add(cookie);
            //RECUPERAR LA PAGINA DE DESTINO
            String destino =
                FormsAuthentication.GetRedirectUrl(this.txtusuario.Text
                , true);
            //REDIRECCIONAMOS AL DESTINO
            Response.Redirect(destino);
        }
        else
        {
            this.lblmensaje.Text = "Usuario/Password incorrectos.";
        }

    }
Ejemplo n.º 4
1
    private void cmdLogin_ServerClick(object sender, System.EventArgs e)
    {
        if (ValidateUser(txtUserName.Value, txtUserPass.Value))
            {
                FormsAuthenticationTicket tkt;
                string cookiestr;
                HttpCookie ck;
                tkt = new FormsAuthenticationTicket(1, txtUserName.Value, DateTime.Now, DateTime.Now.AddMinutes(30), chkPersistCookie.Checked, "your custom data");
                cookiestr = FormsAuthentication.Encrypt(tkt);
                ck = new HttpCookie(FormsAuthentication.FormsCookieName, cookiestr);
                if (chkPersistCookie.Checked)
                    ck.Expires = tkt.Expiration;
                ck.Path = FormsAuthentication.FormsCookiePath;
                Response.Cookies.Add(ck);

                string strRedirect;
                strRedirect = Request["ReturnUrl"];
                if (strRedirect == null)
                    strRedirect = "default.aspx";
                Response.Redirect(strRedirect, false);
            }
            else
            {
                Response.Redirect("logon.aspx", false);
            }
    }
Ejemplo n.º 5
1
    private static void SignIn(string loginName, object userData)
    {
        var jser = new JavaScriptSerializer();
        var data = jser.Serialize(userData);

        //创建一个FormsAuthenticationTicket,它包含登录名以及额外的用户数据。
        var ticket = new FormsAuthenticationTicket(2,
            loginName, DateTime.Now, DateTime.Now.AddDays(1), true, data);

        //加密Ticket,变成一个加密的字符串。
        var cookieValue = FormsAuthentication.Encrypt(ticket);

        //根据加密结果创建登录Cookie
        var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, cookieValue)
        {
            HttpOnly = true,
            Secure = FormsAuthentication.RequireSSL,
            Domain = FormsAuthentication.CookieDomain,
            Path = FormsAuthentication.FormsCookiePath
        };
        //在配置文件里读取Cookie保存的时间
        double expireHours = Convert.ToDouble(ConfigurationManager.AppSettings["loginExpireHours"]);
        if (expireHours > 0)
            cookie.Expires = DateTime.Now.AddHours(expireHours);

        var context = System.Web.HttpContext.Current;
        if (context == null)
            throw new InvalidOperationException();

        //写登录Cookie
        context.Response.Cookies.Remove(cookie.Name);
        context.Response.Cookies.Add(cookie);
    }
Ejemplo n.º 6
1
	protected void cmdLogin_Click (object sender, EventArgs e)
	{
		LoginResponse response;

		Master.ClearLogin ();

		try {
			WebServiceLogin login = new WebServiceLogin ();
			login.User = txtUser.Text;
			login.Password = txtPassword.Text;
			Console.WriteLine ("Trying to log in with {0}/{1}", login.User, login.Password);
			login.Ip4 = Utilities.GetExternalIP (Context.Request);
			response = Master.WebService.Login (login);
			if (response == null) {
				lblMessage.Text = "Could not log in.";
				txtPassword.Text = "";
			} else {
				Console.WriteLine ("Login.aspx: Saved cookie!");
				FormsAuthenticationTicket cookie = new FormsAuthenticationTicket ("cookie", true, 60 * 24);
				Response.Cookies.Add (new HttpCookie ("cookie", response.Cookie));
				Response.Cookies ["cookie"].Expires = DateTime.Now.AddDays (1);
				Response.Cookies.Add (new HttpCookie ("user", login.User));
				FormsAuthentication.SetAuthCookie (response.User, true);
				Response.Redirect (txtReferrer.Value, false);
			}
		} catch (Exception) {
			lblMessage.Text = "Invalid user/password.";
			txtPassword.Text = "";
		}
	}
Ejemplo n.º 7
1
    protected void Prijava_OnClick(object sender, ImageClickEventArgs e)
    {
        Korisnici korisnik = korisniciService.PrijaviKorisnikaPoKorisnickomImenuLozinci(tbKorisnickoIme.Text, tbLozinka.Text);

        if (korisnik != null)
        {
            FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, tbKorisnickoIme.Text, DateTime.Now,
                DateTime.Now.AddMinutes(120), chkZapamtiMe.Checked, "custom data");
            string cookieStr = FormsAuthentication.Encrypt(ticket);
            HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, cookieStr);

            if (chkZapamtiMe.Checked)
                cookie.Expires = ticket.Expiration;

            cookie.Path = FormsAuthentication.FormsCookiePath;
            Response.Cookies.Add(cookie);

            Response.Redirect("User/Default.aspx", true);
        }
        else
        {
            phStatusPrijave.Visible = true;
            lblStatusPrijave.Text = "Pogresni korisnicko ime ili lozinka!";
        }
    }
Ejemplo n.º 8
1
    private void CreateFormsAuthTicket(string username, int ValidMinutes, bool rememberMe)
    {
        FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
            1,
            username,
            DateTime.Now,
            DateTime.Now.AddMinutes(ValidMinutes),
            rememberMe,
            username
            );

        // Bileti şifrele.
        string encryptedTicket = FormsAuthentication.Encrypt(ticket);

        // Bileti sakla.
        HttpCookie formsCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
        HttpContext.Current.Response.Cookies.Add(formsCookie);

        // FormsAuthentication kimliğini yarat.
        FormsIdentity formsId = new FormsIdentity(ticket);

        //roles
        string[] roles = new string[] { "user" };

        // Yeni kullanıcı bilgisini yarat.
        HttpContext.Current.User = new GenericPrincipal(formsId, roles);
    }
Ejemplo n.º 9
1
    protected override Task<HttpResponseMessage> SendAsync(
        HttpRequestMessage request, CancellationToken cancellationToken)
    {
        if (request.Method == HttpMethod.Get && request.RequestUri.Segments.Last() == "authtoken")
        {
            string querystring = request.RequestUri.Query.Substring(1);
            string[] queryParams = querystring.Split(new[] { '&' });

            var queryStringParams = request.RequestUri.ParseQueryString();
            if (queryStringParams.Count > 0)
            {
                string code = queryParams.Where(p => p.StartsWith("code")).First().Split(new[] { '=' })[1];

                return Task.Factory.StartNew(
                    () =>
                    {
                        string accessToken = this.GetFacebookAccessToken(code, request);
                        string username = GetFacebookUsername(accessToken);

                        var ticket = new FormsAuthenticationTicket(username, false, 60);
                        string s = FormsAuthentication.Encrypt(ticket);

                        var response = new HttpResponseMessage();
                        response.Headers.Add("Set-Cookie", string.Format("ticket={0}; path=/", s));

                        var responseContentBuilder = new StringBuilder();
                        responseContentBuilder.AppendLine("<html>");
                        responseContentBuilder.AppendLine("   <head>");
                        responseContentBuilder.AppendLine("      <title>Login Callback</title>");
                        responseContentBuilder.AppendLine("   </head>");
                        responseContentBuilder.AppendLine("   <body>");
                        responseContentBuilder.AppendLine("      <script type=\"text/javascript\">");
                        responseContentBuilder.AppendLine(
                            "         if(window.opener){");

                        if (queryStringParams["callback"] != null)
                        {
                            responseContentBuilder.AppendLine(queryStringParams["callback"] + "();");
                        }

                        responseContentBuilder.AppendLine("            window.close()';");
                        responseContentBuilder.AppendLine("         }");
                        responseContentBuilder.AppendLine("      </script>");
                        responseContentBuilder.AppendLine("   </body>");
                        responseContentBuilder.AppendLine("</html>");

                        response.Content = new StringContent(responseContentBuilder.ToString());
                        response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/html");
                        response.Headers.CacheControl = new CacheControlHeaderValue { NoCache = true };

                        return response;
                    });
            }

            return Task.Factory.StartNew(() => new HttpResponseMessage(HttpStatusCode.InternalServerError));
        }

        return base.SendAsync(request, cancellationToken);
    }
Ejemplo n.º 10
1
    public static string Encrypt(string plaintext)
    {
        FormsAuthenticationTicket ticket;
        ticket = new FormsAuthenticationTicket(1, "", DateTime.Now,
            DateTime.Now, false, plaintext, "");

        return FormsAuthentication.Encrypt(ticket);
    }
Ejemplo n.º 11
1
    protected void btnLogin_Click(object sender, EventArgs e)
    {
        //Activate the message if login is failed
        lblMessage.Visible = true;

        AppSecurity temp =  new AppSecurity();

        temp = AppSecurity.login(txtUsername.Text, txtPassword.Text);

        if (!string.IsNullOrEmpty(txtUsername.Text) & !string.IsNullOrEmpty(txtPassword.Text))
            {

                //set string value to class function that returns string
                temp = AppSecurity.login(txtUsername.Text.Trim(), txtPassword.Text.Trim());
            }

            else
            {
                lblMessage.Text = temp.ErrorLogin.ToString();
                return;
            }

        if (temp.UserId > 0)
        {

            // Use .NET built in security system to set the UserID
            //within a client-side Cookie
            FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(temp.UserId.ToString(), false, 480);

            //For security reasons we may hash the cookies
            string encrytpedTicket = FormsAuthentication.Encrypt(ticket);

            HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encrytpedTicket);
            Response.Cookies.Add(cookie);

            //set the username to a client side cookie for future reference
            HttpCookie MyCookie = new HttpCookie("UserEmail");
            DateTime now = DateTime.Now;

            MyCookie.Value = temp.UserEmail.ToString();
            MyCookie.Expires = now.AddDays(1);
            Response.Cookies.Add(MyCookie);

            //set the userrole to a session variable for future reference
            Session["Role"] = temp.UserRole.ToString();

            // Redirect browser back to home page
            Response.Redirect("~/Default.aspx");
        }
        else
        {
            //or else display the failed login message
            lblMessage.Text = "Login Failed!";
        }
    }
Ejemplo n.º 12
0
    protected void Button1_Click(object sender, EventArgs e)
    {
        FormsAuthentication.Initialize();   // Initializes the FormsAuthentication object based on the configuration settings for the application.

        SqlConnection con = new SqlConnection("server=saurabh-pc;database=ss;integrated security=true");

        SqlCommand cmd = new SqlCommand("select role from roles r inner join users u on r.ID=u.roleid where u.username=@username and u.password=@password",con);

        cmd.Parameters.Add("@username", SqlDbType.VarChar, 30).Value = TextBox1.Text;
        cmd.Parameters.Add("@password", SqlDbType.VarChar, 30).Value = TextBox2.Text;
        FormsAuthentication.HashPasswordForStoringInConfigFile(TextBox2.Text, "md5"); // Or "sha1"

        con.Open();
        SqlDataReader dr = cmd.ExecuteReader();
        if (dr.Read())
        {
            // Create a new ticket used for authentication
            FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
                                                                                1,  // Ticket version
                                                                                TextBox1.Text, // Username associated with ticket
                                                                                DateTime.Now,  // Date/time issued
                                                                                DateTime.Now.AddMinutes(30), // Date/time to expire
                                                                               true,    // "true" for a persistent user cookie
                                                                               dr.GetString(0), // User-data, in this case the roles
                                                                               FormsAuthentication.FormsCookiePath // Path cookie valid for
                                                                                );

            // Encrypt the cookie using the machine key for secure transport

            string hash = FormsAuthentication.Encrypt(ticket);

            HttpCookie ck = new HttpCookie(FormsAuthentication.FormsCookieName,// Name of auth cookie
                                            hash); // Hashed ticket

            // Set the cookie's expiration time to the tickets expiration time

            if (ticket.IsPersistent)
            {
                ck.Expires = ticket.Expiration;
            }
            // Add the cookie to the list for outgoing response
            Response.Cookies.Add(ck);
            // Redirect to requested URL, or homepage if no previous page
            // requested
            string returnUrl=Request.QueryString["ReturnUrl"];
            if (returnUrl == null)
            {
                returnUrl = "home.aspx";
            }
            // Don't call FormsAuthentication.RedirectFromLoginPage since it
            // could
            // replace the authentication ticket (cookie) we just added
            Response.Redirect(returnUrl);

        }
        else
        {
            Label1.Text = "incorrect username/password";
        }
    }
Ejemplo n.º 13
0
    protected void buttonLogin_Click(object sender, EventArgs e)
    {
        // Try to authenticate credentials supplied by user.
        if (FormsAuthentication.Authenticate(UserName.Text, Password.Text))
        {
            FormsAuthenticationTicket ticket = new
                FormsAuthenticationTicket(UserName.Text, false, 5000);

            FormsAuthentication.RedirectFromLoginPage(UserName.Text, RememberMe.Checked);
        }
    }
Ejemplo n.º 14
0
 //驗證函數
 void SetAuthenTicket(string userData, string userId)
 {
     //宣告一個驗證票
     FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, userId, DateTime.Now, DateTime.Now.AddHours(3), false, userData);
     //加密驗證票
     string encryptedTicket = FormsAuthentication.Encrypt(ticket);
     //建立Cookie
     HttpCookie authenticationcookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
     //將Cookie寫入回應
     Response.Cookies.Add(authenticationcookie);
 }
Ejemplo n.º 15
0
 protected void btnLogin_Click(object sender, EventArgs e)
 {
     if (txtUserName.Text == "admin" && txtPassword.Text == "123")
     {
         Session["UserName"] = "******";
         FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1, txtUserName.Text, DateTime.Now, DateTime.Now.AddMinutes(120), false, @"\");
         string strRedirectionUrl = "~/Admin/Default.aspx";
         FormsAuthentication.RedirectFromLoginPage("Admin", false);
         Response.Redirect(strRedirectionUrl);
     }
 }
Ejemplo n.º 16
0
    /// <summary>
    /// Bring access if the User information is correct, else revoke access.
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
    {
        if (ValidateUser(Security.cleanSQL(Login1.UserName), Security.encrypt(Login1.Password)))
        {
            FormsAuthentication.Initialize();
            String strRole = AssignRoles(Security.cleanSQL(Login1.UserName));

            FormsAuthenticationTicket fat = new FormsAuthenticationTicket(1, Login1.UserName, DateTime.Now, DateTime.Now.AddMinutes(3600), false, strRole, FormsAuthentication.FormsCookiePath);
            Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(fat)));
            Response.Redirect(FormsAuthentication.GetRedirectUrl(Security.cleanSQL(Login1.UserName), false));
        }
    }
Ejemplo n.º 17
0
    protected void btnLogin_Click(object sender, EventArgs e)
    {
        //string adPath = "LDAP://DC=mb,DC=com"; //Path to your LDAP directory server
        LdapAuthentication adAuth = new LdapAuthentication(txtDomain.Text);
        try
        {
            if (true == adAuth.IsAuthenticated(txtDomain.Text, txtUsername.Text, txtPassword.Text))
            //if(true)
            {
                // string groups = adAuth.GetGroups();
                string groups = "";

                //Create the ticket, and add the groups.
                bool isCookiePersistent = chkPersist.Checked;
                FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1,
                          txtUsername.Text, DateTime.Now, DateTime.Now.AddMinutes(60), isCookiePersistent, groups);

                //Encrypt the ticket.
                string encryptedTicket = FormsAuthentication.Encrypt(authTicket);

                //Create a cookie, and then add the encrypted ticket to the cookie as data.
                HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
                HttpCookie loginNameCookie = new HttpCookie(ESB_COOKIE_LOGINNAME, txtUsername.Text);

                if (true == isCookiePersistent)
                {
                    authCookie.Expires = authTicket.Expiration;
                    loginNameCookie.Expires = DateTime.Now.AddDays(30);
                }

                //Add the cookie to the outgoing cookies collection.
                Response.Cookies.Add(authCookie);
                Response.Cookies.Add(loginNameCookie);


                //Esb授权校验
                EsbAuthen(txtUsername.Text);

                //Server.Transfer("Default.aspx");
                //You can redirect now.
                //Response.Redirect(FormsAuthentication.GetRedirectUrl(txtUsername.Text, false));
                Response.Redirect("Default.aspx", false);
            }
            else
            {
                errorLabel.Text = "登录失败,请检查用户名和密码!";
            }
        }
        catch (System.Exception ex)
        {
            errorLabel.Text = "登录失败,请检查用户名和密码!";
        }
    }
Ejemplo n.º 18
0
    protected void loginButton_Click(object sender, EventArgs e)
    {     
        if (IsValid)
        {
            string encryptPass;

            ActiveDirectoryResourceService activeDirectoryResourceService = new ActiveDirectoryResourceService();
            User user = null;
            user = activeDirectoryResourceService.AuthenticateUser(this.userNameTextBox.Text, this.passwordTextBox.Text);

            //if (FormsAuthentication.Authenticate(this.userNameTextBox.Text, this.passwordTextBox.Text) == false)
            //{
            //    loginMessage.Text = Resources.UIResource.ErrorLoginMessage;
            //    return;
            //}

            if (user != null)
            {
                
                WebSession.Profile = AuthenticationHelper.MakeUserProfile(this.userNameTextBox.Text);         
                
                FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
                1, // Ticket version
                this.userNameTextBox.Text, // Username to be associated with this ticket
                DateTime.Now, // Date/time issued
                DateTime.Now.AddHours(7), // Date/time to expire
                false, // "true" for a persistent user cookie (could be a checkbox on form)
                "WebSurfer", // User-data (the roles from this user record in our database)
                FormsAuthentication.FormsCookiePath); // Path cookie is valid for

                // Hash the cookie for transport over the wire
                string hash = FormsAuthentication.Encrypt(ticket);
                HttpCookie cookie = new HttpCookie(
                FormsAuthentication.FormsCookieName, // Name of auth cookie (it's the name specified in web.config)
                 hash); // Hashed ticket

                // Add the cookie to the list for outbound response
                Response.Cookies.Add(cookie);                

                String returnUrl = Request.QueryString["ReturnUrl"];
                if ((returnUrl == null)) returnUrl = (FormsAuthentication.DefaultUrl);
                if (returnUrl == null) returnUrl = ResolveClientUrl(Request.AppRelativeCurrentExecutionFilePath);
                //Response.Redirect(returnUrl);               
                
                FormsAuthentication.RedirectFromLoginPage(this.userNameTextBox.Text, false);
            }
            else
            {
                loginMessage.Text = Resources.UIResource.ErrorLoginMessage;
            }
        }
    }
Ejemplo n.º 19
0
    protected void LoginButton_Click1(object sender, EventArgs e)
    {
        SqlConnection con = new SqlConnection();
        //string hh = "select *from tbuser where uname='" + Login1.UserName + "' and upass='******'";
        con.ConnectionString = ConfigurationManager.ConnectionStrings["hpieConnectionString"].ConnectionString;
        con.Open();
        SqlCommand cmd = new SqlCommand();
        cmd.CommandText = "user_log";
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Connection = con;
        cmd.Parameters.Add("@un", SqlDbType.VarChar, 50).Value = LoginUser.UserName.ToString();
        cmd.Parameters.Add("@up", SqlDbType.VarChar, 50).Value = LoginUser.Password.ToString();
        SqlDataReader dr = cmd.ExecuteReader();
        dr.Read();
        if (dr.HasRows)
        {

            FormsAuthenticationTicket tkt = new FormsAuthenticationTicket(1, LoginUser.UserName, DateTime.Now, DateTime.Now.AddMinutes(160), false, dr["role"].ToString(), FormsAuthentication.FormsCookiePath);
            string st1;
            st1 = FormsAuthentication.Encrypt(tkt);
            HttpCookie ck = new HttpCookie(FormsAuthentication.FormsCookieName, st1);
            Response.Cookies.Add(ck);
            trac();
            string cc1 = dr[5].ToString();
            Session["start_a"] = dr[5].ToString();

            if (dr["role"].ToString() == "admin")
            {
                Response.Redirect("~/admin/reportcard_all.aspx");
            }
            if (dr["role"].ToString() == "user")
            {
                Response.Redirect("~/user/Details.aspx");
            }
            if (dr["role"].ToString() == "support")
            {
                Response.Redirect("~/support/");
            }
            if (dr["role"].ToString() == "rep")
            {
                Response.Redirect("~/reports/reportcard_all.aspx");
            }
        }

        else
        {
            trac2();
            //Label1.Text = "Wrong UserName or Password";
        }
    }
Ejemplo n.º 20
0
    protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
    {
        UsuarioDAO obj = new UsuarioDAO();
        Usuario usuario = new Usuario();

        usuario.Login = Login1.UserName;
        usuario.Senha = Login1.Password;
        try
        {

            if (obj.EfetuarLogin(usuario))
            {
                Login1.Visible = false;
                Session["LOGIN"] = usuario.Login;
                e.Authenticated = true;

                FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
                     1,                             // versão
                     this.Login1.UserName.Trim(),   // login
                     DateTime.Now,                  // hora atual
                     DateTime.Now.AddMinutes(10),   // tempo para expirar
                     false,                         // cookie is not persistent
                     "PGTO"                         // role - se houver
                     );
                HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(ticket));
                Response.Cookies.Add(cookie);

                String returnUrl1;

                if (Request.QueryString["ReturnUrl"] == null)
                {
                    returnUrl1 = "Paginas/Home.aspx";
                }
                else
                {
                    returnUrl1 = Request.QueryString["ReturnUrl"];
                }

                Response.Redirect(returnUrl1);
            }
            else
            {
                e.Authenticated = false;
            }
        }
        catch (Exception ex)
        {
            ClientScript.RegisterStartupScript(this.GetType(), "alert", "<script>alert('" + ex.Message.ToString() + "');</script>");
        }
    }
    protected void imgSubmit_Click(object sender, EventArgs e)
    {
        OSAEObject obj = OSAEObjectManager.GetObjectByName(txtUserName.Text);
        if (obj != null)
        {
            string pass = obj.Property("Password").Value;
            if (pass == txtPassword.Text)
            {
                if (pass != "")
                {
                    // Success, create non-persistent authentication cookie.
                    FormsAuthentication.SetAuthCookie(txtUserName.Text.Trim(), false);
                    Int32 cto = Convert.ToInt32(OSAEObjectPropertyManager.GetObjectPropertyValue("Web Server", "Timeout").Value);
                    FormsAuthenticationTicket ticket1 = new FormsAuthenticationTicket(txtUserName.Text.Trim(), true, cto);
                    HttpCookie cookie1 = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(ticket1));
                    Response.Cookies.Add(cookie1);
                    Session["UserName"] = OSAEObjectManager.GetObjectByName(this.txtUserName.Text.Trim()).Name;
                    Session["TrustLevel"] = OSAEObjectPropertyManager.GetObjectPropertyValue(this.txtUserName.Text.Trim(), "Trust Level").Value;
                    Session["SecurityLevel"] = OSAEObjectPropertyManager.GetObjectPropertyValue(this.txtUserName.Text.Trim(), "Security Level").Value;
                }
                else
                {
                    FormsAuthentication.SetAuthCookie(txtUserName.Text.Trim(), false);
                    Int32 cto = Convert.ToInt32(OSAEObjectPropertyManager.GetObjectPropertyValue("Web Server", "Timeout").Value);
                    FormsAuthenticationTicket ticket1 = new FormsAuthenticationTicket(txtUserName.Text.Trim(), true, cto);
                    HttpCookie cookie1 = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(ticket1));
                    Response.Cookies.Add(cookie1);
                    Session["UserName"] = OSAEObjectManager.GetObjectByName(this.txtUserName.Text.Trim()).Name;
                    Session["TrustLevel"] = OSAEObjectPropertyManager.GetObjectPropertyValue(this.txtUserName.Text.Trim(), "Trust Level").Value;
                    Session["SecurityLevel"] = OSAEObjectPropertyManager.GetObjectPropertyValue(this.txtUserName.Text.Trim(), "Security Level").Value;
                }

                // Do the redirect.
                string returnUrl1;
                OSAEAdmin adSet = OSAEAdminManager.GetAdminSettings();
                int tLevel = Convert.ToInt32(Session["TrustLevel"].ToString());
                if (Session["SecurityLevel"].ToString() != "Admin" & tLevel < adSet.ObjectsTrust)
                    returnUrl1 = "screens.aspx?id=" + adSet.defaultScreen;
                else
                {
                    if (Request.QueryString["ReturnUrl"] == null) returnUrl1 = "objects.aspx";  // the login is successful
                    else returnUrl1 = Request.QueryString["ReturnUrl"];  //login not unsuccessful
                }
                Response.Redirect(returnUrl1);
            }
            else lblError.Visible = true;
        }
        lblError.Visible = true;
    }
Ejemplo n.º 22
0
    protected void log_me_in(object sender, EventArgs e)
    {
        try
        {
            string salt = BCrypt.Net.BCrypt.GenerateSalt();
            string hash = BCrypt.Net.BCrypt.HashPassword(pass.Value, salt);
            SqlConnection cn = new SqlConnection();
            cn.ConnectionString = ConfigurationManager.ConnectionStrings["login_connection_str"].ConnectionString;
            string query = string.Format("SELECT [hackers_choice].[tumi],[hackers_choice].[passwd],[sign_up].[firstname],[sign_up].[lastname] FROM [hackers_choice] INNER JOIN [sign_up] ON [hackers_choice].[tumi]=[sign_up].[username] WHERE [hackers_choice].[tumi]='{0}'", usrname.Value.Trim());
            SqlCommand mycommand = new SqlCommand(query, cn);
            cn.Open();
            SqlDataReader myreader = mycommand.ExecuteReader();
            if (myreader.HasRows)
            {
                myreader.Read();
                if (BCrypt.Net.BCrypt.Verify(pass.Value, string.Format("{0}", myreader[1])))
                {
                    log_in.Style["visibility"] = "hidden";
                    bool isPersistent = false;
                    string userData = "ApplicationSpecific data for this user.";
                    string u = BCrypt.Net.BCrypt.HashPassword("logged_in", salt);
                    string name = Convert.ToString(myreader[0]);
                    string fullname = Convert.ToString(myreader[2]) + " " + Convert.ToString(myreader[3]);
                    myreader.Close();
                    cn.Close();
                    Session["username"] = name;
                    Session["fullname"] = fullname;
                    Session["active"] = "active";
                    Session["handling"] = "true";
                    Session.Timeout = 60;
                    FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, name, DateTime.Now, DateTime.Now.AddHours(1), isPersistent, userData, FormsAuthentication.FormsCookiePath);
                    // Encrypt the ticket.
                    string encTicket = FormsAuthentication.Encrypt(ticket);

                    // Create the cookie.
                    Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, encTicket));
                    Server.Transfer("~/index.aspx?login=active");
                }
                else
                    login_invalid.InnerText = "Login username or password is invalid";
                cn.Close();
                myreader.Close();
            }
        }
        catch(Exception e1)
        {
            banner_msg.InnerText = "The server request is timed out";
        }
    }
Ejemplo n.º 23
0
 public static void RedirecionaPaginaInicial(int MinutosDuracaoSessao,
    HttpResponse Response, string ID)
 {
     FormsAuthentication.Initialize();
     FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
         1, ID,
         DateTime.Now,
         DateTime.Now.AddMinutes(MinutosDuracaoSessao),
         true,
         FormsAuthentication.FormsCookiePath);
     string hash = FormsAuthentication.Encrypt(ticket);
     HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hash);
     Response.Cookies.Add(cookie);
     Response.Redirect(PaginasAplicacao.GetPaginaInicial());
 }
Ejemplo n.º 24
0
    protected void Button1_Click(object sender, EventArgs e)
    {

        SqlCommand comm = new SqlCommand();
        try
        {
            string dbConnectionString = ConfigurationManager.ConnectionStrings["conn"].ConnectionString;

            comm.CommandText = "select * from tblLogin where emailid =@emailid and pwd=@pwd";
            comm.CommandType = CommandType.Text;

            comm.Connection = new SqlConnection(dbConnectionString);

            comm.Parameters.AddWithValue("@emailid", TextBox1.Text);
            comm.Parameters.AddWithValue("@pwd", TextBox2.Text);

            comm.Connection.Open();
            if (comm.Connection.State == ConnectionState.Open)
            {
                SqlDataReader dr = comm.ExecuteReader(CommandBehavior.SingleRow);
                if (dr.HasRows)
                {
                    dr.Read();
                    FormsAuthenticationTicket ticket = new
          FormsAuthenticationTicket(1, TextBox1.Text, DateTime.Now, DateTime.Now.AddMinutes(30),
          false, dr["roleName"].ToString(), FormsAuthentication.FormsCookiePath);

                    string hash = FormsAuthentication.Encrypt(ticket);
                    HttpCookie ht = new HttpCookie(FormsAuthentication.FormsCookieName);

                    Session["emailid"] = TextBox1.Text;
                    ht.Value = hash;
                    Response.Cookies.Add(ht);
                   // Response.Write("Ok");
                    Response.Redirect("frmcheckrole.aspx");
                }
                else
                    Response.Write("Invalid Details");

            }

        }
        catch (Exception)
        {
            
            throw;
        }
    }
Ejemplo n.º 25
0
        protected void btnLogin_Click(object sender, EventArgs e)
        {
            string username = txtUserName.Text.Trim();
            string password = Encryptor.EncryptText(txtPassword.Text.Trim());

            tbllogintable = adplogin_table.GetUserByUsernamePassword(username, password);

            if (tbllogintable.Count == 1)
            {
                var row = tbllogintable[0];   // read the only row

                // initialize FormsAuthentication
                FormsAuthentication.Initialize();

                // create a new ticket used for authentication
                FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
                    1,                                    // ticket version
                    username,                             // username associated with ticket
                    DateTime.Now,                         // date/time issued
                    DateTime.Now.AddMinutes(30),          // date/time to expire
                    chkRememberMe.Checked,                // "true" for a persistent user cookie
                    row.role,                             // user-data, in this case the roles
                    FormsAuthentication.FormsCookiePath); // path cookie is valid for

                // encrypt the ticket using the machine key for secure transport
                string hashedTicket = FormsAuthentication.Encrypt(ticket);

                // create cookie
                HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hashedTicket);

                // set the cookie's expiration time to the ticket's expiration time
                if (ticket.IsPersistent)
                {
                    cookie.Expires = ticket.Expiration;
                }

                // add the cookie to the list for outgoing response
                Response.Cookies.Add(cookie);

                // redirect to requested URL, or to the role's homepage
                string returnUrl = Request.QueryString["ReturnUrl"];

                if (returnUrl == null)
                {
                    if (row.role == "admin")
                    {
                        returnUrl = "~/Admin/";
                    }
                    else if (row.role == "member")
                    {
                        returnUrl = "~/Member/";
                    }
                    else if (row.role == "librarian")
                    {
                        returnUrl = "~/Librarian/";
                    }
                    else
                    {
                        returnUrl = "~/";
                    }
                }

                Session["Username"] = username;
                Session["Role"]     = row.role;

                Response.Redirect(returnUrl);
            }
            else
            {
                lblMessage.Text = "Login failed. Please try again.";
            }
        }
Ejemplo n.º 26
0
 private string SetFirstName(FormsAuthenticationTicket ticket)
 {
     string[] data = ticket.UserData.Split('|');
     return(data[2]);
 }
        protected void Page_Load(object sender, EventArgs e)
        {
            HttpContext.Current.Response.Cache.SetAllowResponseInBrowserHistory(false);
            HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
            HttpContext.Current.Response.Cache.SetNoStore();
            Response.Cache.SetExpires(DateTime.Now);
            Response.Cache.SetValidUntilExpires(true);
            Response.Cache.SetCacheability(System.Web.HttpCacheability.NoCache);
            Response.Cache.SetNoStore();

            if (Request.Cookies[FormsAuthentication.FormsCookieName] != null)
            {
                HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
                FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(authCookie.Value);

                if (ticket.Expiration <= DateTime.Now)
                {
                    Response.Redirect("~/PL/Membership/Login.aspx");

                }//end if

                else
                {
                    Session sessionObject = new Session();
                    FormsAuthenticationTicket newTicket = new FormsAuthenticationTicket(ticket.Version, ticket.Name, DateTime.Now, DateTime.Now.AddMinutes(sessionObject.getSessionTimeLimit()), ticket.IsPersistent, ticket.UserData);
                    string encryptedTicket = FormsAuthentication.Encrypt(newTicket);
                    HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
                    cookie.Expires = newTicket.Expiration;
                    Response.Cookies.Add(cookie);

                }//end else

            }//end if

            else
            {
                Response.Redirect("~/PL/Membership/Login.aspx");

            }//end else

            HttpCookie _authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
            FormsAuthenticationTicket _ticket = FormsAuthentication.Decrypt(_authCookie.Value);

            string username = _ticket.Name;

            bool recordExists;

            string errorMessage;

            Select selectObject = new Select();

            recordExists = Select.Select_Focus_Analysis_Worksheet(username);

            errorMessage = selectObject.getErrorMessage();

            if (errorMessage != null)
            {
                lblError.Text = errorMessage;
                lblError.Visible = true;

                ErrorMessage message = new ErrorMessage();

                MsgBox(message.SQLServerErrorMessage);

            }//end if

            else
            {
                if (recordExists == true)
                {
                        string errorMessage2;

                        ArrayList record = new ArrayList();

                        Select selectObject2 = new Select();

                        record = Select.Select_Focus_Analysis_Record(username);

                        errorMessage2 = selectObject2.getErrorMessage();

                        if (errorMessage2 != null)
                        {
                            lblError.Text = errorMessage2;
                            lblError.Visible = true;

                            ErrorMessage message = new ErrorMessage();

                            MsgBox(message.SQLServerErrorMessage);

                        }//end if

                        else
                        {
                            Label1.Text = record[188].ToString();
                            Label2.Text = record[189].ToString();
                            Label3.Text = record[190].ToString();
                            Label4.Text = record[191].ToString();
                            Label5.Text = record[192].ToString();
                            Label6.Text = record[193].ToString();

                        }//end else

                    }//end if

            }//end else

            bool recordExists2;

            string errorMessage3;

            Select selectObject3 = new Select();

            recordExists2 = Select.Select_Education_Inventory(username);

            errorMessage3 = selectObject3.getErrorMessage();

            if (errorMessage3 != null)
            {
                lblError.Text = errorMessage3;
                lblError.Visible = true;

                ErrorMessage message = new ErrorMessage();

                MsgBox(message.SQLServerErrorMessage);

            }//end if

            else
            {
                if (recordExists2 == true)
                {
                    string errorMessage4;

                    ArrayList record2 = new ArrayList();

                    Select selectObject4 = new Select();

                    record2 = Select.Select_Education_Inventory_Record(username);

                    errorMessage4 = selectObject4.getErrorMessage();

                    if (errorMessage4 != null)
                    {
                        lblError.Text = errorMessage4;
                        lblError.Visible = true;

                        ErrorMessage message = new ErrorMessage();

                        MsgBox(message.SQLServerErrorMessage);

                    }//end if

                    else
                    {
                        Label33.Text = record2[15].ToString();
                        Label34.Text = record2[16].ToString();
                        Label35.Text = record2[17].ToString();

                    }//end else

                }//end if

            }//end else

            bool recordExists3;

            string errorMessage5;

            Select selectObject5 = new Select();

            recordExists3 = Select.Select_Natural_Talents(username);

            errorMessage5 = selectObject5.getErrorMessage();

            if (errorMessage5 != null)
            {
                lblError.Text = errorMessage5;
                lblError.Visible = true;

                ErrorMessage message = new ErrorMessage();

                MsgBox(message.SQLServerErrorMessage);

            }//end if

            else
            {
                if (recordExists3 == true)
                {
                    string errorMessage6;

                    ArrayList record3 = new ArrayList();

                    Select selectObject6 = new Select();

                    record3 = Select.Select_Natural_Talents_Record(username);

                    errorMessage6 = selectObject6.getErrorMessage();

                    if (errorMessage6 != null)
                    {
                        lblError.Text = errorMessage6;
                        lblError.Visible = true;

                        ErrorMessage message = new ErrorMessage();

                        MsgBox(message.SQLServerErrorMessage);

                    }//end if

                    else
                    {
                        Label7.Text = record3[1].ToString();
                        Label8.Text = record3[2].ToString();
                        Label9.Text = record3[3].ToString();

                    }//end else

                }//end if

            }//end else

            bool recordExists4;

            string errorMessage7;

            Select selectObject7 = new Select();

            recordExists4 = Select.Select_Sharegiver_Talents(username);

            errorMessage7 = selectObject7.getErrorMessage();

            if (errorMessage7 != null)
            {
                lblError.Text = errorMessage7;
                lblError.Visible = true;

                ErrorMessage message = new ErrorMessage();

                MsgBox(message.SQLServerErrorMessage);

            }//end if

            else
            {
                if (recordExists4 == true)
                {
                    string errorMessage8;

                    ArrayList record4 = new ArrayList();

                    Select selectObject8 = new Select();

                    record4 = Select.Select_Sharegiver_Talents_Record(username);

                    errorMessage8 = selectObject8.getErrorMessage();

                    if (errorMessage8 != null)
                    {
                        lblError.Text = errorMessage8;
                        lblError.Visible = true;

                        ErrorMessage message = new ErrorMessage();

                        MsgBox(message.SQLServerErrorMessage);

                    }//end if

                    else
                    {
                        Label36.Text = record4[76].ToString();
                        Label37.Text = record4[77].ToString();
                        Label38.Text = record4[78].ToString();

                    }//end else

                }//end if

            }//end else

            bool recordExists5;

            string errorMessage9;

            Select selectObject9 = new Select();

            recordExists5 = Select.Select_Total_Spiritual_Gifts(username);

            errorMessage9 = selectObject9.getErrorMessage();

            if (errorMessage9 != null)
            {
                lblError.Text = errorMessage9;
                lblError.Visible = true;

                ErrorMessage message = new ErrorMessage();

                MsgBox(message.SQLServerErrorMessage);

            }//end if

            else
            {
                if (recordExists5 == true)
                {
                    string errorMessage10;

                    ArrayList record5 = new ArrayList();

                    Select selectObject10 = new Select();

                    record5 = Select.Select_Total_Spiritual_Gifts_Record(username);

                    errorMessage10 = selectObject10.getErrorMessage();

                    if (errorMessage10 != null)
                    {
                        lblError.Text = errorMessage10;
                        lblError.Visible = true;

                        ErrorMessage message = new ErrorMessage();

                        MsgBox(message.SQLServerErrorMessage);

                    }//end if

                    else
                    {
                        Label10.Text = record5[21].ToString();
                        Label11.Text = record5[24].ToString();
                        Label12.Text = record5[22].ToString();
                        Label13.Text = record5[25].ToString();
                        Label14.Text = record5[23].ToString();
                        Label15.Text = record5[26].ToString();

                    }//end else

                }//end if

            }//end else

            bool recordExists6;

            string errorMessage11;

            Select selectObject11 = new Select();

            recordExists6 = Select.Select_Personal_Management_Style(username);

            errorMessage11 = selectObject11.getErrorMessage();

            if (errorMessage11 != null)
            {
                lblError.Text = errorMessage11;
                lblError.Visible = true;

                ErrorMessage message = new ErrorMessage();

                MsgBox(message.SQLServerErrorMessage);

            }//end if

            else
            {
                if (recordExists6 == true)
                {
                    string errorMessage12;

                    ArrayList record6 = new ArrayList();

                    Select selectObject12 = new Select();

                    record6 = Select.Select_Personal_Management_Style_Record(username);

                    errorMessage12 = selectObject12.getErrorMessage();

                    if (errorMessage12 != null)
                    {
                        lblError.Text = errorMessage12;
                        lblError.Visible = true;

                        ErrorMessage message = new ErrorMessage();

                        MsgBox(message.SQLServerErrorMessage);

                    }//end if

                    else
                    {
                        Label16.Text = record6[38].ToString();
                        Label17.Text = record6[40].ToString();
                        Label18.Text = record6[41].ToString();
                        Label19.Text = record6[43].ToString();
                        Label20.Text = record6[44].ToString();
                        Label21.Text = record6[46].ToString();
                        Label22.Text = record6[47].ToString();
                        Label23.Text = record6[49].ToString();

                    }//end else

                }//end if

            }//end else

            bool recordExists7;

            string errorMessage13;

            Select selectObject13 = new Select();

            recordExists7 = Select.Select_Perception_Response_Summary(username);

            errorMessage13 = selectObject13.getErrorMessage();

            if (errorMessage13 != null)
            {
                lblError.Text = errorMessage13;
                lblError.Visible = true;

                ErrorMessage message = new ErrorMessage();

                MsgBox(message.SQLServerErrorMessage);

            }//end if

            else
            {
                if (recordExists7 == true)
                {
                    string errorMessage14;

                    ArrayList record7 = new ArrayList();

                    Select selectObject14 = new Select();

                    record7 = Select.Select_Perception_Response_Summary_Record(username);

                    errorMessage14 = selectObject14.getErrorMessage();

                    if (errorMessage14 != null)
                    {
                        lblError.Text = errorMessage14;
                        lblError.Visible = true;

                        ErrorMessage message = new ErrorMessage();

                        MsgBox(message.SQLServerErrorMessage);

                    }//end if

                    else
                    {
                        Label24.Text = record7[0].ToString();
                        Label25.Text = record7[1].ToString();
                        Label26.Text = record7[2].ToString();
                        Label27.Text = record7[3].ToString();
                        Label28.Text = record7[4].ToString();
                        Label29.Text = record7[5].ToString();

                    }//end else

                }//end if

            }//end else

            bool recordExists8;

            string errorMessage15;

            Select selectObject15 = new Select();

            recordExists8 = Select.Select_Fundamental_Life_Motivators(username);

            errorMessage15 = selectObject15.getErrorMessage();

            if (errorMessage15 != null)
            {
                lblError.Text = errorMessage15;
                lblError.Visible = true;

                ErrorMessage message = new ErrorMessage();

                MsgBox(message.SQLServerErrorMessage);

            }//end if

            else
            {
                if (recordExists8 == true)
                {
                    string errorMessage16;

                    ArrayList record8 = new ArrayList();

                    Select selectObject16 = new Select();

                    record8 = Select.Select_Fundamental_Life_Motivators_Record(username);

                    errorMessage16 = selectObject16.getErrorMessage();

                    if (errorMessage16 != null)
                    {
                        lblError.Text = errorMessage16;
                        lblError.Visible = true;

                        ErrorMessage message = new ErrorMessage();

                        MsgBox(message.SQLServerErrorMessage);

                    }//end if

                    else
                    {
                        Label30.Text = record8[0].ToString();
                        Label31.Text = record8[1].ToString();
                        Label32.Text = record8[2].ToString();

                    }//end else

                }//end if

            }//end else

            bool recordExists9;

            string errorMessage17;

            Select selectObject17 = new Select();

            recordExists9 = Select.Select_Expressing_Personal_Genius(username);

            errorMessage17 = selectObject17.getErrorMessage();

            if (errorMessage17 != null)
            {
                lblError.Text = errorMessage17;
                lblError.Visible = true;

                ErrorMessage message = new ErrorMessage();

                MsgBox(message.SQLServerErrorMessage);

            }//end if

            else
            {
                if (recordExists9 == true)
                {
                    string errorMessage18;

                    ArrayList record9 = new ArrayList();

                    Select selectObject18 = new Select();

                    record9 = Select.Select_Expressing_Personal_Genius_Record(username);

                    errorMessage18 = selectObject18.getErrorMessage();

                    if (errorMessage18 != null)
                    {
                        lblError.Text = errorMessage18;
                        lblError.Visible = true;

                        ErrorMessage message = new ErrorMessage();

                        MsgBox(message.SQLServerErrorMessage);

                    }//end if

                    else
                    {
                        Label39.Text = record9[0].ToString();
                        Label40.Text = record9[3].ToString();
                        Label41.Text = record9[1].ToString();
                        Label42.Text = record9[4].ToString();
                        Label43.Text = record9[2].ToString();
                        Label44.Text = record9[5].ToString();

                    }//end else

                }//end if

            }//end else

            bool recordExists10;

            string errorMessage19;

            Select selectObject19 = new Select();

            recordExists10 = Select.Select_Creativity_Cycle(username);

            errorMessage19 = selectObject19.getErrorMessage();

            if (errorMessage19 != null)
            {
                lblError.Text = errorMessage19;
                lblError.Visible = true;

                ErrorMessage message = new ErrorMessage();

                MsgBox(message.SQLServerErrorMessage);

            }//end if

            else
            {
                if (recordExists10 == true)
                {
                    string errorMessage20;

                    ArrayList record10 = new ArrayList();

                    Select selectObject20 = new Select();

                    record10 = Select.Select_Creativity_Cycle_Record(username);

                    errorMessage20 = selectObject20.getErrorMessage();

                    if (errorMessage20 != null)
                    {
                        lblError.Text = errorMessage20;
                        lblError.Visible = true;

                        ErrorMessage message = new ErrorMessage();

                        MsgBox(message.SQLServerErrorMessage);

                    }//end if

                    else
                    {
                        Label45.Text = record10[0].ToString();

                    }//end else

                }//end if

            }//end else

        }//end event
Ejemplo n.º 28
0
        public void SignIn(string username, string password, out int errorCode, out string errorMessage)
        {
            errorCode    = 0;
            errorMessage = null;
            if (string.IsNullOrEmpty(password))
            {
                errorMessage = "Please enter password";
            }
            if (string.IsNullOrEmpty(username))
            {
                errorMessage = "Please enter user name";
            }
            if (string.IsNullOrEmpty(errorMessage))
            {
                // Here must be validation with password. You can add third party validation here;
                bool success = Membership.ValidateUser(username, password);
                if (!success)
                {
                    errorMessage = string.Format("Validation failed. User name '{0}' was not found.", username);
                }
            }
            var values = new KeyValueList();

            if (!string.IsNullOrEmpty(errorMessage))
            {
                errorCode = 1;
                return;
            }
            FormsAuthentication.Initialize();
            var user = Membership.GetUser(username, true);

            if (user == null)
            {
                errorCode    = 1;
                errorMessage = string.Format("'{0}' was not found.", username);
                return;
            }
            var    roles       = Roles.GetRolesForUser(username);
            string rolesString = string.Empty;

            for (int i = 0; i < roles.Length; i++)
            {
                if (i > 0)
                {
                    rolesString += ",";
                }
                rolesString += roles[i];
            }
            var loginRememberMinutes = 30;
            var ticket = new FormsAuthenticationTicket(1, user.UserName, DateTime.Now, DateTime.Now.AddMinutes(loginRememberMinutes), true, rolesString, FormsAuthentication.FormsCookiePath);
            // Encrypt the cookie using the machine key for secure transport.
            var hash   = FormsAuthentication.Encrypt(ticket);
            var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hash); // Hashed ticket

            if (ticket.IsPersistent)
            {
                cookie.Expires = ticket.Expiration;
            }
            HttpContext.Current.Response.Cookies.Add(cookie);
            // Create Identity.
            var identity = new System.Security.Principal.GenericIdentity(user.UserName);
            // Create Principal.
            var principal = new RolePrincipal(identity);

            System.Threading.Thread.CurrentPrincipal = principal;
            // Create User.
            HttpContext.Current.User = new System.Security.Principal.GenericPrincipal(identity, roles);
            errorMessage             = "Welcome!";
        }
Ejemplo n.º 29
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!User.Identity.IsAuthenticated)
            {
                Response.Redirect("index.aspx");
            }

            else if (User.Identity.IsAuthenticated)
            {
                if (HttpContext.Current.User.Identity is FormsIdentity)
                {
                    string        rola;
                    FormsIdentity id =
                        (FormsIdentity)HttpContext.Current.User.Identity;
                    FormsAuthenticationTicket bilet = id.Ticket;
                    Label1.Text = "Zalogowany jako: " + User.Identity.Name;
                    // Get the stored user-data, in this case, our roles
                    rola = bilet.UserData;

                    NpgsqlConnection conn = new NpgsqlConnection("Server=127.0.0.1;Port=5432;User Id=postgres;Password=projekt;Database=projekt;");
                    conn.Open();

                    NpgsqlCommand command1 = new NpgsqlCommand("select * from sala", conn);
                    NpgsqlCommand command2 = new NpgsqlCommand("select * from wyposazenie", conn);
                    try
                    {
                        if (DropDownList1.Items.Count == 0 && DropDownList2.Items.Count == 0)
                        {
                            NpgsqlCommand    count  = new NpgsqlCommand("select count(id_wyp) from wyposazenie", conn);
                            string           liczba = count.ExecuteScalar().ToString();
                            int              coun   = System.Int32.Parse(liczba);
                            string[]         tab1   = new string[50];
                            NpgsqlDataReader dr1    = command1.ExecuteReader();
                            int              i      = 0;
                            {
                                while (dr1.Read())
                                {
                                    tab1[i] = Convert.ToString(dr1[0]);
                                    DropDownList1.Items.Insert(i, tab1[i]);
                                    i++;
                                }
                            }
                            NpgsqlDataReader dr2  = command2.ExecuteReader();
                            string[]         tab2 = new string[500];
                            int j = 0;
                            {
                                while (dr2.Read())
                                {
                                    tab2[j] = Convert.ToString(dr2[0]);
                                    DropDownList2.Items.Insert(j, tab2[j]);
                                    j++;
                                }
                            }
                        }
                    }
                    finally
                    {
                        conn.Close();
                    }


                    if (rola != "admins")
                    {
                        Response.Redirect("index.aspx");
                    }
                }
            }
        }
Ejemplo n.º 30
0
        public ActionResult Login(VLogin login, string ReturnUrl = "")
        {
            string message = "";

            using (PhotoGraphyDbContext dc = new PhotoGraphyDbContext())
            {
                var v = dc.Clients.Where(a => a.Email == login.EmailID).FirstOrDefault();
                var p = dc.PhotoGraphers.Where(x => x.Email == login.EmailID).FirstOrDefault();
                if (v != null)
                {
                    if (string.Compare(login.Password, v.Password) == 0)
                    {
                        int    timeout   = login.RememberMe ? 2 : 3;
                        var    ticket    = new FormsAuthenticationTicket(login.EmailID, login.RememberMe, timeout);
                        string encrypted = FormsAuthentication.Encrypt(ticket);
                        var    cookie    = new HttpCookie(FormsAuthentication.FormsCookieName, encrypted);
                        cookie.Expires  = DateTime.Now.AddMinutes(timeout);
                        cookie.HttpOnly = true;
                        Response.Cookies.Add(cookie);



                        if (Url.IsLocalUrl(ReturnUrl))
                        {
                            return(Redirect(ReturnUrl));
                        }
                        else
                        {
                            Session["useremail"] = v.ClientId;
                            Session["FullName"]  = v.Name;


                            return(RedirectToAction("Index", "Client"));
                            //  Response.Write("<script>alert('Welcome to User')</script>");
                        }
                    }
                    else
                    {
                        message = "Invalid Email Or Password";
                    }
                }

                else if (p != null)
                {
                    if (string.Compare(login.Password, p.Password) == 0)
                    {
                        int    timeout   = login.RememberMe ? 2 : 5;
                        var    ticket    = new FormsAuthenticationTicket(login.EmailID, login.RememberMe, timeout);
                        string encrypted = FormsAuthentication.Encrypt(ticket);
                        var    cookie    = new HttpCookie(FormsAuthentication.FormsCookieName, encrypted);
                        cookie.Expires  = DateTime.Now.AddMinutes(timeout);
                        cookie.HttpOnly = true;
                        Response.Cookies.Add(cookie);



                        if (Url.IsLocalUrl(ReturnUrl))
                        {
                            return(Redirect(ReturnUrl));
                        }
                        else
                        {
                            Session["useremail"] = p.PhotoGrapherId;
                            Session["FullName"]  = p.FullName;

                            return(RedirectToAction("Index", "PhotoGrapher"));
                            //  Response.Write("<script>alert('Welcome to User')</script>");
                        }
                    }
                    else
                    {
                        message = "Invalid Email Or Password";
                    }
                }



                else
                {
                    message = "Invalid UserName Or Password";
                }
            }
            ViewBag.Message = message;
            return(View());
        }
Ejemplo n.º 31
0
        protected void Page_Load(object sender, EventArgs e)
        {
            IncludeJs("LoginEncrytDecryt", "/Modules/Admin/LoginControl/js/AESEncrytDecryt.js");
            IncludeJs("loginanimation", "/Modules/Admin/LoginControl/js/login.js");
            //            IncludeCss("loginCss", "/Modules/Admin/LoginControl/css/module.css");
            IncludeLanguageJS();
            Extension = SageFrameSettingKeys.PageExtension;
            if (!IsPostBack)
            {
                int logHit = Convert.ToInt32(Session[SessionKeys.LoginHitCount]);
                if (logHit >= 3)
                {
                    dvCaptchaField.Visible = true;
                    InitializeCaptcha();
                    objCaptcha.GenerateCaptcha();
                }
                else
                {
                    dvCaptchaField.Visible = false;
                }


                Password.Attributes.Add("onkeypress", "return clickButton(event,'" + LoginButton.ClientID + "')");
                if (!IsParent)
                {
                    hypForgotPassword.NavigateUrl =
                        GetParentURL + "/portal/" + GetPortalSEOName + "/" +
                        pagebase.GetSettingValueByIndividualKey(SageFrameSettingKeys.PortalForgotPassword) + Extension;
                }
                else
                {
                    hypForgotPassword.NavigateUrl =
                        GetParentURL + "/" + pagebase.GetSettingValueByIndividualKey(SageFrameSettingKeys.PortalForgotPassword) +
                        Extension;
                }
                string registerUrl =
                    GetParentURL + "/" + pagebase.GetSettingValueByIndividualKey(SageFrameSettingKeys.PortalUserRegistration) +
                    Extension;

                if (pagebase.GetSettingBoolValueByIndividualKey(SageFrameSettingKeys.RememberCheckbox))
                {
                    chkRememberMe.Visible = true;
                    lblrmnt.Visible       = true;
                }
                else
                {
                    chkRememberMe.Visible = false;
                    lblrmnt.Visible       = false;
                }
            }
            SecurityPolicy            objSecurity = new SecurityPolicy();
            FormsAuthenticationTicket ticket      = objSecurity.GetUserTicket(GetPortalID);

            if (ticket != null && ticket.Name != ApplicationKeys.anonymousUser)
            {
                int      LoggedInPortalID = int.Parse(ticket.UserData.ToString());
                string[] sysRoles         = SystemSetting.SUPER_ROLE;
                if (GetPortalID == LoggedInPortalID || Roles.IsUserInRole(ticket.Name, sysRoles[0]))
                {
                    RoleController _role       = new RoleController();
                    string         userinroles = _role.GetRoleNames(GetUsername, LoggedInPortalID);
                    if (userinroles != "" || userinroles != null)
                    {
                        MultiView1.ActiveViewIndex = 1;
                    }
                    else
                    {
                        MultiView1.ActiveViewIndex = 0;
                    }
                }
                else
                {
                    MultiView1.ActiveViewIndex = 0;
                }
            }
            else
            {
                MultiView1.ActiveViewIndex = 0;
            }
            // Added For openID services
            divOpenIDProvider.Visible = false;
            if (AllowRegistration())
            {
                if (pagebase.GetSettingBoolValueByIndividualKey(SageFrameSettingKeys.ShowOpenID) == true)
                {
                    divOpenIDProvider.Visible = true;
                    CheckOpenID();
                }
            }
        }
Ejemplo n.º 32
0
        public ActionResult Login(LoginViewModel model, string returnUrl)
        {
            try
            {
                string decodedUrl = "";
                if (!string.IsNullOrEmpty(returnUrl))
                {
                    decodedUrl = Server.UrlDecode(returnUrl);
                }

                if (!ModelState.IsValid)
                {
                    return(View(model));
                }
                var getPwdState = repository.Verify(model.Email, model.Password);//customRepository.CheckPassword(model.Password, model.Email);
                if (getPwdState)
                {
                    var getHashedPwd = repository.SelectPasswordOnSuccessfulPasswordValidation(model.Email);

                    var user = new CustomLoginViewModel()
                    {
                        EmailAddress = model.Email, Password = getHashedPwd
                    };
                    user = repository.GetUserLoginDetails(user);

                    if (user != null)
                    {
                        FormsAuthentication.SetAuthCookie(model.Email, false);

                        var    authTicket      = new FormsAuthenticationTicket(1, user.EmailAddress, DateTime.Now, DateTime.Now.AddMinutes(20), false, user.Roles);
                        string encryptedTicket = FormsAuthentication.Encrypt(authTicket);
                        var    authCookie      = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
                        HttpContext.Response.Cookies.Add(authCookie);


                        if (Url.IsLocalUrl(decodedUrl))
                        {
                            return(Redirect(decodedUrl));
                        }
                        else
                        {
                            // Successful login by admin/event user
                            return(RedirectToAction("dashboard", "admin"));
                        }
                    }

                    else
                    {
                        ViewBag.DisplayMessage = "Info";
                        ModelState.AddModelError("", "Invalid username or password.");
                        return(View(model));
                    }
                }
                else
                {
                    ViewBag.DisplayMessage = "Info";
                    ModelState.AddModelError("", "Invalid username or password.");
                    return(View(model));
                }
            }
            catch (Exception ex)
            {
                ViewBag.DisplayMessage = "Info";
                ModelState.AddModelError("", "Invalid username or password.");
                return(View(model));
            }
        }
Ejemplo n.º 33
0
        public async Task <ActionResult> vendorLogin(vendorViewLogin vvl)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return(View(vvl));
                }

                AdminLogin admin = new AdminLogin();
                admin = db.adminlog.Where(x => x.EmailAddress == vvl.VendorEmail && (x.Passkey == vvl.VendorPassword)).FirstOrDefault();
                if (admin != null)
                {
                    //Session["superid"] = vvl.VendorEmail;
                    //Session["EmailId"] = vvl.VendorEmail;
                    //ViewBag.messg = vvl.VendorEmail;
                    FormsAuthentication.SetAuthCookie(vvl.VendorEmail, false);
                    string Roles           = "admin";
                    var    authTicket      = new FormsAuthenticationTicket(1, admin.EmailAddress, DateTime.Now, DateTime.Now.AddMinutes(30), false, Roles);
                    string encryptedTicket = FormsAuthentication.Encrypt(authTicket);
                    var    authCookie      = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
                    HttpContext.Response.Cookies.Add(authCookie);
                    return(RedirectToAction("AdminPortal", "SuperAdmin"));
                }
                else
                {
                    string      q      = vvl.VendorPassword;
                    string      pass   = Encrypt_Password(q);
                    VendorModel vendor = new VendorModel();
                    vendor = db.vendor.Where(m => m.VendorEmail == vvl.VendorEmail && (m.VendorPassword == pass)).FirstOrDefault();
                    if (vendor != null)
                    {
                        var id  = db.vendor.Where(m => m.VendorEmail == vvl.VendorEmail).Select(m => m.VendorId).FirstOrDefault();
                        int vid = Convert.ToInt32(id);
                        //Session["Adminid"] = vid;
                        //Session["EmailId"] = vvl.VendorEmail;
                        VendorLogInOutTime vliot = new VendorLogInOutTime();
                        vliot.LogInTime  = DateTime.Now;
                        vliot.VendorId   = vid;
                        vliot.LogOutTime = null;
                        db.loginouttime.Add(vliot);
                        var a = db.vendor.Where(m => m.VendorEmail == vvl.VendorEmail).FirstOrDefault();
                        a.DataCompleted = true;
                        var b = db.businessdetails.Where(x => x.VendorId == id).FirstOrDefault();
                        b.DataCompleted = true;
                        db.SaveChanges();

                        string Roles = db.userrole.Where(x => x.VendorId == vid).Select(x => x.RoleName).FirstOrDefault();
                        FormsAuthentication.SetAuthCookie(vvl.VendorEmail, false);
                        var    authTicket      = new FormsAuthenticationTicket(1, vendor.VendorEmail, DateTime.Now, DateTime.Now.AddMinutes(20), false, Roles);
                        string encryptedTicket = FormsAuthentication.Encrypt(authTicket);
                        var    authCookie      = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
                        HttpContext.Response.Cookies.Add(authCookie);
                        return(RedirectToAction("Index", "VendorAccess"));
                    }
                    else
                    {
                        ViewBag.errorvalue = "Please enter valid Login Id and Password.";
                        return(View());
                    }
                }
            }
            catch (Exception e)
            {
                Response.Write("<script>alert('Please enter emailId and password')</script>");
                return(View());
            }
        }
Ejemplo n.º 34
0
        protected void SucessFullLogin(UserInfo user)
        {
            RoleController role = new RoleController();

            Session[SessionKeys.LoginHitCount] = null;
            string userRoles = role.GetRoleIDs(user.UserName, GetPortalID);

            if (userRoles.Length > 0)
            {
                SetUserRoles(userRoles);
                MembershipController member = new MembershipController();
                user.LastLoginDate = DateTime.UtcNow;
                member.UpdateUserLoginActivity(user);
                //SessionTracker sessionTracker = (SessionTracker)Session[SessionKeys.Tracker];
                //sessionTracker.PortalID = GetPortalID.ToString();
                //sessionTracker.Username = UserName.Text;
                //Session[SessionKeys.Tracker] = sessionTracker;
                SageFrame.Web.SessionLog SLog = new SageFrame.Web.SessionLog();
                SLog.SessionTrackerUpdateUsername(UserName.Text, GetPortalID.ToString());
                StringBuilder             redirectURL = new StringBuilder();
                SecurityPolicy            objSecurity = new SecurityPolicy();
                FormsAuthenticationTicket ticket      = new FormsAuthenticationTicket(1,
                                                                                      user.UserName,
                                                                                      DateTime.Now,
                                                                                      DateTime.Now.AddMinutes(30),
                                                                                      true,
                                                                                      GetPortalID.ToString(),
                                                                                      FormsAuthentication.FormsCookiePath);

                // Encrypt the ticket.
                string encTicket = FormsAuthentication.Encrypt(ticket);
                //generate random cookieValue
                string randomCookieValue = GenerateRandomCookieValue();
                Session[SessionKeys.RandomCookieValue] = randomCookieValue;
                //create new cookie with random cookie name and encrypted ticket
                HttpCookie cookie = new HttpCookie(objSecurity.FormsCookieName(GetPortalID), encTicket);
                //get default time from  setting
                SageFrameConfig objConfig = new SageFrameConfig();
                string          ServerCookieExpiration = objConfig.GetSettingValueByIndividualKey(SageFrameSettingKeys.ServerCookieExpiration);
                int             expiryTime             = Math.Abs(int.Parse(ServerCookieExpiration));
                expiryTime = expiryTime < 5 ? 5 : expiryTime;
                //set cookie expiry time
                cookie.Expires = DateTime.Now.AddMinutes(expiryTime);
                //add cookie to the browser
                Response.Cookies.Add(cookie);

                string roleRedirectURL = string.Empty;
                roleRedirectURL = member.GetRedirectUrlByRoleID(strRoles);
                if (roleRedirectURL == string.Empty || roleRedirectURL == null)
                {
                    roleRedirectURL = PortalAPI.DefaultPageWithExtension;
                }
                if (Request.QueryString["ReturnUrl"] != null)
                {
                    string PageNotFoundPage          = PortalAPI.PageNotFoundURLWithRoot;
                    string UserRegistrationPage      = PortalAPI.RegistrationURLWithRoot;
                    string PasswordRecoveryPage      = PortalAPI.PasswordRecoveryURLWithRoot;
                    string ForgotPasswordPage        = PortalAPI.ForgotPasswordURL;
                    string PageNotAccessiblePage     = PortalAPI.PageNotAccessibleURLWithRoot;
                    string ReturnUrlPage             = Request.QueryString["ReturnUrl"].Replace("%2f", "-").ToString();
                    bool   IsWellFormedReturnUrlPage = Uri.IsWellFormedUriString(ReturnUrlPage, UriKind.Absolute);
                    string RequestURL        = Request.Url.ToString();
                    Uri    RequestURLPageUri = new Uri(RequestURL);
                    string portalHostURL     = RequestURLPageUri.AbsolutePath.TrimStart('/');
                    if (IsWellFormedReturnUrlPage)
                    {
                        Uri    ReturnUrlPageUri = new Uri(ReturnUrlPage);
                        string ReturnURl        = ReturnUrlPageUri.Scheme + Uri.SchemeDelimiter + ReturnUrlPageUri.Host + ":" + ReturnUrlPageUri.Port;
                        string HostUrl          = GetHostURL();
                        Uri    uriHostURL       = new Uri(HostUrl);
                        Uri    uriReturnURL     = new Uri(ReturnURl);
                        var    resultCompareURL = Uri.Compare(uriHostURL, uriReturnURL,
                                                              UriComponents.Host | UriComponents.PathAndQuery,
                                                              UriFormat.SafeUnescaped, StringComparison.OrdinalIgnoreCase);
                        int resultComparePortalURL = 0;
                        if (portalHostURL.ToLower().Contains("portal") && resultCompareURL == 0)
                        {
                            Uri      ReturnUrlPageHostUri     = new Uri(ReturnUrlPage);
                            string   portalReturnURL          = ReturnUrlPageHostUri.AbsolutePath.TrimStart('/');
                            string[] portalReturnURLSplit     = portalReturnURL.Split('/');
                            string   ReturnURLSplitPortal     = portalReturnURLSplit[0];
                            string   ReturnURLSplitPortalName = portalReturnURLSplit[1];
                            string   ReturnURLWithPortal      = ReturnURLSplitPortal + "/" + ReturnURLSplitPortalName;

                            string[] portalHostURLSplit     = portalHostURL.Split('/');
                            string   HostURLSplitPortal     = portalHostURLSplit[0];
                            string   HostURLSplitPortalName = portalHostURLSplit[1];
                            string   HostURLWithPortal      = HostURLSplitPortal + "/" + HostURLSplitPortalName;
                            resultComparePortalURL = string.Compare(ReturnURLWithPortal, HostURLWithPortal);
                        }
                        if (resultCompareURL != 0 || resultComparePortalURL != 0)
                        {
                            PageNotFoundURL();
                        }
                    }
                    else
                    {
                        PageNotFoundURL();
                    }

                    if (ReturnUrlPage == PageNotFoundPage || ReturnUrlPage == UserRegistrationPage || ReturnUrlPage == PasswordRecoveryPage || ReturnUrlPage == ForgotPasswordPage || ReturnUrlPage == PageNotAccessiblePage)
                    {
                        redirectURL.Append(GetParentURL);
                        redirectURL.Append(PortalAPI.DefaultPageWithExtension);
                    }
                    else
                    {
                        redirectURL.Append(ResolveUrl(Request.QueryString["ReturnUrl"].ToString()));
                    }
                }
                else
                {
                    if (!IsParent)
                    {
                        redirectURL.Append(GetParentURL);
                        redirectURL.Append("/portal/");
                        redirectURL.Append(GetPortalSEOName);
                        redirectURL.Append("/");
                        redirectURL.Append(roleRedirectURL);
                    }
                    else
                    {
                        redirectURL.Append(GetParentURL);
                        redirectURL.Append("/");
                        redirectURL.Append(roleRedirectURL);
                    }
                }
                HttpContext.Current.Session[SessionKeys.IsLoginClick] = true;
                if (Session[SessionKeys.LoginHitCount] != null)
                {
                    HttpContext.Current.Session.Remove(SessionKeys.LoginHitCount);
                }
                Response.Redirect(redirectURL.ToString(), false);
            }
            else
            {
                FailureText.Text = string.Format("<p class='sfError'>{0}</p>", GetSageMessage("UserLogin", "Youarenotauthenticatedtothisportal"));//"You are not authenticated to this portal!";
            }
        }
Ejemplo n.º 35
0
        public async Task <ActionResult> Index(string username, string password)
        {
            if (!CheckIpControl())
            {
                return(Redirect("http://www.baidu.com"));
            }
            string          notice       = string.Empty;
            AdminLoginModel model        = new AdminLoginModel();
            bool            loginSuccess = false;
            string          path         = HttpContext.Server.MapPath("/App_Data/adminconfig.xml");
            XmlDocument     config       = new XmlDocument();

            config.Load(path);
            password = SecurityHelper.MD5(password);
            string SuperUser = config.SelectSingleNode("root/SuperUser").InnerText;

            if (username.Equals(SuperUser))
            {
                string SuperUserPassword = config.SelectSingleNode("root/SuperUserPassword").InnerText;
                if (SuperUserPassword.Equals(password))
                {
                    model.Id          = -1;
                    model.UserName    = SuperUser;
                    model.Password    = SuperUserPassword;
                    model.OpratePwd   = SuperUserPassword;
                    model.IsSuperUser = true;
                    config.SelectSingleNode("root/LastLoginTime").InnerText    = config.SelectSingleNode("root/CurrentLoginTime").InnerText;
                    config.SelectSingleNode("root/CurrentLoginTime").InnerText = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                    config.Save(path);
                    loginSuccess = true;
                }
                else
                {
                    return(new JavaScriptResult()
                    {
                        Script = "show_message('用户名或密码错误!')"
                    });
                }
            }
            else
            {
                var user = _repositoryFactory.ISystemUser.Single(m => m.UserName == username && m.Password == password && m.Status == (int)EnumHepler.UserStatus.Available);
                if (user != null)
                {
                    model.Id              = user.Id;
                    model.UserName        = username;
                    model.Password        = password;
                    model.OpratePwd       = SecurityHelper.MD5(user.OpratePwd);
                    model.IsSuperUser     = false;
                    model.RoleString      = user.RoleList;
                    user.LastLoginTime    = user.CurrentLoginTime;
                    user.CurrentLoginTime = DateTime.Now;
                    _repositoryFactory.ISystemUser.Modify(user, "LastLoginTime", "CurrentLoginTime");
                    loginSuccess = true;
                }
                else
                {
                    return(new JavaScriptResult()
                    {
                        Script = "show_message('用户名或密码错误!')"
                    });
                }
            }
            if (loginSuccess)
            {
                //写登录日志
                string loginLog = $"登录账号:{model.UserName},登录IP:{CommonTools.GetIpAddress()}";
                _repositoryFactory.ISysLog.Add(new Entity.SysLog()
                {
                    CreateTime = DateTime.Now, Type = (int)EnumHepler.LogType.Login, Remark = loginLog
                });
                await _repositoryFactory.SaveChanges();

                //序列化admin对象
                string accountJson = JsonConvert.SerializeObject(model);
                //创建用户票据
                var ticket = new FormsAuthenticationTicket(1, model.UserName, DateTime.Now, DateTime.Now.AddDays(1), false, accountJson);
                //加密
                string encryptAccount = FormsAuthentication.Encrypt(ticket);
                //创建cookie
                var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptAccount)
                {
                    HttpOnly = true,
                    Secure   = FormsAuthentication.RequireSSL,
                    Domain   = FormsAuthentication.CookieDomain,
                    Path     = FormsAuthentication.FormsCookiePath
                };
                cookie.Expires = DateTime.Now.AddDays(1);
                //写入Cookie
                Response.Cookies.Remove(cookie.Name);
                Response.Cookies.Add(cookie);
                return(new JavaScriptResult()
                {
                    Script = "login_status=true;location.href='" + Url.Action("Index", "Console") + "'"
                });
            }
            else
            {
                return(new JavaScriptResult()
                {
                    Script = "show_message('登录失败!')"
                });
            }
        }
Ejemplo n.º 36
0
        public ActionResult LoginFormAD(string userNum, string pwd, string returnUrl)
        {
            //判断员工编号是否为系统用户、判断用户是否删除
            var userInfo = db.UserInfo.Where(w => w.UserNum == userNum & w.UserState == 0).FirstOrDefault();

            if (userInfo == null)
            {
                ModelState.AddModelError("", "您还不是此系统用户,如有疑问请联系管理员,电话5615713!");
                return(View());
            }
            //将用户的全部信息存入session,便于在其他页面调用
            System.Web.HttpContext.Current.Session["user"] = userInfo;

            //通过考勤数据库验证员工编号、考勤密码
            var result = "yes";

            //result = CheckAD(userNum, pwd);//系统测试时,注释。正式运行时,取消注释。

            if (result == "yes")
            {
                #region 加载、设置用户权限
                var userRoles = from u in db.UserRole
                                join r in db.RoleAuthority on u.RoleID equals r.RoleID
                                join a in db.AuthorityInfo on r.AuthorityID equals a.AuthorityID
                                where u.UserID == userInfo.UserID
                                select a.AuthorityName;

                var roles = userRoles.Distinct().ToArray();
                var userAuthorityString = "";
                foreach (var item in roles)
                {
                    userAuthorityString += item + ",";
                }
                userAuthorityString = userAuthorityString.Substring(0, userAuthorityString.Length - 1);

                //写入用户角色
                FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1,
                                                                                     userNum,
                                                                                     DateTime.Now,
                                                                                     DateTime.Now.AddMinutes(2),
                                                                                     false,
                                                                                     userAuthorityString);

                string     encryptedTicket = FormsAuthentication.Encrypt(authTicket);
                HttpCookie authCookie      = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
                System.Web.HttpContext.Current.Response.Cookies.Add(authCookie);
                #endregion

                #region 设置用户姓名的cookie
                var cUserName = System.Web.HttpContext.Current.Server.UrlEncode(userInfo.UserName);
                System.Web.HttpCookie userNameCookie = new System.Web.HttpCookie("cUserName", cUserName);
                System.Web.HttpContext.Current.Response.Cookies.Add(userNameCookie);
                #endregion

                return(Redirect(returnUrl ?? Url.Action("Index", "Home")));
            }
            else
            {
                ModelState.AddModelError("", "用户名或密码错误!");
                return(View());
            }
        }
Ejemplo n.º 37
0
 private Guid SetId(FormsAuthenticationTicket ticket)
 {
     string[] data = ticket.UserData.Split('|');
     return(new Guid(data[4]));
 }
Ejemplo n.º 38
0
        protected void btnLogin_Click(object sender, EventArgs e)
        {
            //  Response.Redirect("Index.aspx");

            var     hash = FormsAuthentication.HashPasswordForStoringInConfigFile(txtPass.Value + "~!@", "MD5");
            DataSet ds   = TaxiDAL.UsersClass.GetList(null, txtUserName.Value, hash, null, null, null, null, null, null, null, null, null);


            if (ds.Tables[0].Rows.Count != 0)
            {
                //
                //  DError.Visible = true;
                DataRow dr = ds.Tables[0].Rows[0];
                Session["UserID"]       = dr["userID"].ToString();
                Session["FullNameUser"] = dr["FullNameUser"].ToString();
                Session["Region"]       = dr["Region"].ToString();
                String userid = dr["UserID"].ToString();
                Session["semat"] = dr["semat"].ToString();
                string role;

                if (dr["semat"].ToString() == "7" || dr["semat"].ToString() == "3")
                {
                    Session["role"] = "admin";
                    role            = "admin";
                }
                else if (dr["semat"].ToString() == "8" || dr["semat"].ToString() == "9" || dr["semat"].ToString() == "10" ||
                         dr["semat"].ToString() == "14" || dr["semat"].ToString() == "15" ||
                         dr["semat"].ToString() == "17" || dr["semat"].ToString() == "18")
                {
                    Session["role"]   = "cityzenrol";
                    role              = "cityzenrol";
                    Session["roleid"] = "1";
                }
                else if (dr["semat"].ToString() == "2" || dr["semat"].ToString() == "6" || dr["semat"].ToString() == "1" ||
                         dr["semat"].ToString() == "13" || dr["semat"].ToString() == "4" ||
                         dr["semat"].ToString() == "16" || dr["semat"].ToString() == "19"
                         )
                {
                    Session["sematID"] = dr["semat"].ToString();
                    Session["role"]    = "bazras";
                    role = "bazras";
                }
                else
                {
                    CSharp.Utility.ShowMsg(Page, CSharp.ProPertyData.MsgType.warning, "کاربر گرامی شما برای ورود به سیستم دسترسی ندارید");
                    return;
                }
                if (dr["semat"].ToString() == "8")// نقش مدیر فضای سبز
                {
                    Session["roleid"] = "1";
                }
                else if (dr["semat"].ToString() == "9" || dr["semat"].ToString() == "4") //نقش مسئول فضای سبز
                {
                    Session["roleid"] = "2";
                }
                else if (dr["semat"].ToString() == "10")// نقش کارشناس فضای سبز
                {
                    Session["roleid"] = "3";
                }
                Session["roleid"] = "3";


                HttpContext.Current.User = new GenericPrincipal(User.Identity, new string[] { role });
                FormsAuthentication.Initialize();
                FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, userid, DateTime.Now, DateTime.Now.AddMinutes(540), false, role, FormsAuthentication.FormsCookiePath);
                hash = FormsAuthentication.Encrypt(ticket);
                HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hash);
                if (ticket.IsPersistent == true)
                {
                    cookie.Expires = ticket.Expiration;
                }

                Response.Cookies.Add(cookie);
                // Roles.AddUserToRole(userid, role);

                // Roles.AddUserToRole(dr["UserName"].ToString(),"admin");

                if (role == "admin")
                {
                    Response.Redirect("Dashboard.aspx");
                }
                else if (
                    dr["semat"].ToString() == "8" || dr["semat"].ToString() == "9" || dr["semat"].ToString() == "10" ||
                    dr["semat"].ToString() == "14" || dr["semat"].ToString() == "15" ||
                    dr["semat"].ToString() == "17" || dr["semat"].ToString() == "18")
                {
                    Response.Redirect("~/CityZen/Dashboard.aspx?Mode=" + Session["roleid"], false);
                }
                else
                {
                    Response.Redirect("~/Bazras/AllPeyman.aspx");
                }
            }
            else

            {
                lblUserPassError.Text = "نام کاربری یا کلمه عبور اشتباه میباشد";
                //CSharp.Utility.ShowMsg(Page, CSharp.ProPertyData.MsgType.warning, "نام کاربری یا کلمه عبور اشتباه میباشد");
                return;
            }
        }
Ejemplo n.º 39
0
        public async Task <ActionResult> Login(LoginModel model, string returnUrl)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    using (GuptaAgroDbContext db = new GuptaAgroDbContext())
                    {
                        ViewBag.Roles = db.tbl_roles.Select(r => r).ToList();
                    }
                    return(View(model));
                }
                using (GuptaAgroDbContext db = new GuptaAgroDbContext())
                {
                    var user = db.tbl_employee.Where(e => (e.userid == model.UserName && e.password == model.Password) || (e.ContactNo == model.UserName && e.password == model.Password)).Select(e => e).FirstOrDefault();

                    if (user != null)
                    {
                        FormsAuthentication.SetAuthCookie(model.UserName, false);

                        var    authTicket      = new FormsAuthenticationTicket(1, user.EmployeeName, DateTime.Now, DateTime.Now.AddMinutes(30), false, user.Role);
                        string encryptedTicket = FormsAuthentication.Encrypt(authTicket);
                        var    authCookie      = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
                        HttpContext.Response.Cookies.Add(authCookie);
                        Session["role"] = user.Role;
                        Session["ID"]   = user.EmployeeID;
                        Session.Timeout = 30;
                        if (user.Role == "Admin")
                        {
                            return(RedirectToAction("BeneficiaryDetails", "Home"));
                        }
                        else if (user.Role == "Field Assitant")
                        {
                            return(RedirectToAction("OandMSheet", "Home"));
                        }
                        else if (user.Role == "Manager")
                        {
                            return(RedirectToAction("ComplaintForm", "Home"));
                        }
                        else if (user.Role == "Inventory Admin")
                        {
                            return(RedirectToAction("StockDistribution", "Home"));
                        }
                        else
                        {
                            throw new Exception();
                        }
                    }

                    else
                    {
                        ViewBag.Roles = db.tbl_roles.Select(r => r).ToList();

                        ModelState.AddModelError("", "Invalid login attempt.");
                        return(View(model));
                    }
                }
            }
            catch (Exception ex)
            {
                return(View("Error"));
            }
            //// This doesn't count login failures towards account lockout
            //// To enable password failures to trigger account lockout, change to shouldLockout: true
            //var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false);
            //switch (result)
            //{
            //    case SignInStatus.Success:
            //        return RedirectToLocal(returnUrl);
            //    case SignInStatus.LockedOut:
            //        return View("Lockout");
            //    case SignInStatus.RequiresVerification:
            //        return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
            //    case SignInStatus.Failure:
            //    default:
            //        ModelState.AddModelError("", "Invalid login attempt.");
            //        return View(model);
            //}
        }
Ejemplo n.º 40
0
        protected void btnCommit_Click(object sender, EventArgs e)
        {
            string userName = tbName.Text.Trim();
            string psw      = tbPsw.Text.Trim();

            //string sVc = tbVc.Text.Trim();

            if (string.IsNullOrEmpty(userName) || string.IsNullOrEmpty(psw))
            {
                WebHelper.MessageBox.Messager(this.Page, btnCommit, "用户名或密码输入不能为空!", "操作错误", "error");
                return;
            }

            //if (string.IsNullOrEmpty(sVc))
            //{
            //    WebHelper.MessageBox.Show(this.Page, btnCommit, "验证码输入不能为空!");
            //    return;
            //}

            //if (sVc.ToLower() != Request.Cookies["LoginVc"].Value.ToLower())
            //{
            //    WebHelper.MessageBox.Show(this.Page, btnCommit, "验证码输入不正确,请检查!");
            //    return;
            //}

            string userData = string.Empty;

            try
            {
                MembershipUser userInfo = Membership.GetUser(userName);
                if (!Membership.ValidateUser(userName, psw))
                {
                    if (userInfo == null)
                    {
                        WebHelper.MessageBox.Messager(this.Page, btnCommit, "用户名不存在!", "系统提示");
                        return;
                    }
                    if (userInfo.IsLockedOut)
                    {
                        WebHelper.MessageBox.Messager(this.Page, btnCommit, "您的账号已被锁定,请联系管理员先解锁后才能登录!", "系统提示");
                        return;
                    }
                    if (!userInfo.IsApproved)
                    {
                        WebHelper.MessageBox.Messager(this.Page, btnCommit, "您的帐户尚未获得批准。您无法登录,直到管理员批准您的帐户!", "系统提示");
                        return;
                    }
                    else
                    {
                        WebHelper.MessageBox.Messager(this.Page, btnCommit, "密码不正确,请检查!", "系统提示");
                        return;
                    }
                }

                userData = userInfo.ProviderUserKey.ToString() + "|";
            }
            catch (Exception ex)
            {
                WebHelper.MessageBox.Messager(this.Page, btnCommit, ex.Message, "系统提示");
                return;
            }

            //登录成功,则

            bool isPersistent = true;
            //bool isRemember = true;
            bool   isAuto = false;
            double d      = 180;

            //if (cbRememberMe.Checked) isAuto = true;
            //自动登录 设置时间为1年
            if (isAuto)
            {
                d = 525600;
            }

            string[] roles = Roles.GetRolesForUser(userName);
            foreach (string role in roles)
            {
                userData += role + ",";
            }

            userData = userData.Trim(',');

            //创建票证
            FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, userName, DateTime.Now, DateTime.Now.AddMinutes(d),
                                                                             isPersistent, userData, FormsAuthentication.FormsCookiePath);
            //加密票证
            string encTicket = FormsAuthentication.Encrypt(ticket);

            //创建cookie
            Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, encTicket));

            //FormsAuthentication.RedirectFromLoginPage(userName, isPersistent);//使用此行会清空ticket中的userData ?!!!
            Response.Redirect(FormsAuthentication.GetRedirectUrl(userName, isPersistent));
        }
Ejemplo n.º 41
0
        public ActionResult PasswordUpdate()
        {
            HttpCookie authCookie            = Request.Cookies["a"];                          // 获取cookie
            FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(authCookie.Value); // 解密
            var user = SerializeHelper.FromJson <Tab_User>(ticket.UserData);

            //var nvc = Request.Form;
            //string[] keys = nvc.AllKeys;
            //var a = keys.Contains("pwd1");
            //var b = keys.Contains("pwd2");
            //var c = keys.Contains("pwd3");

            var pwd1 = Request.Form["pwd1"]; // 旧密码
            var pwd2 = Request.Form["pwd2"]; // 新密码
            var pwd3 = Request.Form["pwd3"]; // 确认密码

            if (pwd1 == null || pwd1.Length < 6 || pwd1.Length > 20)
            {
                return(Json(new DWZJson()
                {
                    statusCode = (int)DWZStatusCode.ERROR, message = "旧密码长度必须大于6个字符小于20字符"
                }));
            }

            if (pwd2 == null || pwd2.Length < 6 || pwd2.Length > 20)
            {
                return(Json(new DWZJson()
                {
                    statusCode = (int)DWZStatusCode.ERROR, message = "新密码长度必须大于6个字符小于20字符"
                }));
            }

            if (pwd3 == null || pwd3.Length < 6 || pwd3.Length > 20)
            {
                return(Json(new DWZJson()
                {
                    statusCode = (int)DWZStatusCode.ERROR, message = "新密码长度必须大于6个字符小于20字符"
                }));
            }

            if (pwd2 != pwd3)
            {
                return(Json(new DWZJson()
                {
                    statusCode = (int)DWZStatusCode.ERROR, message = "密码不一致"
                }));
            }

            if (pwd1 == pwd2)
            {
                return(Json(new DWZJson()
                {
                    statusCode = (int)DWZStatusCode.ERROR, message = "新旧密码不能相同"
                }));
            }

            var oldpwd = Tools.MD5Encrypt32(pwd1);
            var newpwd = Tools.MD5Encrypt32(pwd2);
            var i      = _us.UpdatePassword(user.F_Id, oldpwd, newpwd);

            if (i == 1)
            {
                var now = DateTime.Now;
                user.F_CreateDate = DateTime.Now;
                user.F_Password   = newpwd;
                string UserData = SerializeHelper.ToJson <Tab_User>(user);                              // 序列化用户实体
                ticket = new FormsAuthenticationTicket(1, "user", now, now, true, UserData);
                HttpCookie cookie = new HttpCookie("a", FormsAuthentication.Encrypt(ticket).ToLower()); // 加密身份信息,保存至Cookie
                cookie.HttpOnly = true;

                Response.SetCookie(cookie);

                return(Json(new DWZJson()
                {
                    statusCode = (int)DWZStatusCode.OK, message = "操作成功"
                }));
            }
            else
            {
                return(Json(new DWZJson()
                {
                    statusCode = (int)DWZStatusCode.ERROR, message = "旧密码不正确"
                }));
            }
        }
Ejemplo n.º 42
0
        /// <summary>
        /// 系统管理员登陆系统
        /// </summary>
        /// <param name="adminName"></param>
        /// <param name="adminPwd"></param>
        /// <returns></returns>
        public bool AdminLogin(string adminName, string adminPwd)
        {
            SOSOshop.BLL.Administrators   bll   = new SOSOshop.BLL.Administrators();
            SOSOshop.Model.Administrators model = bll.GetModelByAdminName(adminName);
            //无数据
            if (model == null)
            {
                message = "用户名或密码错误!";
                return(false);
            }
            //密码错误
            if (!model.PassWord.ToLower().Equals(adminPwd.ToLower()))
            {
                message = "用户名或密码错误!";
                model   = null;
                return(false);
            }

            //帐号被冻结
            if (model.State.Equals(1))
            {
                message = "您输入的账户以被冻结!";
                model   = null;
                return(false);
            }

            //帐号已经过期
            if (model.ManageEndTime < DateTime.Now)
            {
                message = "你的帐户已经过期!";
                model   = null;
                return(false);
            }

            //一人一机登陆验证
            //ChangeHope.Common.DEncryptHelper.Encrypt(model.Name, 1);
            //if (model.Name != "admin")
            //{
            //    object AllowOtherLogin = new SOSOshop.BLL.Db().ExecuteScalar("select top (1) AllowOtherLogin from yxs_CustomerSetting");
            //    if (AllowOtherLogin != null && AllowOtherLogin.ToString() == "0")
            //    {
            //        //查询登陆日志
            //        object adminid = new SOSOshop.BLL.Db().ExecuteScalar("select top (1) id from yxs_adminloginlog where " +
            //            "adminname = '" + model.Name + "' " +
            //            "and convert(char(10),loginintime,120) = '" + DateTime.Now.ToString("yyyy-MM-dd") + "' and loginintime = loginouttime " +
            //            "and loginip != '" + Request.UserHostAddress + "' " +
            //            "and operatenote = '登陆成功!' order by loginintime desc");
            //        if (adminid != null)
            //        {
            //            message = "你的帐户已经登陆!";
            //            model = null;
            //            return false;
            //        }
            //    }
            //}

            string DstMobile = Convert.ToString(new SOSOshop.BLL.Db().ExecuteScalar("select LoginAuthenticationOfficePhone from yxs_administrators where adminid = " + model.AdminId)).Trim();

            if (DstMobile.Trim() != "" && false)
            {
                //发送短信
                ArrayList smsRecord = new ArrayList();
                if (Session["smsRecord"] != null)
                {
                    smsRecord = Session["smsRecord"] as ArrayList;
                }
                bool ok = smsRecord != null && smsRecord.Count > 0 && txtCheckCode.Text.ToUpper() == smsRecord[smsRecord.Count - 1].ToString().ToUpper();
                if (!ok)
                {
                    message = "验证码错误!";
                    model   = null;
                    return(false);
                }
            }


            //初始化权限
            SOSOshop.Model.AdminInfo admin = new SOSOshop.Model.AdminInfo();
            if (model.Power.Equals(0))
            {
                admin.AdminPowerType = "all";
            }
            else
            {
                //非管理员权限,等待添加相关内容
                admin.AdminPowerType = "";
            }

            admin.AdminId   = model.AdminId;
            admin.AdminName = model.Name;
            admin.AdminRole = model.Role;
            SOSOshop.BLL.AdministrorManager.Set(admin);

            FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
                1,
                admin.AdminName,
                DateTime.Now,
                DateTime.Now.AddMinutes(1000),
                true,
                ""
                );
            HttpCookie cookie = new System.Web.HttpCookie(FormsAuthentication.FormsCookieName,
                                                          FormsAuthentication.Encrypt(ticket));

            cookie.Domain  = System.Configuration.ConfigurationManager.AppSettings["Domain"];
            cookie.Expires = DateTime.Now.AddHours(10);
            System.Web.HttpContext.Current.Response.Cookies.Add(cookie);


            admin   = null;
            message = "登陆成功!";
            return(true);
        }
Ejemplo n.º 43
0
        public async Task <ActionResult> Index()
        {
            List <string> upperCarousel = new List <string>();
            List <string> lowerCarousel = new List <string>();
            var           clients       = obj.Clients.Where(x => x.Status != 0 && x.Image != null).ToList();

            foreach (var details in clients)
            {
                var clientPackages = obj.ClientPakages.Where(x => x.ClientId.Equals(details.Id)).ToList();
                foreach (var details1 in clientPackages)
                {
                    if (details1.Pakage.PakageType == "gold")
                    {
                        upperCarousel.Add(details.Image);
                    }
                    else if (details1.Pakage.PakageType == "silver")
                    {
                        lowerCarousel.Add(details.Image);
                    }
                }
            }

            ViewBag.upperCarousel = upperCarousel;
            ViewBag.lowerCarousel = lowerCarousel;



            try
            {
                ViewBag.ErrorMessage = (string)TempData["ErrorMessage"];
            }
            catch (Exception ee) { }
            try
            {
                HttpCookie authCookie            = Request.Cookies["TraineeHellodjfdshfsdanfkjdsfsfwgbhwvifbwsdjwiufdn"];
                FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(authCookie.Value);

                string   cookiePath   = ticket.CookiePath;
                DateTime expiration   = ticket.Expiration;
                bool     expired      = ticket.Expired;
                bool     isPersistent = ticket.IsPersistent;
                DateTime issueDate    = ticket.IssueDate;
                string   CookieId     = ticket.Name;
                string   userData     = ticket.UserData;
                int      version      = ticket.Version;

                if (!expired)
                {
                    ViewBag.UserId = CookieId;
                }
            }
            catch (Exception e) { }

            var value       = obj.AccessTokens.First();
            var accessToken = value.AccessToken1;



            if (accessToken == "")
            {
                return(View("Index2"));
            }
            //curly braces
            string         s       = accessToken;
            string         url     = String.Format("https://graph.facebook.com/me?fields=id,name,groups{{feed.limit(1000){{from,message,story,created_time,attachments{{description,type,url,title,media,target}},likes{{pic}},comments}}}}&access_token={0}", accessToken);
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;

            request.Method = "GET";

            //curly braces

            try
            {
                using (HttpWebResponse response = await request.GetResponseAsync() as HttpWebResponse)
                {
                    StreamReader reader = new StreamReader(response.GetResponseStream());
                    string       result = await reader.ReadToEndAsync();

                    dynamic jsonObj = System.Web.Helpers.Json.Decode(result);

                    Models.SocialMedia.SocialMedia.posts posts = new Models.SocialMedia.SocialMedia.posts(jsonObj);

                    List <string> pictures          = new List <string>();
                    List <string> comments_pictures = new List <string>();


                    foreach (var post in posts.feed.data)
                    {
                        if (post.comments != null)
                        {
                            foreach (var id in post.comments.data)
                            {
                                comments_pictures.Add(id.from.id);
                            }
                        }
                    }

                    foreach (var post in posts.feed.data)
                    {
                        pictures.Add(post.From.id);
                    }

                    foreach (var id in comments_pictures)
                    {
                        string         url2     = String.Format("https://graph.facebook.com/" + id + "?fields=picture&access_token={0}", accessToken);
                        HttpWebRequest request2 = WebRequest.Create(url2) as HttpWebRequest;
                        request2.Method = "GET";

                        using (HttpWebResponse response2 = await request2.GetResponseAsync() as HttpWebResponse)
                        {
                            StreamReader reader2 = new StreamReader(response2.GetResponseStream());
                            string       result2 = await reader2.ReadToEndAsync();

                            dynamic jsonObj2 = System.Web.Helpers.Json.Decode(result2);
                            Models.SocialMedia.SocialMedia.Profile from2 = new Models.SocialMedia.SocialMedia.Profile(jsonObj2);
                            comment_profile.Add(from2.profile);
                        }
                    }

                    foreach (var from in pictures)
                    {
                        string         url1     = String.Format("https://graph.facebook.com/" + from + "?fields=picture&access_token={0}", accessToken);
                        HttpWebRequest request1 = WebRequest.Create(url1) as HttpWebRequest;
                        request1.Method = "GET";
                        using (HttpWebResponse response1 = await request1.GetResponseAsync() as HttpWebResponse)
                        {
                            StreamReader reader1 = new StreamReader(response1.GetResponseStream());
                            string       result1 = await reader1.ReadToEndAsync();

                            dynamic jsonObj1 = System.Web.Helpers.Json.Decode(result1);
                            Models.SocialMedia.SocialMedia.Profile from1 = new Models.SocialMedia.SocialMedia.Profile(jsonObj1);
                            profile.Add(from1.profile);
                        }
                    }
                    Models.SocialMedia.SocialMedia.Pictures pics = new Models.SocialMedia.SocialMedia.Pictures(profile, comment_profile);

                    return(View(Tuple.Create(pics, posts)));
                }
            }
            catch (Exception exs)
            { return(RedirectToAction("Index2")); }
        }
Ejemplo n.º 44
0
        public ActionResult LogOnCallback(string state, string code)
        {
            var returnUrl = state;

            if (string.IsNullOrEmpty(code))
            {
                return(RedirectToAction("Error", new { returnUrl = returnUrl, error = "Response status is not Authenticated" }));
            }

            string email = RetrieveUserEmail(code);

            if (string.IsNullOrWhiteSpace(email))
            {
                return(RedirectToAction("Error", new { returnUrl = returnUrl, error = "Response Email is empty" }));
            }

            if (!email.EndsWith(EmailSuffix))
            {
                return(RedirectToAction("Error", new { returnUrl = returnUrl, error = "Only emails ended with " + EmailSuffix + " are allowed" }));
            }

            var username = email.Substring(0, email.Length - EmailSuffix.Length);

            FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
                1,
                username,
                DateTime.Now,
                DateTime.Now.AddDays(2),
                true,
                "",
                FormsAuthentication.FormsCookiePath);

            string encTicket = FormsAuthentication.Encrypt(ticket);
            var    cookie    = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket)
            {
                // setting the Expires property to the same value in the future
                // as the forms authentication ticket validity
                Expires = ticket.Expiration
            };

            Response.Cookies.Add(cookie);

            var user = RavenSession.Load <User>("Users/" + username);

            log.Debug("User {0} found: {1}", username, user != null);

            if (user != null)
            {
                log.Dump(LogLevel.Debug, user, "RavenDB User");
            }

            if (!string.IsNullOrWhiteSpace(returnUrl) && Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/") &&
                !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
            {
                return(Redirect(returnUrl));
            }
            else
            {
                return(RedirectToAction("Index", "Home"));
            }
        }
Ejemplo n.º 45
0
        public ActionResult SignInTable(UserLogin u)
        {
            List <string> upperCarousel = new List <string>();
            List <string> lowerCarousel = new List <string>();
            var           clients       = obj.Clients.Where(x => x.Status != 0 && x.Image != null).ToList();

            foreach (var details in clients)
            {
                var clientPackages = obj.ClientPakages.Where(x => x.ClientId.Equals(details.Id)).ToList();
                foreach (var details1 in clientPackages)
                {
                    if (details1.Pakage.PakageType == "gold")
                    {
                        upperCarousel.Add(details.Image);
                    }
                    else if (details1.Pakage.PakageType == "silver")
                    {
                        lowerCarousel.Add(details.Image);
                    }
                }
            }

            ViewBag.upperCarousel = upperCarousel;
            ViewBag.lowerCarousel = lowerCarousel;

            Client obj2  = new Client();
            var    data2 = obj.Clients.Where(x => x.Status != 0 && x.Image != null).ToList();

            ViewBag.details1 = data2;
            string    SessionValue = "";
            UserLogin login        = new UserLogin();

            try
            {
                login = obj.UserLogins.First(x => x.UserName.Equals(u.UserName) && x.Password.Equals(u.Password));
            }
            catch (Exception e) { }

            var  check = "true";
            User temp  = new User();

            try
            {
                temp         = obj.Users.First(x => x.Id.Equals(login.UserId));
                SessionValue = temp.Name;
                SessionValue = SessionValue + "$";
                SessionValue = SessionValue + temp.Email;
            }
            catch (Exception e1) { check = "false"; }
            if (check == "true")
            {
                FormsAuthentication.SignOut();
                DateTime cookieIssuedDate = DateTime.Now;

                var ticket = new FormsAuthenticationTicket(0,
                                                           temp.Id.ToString(),
                                                           cookieIssuedDate,
                                                           cookieIssuedDate.AddMinutes(FormsAuthentication.Timeout.TotalMinutes),
                                                           false,
                                                           SessionValue,
                                                           FormsAuthentication.FormsCookiePath);

                string encryptedCookieContent = FormsAuthentication.Encrypt(ticket);

                var formsAuthenticationTicketCookie = new HttpCookie("userteripengfkansdHello1234hytusksdbsdfasdjasdidasdijnasd", encryptedCookieContent)
                {
                    Domain   = FormsAuthentication.CookieDomain,
                    Path     = FormsAuthentication.FormsCookiePath,
                    HttpOnly = true,
                    Secure   = FormsAuthentication.RequireSSL
                };

                System.Web.HttpContext.Current.Response.Cookies.Add(formsAuthenticationTicketCookie);
                FormsAuthentication.SetAuthCookie(temp.Name, false);

                return(RedirectToAction("Index", "Home"));
            }

            return(RedirectToAction("Index", "Home"));
        }
Ejemplo n.º 46
0
        public ActionResult Login(User obj)
        {
            if (string.IsNullOrEmpty(obj.UserName) || string.IsNullOrWhiteSpace(obj.Password))
            {
                Session["Messenger"] = new Notified {
                    Value = EnumNotifield.Error, Messenger = "Bạn chưa nhập tên đăng nhập hoặc mật khẩu nhập vào không đúng!"
                };
                return(View("/Areas/Admin/Views/Account/Login.cshtml"));
            }
            var user = _userRepository.GetAll().FirstOrDefault(u => u.Password == HelperEncryptor.Md5Hash(obj.Password) && u.UserName == obj.UserName);

            if (user != null)
            {
                user.TimeLogin = DateTime.Now;
                user.IPLogin   = obj.IPLogin;
                _userRepository.Edit(user);
                if (user.Active == false)
                {
                    Session["Messenger"] = new Notified {
                        Value = EnumNotifield.Error, Messenger = "Tài khoản này chưa được kích hoạt!"
                    };
                    return(View("/Areas/Admin/Views/Account/Login.cshtml"));
                }
                var serializeModel = new CustomPrincipalSerializeModel
                {
                    ID        = user.ID,
                    Username  = user.UserName,
                    FullName  = user.FullName,
                    Email     = user.Email,
                    GroupUser = user.GroupUserID,
                    UserType  = user.UserType,
                    isAdmin   = user.isAdmin,
                };
                var serializer = new JavaScriptSerializer();

                var userData = serializer.Serialize(serializeModel);

                var authTicket = new FormsAuthenticationTicket(
                    1,
                    obj.UserName,
                    DateTime.Now,
                    DateTime.Now.AddHours(1),
                    false,
                    userData);

                var encTicket = FormsAuthentication.Encrypt(authTicket);
                var faCookie  = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket);
                faCookie.Name = "ADMIN_COOKIES";
                Response.Cookies.Add(faCookie);
            }
            else
            {
                Session["Messenger"] = new Notified {
                    Value = EnumNotifield.Error, Messenger = "Bạn chưa nhập tên đăng nhập hoặc mật khẩu nhập vào không đúng!"
                };

                return(View("/Areas/Admin/Views/Account/Login.cshtml"));
            }
            var preUrl = (Uri)Session["returnUrl"];

            if (preUrl != null)
            {
                Session["returnUrl"] = null;
                return(Redirect(preUrl.ToString()));
            }
            return(RedirectToAction("Index", "Home", new { area = "Admin" }));
        }
Ejemplo n.º 47
0
        public ActionResult Login([Bind(Include = "SchoolId")] TblSchool tblSchool, FormCollection form)
        {
            //Uri currentUrl = Request.UrlReferrer;
            //if (currentUrl == null)
            //{
            //    return HttpNotFound();
            //}

            //Create(); //Only Called when we need to create the first PCMS User
            try
            {
                string username = Hash(form["EmailAddress"]);
                string password = form["PasswordHash"];
                var    user     = db.TblSystemAdmins.Where(t => t.Username == username);

                if (user.Any())
                {
                    if (user.FirstOrDefault().PasswordHash == Hash(password))
                    {
                        SetGlobals(user.FirstOrDefault().UserId, user.FirstOrDefault().EmailAddress);

                        try
                        {
                            string userData = "";
                            int?   schoolId = tblSchool.SchoolId;
                            if (schoolId == null)
                            {
                                schoolId = 0;
                            }
                            userData = EmailG + ";" + schoolId + ";" + 0 + ";" + UserIdG + ";";


                            FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, EmailG, DateTime.Now,
                                                                                             DateTime.Now.AddDays(2),
                                                                                             true,
                                                                                             userData,
                                                                                             FormsAuthentication.FormsCookiePath);

                            // Encrypt the ticket.
                            string encTicket = FormsAuthentication.Encrypt(ticket);

                            // Create the cookie.
                            HttpCookie userCookie = new HttpCookie("UserInformation", encTicket);
                            userCookie.Expires = DateTime.Now.AddDays(2);

                            Response.Cookies.Add(userCookie);
                            //return RedirectToAction("NavigationHomeIndex", "PCMSNavigation");
                            return(RedirectToAction("SelectSchool"));
                        }
                        catch (Exception e)
                        {
                            string error = e.Message;
                        }

                        //return RedirectToAction("NavigationHomeIndex", "PCMSNavigation");
                        return(RedirectToAction("SelectSchool"));
                    }
                }
            }
            catch (Exception e)
            {
                string error = e.Message;
            }

            return(RedirectToAction("Login"));
        }
Ejemplo n.º 48
0
        public ActionResult Login(string userName, string password, string verifyCode, string isRemember)
        {
            ResultView <string> result;

            try
            {
                userName   = userName ?? Request.Form["userName"];
                password   = password ?? Request.Form["password"];
                verifyCode = verifyCode ?? Request.Form["verifyCode"];
                isRemember = isRemember ?? Request.Form["isRemember"];

                if (string.IsNullOrWhiteSpace(userName) || string.IsNullOrWhiteSpace(password))
                {
                    result = (new ResultView <string> {
                        Flag = false, Message = "用户名或登录密码为空!"
                    });
                    return(Json(result));
                }

                if (string.IsNullOrWhiteSpace(verifyCode))
                {
                    result = (new ResultView <string> {
                        Flag = false, Message = "请输入验证码!"
                    });
                    return(Json(result));
                }
                string code = (Session[ConstStr_Session.CurrValidateCode] ?? "").ToString();
                if (string.IsNullOrWhiteSpace(code))
                {
                    result = (new ResultView <string> {
                        Flag = false, Message = "验证码超时!"
                    });
                    return(Json(result));
                }
                if (!verifyCode.Equals(code))
                {
                    result = (new ResultView <string> {
                        Flag = false, Message = "验证码错误,请重新输入!"
                    });
                    return(Json(result));
                }

                password = DesTool.DesEncrypt(password);
                using (ClientSiteClientProxy proxy = new ClientSiteClientProxy(ProxyEx(Request)))
                {
                    Result <UserView> loginResult = proxy.Login(userName, password, IsOpenSxLogin);
                    if (loginResult.Flag == 0)
                    {
                        Session[ConstStr_Session.CurrentUserEntity] = loginResult.Data;

                        //自动登录
                        if ("true".Equals(isRemember))
                        {
                            //保存用户名
                            HttpCookie cook = new HttpCookie(ConstString.COOKIEADMINNAME);
                            cook.Value   = userName;
                            cook.Expires = DateTime.Now.AddDays(7);
                            Response.Cookies.Add(cook);
                            //保存密码
                            cook         = new HttpCookie(ConstString.COOKIEADMINPWD);
                            cook.Value   = password;
                            cook.Expires = DateTime.Now.AddDays(7);
                            Response.Cookies.Add(cook);

                            //存储在票据中,使用User.Identity或Request 中的Cookie 解密获取Ticket
                            FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1, userName, DateTime.Now,
                                                                                                 DateTime.Now.AddMinutes(Session.Timeout - 1), false, userName);
                            string     encryptedTicket = FormsAuthentication.Encrypt(authTicket);
                            HttpCookie authCookie      = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
                            authCookie.HttpOnly = true;
                            Response.Cookies.Add(authCookie);

                            authTicket = new FormsAuthenticationTicket(1, password, DateTime.Now,
                                                                       DateTime.Now.AddMinutes(Session.Timeout - 1), false, password);
                            encryptedTicket     = FormsAuthentication.Encrypt(authTicket);
                            authCookie          = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
                            authCookie.HttpOnly = true;
                            Response.Cookies.Add(authCookie);
                        }
                        else//清除cookie
                        {
                            var nameCookie = new HttpCookie(ConstString.COOKIEADMINNAME);
                            var pwdCookie  = new HttpCookie(ConstString.COOKIEADMINPWD);
                            nameCookie.Expires = DateTime.Now.AddDays(-1);
                            pwdCookie.Expires  = DateTime.Now.AddDays(-1);
                            Response.Cookies.Add(nameCookie);
                            Response.Cookies.Add(pwdCookie);
                        }

                        LoadUserRight(loginResult.Data.RoleType.ToString(), loginResult.Data.UserId);

                        result = (new ResultView <string> {
                            Flag = true, Message = "登录成功,正在跳转...", Data = "/Home/SignIndex"
                        });
                    }
                    else
                    {
                        result = (new ResultView <string> {
                            Flag = false, Message = loginResult.Exception.Decription
                        });
                    }
                }
            }
            catch (Exception e)
            {
                //验证不通过,给出错误提示
                return(Json(new ResultView <string> {
                    Flag = false, Message = "登录异常!" + e.Message
                }));
            }
            return(Json(result));
        }
Ejemplo n.º 49
0
        private FormsAuthenticationTicket GetAuthenticationTicket(string token)
        {
            FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(token);

            return(ticket);
        }
        public ActionResult Authenticate(UsersLog user)
        {
            string result = "";

            db.Database.CommandTimeout = 0;
            try
            {
                string  pass  = EncodePasswordMd5(user.Password);
                M_Users check = (from c in db.M_Users
                                 where c.UserName == user.UserName &&
                                 c.Password == pass &&
                                 c.IsDeleted == false
                                 select c).FirstOrDefault();
                check.CostCode = (from c in db.M_Employee_CostCenter where c.EmployNo == user.UserName orderby c.ID descending select c.CostCenter_AMS).FirstOrDefault();
                string CostCodenow = check.CostCode;
                check.Section = (from c in db.M_Cost_Center_List where c.Cost_Center == CostCodenow select c.GroupSection).FirstOrDefault();

                if (check != null)
                {
                    bool rememberme = false;
                    if (user.Rememberme)
                    {
                        rememberme = true;
                    }

                    string emailtemplatepath = Server.MapPath(@"~/Content/EmailForm/OTEmail.html");
                    System.Web.HttpContext.Current.Session["emailpath"] = emailtemplatepath;
                    System.Web.HttpContext.Current.Session["UserName"]  = check.FirstName + ' ' + check.LastName;
                    System.Web.HttpContext.Current.Session["user"]      = check;
                    FormsAuthentication.SetAuthCookie(user.UserName, true);
                    FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(
                        1,
                        user.UserName,
                        DateTime.Now,
                        DateTime.Now.AddMinutes(FormsAuthentication.Timeout.TotalMinutes),
                        rememberme,
                        user.ToString());

                    RefreshPageAccess(check.UserName, check.Section);


                    List <CostCenterM> newCostCode = (from c in db.M_Cost_Center_List where c.GroupSection == "" || c.GroupSection == null
                                                      select new CostCenterM {
                        CostCodenew = c.Cost_Center,
                        CostCodenewname = c.Section
                    }).ToList();
                    System.Web.HttpContext.Current.Session["newCostCode"] = newCostCode;
                }
                result = (check == null) ? "Failed" : "Success";
                if (result == "Failed")
                {
                    //Error_Logs error = new Error_Logs();
                    //error.PageModule = "Login";
                    //error.ErrorLog = "Incorrect Username or Password";
                    //error.DateLog = db.TT_GETTIME().FirstOrDefault();//DateTime.Now;;
                    //error.Username = user.UserName;
                    //db.Error_Logs.Add(error);
                    //db.SaveChanges();
                }

                string urlmail = (Session["urlmail"] != null) ? Session["urlmail"].ToString() : "/";
                return(Json(new { result = result, urlmail = urlmail }, JsonRequestBehavior.AllowGet));
            }
            catch (Exception err)
            {
                Error_Logs error = new Error_Logs();
                error.PageModule = "Login";
                error.ErrorLog   = err.Message;
                error.DateLog    = db.TT_GETTIME().FirstOrDefault();//DateTime.Now;;
                error.Username   = user.UserName;
                db.Error_Logs.Add(error);
                db.SaveChanges();
                return(Json(new { result = result, urlmail = "" }, JsonRequestBehavior.AllowGet));
            }
        }
Ejemplo n.º 51
0
        public ActionResult Login(UserLoginModel userLoginModel)
        {
            SetPageSeo("用户登录");
            if (!ModelState.IsValid)
            {
                return(View());
            }
            List <string> msgList    = new List <string>();
            string        verifyCode = Session["ValidateCode"] as string;

            if (userLoginModel.VerifyCode != verifyCode)
            {
                msgList.Add("验证码输入错误");
            }

            userLoginModel = new UserLoginModel()
            {
                VerifyCode = Sanitizer.GetSafeHtmlFragment(userLoginModel.VerifyCode),
                UserName   = Sanitizer.GetSafeHtmlFragment(userLoginModel.UserName),
                Password   = userLoginModel.Password
            };

            var userinfo = userBusinessLogic.GetUserInfo(userLoginModel.UserName, Md5.GetMd5(userLoginModel.Password));

            if (userinfo != null)
            {
                UserInfo user     = new UserInfo(userinfo.ID, userinfo.UserName, userinfo.IsAdmin);
                var      userJson = JsonConvert.SerializeObject(user);
                var      ticket   = new FormsAuthenticationTicket(1, userinfo.UserName, DateTime.Now, DateTime.Now.AddDays(1), true, userJson);
                //FormsAuthentication.SetAuthCookie(userLoginModel.UserName, true);
                string     cookieString = FormsAuthentication.Encrypt(ticket);
                HttpCookie authCookie   = new HttpCookie(FormsAuthentication.FormsCookieName, cookieString);
                authCookie.Expires = ticket.Expiration;
                authCookie.Path    = FormsAuthentication.FormsCookiePath;
                Response.Cookies.Add(authCookie);


                bool isAuth = Request.IsAuthenticated;

                // add log
                if (user.IsAdmin > 0)
                {
                    T_UserLog log = new T_UserLog()
                    {
                        AddDate  = DateTime.Now,
                        Content  = string.Format("{0}于{1}登录系统", user.UserName, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")),
                        UserID   = user.UserID,
                        UserName = user.UserName
                    };
                    userBusinessLogic.AddUserLog(log);
                }

                return(RedirectToAction("Profile", "User", null));
            }
            else
            {
                msgList.Add("用户名或密码错误");
                ViewBag.MsgList = msgList;
                return(View());
            }
        }
Ejemplo n.º 52
0
 private string SetEmail(FormsAuthenticationTicket ticket)
 {
     string[] data = ticket.UserData.Split('|');
     return(data[0]);
 }
Ejemplo n.º 53
0
 private string[] SetRoles(FormsAuthenticationTicket ticket)
 {
     string[] data  = ticket.UserData.Split('|');
     string[] roles = data[1].Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
     return(roles);
 }
Ejemplo n.º 54
0
 private string SetName(FormsAuthenticationTicket ticket)
 {
     return(ticket.Name);
 }
Ejemplo n.º 55
-1
    void RedirectFromLoginPage(string username, string role, bool persistent)
    {
        //Create ticket for authenticate
        FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
            1,//Version
            username,
            DateTime.Now,
            DateTime.Now.AddMinutes(60),    //set expire time
            persistent,
            role);

        //Add authentication information to cookie (Session may be better to use...)
        HttpCookie cookie = new HttpCookie(
            FormsAuthentication.FormsCookieName,
            FormsAuthentication.Encrypt(ticket));

        if (persistent)
        {
            cookie.Expires = DateTime.Now.AddYears(50); //set 50year if persistent is true
        }
        Response.Cookies.Add(cookie);
        Response.Redirect("~/accountCreated.aspx");

        //Redirect to the page where user intended to access
        //Response.Redirect(FormsAuthentication.GetRedirectUrl(username, persistent));
    }