SignIn() public method

public SignIn ( string userName, bool createPersistentCookie ) : void
userName string
createPersistentCookie bool
return void
示例#1
0
        public ActionResult LogOn(LogOn logOn, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                logOn.User.PW = Convert.ToBase64String(
                    new System.Security.Cryptography.SHA1CryptoServiceProvider().ComputeHash(
                        Encoding.ASCII.GetBytes(logOn.User.PW)));

                var contextUser = db.Users.Where(e => e.UserName == logOn.User.UserName && e.PW == logOn.User.PW).FirstOrDefault();

                if (contextUser != null)
                {
                    IFormsAuthenticationService formsService = new FormsAuthenticationService();
                    formsService.SignIn(logOn.User.UserName, logOn.RememberMe);

                    if (!String.IsNullOrEmpty(returnUrl))
                    {
                        return(Redirect(returnUrl));
                    }
                    else
                    {
                        return(RedirectToAction("Index", "Home"));
                    }
                }
                else
                {
                    ModelState.AddModelError("", "The user name or password provided is incorrect.");
                }
            }

            // If we got this far, something failed, redisplay form
            //return View(new LogOnViewModel(logOnModel));

            return(View(new LogOn()));
        }
示例#2
0
        protected void btnLogin_Click(object sender, EventArgs e)
        {
            SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["myConnection"].ToString());

            string hashedPassword = FormsAuthentication.HashPasswordForStoringInConfigFile(txtPassword.Text, "SHA1");

            string errorMessage = _userService.CheckUserBeforeLogin(txtEmail.Text, hashedPassword);

            if (errorMessage != "")
            {
                error.InnerText        = errorMessage;
                error.Style["display"] = "block";
            }

            else
            {
                var user = _userService.GetUserByEmail(txtEmail.Text);
                _authenticationService.SignIn(user, cbRememberMe.Checked, true);
                var returnUrl = Request.QueryString["ReturnUrl"];
                if (returnUrl != null)
                {
                    Response.Redirect(returnUrl);
                }
                else
                {
                    Response.Redirect("/home");
                }
            }
        }
示例#3
0
        public ActionResult Login(UserViewModel model)
        {
            if (ModelState.IsValid)
            {
                var userService = new UserRepository();
                var user        = userService.GetUser(model.UserName);
                if (user != null)
                {
                    if (TextHelper.Sha256(model.Password) == user.Password)
                    {
                        var formsAuthenticationServic = new FormsAuthenticationService();
                        formsAuthenticationServic.SignIn(user, false);
                        return(RedirectToAction("Index", "Home"));
                    }
                    else
                    {
                        ModelState.AddModelError("Message", "密码错误");
                        return(View());
                    }
                }
                else
                {
                    ModelState.AddModelError("Message", "用户名不存在");
                }
            }

            ModelState.AddModelError("Message", "用户名或密码错误");
            return(View());
        }
示例#4
0
        private void LoginSucceed(LoginUserInfo loginUser, bool isRemberUserName)
        {
            ViewBag.Message = null;
            FormsAuthenticationService.SignIn(loginUser, false);

            Session["LoginTime"] = DateTime.Now;

            if (isRemberUserName)
            {
                HttpCookie aCookie = new HttpCookie(_persistentCookie);
                aCookie.Values["user"]   = loginUser.CODE;
                aCookie.Values["rember"] = "1";
                aCookie.Expires          = DateTime.Now.AddDays(15);
                aCookie.Path             = "/";
                Response.Cookies.Add(aCookie);
            }
            else
            {
                HttpCookie aCookie = new HttpCookie(_persistentCookie);
                aCookie.Value   = string.Empty;
                aCookie.Expires = new DateTime(1900, 1, 1);
                aCookie.Path    = "/";
                Response.Cookies.Add(aCookie);
            }
        }
示例#5
0
        public ActionResult Register(Register register)
        {
            if (ModelState.IsValid)
            {
                if (!String.Equals(register.User.PW, register.ConfirmPassword))
                {
                    ModelState.AddModelError("", "Password and confirm password does not match");
                    return(View(register));
                }

                var user = db.Users.Where(e => e.UserName == register.User.UserName).FirstOrDefault();

                if (user != null)
                {
                    ModelState.AddModelError("", "Username already exists");
                    return(View(register));
                }

                var userEmail = db.Users.Where(e => e.Email == register.Email).FirstOrDefault();

                if (userEmail != null)
                {
                    ModelState.AddModelError("", "Email already exists");
                    return(View(register));
                }

                register.User.PW = Convert.ToBase64String(
                    new System.Security.Cryptography.SHA1CryptoServiceProvider().ComputeHash(
                        Encoding.ASCII.GetBytes(register.ConfirmPassword)));
                register.User.SignUpDateTime = DateTime.Now;
                register.User.Email          = register.Email;
                register.User.Active         = true;

                var newUser = register.User;

                db.Users.Add(newUser);
                db.SaveChanges();

                using (var mySmtp = new MySmtpClient())
                {
                    using (var message = new MyEmail(newUser.Email))
                    {
                        message.Subject = "Welcome to Crafty Losers!";
                        message.Body    = "Welcome to Crafty Losers!  Good luck!";
                        mySmtp.Send(message);
                    }
                }

                IFormsAuthenticationService formsService = new FormsAuthenticationService();
                formsService.SignIn(newUser.UserName, true);
            }
            else
            {
                return(View(register));
            }

            return(RedirectToAction("Index", "Home"));
        }
