Exemple #1
0
        private List <TreeWebViewModel> TransModel(List <TreeViewModel> model)
        {
            var       result = new List <TreeWebViewModel>();
            UrlHelper url    = new UrlHelper(HttpContext.Current.Request.RequestContext);

            foreach (var node in model)
            {
                var newItem = new TreeWebViewModel
                {
                    Name      = node.Name,
                    RouteName = node.Url,
                    Url       = RouteHelper.BaseUrl() + url.Action("Get", "Item", new { routeName = node.Url }),
                    Nodes     = new List <TreeWebViewModel>()
                };

                if (node.Nodes.Any())
                {
                    newItem.Nodes = TransModel(node.Nodes);
                }

                result.Add(newItem);
            }

            return(result);
        }
        public ActionResult FacebookLogin(string url = null)
        {
            //APIKeyEmpty return error
            if (string.IsNullOrEmpty(ApplicationHelper.ApiKey?.FacebookAppId) || string.IsNullOrEmpty(ApplicationHelper.ApiKey?.FacebookAppSecret))
            {
                SetAlertMessage(SystemMessage.FacebookError, AlertType.error);
                return(RedirectToAction("Login", "Member"));
            }

            SessionManager.FBstate   = Guid.NewGuid().ToString();
            SessionManager.ReturnUrl = url;

            // redirect_uri必須和APP裡的一致
            string targetUri = "https://www.facebook.com/v3.1/dialog/oauth?"
                               + "client_id=" + ApplicationHelper.ApiKey.FacebookAppId
                               + "&redirect_uri=" + RouteHelper.BaseUrl() + Url.Action("FacebookLoginCallback", "Member")
                               + "&scope=email"
                               + "&state=" + SessionManager.FBstate;

            return(Redirect(targetUri));
        }
Exemple #3
0
        /// <summary>
        /// 寄送簡訊
        /// </summary>
        /// <param name="userID">user id</param>
        /// <param name="model">Mail內容取代字串</param>
        /// <param name="systemMailType">郵件類型</param>
        /// <param name="validType">驗證碼類型</param>
        /// <param name="structureID">郵件類型structure</param>
        /// <param name="fromFn">來源</param>
        /// <returns></returns>
        public async Task <CiResult> SendSms(Guid userID, ReplaceMailContent model,
                                             SystemMailType systemMailType, ValidType?validType = null, Guid?structureID = null,
                                             string fromFn = "")
        {
            var result = new CiResult <SMSViewModel> {
                IsSuccess = true
            };
            var smsTool = new SmsTool {
            };

            //ReplaceMailContent
            model.WebsiteUrl = RouteHelper.BaseUrl();
            if (string.IsNullOrEmpty(model.PhoneNumber) || !_Check.IsPhone(model.PhoneNumber))
            {
                result.IsSuccess = false;
            }

            //system setting
            if (!ApplicationHelper.ClientSettings.Contains(ClientSetting.SMS))
            {
                result.IsSuccess = false;
                _Log.CreateText($"SendSms no setting");
            }

            //get setting
            if (result.IsSuccess)
            {
                var smsResult = settingService.Get <SmsServiceViewModel>(SystemSettingType.SmsService);
                smsTool.setting = smsResult.Data;
                if (!smsResult.IsSuccess || !smsResult.Data.IsEnabled)
                {
                    result.IsSuccess = false;
                }
            }

            if (result.IsSuccess)
            {
                var siteResult = settingService.Get <SiteInfoViewModel>(SystemSettingType.SiteInfo);
                if (siteResult.IsSuccess)
                {
                    model.WebsiteName = siteResult.Data.SiteName;
                }
                else
                {
                    result.IsSuccess = false;
                }
            }

            //create validCode
            if (result.IsSuccess && validType != null)
            {
                var validCodeResult = userService.CreateValidCode(userID, validType.Value, length: 5);
                if (validCodeResult.IsSuccess)
                {
                    model.ValidCode = validCodeResult.Data;
                }
                else
                {
                    result.IsSuccess = false;
                }
            }

            //get template
            var template = new cms_EmailTemplate();

            if (result.IsSuccess)
            {
                template = templateService.GetByType(systemMailType, structureID);
                if (template != null)
                {
                    // set template
                    smsTool.message = model.ReplaceContent(template.SMSContent);
                }
                else
                {
                    result.IsSuccess = false;
                    _Log.CreateText($"SendSms no template: {systemMailType.ToString()}");
                }
            }

            //send mail (測試中不寄簡訊)
            if (result.IsSuccess)
            {
                if (ApplicationHelper.IsLocal)
                {
                    _Log.CreateText($"Local not send SMS: {model.PhoneNumber} >> {smsTool.message}");
                }
                else
                {
                    result = await smsTool.Send(userID, model.PhoneNumber);
                }

                //add log
                var log = new cms_SmsLog
                {
                    PhoneNumber = model.PhoneNumber,
                    SMSContent  = smsTool.message,
                    ToUser      = userID,
                    IsSend      = result.IsSuccess,//是否已發送
                    SendTime    = DateTime.Now,
                    CreateTime  = DateTime.Now,
                };
                if (result.IsSuccess && result.Data != null)
                {
                    log.Msgid            = result.Data.MsgId;
                    log.SmsResultType    = (int)result.Data.ResultType;
                    log.UpdateResultTime = DateTime.Now;
                }
                smsService.CreateLog(log);
            }

            if (result.IsSuccess)
            {
                if (systemMailType == SystemMailType.ConfirmEmail)
                {
                    result.Message = string.Format(SystemMessage.PhoneConfirm, model.PhoneNumber);
                }
                else
                {
                    result.Message = SystemMessage.SendSmsSuccess;
                }
            }
            else if (string.IsNullOrEmpty(result.Message))
            {
                result.Message = SystemMessage.SmsServiceError;
            }

            SessionManager.Captcha = "";

            return(result);
        }
