public ActionResult Create([Bind(Include = "Id,Nombre")] Especie especie) { if (ModelState.IsValid) { try { db.Add(especie); TempData["MessageViewBagName"] = new GenericMessageViewModel { Message = "Registro agregado a la base de datos.", // orivle MessageType = GenericMessages.success }; return(RedirectToAction("Index")); } catch (Exception ex) { TempData["MessageViewBagName"] = new GenericMessageViewModel { Message = ex.Message, MessageType = GenericMessages.danger, ConstantMessage = true }; } } return(View(especie)); }
public GenericMessageControl(GenericMessageViewModel viewModel) { InitializeComponent(); this.viewModel = viewModel; this.DataContext = this.viewModel; }
public ActionResult DeleteConfirmed(int id) { try { // TODO: Add insert logic here var result = process.Ver(id); process.Eliminar(result); TempData["MessageViewBagName"] = new GenericMessageViewModel { Message = "Registro eliminado de la base de datos.", // orivle MessageType = GenericMessages.success }; return(RedirectToAction("Index")); } catch (Exception ex) { TempData["MessageViewBagName"] = new GenericMessageViewModel { Message = ex.Message, MessageType = GenericMessages.danger, ConstantMessage = true }; return(View(process.Ver(id))); } }
public ActionResult Edit(Paciente Paciente) { try { // TODO: Add insert logic here process.Editar(Paciente); TempData["MessageViewBagName"] = new GenericMessageViewModel { Message = "Registro actualizado a la base de datos.", // orivle MessageType = GenericMessages.success }; return(RedirectToAction("Index")); } catch (Exception ex) { TempData["MessageViewBagName"] = new GenericMessageViewModel { Message = ex.Message, MessageType = GenericMessages.danger, ConstantMessage = true }; return(View(Paciente)); } }
/// <summary> /// Takes the errors from the Model state and displays them /// </summary> public void ShowMessage() { if (!ModelState.IsValid) { var messageViewModel = new GenericMessageViewModel { MessageType = GenericMessages.Danger }; var sb = new StringBuilder(); // Collate the errors sb.Append("<ul>"); foreach (var modelState in ViewData.ModelState.Values) { foreach (var error in modelState.Errors) { sb.Append($"<li>{error.ErrorMessage}</li>"); } } sb.Append("<ul>"); // Add the message messageViewModel.Message = sb.ToString(); // We have to put it on two because some umbraco redirects only work with ViewData!! ViewData[AppConstants.MessageViewBagName] = messageViewModel; TempData[AppConstants.MessageViewBagName] = messageViewModel; } }
public ActionResult LogOn(LogOnViewModel model) { try { if (ModelState.IsValid) { var message = new GenericMessageViewModel(); var user = new Member(); if (MemberService.Login(model.UserName, model.Password)) { // Set last login date user = MemberService.Get(model.UserName); if (user.IsApproved && !user.IsLockedOut) { if (Url.IsLocalUrl(model.ReturnUrl) && model.ReturnUrl.Length >= 1 && model.ReturnUrl.StartsWith("/") && !model.ReturnUrl.StartsWith("//") && !model.ReturnUrl.StartsWith("/\\")) { return(Redirect(model.ReturnUrl)); } message.Message = Lang("Members.NowLoggedIn"); message.MessageType = GenericMessages.Success; return(RedirectToUmbracoPage(Dialogue.Settings().ForumId)); } } // Only show if we have something to actually show to the user if (!string.IsNullOrEmpty(message.Message)) { ShowMessage(message); } else { if (!user.IsApproved) { ModelState.AddModelError(string.Empty, Lang("Members.Errors.NotApproved")); } else if (user.IsLockedOut) { ModelState.AddModelError(string.Empty, Lang("Members.Errors.LockedOut")); } else { ModelState.AddModelError(string.Empty, Lang("Members.Errors.LogonGeneric")); } } } else { ModelState.AddModelError(string.Empty, Lang("Members.Errors.LogonGeneric")); } } catch (Exception ex) { LogError("Error when user logging in", ex); } return(CurrentUmbracoPage()); }
private void App_MessageRequested(object sender, MessageRequestedEventArgs ea) { var vm = new GenericMessageViewModel(); vm.ActionChecked = ea.ActionChecked; vm.ActionText = ea.ActionText; vm.HasAction = ea.HasAction; vm.MessageId = ea.MessageId; vm.MessageText = ea.MessageText; vm.MessageType = ea.MessageType; ea.Buttons.Select(o => new GenericMessageButton { ButtonText = string.IsNullOrWhiteSpace(o.Text)?null:o.Text, ButtonTip = string.IsNullOrWhiteSpace(o.Tip) ? null :o.Tip, ButtonResult = o.Result }).ToList().ForEach(o => vm.Buttons.Add(o)); var wnd = new Window(); wnd.SizeToContent = SizeToContent.WidthAndHeight; wnd.ResizeMode = ResizeMode.NoResize; wnd.WindowStyle = WindowStyle.None; wnd.Content = vm; wnd.Owner = Application.Current.MainWindow; wnd.WindowStartupLocation = WindowStartupLocation.CenterOwner; vm.CloseWindow = () => wnd.Close(); wnd.ShowDialog(); ea.ActionChecked = vm.ActionChecked; ea.SelectedButtonResult = vm.SelectedButtonResult; }
public ActionResult Create(Cita Cita) { try { // TODO: Add insert logic here Cita.Fecha = this.GetCitas(Cita.Fecha); if (Cita.Fecha.Hour == 0) { throw new Exception("No se puede cargar mas citas durante el dia de hoy!"); } var result = process.Agregar(Cita); TempData["MessageViewBagName"] = new GenericMessageViewModel { Message = "Registro agregado a la base de datos.", // orivle MessageType = GenericMessages.success }; return(RedirectToAction("Index")); } catch (Exception ex) { TempData["MessageViewBagName"] = new GenericMessageViewModel { Message = ex.Message, MessageType = GenericMessages.danger, ConstantMessage = true }; return(View(Cita)); } }
public ActionResult Create(Paciente paciente) { if (ModelState.IsValid) { try { db.Add(paciente); TempData["MessageViewBagName"] = new GenericMessageViewModel { Message = "Registro agregado a la base de datos.", MessageType = GenericMessages.success }; return(RedirectToAction("Index")); } catch (Exception ex) { TempData["MessageViewBagName"] = new GenericMessageViewModel { Message = ex.Message, MessageType = GenericMessages.danger, ConstantMessage = true }; } } return(View(paciente)); }
public ActionResult PrivateMessages(DialoguePage page) { if (CurrentMember.DisablePrivateMessages) { var message = new GenericMessageViewModel { Message = Lang("Errors.NoPermission"), MessageType = GenericMessages.Danger }; ShowMessage(message); return(Redirect(Settings.ForumRootUrl)); } using (UnitOfWorkManager.NewUnitOfWork()) { var pageIndex = AppHelpers.ReturnCurrentPagingNo(); var pagedMessages = ServiceFactory.PrivateMessageService.GetPagedReceivedMessagesByUser(pageIndex, AppConstants.PrivateMessageListSize, CurrentMember); var viewModel = new PageListPrivateMessageViewModel(page) { ListPrivateMessageViewModel = new ListPrivateMessageViewModel { Messages = pagedMessages, PageIndex = pageIndex, TotalCount = pagedMessages.TotalCount }, PageTitle = Lang("PM.ReceivedPrivateMessages") }; return(View(PathHelper.GetThemeViewPath("PrivateMessages"), viewModel)); } }
public ActionResult Create(Especie especie) { try { // TODO: Add insert logic here var result = process.Agregar(especie); TempData["MessageViewBagName"] = new GenericMessageViewModel { Message = "Registro agregado a la base de datos.", // orivle MessageType = GenericMessages.success }; return(RedirectToAction("Index")); } catch (Exception ex) { TempData["MessageViewBagName"] = new GenericMessageViewModel { Message = ex.Message, MessageType = GenericMessages.danger, ConstantMessage = true }; return(View(especie)); } }
protected void ShowMessage(GenericMessageViewModel messageViewModel) { if (TempData[AppConstants.MessageViewBagName] == null) { TempData[AppConstants.MessageViewBagName] = new List <GenericMessageViewModel>(); } ((List <GenericMessageViewModel>)TempData[AppConstants.MessageViewBagName]).Add(messageViewModel); }
public ActionResult ClearLog() { _loggingService.ClearLogFiles(); TempData["MessageViewBagName"] = new GenericMessageViewModel { Message = "Archivo de registro borrado", MessageType = GenericMessages.success }; return(RedirectToAction("Index")); }
public ActionResult NoPermission(Topic topic) { // Trying to be a sneaky mo fo, so tell them var message = new GenericMessageViewModel { Message = Lang("Errors.NoPermission"), MessageType = GenericMessages.Warning }; ShowMessage(message); return(Redirect(topic.Url)); }
public ActionResult DeleteConfirmed(int id) { Operador operador = db.Find(id); db.Remove(operador); TempData["MessageViewBagName"] = new GenericMessageViewModel { Message = "Registro eliminado de la base de datos.", MessageType = GenericMessages.success }; return(RedirectToAction("Index")); }
public ActionResult Edit([Bind(Include = "Id,Apellido,Nombre,Email,Telefono,Url,Edad,Domicilio")] Operador operador) { if (ModelState.IsValid) { db.Edit(operador); TempData["MessageViewBagName"] = new GenericMessageViewModel { Message = "Registro editado en la base de datos.", MessageType = GenericMessages.success }; return(RedirectToAction("Index")); } return(View(operador)); }
public ActionResult Create(Cita cita) { try { var p = new CitaApiProcess(); var existeTurno = p.ToList().Where(x => x.Fecha == cita.Fecha).FirstOrDefault(); if (existeTurno == null) { p.Add(cita); TempData["MessageViewBagName"] = new GenericMessageViewModel { Message = "Registro agregado a la base de datos.", MessageType = GenericMessages.success }; return(RedirectToAction("Index")); } else { TempData["MessageViewBagName"] = new GenericMessageViewModel { Message = "Horario NO disponible", MessageType = GenericMessages.danger, ConstantMessage = true }; return(View(cita)); } } catch (Exception ex) { TempData["MessageViewBagName"] = new GenericMessageViewModel { Message = ex.Message, MessageType = GenericMessages.danger, ConstantMessage = true }; return(View(cita)); } }
public ActionResult KillSpammer() { //Check permission if (User.IsInRole(AppConstants.AdminRoleName) || CurrentMember.CanEditOtherMembers) { using (var unitOfWork = UnitOfWorkManager.NewUnitOfWork()) { var id = Request["id"]; if (id != null) { // Get the member var member = ServiceFactory.MemberService.Get(Convert.ToInt32(id)); // Delete all their posts and votes and delete etc.. var worked = ServiceFactory.MemberService.DeleteAllAssociatedMemberInfo(member.Id, unitOfWork); // SAVE UOW var message = new GenericMessageViewModel { Message = Lang("Member.SpammerIsKilled"), MessageType = GenericMessages.Success }; try { // Clear the website and signature fields and ban them ServiceFactory.MemberService.KillSpammer(member); } catch (Exception ex) { LogError(ex); message.MessageType = GenericMessages.Danger; message.Message = ex.Message; } ShowMessage(message); return(Redirect(member.Url)); } } } return(ErrorToHomePage(Lang("Errors.NoPermission"))); }
public void ShowModelErrors() { var message = new GenericMessageViewModel(); var sb = new StringBuilder(); foreach (var modelState in ViewData.ModelState.Values) { foreach (var error in modelState.Errors) { sb.AppendFormat("<li>{0}</li>", error.ErrorMessage); } } var fullMessage = sb.ToString(); if (!string.IsNullOrEmpty(fullMessage)) { message.Message = string.Concat("<ul>", fullMessage, "</ul>"); message.MessageType = GenericMessages.Danger; ShowMessage(message); } }
public ActionResult Create(Paciente Paciente) { try { // TODO: Add insert logic here var result = process.Agregar(Paciente); TempData["MessageViewBagName"] = new GenericMessageViewModel { Message = "Registro agregado a la base de datos.", // orivle MessageType = GenericMessages.success }; return(RedirectToAction("Index")); } catch (Exception ex) { TempData["MessageViewBagName"] = new GenericMessageViewModel { Message = ex.Message, MessageType = GenericMessages.danger, ConstantMessage = true }; var medicos = Cliprocess.ListarTodos().Select(x => new { Id = x.Id, Nombre = x.Apellido + " " + x.Nombre }); ViewBag.Clientes = new SelectList(medicos, "Id", "Nombre"); var pacientes = Espprocess.ListarTodos() .Select(x => new { Id = x.Id, Nombre = x.Nombre }); ViewBag.Especies = new SelectList(pacientes, "Id", "Nombre"); return(View(Paciente)); } }
public ActionResult SendTestEmail() { using (var uow = UnitOfWorkManager.NewUnitOfWork()) { var sb = new StringBuilder(); sb.AppendFormat("<p>{0}</p>", string.Concat("This is a test email from ", SettingsService.GetSettings().ForumName)); var email = new Email { EmailTo = SettingsService.GetSettings().AdminEmailAddress, NameTo = "Email Test Admin", Subject = string.Concat("Email Test From ", SettingsService.GetSettings().ForumName) }; email.Body = _emailService.EmailTemplate(email.NameTo, sb.ToString()); _emailService.SendMail(email); var message = new GenericMessageViewModel { Message = "Test Email Sent", MessageType = GenericMessages.success }; try { uow.Commit(); } catch (Exception ex) { uow.Rollback(); LoggingService.Error(ex); message.Message = "Error sending email"; message.MessageType = GenericMessages.danger; } TempData[AppConstants.MessageViewBagName] = message; return(RedirectToAction("Index")); } }
public ActionResult Report(ReportPostViewModel viewModel) { if (Settings.EnableSpamReporting) { using (UnitOfWorkManager.NewUnitOfWork()) { var post = ServiceFactory.PostService.Get(viewModel.PostId); // Banned link? if (ServiceFactory.BannedLinkService.ContainsBannedLink(viewModel.Reason)) { ShowMessage(new GenericMessageViewModel { Message = Lang("Errors.BannedLink"), MessageType = GenericMessages.Danger }); return(Redirect(post.Topic.Url)); } var report = new Report { Reason = viewModel.Reason, ReportedPost = post, Reporter = CurrentMember }; ServiceFactory.ReportService.PostReport(report); var message = new GenericMessageViewModel { Message = Lang("Report.ReportSent"), MessageType = GenericMessages.Success }; ShowMessage(message); return(Redirect(post.Topic.Url)); } } return(ErrorToHomePage(Lang("Errors.GenericMessage"))); }
public ActionResult SendTestEmail() { var settings = SettingsService.GetSettings(); var sb = new StringBuilder(); sb.Append($"<p>{string.Concat("This is a test email from ", settings.ForumName)}</p>"); var email = new Email { EmailTo = settings.AdminEmailAddress, NameTo = "Email Test Admin", Subject = string.Concat("Email Test From ", settings.ForumName) }; email.Body = _emailService.EmailTemplate(email.NameTo, sb.ToString()); _emailService.SendMail(email); var message = new GenericMessageViewModel { Message = "Test Email Sent", MessageType = GenericMessages.success }; try { Context.SaveChanges(); } catch (Exception ex) { Context.RollBack(); LoggingService.Error(ex); message.Message = "Error sending email"; message.MessageType = GenericMessages.danger; } TempData[AppConstants.MessageViewBagName] = message; return(RedirectToAction("Index")); }
public ActionResult Create(Cliente cliente) { try { var p = new ClienteApiProcess(); p.Add(cliente); TempData["MessageViewBagName"] = new GenericMessageViewModel { Message = "Registro agregado a la base de datos.", MessageType = GenericMessages.success }; return(RedirectToAction("Index")); } catch (Exception ex) { TempData["MessageViewBagName"] = new GenericMessageViewModel { Message = ex.Message, MessageType = GenericMessages.danger, ConstantMessage = true }; } return(View(cliente)); }
public ActionResult Index() { IList <LogEntry> logs = new List <LogEntry>(); try { logs = _loggingService.ListLogFile(); } catch (Exception ex) { var err = $"No se puede acceder a los registros: {ex.Message}"; TempData["MessageViewBagName"] = new GenericMessageViewModel { Message = err, MessageType = GenericMessages.danger }; _loggingService.Error(err); } return(View(new ListLogViewModel { LogFiles = logs })); }
public ActionResult UnBanMember() { //Check permission if (User.IsInRole(AppConstants.AdminRoleName) || CurrentMember.CanEditOtherMembers) { using (UnitOfWorkManager.NewUnitOfWork()) { var id = Request["id"]; if (id != null) { // Get the member var member = ServiceFactory.MemberService.Get(Convert.ToInt32(id)); var message = new GenericMessageViewModel { Message = Lang("Member.IsUnBanned"), MessageType = GenericMessages.Success }; try { ServiceFactory.MemberService.UnBanMember(member); } catch (Exception ex) { LogError(ex); message.MessageType = GenericMessages.Danger; message.Message = ex.Message; } ShowMessage(message); return(Redirect(member.Url)); } } } return(ErrorToHomePage(Lang("Errors.NoPermission"))); }
public ActionResult LogOn(LogOnViewModel model) { using (var unitOfWork = UnitOfWorkManager.NewUnitOfWork()) { var username = model.UserName; var password = model.Password; try { if (ModelState.IsValid) { // We have an event here to help with Single Sign Ons // You can do manual lookups to check users based on a webservice and validate a user // Then log them in if they exist or create them and log them in - Have passed in a UnitOfWork // To allow database changes. var e = new LoginEventArgs { UserName = model.UserName, Password = model.Password, RememberMe = model.RememberMe, ReturnUrl = model.ReturnUrl, UnitOfWork = unitOfWork }; EventManager.Instance.FireBeforeLogin(this, e); if (!e.Cancel) { var message = new GenericMessageViewModel(); var user = new MembershipUser(); if (MembershipService.ValidateUser(username, password, Membership.MaxInvalidPasswordAttempts)) { // Set last login date user = MembershipService.GetUser(username); if (user.IsApproved && !user.IsLockedOut && !user.IsBanned) { FormsAuthentication.SetAuthCookie(username, model.RememberMe); user.LastLoginDate = DateTime.UtcNow; if (Url.IsLocalUrl(model.ReturnUrl) && model.ReturnUrl.Length > 1 && model.ReturnUrl.StartsWith("/") && !model.ReturnUrl.StartsWith("//") && !model.ReturnUrl.StartsWith("/\\")) { return Redirect(model.ReturnUrl); } message.Message = LocalizationService.GetResourceString("Members.NowLoggedIn"); message.MessageType = GenericMessages.success; EventManager.Instance.FireAfterLogin(this, new LoginEventArgs { UserName = model.UserName, Password = model.Password, RememberMe = model.RememberMe, ReturnUrl = model.ReturnUrl, UnitOfWork = unitOfWork }); return RedirectToAction("Index", "Home", new { area = string.Empty }); } //else if (!user.IsApproved && SettingsService.GetSettings().ManuallyAuthoriseNewMembers) //{ // message.Message = LocalizationService.GetResourceString("Members.NowRegisteredNeedApproval"); // message.MessageType = GenericMessages.success; //} //else if (!user.IsApproved && SettingsService.GetSettings().NewMemberEmailConfirmation == true) //{ // message.Message = LocalizationService.GetResourceString("Members.MemberEmailAuthorisationNeeded"); // message.MessageType = GenericMessages.success; //} } // Only show if we have something to actually show to the user if (!string.IsNullOrEmpty(message.Message)) { TempData[AppConstants.MessageViewBagName] = message; } else { // get here Login failed, check the login status var loginStatus = MembershipService.LastLoginStatus; switch (loginStatus) { case LoginAttemptStatus.UserNotFound: case LoginAttemptStatus.PasswordIncorrect: ModelState.AddModelError(string.Empty, LocalizationService.GetResourceString("Members.Errors.PasswordIncorrect")); break; case LoginAttemptStatus.PasswordAttemptsExceeded: ModelState.AddModelError(string.Empty, LocalizationService.GetResourceString("Members.Errors.PasswordAttemptsExceeded")); break; case LoginAttemptStatus.UserLockedOut: ModelState.AddModelError(string.Empty, LocalizationService.GetResourceString("Members.Errors.UserLockedOut")); break; case LoginAttemptStatus.Banned: ModelState.AddModelError(string.Empty, LocalizationService.GetResourceString("Members.NowBanned")); break; case LoginAttemptStatus.UserNotApproved: ModelState.AddModelError(string.Empty, LocalizationService.GetResourceString("Members.Errors.UserNotApproved")); user = MembershipService.GetUser(username); SendEmailConfirmationEmail(user); break; default: ModelState.AddModelError(string.Empty, LocalizationService.GetResourceString("Members.Errors.LogonGeneric")); break; } } } } } finally { try { unitOfWork.Commit(); } catch (Exception ex) { unitOfWork.Rollback(); LoggingService.Error(ex); } } return View(model); } }
public ActionResult GoogleLogin() { var resultMessage = new GenericMessageViewModel(); Callback = Request.QueryString["callback"]; ContentTypeAlias = Request.QueryString["contentTypeAlias"]; PropertyAlias = Request.QueryString["propertyAlias"]; Feature = Request.QueryString["feature"]; if (AuthState != null) { var stateValue = Session["MVCForum_" + AuthState] as NameValueCollection; if (stateValue != null) { Callback = stateValue["Callback"]; ContentTypeAlias = stateValue["ContentTypeAlias"]; PropertyAlias = stateValue["PropertyAlias"]; Feature = stateValue["Feature"]; } } if (string.IsNullOrEmpty(SiteConstants.Instance.GooglePlusAppId) || string.IsNullOrEmpty(SiteConstants.Instance.GooglePlusAppSecret)) { resultMessage.Message = "You need to add the Google app credentials"; resultMessage.MessageType = GenericMessages.danger; } else { // Configure the OAuth client based on the options of the prevalue options var client = new GoogleOAuthClient { ClientId = SiteConstants.Instance.GooglePlusAppId, ClientSecret = SiteConstants.Instance.GooglePlusAppSecret, RedirectUri = ReturnUrl }; // Session expired? if (AuthState != null && Session["MVCForum_" + AuthState] == null) { resultMessage.Message = "Session Expired"; resultMessage.MessageType = GenericMessages.danger; } // Check whether an error response was received from Google if (AuthError != null) { resultMessage.Message = AuthErrorDescription; resultMessage.MessageType = GenericMessages.danger; if (AuthState != null) Session.Remove("MVCForum_" + AuthState); } // Redirect the user to the Google login dialog if (AuthCode == null) { // Generate a new unique/random state var state = Guid.NewGuid().ToString(); // Save the state in the current user session Session["MVCForum_" + state] = new NameValueCollection { { "Callback", Callback}, { "ContentTypeAlias", ContentTypeAlias}, { "PropertyAlias", PropertyAlias}, { "Feature", Feature} }; // Declare the scope var scope = new[] { GoogleScopes.OpenId, GoogleScopes.Email, GoogleScopes.Profile }; // Construct the authorization URL var url = client.GetAuthorizationUrl(state, scope, GoogleAccessType.Offline, GoogleApprovalPrompt.Force); // Redirect the user return Redirect(url); } var info = new GoogleAccessTokenResponse(); try { info = client.GetAccessTokenFromAuthorizationCode(AuthCode); } catch (Exception ex) { resultMessage.Message = $"Unable to acquire access token<br/>{ex.Message}"; resultMessage.MessageType = GenericMessages.danger; } try { // Initialize the Google service var service = GoogleService.CreateFromRefreshToken(client.ClientIdFull, client.ClientSecret, info.RefreshToken); // Get information about the authenticated user var user = service.GetUserInfo(); using (UnitOfWorkManager.NewUnitOfWork()) { var userExists = MembershipService.GetUserByEmail(user.Email); if (userExists != null) { // Users already exists, so log them in FormsAuthentication.SetAuthCookie(userExists.UserName, true); resultMessage.Message = LocalizationService.GetResourceString("Members.NowLoggedIn"); resultMessage.MessageType = GenericMessages.success; ShowMessage(resultMessage); return RedirectToAction("Index", "Home"); } else { // Not registered already so register them var viewModel = new MemberAddViewModel { Email = user.Email, LoginType = LoginType.Google, Password = StringUtils.RandomString(8), UserName = user.Name, SocialProfileImageUrl = user.Picture, UserAccessToken = info.RefreshToken }; // Store the viewModel in TempData - Which we'll use in the register logic TempData[AppConstants.MemberRegisterViewModel] = viewModel; return RedirectToAction("SocialLoginValidator", "Members"); } } } catch (Exception ex) { resultMessage.Message = $"Unable to get user information<br/>{ex.Message}"; resultMessage.MessageType = GenericMessages.danger; LoggingService.Error(ex); } } ShowMessage(resultMessage); return RedirectToAction("LogOn", "Members"); }
public ActionResult MicrosoftLogin() { var resultMessage = new GenericMessageViewModel(); var input = new { Code = AuthCode, State = AuthState, Error = new { HasError = !String.IsNullOrWhiteSpace(AuthError), Text = AuthError, ErrorDescription = AuthErrorDescription } }; // Get the prevalue options if (string.IsNullOrEmpty(SiteConstants.Instance.MicrosoftAppId) || string.IsNullOrEmpty(SiteConstants.Instance.MicrosoftAppSecret)) { resultMessage.Message = "You need to add the Microsoft app credentials to the web.config"; resultMessage.MessageType = GenericMessages.danger; } else { var client = new MicrosoftOAuthClient { ClientId = SiteConstants.Instance.MicrosoftAppId, ClientSecret = SiteConstants.Instance.MicrosoftAppSecret, RedirectUri = ReturnUrl }; // Session expired? if (input.State != null && Session["MVCForum_" + input.State] == null) { resultMessage.Message = "Session Expired"; resultMessage.MessageType = GenericMessages.danger; } // Check whether an error response was received from Microsoft if (input.Error.HasError) { Session.Remove("MVCForum_" + input.State); resultMessage.Message = AuthErrorDescription; resultMessage.MessageType = GenericMessages.danger; } // Redirect the user to the Microsoft login dialog if (string.IsNullOrWhiteSpace(input.Code)) { // Generate a new unique/random state var state = Guid.NewGuid().ToString(); // Save the state in the current user session Session["MVCForum_" + state] = "/"; // Construct the authorization URL var url = client.GetAuthorizationUrl(state, WindowsLiveScopes.Emails + WindowsLiveScopes.Birthday); // Redirect the user return Redirect(url); } // Exchange the authorization code for an access token MicrosoftTokenResponse accessTokenResponse; try { Session.Remove("MVCForum_" + input.State); accessTokenResponse = client.GetAccessTokenFromAuthCode(input.Code); } catch (Exception ex) { accessTokenResponse = null; resultMessage.Message = $"Unable to acquire access token<br/>{ex.Message}"; resultMessage.MessageType = GenericMessages.danger; } try { if (string.IsNullOrEmpty(resultMessage.Message) || accessTokenResponse != null) { //MicrosoftScope debug = accessTokenResponse.Body.Scope.Items; //accessTokenResponse.Body.AccessToken //foreach (MicrosoftScope scope in accessTokenResponse.Body.Scope.Items) { // scope //} //accessTokenResponse.Response.Body // Initialize a new MicrosoftService so we can make calls to the API var service = MicrosoftService.CreateFromAccessToken(accessTokenResponse.Body.AccessToken); // Make the call to the Windows Live API / endpoint var response = service.WindowsLive.GetSelf(); // Get a reference to the response body var user = response.Body; var getEmail = !string.IsNullOrWhiteSpace(user.Emails?.Preferred); if (!getEmail) { resultMessage.Message = LocalizationService.GetResourceString("Members.UnableToGetEmailAddress"); resultMessage.MessageType = GenericMessages.danger; ShowMessage(resultMessage); return RedirectToAction("LogOn", "Members"); } using (UnitOfWorkManager.NewUnitOfWork()) { var userExists = MembershipService.GetUserByEmail(user.Emails.Preferred); if (userExists != null) { try { // Users already exists, so log them in FormsAuthentication.SetAuthCookie(userExists.UserName, true); resultMessage.Message = LocalizationService.GetResourceString("Members.NowLoggedIn"); resultMessage.MessageType = GenericMessages.success; ShowMessage(resultMessage); return RedirectToAction("Index", "Home"); } catch (Exception ex) { LoggingService.Error(ex); } } else { // Not registered already so register them var viewModel = new MemberAddViewModel { Email = user.Emails.Preferred, LoginType = LoginType.Microsoft, Password = StringUtils.RandomString(8), UserName = user.Name, UserAccessToken = accessTokenResponse.Body.AccessToken, SocialProfileImageUrl = $"https://apis.live.net/v5.0/{user.Id}/picture" }; //var uri = string.Concat("https://apis.live.net/v5.0/me?access_token=",viewModel.UserAccessToken); //using (var dl = new WebClient()) //{ // var profile = JObject.Parse(dl.DownloadString(uri)); // var pictureUrl = ; // if (!string.IsNullOrEmpty(pictureUrl)) // { // //viewModel.SocialProfileImageUrl = getImageUrl; // } //} // Store the viewModel in TempData - Which we'll use in the register logic TempData[AppConstants.MemberRegisterViewModel] = viewModel; return RedirectToAction("SocialLoginValidator", "Members"); } } } else { resultMessage.MessageType = GenericMessages.danger; ShowMessage(resultMessage); return RedirectToAction("LogOn", "Members"); } } catch (Exception ex) { resultMessage.Message = $"Unable to get user information<br/>{ex.Message}"; resultMessage.MessageType = GenericMessages.danger; LoggingService.Error(ex); } } ShowMessage(resultMessage); return RedirectToAction("LogOn", "Members"); }
public ActionResult FacebookLogin() { var resultMessage = new GenericMessageViewModel(); Callback = Request.QueryString["callback"]; ContentTypeAlias = Request.QueryString["contentTypeAlias"]; PropertyAlias = Request.QueryString["propertyAlias"]; if (AuthState != null) { var stateValue = Session["MVCForum_" + AuthState] as string[]; if (stateValue != null && stateValue.Length == 3) { Callback = stateValue[0]; ContentTypeAlias = stateValue[1]; PropertyAlias = stateValue[2]; } } // Get the prevalue options if (string.IsNullOrEmpty(SiteConstants.Instance.FacebookAppId) || string.IsNullOrEmpty(SiteConstants.Instance.FacebookAppSecret)) { resultMessage.Message = "You need to add the Facebook app credentials"; resultMessage.MessageType = GenericMessages.danger; } else { // Settings valid move on // Configure the OAuth client based on the options of the prevalue options var client = new FacebookOAuthClient { AppId = SiteConstants.Instance.FacebookAppId, AppSecret = SiteConstants.Instance.FacebookAppSecret, RedirectUri = ReturnUrl }; // Session expired? if (AuthState != null && Session["MVCForum_" + AuthState] == null) { resultMessage.Message = "Session Expired"; resultMessage.MessageType = GenericMessages.danger; } // Check whether an error response was received from Facebook if (AuthError != null) { Session.Remove("MVCForum_" + AuthState); resultMessage.Message = AuthErrorDescription; resultMessage.MessageType = GenericMessages.danger; } // Redirect the user to the Facebook login dialog if (AuthCode == null) { // Generate a new unique/random state var state = Guid.NewGuid().ToString(); // Save the state in the current user session Session["MVCForum_" + state] = new[] { Callback, ContentTypeAlias, PropertyAlias }; // Construct the authorization URL var url = client.GetAuthorizationUrl(state, "public_profile", "email"); //"user_friends" // Redirect the user return Redirect(url); } // Exchange the authorization code for a user access token var userAccessToken = string.Empty; try { userAccessToken = client.GetAccessTokenFromAuthCode(AuthCode); } catch (Exception ex) { resultMessage.Message = $"Unable to acquire access token<br/>{ex.Message}"; resultMessage.MessageType = GenericMessages.danger; } try { if (string.IsNullOrEmpty(resultMessage.Message)) { // Initialize the Facebook service (no calls are made here) var service = FacebookService.CreateFromAccessToken(userAccessToken); // Declare the options for the call to the API var options = new FacebookGetUserOptions { Identifier = "me", Fields = new[] { "id", "name", "email", "first_name", "last_name", "gender" } }; var user = service.Users.GetUser(options); // Try to get the email - Some FB accounts have protected passwords var email = user.Body.Email; if (string.IsNullOrEmpty(email)) { resultMessage.Message = LocalizationService.GetResourceString("Members.UnableToGetEmailAddress"); resultMessage.MessageType = GenericMessages.danger; ShowMessage(resultMessage); return RedirectToAction("LogOn", "Members"); } // First see if this user has registered already - Use email address using (UnitOfWorkManager.NewUnitOfWork()) { var userExists = MembershipService.GetUserByEmail(email); if (userExists != null) { try { // Users already exists, so log them in FormsAuthentication.SetAuthCookie(userExists.UserName, true); resultMessage.Message = LocalizationService.GetResourceString("Members.NowLoggedIn"); resultMessage.MessageType = GenericMessages.success; ShowMessage(resultMessage); return RedirectToAction("Index", "Home"); } catch (Exception ex) { LoggingService.Error(ex); } } else { // Not registered already so register them var viewModel = new MemberAddViewModel { Email = email, LoginType = LoginType.Facebook, Password = StringUtils.RandomString(8), UserName = user.Body.Name, UserAccessToken = userAccessToken }; // Get the image and save it var getImageUrl = $"http://graph.facebook.com/{user.Body.Id}/picture?type=square"; viewModel.SocialProfileImageUrl = getImageUrl; //Large size photo https://graph.facebook.com/{facebookId}/picture?type=large //Medium size photo https://graph.facebook.com/{facebookId}/picture?type=normal //Small size photo https://graph.facebook.com/{facebookId}/picture?type=small //Square photo https://graph.facebook.com/{facebookId}/picture?type=square // Store the viewModel in TempData - Which we'll use in the register logic TempData[AppConstants.MemberRegisterViewModel] = viewModel; return RedirectToAction("SocialLoginValidator", "Members"); } } } } catch (Exception ex) { resultMessage.Message = $"Unable to get user information<br/>{ex.Message}"; resultMessage.MessageType = GenericMessages.danger; LoggingService.Error(ex); } } ShowMessage(resultMessage); return RedirectToAction("LogOn", "Members"); }
public ActionResult MicrosoftLogin() { var resultMessage = new GenericMessageViewModel(); var input = new { Code = AuthCode, State = AuthState, Error = new { HasError = !String.IsNullOrWhiteSpace(AuthError), Text = AuthError, ErrorDescription = AuthErrorDescription } }; // Get the prevalue options if (string.IsNullOrEmpty(SiteConstants.Instance.MicrosoftAppId) || string.IsNullOrEmpty(SiteConstants.Instance.MicrosoftAppSecret)) { resultMessage.Message = "You need to add the Microsoft app credentials to the web.config"; resultMessage.MessageType = GenericMessages.danger; } else { var client = new MicrosoftOAuthClient { ClientId = SiteConstants.Instance.MicrosoftAppId, ClientSecret = SiteConstants.Instance.MicrosoftAppSecret, RedirectUri = ReturnUrl }; // Session expired? if (input.State != null && Session["MVCForum_" + input.State] == null) { resultMessage.Message = "Session Expired"; resultMessage.MessageType = GenericMessages.danger; } // Check whether an error response was received from Microsoft if (input.Error.HasError) { Session.Remove("MVCForum_" + input.State); resultMessage.Message = AuthErrorDescription; resultMessage.MessageType = GenericMessages.danger; } // Redirect the user to the Microsoft login dialog if (string.IsNullOrWhiteSpace(input.Code)) { // Generate a new unique/random state var state = Guid.NewGuid().ToString(); // Save the state in the current user session Session["MVCForum_" + state] = "/"; // Construct the authorization URL var url = client.GetAuthorizationUrl(state, WindowsLiveScopes.Emails + WindowsLiveScopes.Birthday); // Redirect the user return(Redirect(url)); } // Exchange the authorization code for an access token MicrosoftTokenResponse accessTokenResponse; try { Session.Remove("MVCForum_" + input.State); accessTokenResponse = client.GetAccessTokenFromAuthCode(input.Code); } catch (Exception ex) { accessTokenResponse = null; resultMessage.Message = $"Unable to acquire access token<br/>{ex.Message}"; resultMessage.MessageType = GenericMessages.danger; } try { if (string.IsNullOrEmpty(resultMessage.Message) || accessTokenResponse != null) { //MicrosoftScope debug = accessTokenResponse.Body.Scope.Items; //accessTokenResponse.Body.AccessToken //foreach (MicrosoftScope scope in accessTokenResponse.Body.Scope.Items) { // scope //} //accessTokenResponse.Response.Body // Initialize a new MicrosoftService so we can make calls to the API var service = MicrosoftService.CreateFromAccessToken(accessTokenResponse.Body.AccessToken); // Make the call to the Windows Live API / endpoint var response = service.WindowsLive.GetSelf(); // Get a reference to the response body var user = response.Body; var getEmail = !string.IsNullOrWhiteSpace(user.Emails?.Preferred); if (!getEmail) { resultMessage.Message = LocalizationService.GetResourceString("Members.UnableToGetEmailAddress"); resultMessage.MessageType = GenericMessages.danger; ShowMessage(resultMessage); return(RedirectToAction("LogOn", "Members")); } using (UnitOfWorkManager.NewUnitOfWork()) { var userExists = MembershipService.GetUserByEmail(user.Emails.Preferred); if (userExists != null) { try { // Users already exists, so log them in FormsAuthentication.SetAuthCookie(userExists.UserName, true); resultMessage.Message = LocalizationService.GetResourceString("Members.NowLoggedIn"); resultMessage.MessageType = GenericMessages.success; ShowMessage(resultMessage); return(RedirectToAction("Index", "Home")); } catch (Exception ex) { LoggingService.Error(ex); } } else { // Not registered already so register them var viewModel = new MemberAddViewModel { Email = user.Emails.Preferred, LoginType = LoginType.Microsoft, Password = StringUtils.RandomString(8), UserName = user.Name, UserAccessToken = accessTokenResponse.Body.AccessToken, SocialProfileImageUrl = $"https://apis.live.net/v5.0/{user.Id}/picture" }; //var uri = string.Concat("https://apis.live.net/v5.0/me?access_token=",viewModel.UserAccessToken); //using (var dl = new WebClient()) //{ // var profile = JObject.Parse(dl.DownloadString(uri)); // var pictureUrl = ; // if (!string.IsNullOrEmpty(pictureUrl)) // { // //viewModel.SocialProfileImageUrl = getImageUrl; // } //} // Store the viewModel in TempData - Which we'll use in the register logic TempData[AppConstants.MemberRegisterViewModel] = viewModel; return(RedirectToAction("SocialLoginValidator", "Members")); } } } else { resultMessage.MessageType = GenericMessages.danger; ShowMessage(resultMessage); return(RedirectToAction("LogOn", "Members")); } } catch (Exception ex) { resultMessage.Message = $"Unable to get user information<br/>{ex.Message}"; resultMessage.MessageType = GenericMessages.danger; LoggingService.Error(ex); } } ShowMessage(resultMessage); return(RedirectToAction("LogOn", "Members")); }
public void ShowMessage(GenericMessageViewModel messageViewModel) { // We have to put it on two because some umbraco redirects only work with ViewData!! ViewData[AppConstants.MessageViewBagName] = messageViewModel; TempData[AppConstants.MessageViewBagName] = messageViewModel; }
public ActionResult GoogleLogin() { var resultMessage = new GenericMessageViewModel(); Callback = Request.QueryString["callback"]; ContentTypeAlias = Request.QueryString["contentTypeAlias"]; PropertyAlias = Request.QueryString["propertyAlias"]; Feature = Request.QueryString["feature"]; if (AuthState != null) { var stateValue = Session["Dialogue_" + AuthState] as NameValueCollection; if (stateValue != null) { Callback = stateValue["Callback"]; ContentTypeAlias = stateValue["ContentTypeAlias"]; PropertyAlias = stateValue["PropertyAlias"]; Feature = stateValue["Feature"]; } } if (string.IsNullOrEmpty(Dialogue.Settings().GoogleClientId) || string.IsNullOrEmpty(Dialogue.Settings().GoogleClientSecret)) { resultMessage.Message = "You need to add the Google app credentials"; resultMessage.MessageType = GenericMessages.Danger; } else { // Configure the OAuth client based on the options of the prevalue options var client = new GoogleOAuthClient { ClientId = Dialogue.Settings().GoogleClientId, ClientSecret = Dialogue.Settings().GoogleClientSecret, RedirectUri = ReturnUrl }; // Session expired? if (AuthState != null && Session["Dialogue_" + AuthState] == null) { resultMessage.Message = "Session Expired"; resultMessage.MessageType = GenericMessages.Danger; } // Check whether an error response was received from Google if (AuthError != null) { resultMessage.Message = AuthErrorDescription; resultMessage.MessageType = GenericMessages.Danger; if (AuthState != null) { Session.Remove("Dialogue_" + AuthState); } } // Redirect the user to the Google login dialog if (AuthCode == null) { // Generate a new unique/random state var state = Guid.NewGuid().ToString(); // Save the state in the current user session Session["Dialogue_" + state] = new NameValueCollection { { "Callback", Callback }, { "ContentTypeAlias", ContentTypeAlias }, { "PropertyAlias", PropertyAlias }, { "Feature", Feature } }; // Declare the scope var scope = new[] { GoogleScope.OpenId, GoogleScope.Email, GoogleScope.Profile }; // Construct the authorization URL var url = client.GetAuthorizationUrl(state, scope, GoogleAccessType.Offline, GoogleApprovalPrompt.Force); // Redirect the user return(Redirect(url)); } var info = new GoogleAccessTokenResponse(); try { info = client.GetAccessTokenFromAuthorizationCode(AuthCode); } catch (Exception ex) { resultMessage.Message = string.Format("Unable to acquire access token<br/>{0}", ex.Message); resultMessage.MessageType = GenericMessages.Danger; } try { // Initialize the Google service var service = GoogleService.CreateFromRefreshToken(client.ClientIdFull, client.ClientSecret, info.RefreshToken); // Get information about the authenticated user var user = service.GetUserInfo(); using (UnitOfWorkManager.NewUnitOfWork()) { var userExists = AppHelpers.UmbServices().MemberService.GetByEmail(user.Email); if (userExists != null) { // Update access token userExists.Properties[AppConstants.PropMemberGoogleAccessToken].Value = info.RefreshToken; AppHelpers.UmbServices().MemberService.Save(userExists); // Users already exists, so log them in FormsAuthentication.SetAuthCookie(userExists.Username, true); resultMessage.Message = Lang("Members.NowLoggedIn"); resultMessage.MessageType = GenericMessages.Success; } else { // Not registered already so register them var viewModel = new RegisterViewModel { Email = user.Email, LoginType = LoginType.Google, Password = AppHelpers.RandomString(8), UserName = user.Name, SocialProfileImageUrl = user.Picture, UserAccessToken = info.RefreshToken }; return(RedirectToAction("MemberRegisterLogic", "DialogueLoginRegisterSurface", viewModel)); } } } catch (Exception ex) { resultMessage.Message = string.Format("Unable to get user information<br/>{0}", ex.Message); resultMessage.MessageType = GenericMessages.Danger; } } ShowMessage(resultMessage); return(RedirectToUmbracoPage(Dialogue.Settings().ForumId)); }
protected void ShowMessage(GenericMessageViewModel messageViewModel) { //ViewData[AppConstants.MessageViewBagName] = messageViewModel; TempData[AppConstants.MessageViewBagName] = messageViewModel; }