示例#6
0
        public ActionResult Edit(Guid?id, PersonEditModel personEditModel, HttpPostedFileBase profilepic)
        {
            User user = null;

            // admin is trying to edit, authorize them
            if (id.HasValue)
            {
                // current user must be in User role
                if (Roles.IsUserInRole(RoleNames.User))
                {
                    user = _userRepository.GetNullableById(id.Value);
                }
            }
            else
            {
                user = Repository.OfType <User>().Queryable.Where(a => a.LoweredUserName == CurrentUser.Identity.Name.ToLower()).FirstOrDefault();
            }

            if (user == null)
            {
                return(this.RedirectToAction <ErrorController>(a => a.NotAuthorized()));
            }

            //var seminarPerson = _seminarPersonRepository.GetNullableById(personEditModel.SeminarPersonId);
            var person = SetPerson(personEditModel, null, ModelState, user.Person, profilepic);

            var membership = user.Membership;

            membership.SetEmail(personEditModel.Email);

            if (ModelState.IsValid)
            {
                _personRepository.EnsurePersistent(person);
                _membershipRepository.EnsurePersistent(membership);

                Message = string.Format(Messages.Saved, "Person");

                if (personEditModel.UserName != CurrentUser.Identity.Name.ToLower())
                {
                    user.SetUserName(personEditModel.UserName);
                    _userRepository.EnsurePersistent(user);

                    var formsService = new FormsAuthenticationService();
                    formsService.SignOut();
                    formsService.SignIn(user.LoweredUserName, false);
                }

                // send to crop photo if one was uploaded
                if (profilepic != null)
                {
                    return(this.RedirectToAction(a => a.UpdateProfilePicture(person.Id, null, true)));
                }
            }

            var viewModel = PersonViewModel.Create(Repository, _firmService, Site, null, person, user.Email);

            return(View(viewModel));
        }
示例#7
0
        public ActionResult FacebookAuth(string returnUrl)
        {
            string appId        = ConfigurationManager.AppSettings["AppId"];
            string facebookauth = ConfigurationManager.AppSettings["FacebookAuthURL"];
            string appsecret    = ConfigurationManager.AppSettings["AppSecret"];

            // if code is not available, we should request some.
            if (Request.Params["code"] == null)
            {
                string code_url = @"https://www.facebook.com/dialog/oauth?client_id=" + appId +
                                  "&redirect_uri=" + Server.UrlEncode(facebookauth) + "&scope=email,read_stream";
                Response.Redirect(code_url);
            }
            else
            {
                string token_url = @"https://graph.facebook.com/oauth/access_token?client_id=" + appId +
                                   "&redirect_uri=" + facebookauth + "&client_secret=" + appsecret + "&code=" + Request.Params["code"];

                string tokenKeyValue = PostHelper.file_get_contents(token_url);
                string token         = PostHelper.GetKeyValueFromString(tokenKeyValue, "access_token");

                Facebook.FacebookAPI api = new Facebook.FacebookAPI(token);

                Facebook.JSONObject me = api.Get("/me");

                UsersModels user = new UsersModels();

                // NOTE:
                // api.AccessToken is temporary. It will be replaced to a
                // more proper ClaimedOpenId or public profile for facebook. e.g. http://www.facebook.com/robiboi

                user = user.GetUserByOpenId(api.AccessToken);   // should be the identifier of the user in facebook, e.g. profile link.
                if (user == null)
                {
                    RegisterOpenId roi = new RegisterOpenId();
                    roi.ClaimedOpenId  = api.AccessToken; // same as above
                    roi.FriendlyOpenId = api.AccessToken; // could be profile link.
                    roi.ReturnUrl      = returnUrl;
                    roi.Email          = null;
                    return(View(roi));
                }

                FormsAuthenticationService formAuth = new FormsAuthenticationService();
                formAuth.SignIn(api.AccessToken, false);

                if (!string.IsNullOrEmpty(returnUrl))
                {
                    return(Redirect(returnUrl));
                }
                else
                {
                    return(RedirectToAction("Index", "Home"));
                }
            }
            return(new EmptyResult());
        }