Exemple #4
0
        /// <summary>
        /// 寄送郵件
        /// </summary>
        /// <param name="userID">user id</param>
        /// <param name="model">Mail內容取代字串</param>
        /// <param name="systemMailType">郵件類型</param>
        /// <param name="validType">驗證碼類型</param>
        /// <param name="structureID">郵件類型structure</param>
        /// <param name="fromFn">來源</param>
        /// <returns></returns>
        public async Task <CiResult> SendEmail(Guid userID, ReplaceMailContent model,
                                               SystemMailType systemMailType, ValidType?validType = null, Guid?structureID = null,
                                               string fromFn = "")
        {
            var result = new CiResult {
                IsSuccess = true
            };
            var mailTool = new MailTool {
                email = model.UserEmail
            };

            //ReplaceMailContent
            model.WebsiteUrl = RouteHelper.BaseUrl();
            if (string.IsNullOrEmpty(model.UserName) || string.IsNullOrEmpty(model.UserEmail) || !_Check.IsEmail(model.UserEmail))
            {
                result.IsSuccess = false;
            }

            //get setting
            if (result.IsSuccess)
            {
                var smtpResult = settingService.Get <SmtpServerViewModel>(SystemSettingType.SmtpServer);
                mailTool.setting = smtpResult.Data;
                if (!smtpResult.IsSuccess || !smtpResult.Data.IsEnabled)
                {
                    result.IsSuccess = false;
                }
            }

            if (result.IsSuccess)
            {
                var siteResult = settingService.Get <SiteInfoViewModel>(SystemSettingType.SiteInfo);
                if (siteResult.IsSuccess)
                {
                    model.WebsiteName = siteResult.Data.SiteName;
                }
                else
                {
                    result.IsSuccess = false;
                }
            }

            //create validCode
            if (result.IsSuccess && validType != null)
            {
                var validCodeResult = userService.CreateValidCode(userID, validType.Value);
                if (validCodeResult.IsSuccess)
                {
                    model.ConfirmUrl = RouteHelper.GetConfirmUrl(validType.Value, validCodeResult.Data, model.UserEmail);
                }
                else
                {
                    result.IsSuccess = false;
                }
            }

            //get template
            var template = new cms_EmailTemplate();

            if (result.IsSuccess)
            {
                template = templateService.GetByType(systemMailType, structureID);
                if (template != null)
                {
                    // ckeditor
                    template.Content = HttpUtility.HtmlDecode(template.Content);

                    // set template
                    mailTool.subject = model.ReplaceContent(template.Subject);
                    mailTool.content = model.ReplaceContent(template.Content);
                    if (!string.IsNullOrEmpty(template.TemplateBcc))
                    {
                        mailTool.bccReceiver = template.TemplateBcc.Split(',');
                    }
                }
                else
                {
                    result.IsSuccess = false;
                    _Log.CreateText($"SendEmail no template: {systemMailType.ToString()}");
                }
            }

            //send mail (測試中:只能寄給開發者)
            if (result.IsSuccess)
            {
                if (!ApplicationHelper.IsLocal || (ApplicationHelper.IsLocal && mailTool.IsTestingMail(model.UserEmail)))
                {
                    result.IsSuccess = await mailTool.SendAsync(fromFn);
                }
                else
                {
                    _Log.CreateText($"Local not send: {mailTool.email}");
                }

                //add log
                emailService.CreateLog(new EmailViewModel
                {
                    Email = new cms_Email
                    {
                        Subject        = mailTool.subject,
                        Content        = mailTool.content,
                        SystemMailType = (int)systemMailType,
                        Status         = (int)MailStatus.Done,
                        SendTime       = DateTime.Now
                    },
                    SendUsers = new List <cms_EmailSendUser> {
                        new cms_EmailSendUser {
                            ToEmail  = model.UserEmail,
                            ToUser   = userID,
                            IsSend   = result.IsSuccess,//是否已發送
                            SendTime = DateTime.Now
                        }
                    }
                });
            }

            if (result.IsSuccess)
            {
                if (systemMailType == SystemMailType.ConfirmEmail)
                {
                    result.Message = string.Format(SystemMessage.EmailConfirm, model.UserEmail);
                }
                else if (systemMailType == SystemMailType.ForgotPassword)
                {
                    result.Message = string.Format(SystemMessage.PasswordReset, model.UserEmail);
                }
                else
                {
                    result.Message = SystemMessage.SendSuccess;
                }
            }
            else if (string.IsNullOrEmpty(result.Message))
            {
                result.Message = SystemMessage.MailServerError;
            }

            SessionManager.Captcha = "";

            return(result);
        }
        public ActionResult FacebookLoginCallback(string state, string code)
        {
            if (string.IsNullOrEmpty(state) || state != SessionManager.FBstate)
            {
                return(ErrorPage());
            }

            string        returnUrl   = SessionManager.ReturnUrl;
            List <string> exceptRoute = new List <string> {
                "FacebookLoginCallback", "Confirm"
            };

            if (exceptRoute.Any(x => returnUrl.Contains(x)))
            {
                returnUrl = "";
            }

            SessionManager.ReturnUrl     = "";
            SessionManager.FBstate       = "";
            SessionManager.ExternalLogin = null;

            string errorMessage = "", successMessage = "";
            var    tokenModel = new FacebookTokenModel();
            var    userModel  = new FacebookUserModel();
            var    loginModel = new LoginViewModel();

            //1.取得access_token
            string url = "https://graph.facebook.com/v3.1/oauth/access_token?"
                         + "client_id=" + ApplicationHelper.ApiKey.FacebookAppId
                         + "&client_secret=" + ApplicationHelper.ApiKey.FacebookAppSecret
                         + "&redirect_uri=" + RouteHelper.BaseUrl() + Url.Action("FacebookLoginCallback", "Member")
                         + "&code=" + code;

            try
            {
                var request  = (HttpWebRequest)WebRequest.Create(url);
                var response = (HttpWebResponse)request.GetResponse();
                var reader   = new StreamReader(response.GetResponseStream());

                string jsonStr = reader.ReadToEnd().ToString();
                tokenModel = _Json.JsonToModel <FacebookTokenModel>(jsonStr);

                reader.Close();
                response.Close();
            }
            catch (Exception)
            {
                errorMessage = "無法取得Facebook存取權";
            }

            //2.取得使用者資訊
            if (string.IsNullOrEmpty(errorMessage))
            {
                try
                {
                    url = "https://graph.facebook.com/me?fields=id,name,email&access_token=" + tokenModel.access_token;

                    var request  = (HttpWebRequest)WebRequest.Create(url);
                    var response = (HttpWebResponse)request.GetResponse();
                    var reader   = new StreamReader(response.GetResponseStream());

                    var jsonStr = reader.ReadToEnd().ToString();
                    userModel = _Json.JsonToModel <FacebookUserModel>(jsonStr);

                    reader.Close();
                    response.Close();
                }
                catch (Exception)
                {
                    errorMessage = "取得Facebook使用者錯誤";
                }
            }

            //3.Login/SignUp
            if (string.IsNullOrEmpty(errorMessage))
            {
                var model = new ExternalLoginViewModel
                {
                    ExternalType = ExternalType.Facebook,
                    ExternalKey  = userModel.id,
                    UserName     = userModel.name,
                    Email        = userModel.email
                };

                //FB新註冊, 一律先到確認頁 > 送出驗證Email
                if (!service.ExistExternalLogin(model))
                {
                    SessionManager.ExternalLogin = model;
                    return(RedirectToAction("SignUp", model));
                }

                //可外部登入
                loginModel = new LoginViewModel
                {
                    Account   = userModel.id,
                    LoginType = LoginType.Facebook
                };
            }

            return(LoginHelper(loginModel, returnUrl, errorMessage, successMessage));
        }