示例#8
0
        public void Signin_when_name_is_empty_throws_new_argumentexception_value_cannot_be_null_or_empty()
        {
            //arrange
            var mut = new FormsAuthenticationService();

            //act
            mut.SignIn(string.Empty, false);
            //assert
            //cleanup
        }
示例#9
0
        protected void signInButton_Click(object sender, EventArgs e)
        {
            if (pageActionType.Value == "signin")
            {
                try
                {
                    var user = UserService.Get(x => x.UserName == this.username.Text);
                    if (user != null && HashPasswordService.ArePasswordsMatching(this.password.Text, user.Password))
                    {
                        using (var formsAuthService = new FormsAuthenticationService(Context))
                        {
                            string returnUrl;

                            formsAuthService.SignIn(user.UserName, rememberMe.Checked, user.Id.ToString(), out returnUrl);

                            if (!File.Exists(user.ProfileImage64Url) || !File.Exists(user.ProfileImage64Url) || !File.Exists(user.ProfileImage128Url))
                            {
                                UserService.SetProfilePicture(user, Image.FromFile(Server.MapPath("~/Content/images/default_profile.jpg")));
                                UserService.CommitChanges();
                            }

                            Response.Redirect(returnUrl);
                        }
                    }
                }
                catch (Exception exception)
                {
                    //handle exception
                    this.message.InnerText = GenericErrorMessage;
                    this.message.Visible   = true;
                }

                if (!SecurityContext.IsAuthenticated)
                {
                    this.message.InnerText = "Utilizatorul sau parola sunt gresite!";
                    this.message.Visible   = true;
                    this.password.Text     = string.Empty;
                }
            }
            else
            {
                Response.RedirectToRoute("Auth", new { action = "signin" });
            }
        }
示例#10
0
        public ActionResult LogOn(LogonViewModel model)
        {
            if (ModelState.IsValid)
            {
                IValidationState validationState = memberService.ValidatePassword(model.MemberName, model.Password);

                if (!validationState.IsValid)
                {
                    ModelState.MergeError(validationState);
                }
                else
                {
                    FormsAuthenticationService.SignIn(model.MemberName, model.RememberMe);
                    return(RedirectToAction("Index", "Home"));
                }
            }

            return(View(model));
        }
示例#11
0
        public ActionResult OpenIdConfirm(RegisterOpenId openId)
        {
            UsersModels user = new UsersModels();

            user.CreateNewUser(openId.ClaimedOpenId, openId.FriendlyOpenId, openId.Email);

            FormsAuthenticationService formAuth = new FormsAuthenticationService();

            formAuth.SignIn(openId.ClaimedOpenId, false);

            if (!string.IsNullOrEmpty(openId.ReturnUrl))
            {
                return(Redirect(openId.ReturnUrl));
            }
            else
            {
                return(RedirectToAction("Index", "Home"));
            }
        }
示例#12
0
        public HttpResponseMessage Post(User user)
        {
            var response = new HttpResponseMessage();

            if (user != null && authService.Authorize(user.UserName, user.Password))
            {
                //user has been authorized
                response.StatusCode = HttpStatusCode.OK;
                formsAuthService.SignIn(user.UserName, true);

                return(response);
            }

            //if we come this far, it means that user hasn't been authorized
            response.StatusCode = HttpStatusCode.Unauthorized;
            response.Content    = new StringContent("The user hasn't been authorized.");

            return(response);
        }
示例#13
0
        public HttpResponseMessage Post(User user)
        {
            var response   = new HttpResponseMessage();
            var authResult = authService.Authorize(user.UserName, user.Password);

            if (user != null && authResult.Item1)
            {
                //user has been authorized
                response.StatusCode = HttpStatusCode.OK;
                formsAuthService.SignIn(
                    user.UserName,
                    true,
                    authResult.Item2.Roles.Select(x => x.Name).ToArray());

                return(response);
            }

            //if we come this far, it means that user hasn't been authorized
            response.StatusCode = HttpStatusCode.Unauthorized;

            return(response);
        }
示例#14
0
        public ActionResult Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                Guid             memberId;
                IValidationState memberValidationState = memberService.CreateMember(model.MemberName, model.Password, out memberId);
                userService.CreateUser(new Models.User()
                {
                    Id = memberId, UserName = model.MemberName
                });
                if (!memberValidationState.IsValid)
                {
                    ModelState.MergeError(memberValidationState);
                }
                else
                {
                    FormsAuthenticationService.SignIn(model.MemberName, false);
                    return(RedirectToAction("Index", "Home"));
                }
            }

            return(View(model));
        }
示例#15
0
        public ActionResult Index(UserViewModel model, String vcode)
        {
            String  message = String.Empty;
            Boolean result  = false;

            if (false)
            {
                if (Session["vcode"] == null)
                {
                    message       = "验证码过期";
                    model.Message = message;
                    model.UserPwd = String.Empty;
                    return(View("Index", model));
                }

                if (Session["vcode"].ToString() != vcode)
                {
                    message       = "验证码错误";
                    model.Message = message;
                    model.UserPwd = String.Empty;
                    return(View("Index", model));
                }
            }

            if (String.IsNullOrEmpty(model.UserAccount) || String.IsNullOrEmpty(model.UserPwd))
            {
                message       = "请输入账号、密码!";
                model.Message = message;
                model.UserPwd = String.Empty;
                return(View("Index", model));
            }

            var loginUserByDB = GetUser(model.UserAccount, model.UserPwd);

            if (loginUserByDB == null)
            {
                message       = "请输入正确的账号、密码!";
                model.Message = message;
                model.UserPwd = String.Empty;
                return(View("Index", model));
            }

            if (loginUserByDB.Status != 0)
            {
                message       = "您的帐号已被锁定,请联系管理员!";
                model.Message = message;
                model.UserPwd = String.Empty;
                return(View("Index", model));
            }

            var loginUser = ModelConvert(loginUserByDB);
            var loginIp   = Request.UserHostAddress;

            UpdateLoginInfo(loginUserByDB, loginIp);
            FormsAuthenticationService.SignIn(loginUser);

            //日志记录
            DataAccessBLL.Insert(new UserOperationLog
            {
                UserID          = loginUser.UserID,
                UserAccount     = loginUser.UserAccount,
                OperationMothod = "login.Index",
                OperationName   = "系统登录",
                OperationData   = "",
                ReturnData      = String.Empty,
                Crdate          = DateTime.Now
            });

            Session["vcode"] = String.Empty;

            // 登陆成功 判断之前是否访问某个页面 没有就跳转到home
            if (String.IsNullOrEmpty(model.ReturnUrl) || model.ReturnUrl.Trim() == "/")
            {
                return(RedirectToAction("Index", "Home"));
            }
            else
            {
                return(Redirect(model.ReturnUrl));
            }
        }
示例#16
0
        public ActionResult Authenticate(string returnUrl)
        {
            // handle oauth authentication
            if (string.IsNullOrEmpty(Request.Form["openid_identifier"]))
            {
                // handle oauth version 2.0
                if (Request.Form["oauth_version"] == "2.0")
                {
                    return(FacebookAuth(returnUrl));
                }
            }

            var response = openid.GetResponse();

            if (response == null)
            {
                // Stage 2: user submitting Identifier
                Identifier id;
                if (Identifier.TryParse(Request.Form["openid_identifier"], out id))
                {
                    try
                    {
                        var request = openid.CreateRequest(Request.Form["openid_identifier"]);
                        var fetch   = new FetchRequest();
                        fetch.Attributes.AddRequired(WellKnownAttributes.Contact.Email);
                        request.AddExtension(fetch);

                        return(request.RedirectingResponse.AsActionResult());
                    }
                    catch (ProtocolException ex)
                    {
                        ViewData["Message"] = ex.Message;
                        return(View("Logon"));
                    }
                }
                else
                {
                    ViewData["Message"] = "Invalid identifier";
                    return(View("Logon"));
                }
            }
            else
            {
                // Stage 3: OpenID Provider sending assertion response
                switch (response.Status)
                {
                case AuthenticationStatus.Authenticated:

                    UsersModels user = new UsersModels();

                    var    fetch = response.GetExtension <FetchResponse>();
                    string email = null;
                    if (fetch != null)
                    {
                        email = fetch.GetAttributeValue(WellKnownAttributes.Contact.Email);
                    }

                    // for new OpenId
                    user = user.GetUserByOpenId(response.ClaimedIdentifier);
                    if (user == null)
                    {
                        RegisterOpenId roi = new RegisterOpenId();
                        roi.ClaimedOpenId  = response.ClaimedIdentifier;
                        roi.FriendlyOpenId = PostHelper.GetFriendlyOpenId(response, email);
                        roi.ReturnUrl      = returnUrl;
                        roi.Email          = email;
                        return(View(roi));
                    }

                    FormsAuthenticationService formAuth = new FormsAuthenticationService();
                    formAuth.SignIn(response.ClaimedIdentifier, false);

                    if (!string.IsNullOrEmpty(returnUrl))
                    {
                        return(Redirect(returnUrl));
                    }
                    else
                    {
                        return(RedirectToAction("Index", "Home"));
                    }

                case AuthenticationStatus.Canceled:
                    ViewData["Message"] = "Canceled at provider";
                    return(View("Logon"));

                case AuthenticationStatus.Failed:
                    ViewData["Message"] = response.Exception.Message;
                    return(View("Logon"));
                }
            }
            return(new EmptyResult());
        }