public System.Web.Http.Results.JsonResult <Laser.Orchard.StartupConfig.ViewModels.Response> Post([FromUri] string tk, [FromBody] DatiPost valori) { Response result = _utilsServices.GetResponse(ResponseType.Validation, "Validation error."); try { int id = 0; var tkOrig = System.Text.ASCIIEncoding.Unicode.GetString(Convert.FromBase64String(tk)); if (tkOrig.Length > 10) { var mailerConfig = _orchardServices.WorkContext.CurrentSite.As <MailerSiteSettingsPart>(); DateTime dt0 = DateTime.ParseExact(tkOrig.Substring(0, 10), "yyyyMMddHH", System.Globalization.CultureInfo.InvariantCulture); if (DateTime.Now < dt0.AddDays(mailerConfig.TokenValidity)) { id = int.Parse(tkOrig.Substring(10)); // aggiorna il dato su orchard var item = _contentManager.Get <MailCommunicationPart>(id); item.SentMailsNumber += valori.num; result = _utilsServices.GetResponse(ResponseType.Success, "OK"); } } } catch { // non fa nulla perché la risposta negativa è già il default e non si voglionon dare dettagli sul'errore a eventuali hacker } return(Json(result)); }
public JsonResult GetIconsIds() { var items = _contentManager.Query <TermPart, TermPartRecord>().List(); var listIconIds = new List <int>(); try { foreach (dynamic item in items) { if (item.Icon != null && ((int[])item.Icon.Ids).Length > 0) { listIconIds = listIconIds.Union((int[])item.Icon.Ids).ToList(); } else if (item.Icon == null) { var error = _utilsServices.GetResponse(StartupConfig.ViewModels.ResponseType.None); error.ErrorCode = StartupConfig.ViewModels.ErrorCode.GenericError; error.Data = T("Missing Icon field in Term Part.").Text; return(Json(error, JsonRequestBehavior.AllowGet)); } } // verifica che le icon non siano state eliminate listIconIds = _contentManager.Query().ForContentItems(listIconIds).List().Select(x => x.Id).ToList <int>(); } catch (Exception ex) { var error = _utilsServices.GetResponse(StartupConfig.ViewModels.ResponseType.None); error.ErrorCode = StartupConfig.ViewModels.ErrorCode.GenericError; error.Data = ex.Message; return(Json(error, JsonRequestBehavior.AllowGet)); } return(Json(listIconIds.ToArray(), JsonRequestBehavior.AllowGet)); }
public Response Post([FromBody] PoliciesApiModel policiesModel) { try { if ((_orchardServices.WorkContext.CurrentUser != null && _csrfTokenHelper.DoesCsrfTokenMatchAuthToken()) || _orchardServices.WorkContext.CurrentUser == null) { var fullModel = policiesModel.PoliciesForUser.Policies.Select(s => new PolicyForUserViewModel { Accepted = s.Accepted, AnswerDate = s.AnswerDate, AnswerId = s.AnswerId, OldAccepted = s.OldAccepted, PolicyTextId = s.PolicyTextId, PolicyText = null, // non serve per l'update è sufficinete l'ID UserId = s.UserId }).ToList(); _policySerivces.PolicyForUserMassiveUpdate(fullModel); return(_utilsServices.GetResponse(ResponseType.Success)); // { Message = "Ok", Success = true }); } else { return(_utilsServices.GetResponse(ResponseType.InvalidXSRF)); // { Message = "Invalid Token/csrfToken", Success = false }); } } catch (Exception ex) { Log.Error("Policy -> PoliciesApi -> Post : " + ex.Message + " <Stack> " + ex.StackTrace); return(_utilsServices.GetResponse(ResponseType.None, "Error:" + ex.Message)); } }
public Response StoreInspectExpando(ExpandoObject theExpando, ContentItem theContentItem) { try { foreach (var kvp in theExpando) { string key = kvp.Key.ToString(); string valueType = kvp.Value.GetType().Name; object value = kvp.Value; if (kvp.Value is ExpandoObject) { StoreInspectExpando(kvp.Value as ExpandoObject, theContentItem); } // provo a registrare nel profile part altrimenti provo a registrare nel IUser //currentUser.GetType().GetProperty(key).SetValue(currentUser,value, null); StoreInspectExpandoFields(theContentItem.Parts.ToList(), key, value, theContentItem); } } catch (Exception ex) { Log.Error("Startupconfig -> ContentExtensionService -> StoreInspectExpando : " + ex.Message + " <Stack> " + ex.StackTrace); return(_utilsServices.GetResponse(ResponseType.None, "Error:" + ex.Message)); } // if (TheContentItem.ContentType != "User") return(StoreInspectExpandoPart(theExpando, theContentItem)); // return (_utilsServices.GetResponse(ResponseType.Success)); }
/// <summary> /// Metodo per generare l'elenco di checkbox delle tassonomie attualmente selezionate /// http://localhost/Orchard.Community/expoincitta/api/laser.orchard.mobile/taxonomiepush/?Language=en-US /// </summary> /// <param name="Language"></param> /// <returns></returns> //public List<category> Get(string Language) { public dynamic Get(string Language) { Language = Language ?? ""; var authenticatedUser = _authenticationService.GetAuthenticatedUser(); if (authenticatedUser != null) { #region [get taxonomy linked to user part of type declared on setting of pushmobile] string taxonomyId = _orchardServices.WorkContext.CurrentSite.As <PushMobileSettingsPart>().TaxonomyName; string taxonomyname = _taxonomyService.GetTaxonomy(Convert.ToInt32(taxonomyId)).Name; string nomefield = authenticatedUser.ContentItem.Parts.SelectMany(x => x.Fields.Where(f => f.FieldDefinition.Name == typeof(TaxonomyField).Name && f.PartFieldDefinition.Settings["TaxonomyFieldSettings.Taxonomy"] == taxonomyname)).Cast <TaxonomyField>().FirstOrDefault().Name; #endregion List <category> elements = new List <category>(); List <TermPart> cata = _taxonomyService.GetTermsForContentItem(authenticatedUser.Id, nomefield).ToList(); // List<TermPart> cata = ((dynamic)((dynamic)(authenticatedUser.ContentItem)).User).Pushcategories.Terms; List <string> ListCategory = cata.Select(x => (string)((dynamic)x).tipoUnivoco.Value).ToList(); var taxobase = GetPushTaxonomy(Language); foreach (var term in taxobase.Terms) { elements.Add(new category() { testo = term.Name, valore = ((dynamic)term).tipoUnivoco.Value, flag = ListCategory.Contains(((dynamic)term).tipoUnivoco.Value) }); } return(elements); } else { // throw new OrchardSecurityException(T("Can't retrieve user category, user not logged in")); return(_utilsServices.GetResponse(ResponseType.InvalidUser)); } }
public Response Get(int pageId) { if (pageId < 1) { throw new Exception("Incorrect input parameter."); } ReactionsSummaryVM typeClick = _userReactionService.GetSummaryReaction(pageId); return(_utilsServices.GetResponse(ResponseType.Success, "", typeClick)); }
public Response PostId(parameterint pint) { bool saltotest = false; if (pint == null) { return(_utilsServices.GetResponse(ResponseType.Validation, "Unknow Parameter type")); } var currentUser = _orchardServices.WorkContext.CurrentUser; if (currentUser == null) { return(_utilsServices.GetResponse(ResponseType.UnAuthorized)); } else { if (_csrfTokenHelper.DoesCsrfTokenMatchAuthToken() || saltotest) { if (pint.id > 0) { return(post_method(currentUser.Id, pint.id)); } else { return(_utilsServices.GetResponse(ResponseType.Validation, "Content not found")); } } else { return(_utilsServices.GetResponse(ResponseType.InvalidXSRF)); // { Message = "Invalid Token/csrfToken", Success = false, ErrorCode=ErrorCode.InvalidXSRF,ResolutionAction=ResolutionAction.Login }); } } }
/// <summary> /// test in feedler /// User-Agent: Fiddler ///Content-Type: application/json ///Host: localhost ///Content-Length: 105 ///Cookie: .ASPXAUTH=3BDDACF3339764AE73D8AF6A9992CE0C34247D3107C7E66561BCF0A8ACB81C0B0708A274B5B5A57B3C9425AA98825AF5429AE0DE9958CEC8923B998667D89184755E3446DAA5832C7C16C519ABDD1981E919AC22E1A81D277F615F3240264D5FB0B46F174EEC84EB839387462EA250CC71B856178CE26EF0EDEFD6B00E40FACF ///X-XSRF-TOKEN: Tnaq+qFFu+B/NPrfJZnTg5FoATHDCrTP3aAAXA90MiS1vpkk5y2QwfRJ5aAmqu4n7GFv+6CcUos+klKlOXBu1A== ///{"ContentType":"contenutoutente","TitlePart.Title":"Titolodiprova","sottotitolo":"il mio sottotitolo","BodyPart.Text":"<b>il mio body</b>","media":[158] } /// </summary> /// <param name="eObj"></param> /// <returns></returns> public Response Post(ExpandoObject eObj) { // try { var currentUser = _orchardServices.WorkContext.CurrentUser; if (currentUser == null) { return(StoreNewContentItem(eObj, null)); //return (_utilsServices.GetResponse(ResponseType.InvalidUser)); } else if (_csrfTokenHelper.DoesCsrfTokenMatchAuthToken()) { return(StoreNewContentItem(eObj, currentUser.ContentItem)); } else { //if (!_orchardServices.Authorizer.Authorize(OrchardCore.Settings.Permissions.ManageSettings, T("You don't have permission \"Manage settings\" to define and manage User Groups!"))) { //} //else { // return new HttpUnauthorizedResult(); //} return(_utilsServices.GetResponse(ResponseType.InvalidXSRF)); // { Message = "Invalid Token/csrfToken", Success = false, ErrorCode=ErrorCode.InvalidXSRF,ResolutionAction=ResolutionAction.Login }); } }
public override void OnActionExecuting(ActionExecutingContext filterContext) { filterContext.RequestContext.GetWorkContext().TryResolve <IWebApiFilterService>(out _webApiFilterService); filterContext.RequestContext.GetWorkContext().TryResolve <IUtilsServices>(out _utilsServices); _webApiFilterService.ApplyFilter(() => base.OnActionExecuting(filterContext), (result) => { if (filterContext == null) { return; } filterContext.HttpContext.Response.Clear(); filterContext.HttpContext.Response.TrySkipIisCustomErrors = true; filterContext.HttpContext.Response.StatusCode = (int)System.Net.HttpStatusCode.Forbidden; var response = _utilsServices.GetResponse(ViewModels.ResponseType.UnAuthorized); response.Data = result; filterContext.Result = new JsonResult { Data = response, JsonRequestBehavior = JsonRequestBehavior.AllowGet }; return; }, () => { return(filterContext.RequestContext.GetWorkContext()); }, _protectAlways); }
public Response Post([FromBody] Signal signal) { if (String.IsNullOrWhiteSpace(signal.Name) || signal.ContentId <= 0) { throw new Exception("Invalid Signal parameters"); } var currentUser = _orchardServices.WorkContext.CurrentUser; if (currentUser != null) { if (!_csrfTokenHelper.DoesCsrfTokenMatchAuthToken()) { return(_utilsServices.GetResponse(ResponseType.InvalidXSRF)); } } // aggiunge l'header Access-Control-Allow-Origin necessario nel caso di chiamate CORS da browser var httpResponse = HttpContext.Current.Response; httpResponse.Headers.Add("Access-Control-Allow-Origin", "*"); try { var response = _activityServices.TriggerSignal(signal.Name, signal.ContentId); return(response); } catch (Exception ex) { return(new Response { Success = false, Message = ex.Message, ErrorCode = ErrorCode.GenericError }); } }
public JsonResult PostFile(HttpPostedFileBase file, string contentType = "") { var currentUser = _orchardServices.WorkContext.CurrentUser; if (currentUser == null) { return(PostFileFunction(file, contentType)); } else if (_csrfTokenHelper.DoesCsrfTokenMatchAuthToken()) { return(PostFileFunction(file, contentType)); } else { return(Json(_utilsServices.GetResponse(ResponseType.InvalidXSRF))); // { Message = "Invalid Token/csrfToken", Success = false, ErrorCode=ErrorCode.InvalidXSRF,ResolutionAction=ResolutionAction.Login }); } }
public Response StoreInspectExpando(ExpandoObject theExpando, ContentItem theContentItem) { try { foreach (var kvp in theExpando) { string key = kvp.Key.ToString(); string valueType = kvp.Value.GetType().Name; object value = kvp.Value; if (kvp.Value is ExpandoObject) { StoreInspectExpando(kvp.Value as ExpandoObject, theContentItem); } _utilsServices.StoreInspectExpandoFields(theContentItem.Parts.ToList(), key, value); } } catch (Exception ex) { Log.Error("ContentExtension -> ContentExtensionService -> StoreInspectExpando : " + ex.Message + " <Stack> " + ex.StackTrace); return(_utilsServices.GetResponse(ResponseType.None, "Error:" + ex.Message)); } return(StoreInspectExpandoPart(theExpando, theContentItem)); }
public Response Get(string mail) { var uuid = GetUUIDFromHeader(); if (string.IsNullOrWhiteSpace(uuid)) { return(_utilsServices.GetResponse(ResponseType.UnAuthorized)); } var user = _usersExtensionsServices.GetUserByMail(mail); var flowToUse = FlowType.Website; if (user != null) { var data = new Dictionary <string, string>(); if (!string.IsNullOrEmpty(uuid)) { data.Add("uuid", uuid);// uuid used only by mobile channel flowToUse = FlowType.App; } // create and send an OTP (this may overwrite any previous OTP for the user) _nonceService.SendNewOTP(user, data, DeliveryChannelType.Email, flowToUse); return(_utilsServices.GetResponse(ResponseType.Success)); } return(_utilsServices.GetResponse(ResponseType.UnAuthorized)); }
public JsonResult GetReactionClicked(int reactionTypeId, int pageId) { ReactionsClickVM result = new ReactionsClickVM(); var contentItem = _orchardServices.ContentManager.Get(pageId); if (_userReactionService.HasPermission(contentItem.ContentType) == false) { return(Json(_utilsServices.GetResponse(ResponseType.UnAuthorized))); } result.Result = _userReactionService.CalculateTypeClick(reactionTypeId, pageId); result.Status = _userReactionService.GetSummaryReaction(pageId); return(Json(result)); }
public Response Post([FromBody] List <AnswerWithResultViewModel> Risps) { if (Risps != null) { return(ExecPost(Risps)); } else { return(_utilsServices.GetResponse(ResponseType.Validation, T("Validation: invalid input data structure.").ToString())); } }
internal Response ErrorHandler(string msgJson) { VimeoResponse resp = JsonConvert.DeserializeObject <VimeoResponse>(msgJson); int mpId = resp.Data.id; //the id of the MediaPart for whom we were doing the upload Laser.Orchard.StartupConfig.ViewModels.Response response; string msg = ""; switch (resp.ErrorCode) { case VimeoErrorCode.NoError: //nothing to do here. Honestly, the app should not have called the error action response = _utilsServices.GetResponse(ResponseType.None, ""); break; case VimeoErrorCode.GenericError: //Something happened, but we do not know what. //Just log this response = _utilsServices.GetResponse(ResponseType.None, ""); break; case VimeoErrorCode.UserStopped: //The user stopped the upload, with no intention of resuming it. //clear the records and destroy the MediaPart we were creating msg = _vimeoUploadServices.DestroyUpload(mpId); response = _utilsServices.GetResponse(ResponseType.Success, msg); break; case VimeoErrorCode.UploadStopped: //The upload stopped for an error, and there is no way to resume it. //clear the records and destroy the MediaPart we were creating msg = _vimeoUploadServices.DestroyUpload(mpId); response = _utilsServices.GetResponse(ResponseType.Success, msg); break; case VimeoErrorCode.UploadMayResume: //The upload stopped for an error, but may resume later. //Do not clear or destroy anything. response = _utilsServices.GetResponse(ResponseType.None, ""); break; default: //No reason why we should be here response = _utilsServices.GetResponse(ResponseType.None, ""); break; } Logger.Error(msgJson); if (!string.IsNullOrWhiteSpace(msg)) { Logger.Information(msg); } return(response); }
public Response TriggerSignal(string signalName, int contentId) { Response triggerResult = _utilsServices.GetResponse(ResponseType.Success); try { var content = _orchardServices.ContentManager.Get(contentId, VersionOptions.Published); var tokens = new Dictionary <string, object> { { "Content", content }, { SignalActivity.SignalEventName, signalName }, { "WebApiResponse", triggerResult } }; _workflowManager.TriggerEvent(SignalActivity.SignalEventName, content, () => tokens); } catch (Exception ex) { Log.Error("TriggerSignal " + ex.Message + "stack" + ex.StackTrace); } return(triggerResult); }
private void ErrorResult(ActionExecutingContext filterContext, string errorData) { if (filterContext == null) { return; } filterContext.HttpContext.Response.Clear(); filterContext.HttpContext.Response.TrySkipIisCustomErrors = true; filterContext.HttpContext.Response.StatusCode = (int)System.Net.HttpStatusCode.Forbidden; var response = _utilsServices.GetResponse(ViewModels.ResponseType.UnAuthorized); response.Data = errorData; filterContext.Result = new JsonResult { Data = response, JsonRequestBehavior = JsonRequestBehavior.AllowGet }; return; }
public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext) { actionContext.ControllerContext.GetWorkContext().TryResolve <IWebApiFilterService>(out _webApiFilterService); actionContext.ControllerContext.GetWorkContext().TryResolve <IUtilsServices>(out _utilsServices); _webApiFilterService.ApplyFilter(() => base.OnActionExecuting(actionContext), (result) => { if (actionContext == null) { return; } var response = _utilsServices.GetResponse(ViewModels.ResponseType.UnAuthorized); response.Data = result; actionContext.Response = actionContext.ControllerContext.Request.CreateResponse(HttpStatusCode.Unauthorized, response, "application/json"); }, () => { return(actionContext.ControllerContext.GetWorkContext()); }, _protectAlways); }
/// <summary> /// test in feedler /// User-Agent: Fiddler ///Content-Type: application/json ///Host: localhost ///Content-Length: 105 ///Cookie: .ASPXAUTH=3BDDACF3339764AE73D8AF6A9992CE0C34247D3107C7E66561BCF0A8ACB81C0B0708A274B5B5A57B3C9425AA98825AF5429AE0DE9958CEC8923B998667D89184755E3446DAA5832C7C16C519ABDD1981E919AC22E1A81D277F615F3240264D5FB0B46F174EEC84EB839387462EA250CC71B856178CE26EF0EDEFD6B00E40FACF ///X-XSRF-TOKEN: Tnaq+qFFu+B/NPrfJZnTg5FoATHDCrTP3aAAXA90MiS1vpkk5y2QwfRJ5aAmqu4n7GFv+6CcUos+klKlOXBu1A== ///{"ContentType":"contenutoutente","TitlePart.Title":"Titolodiprova","sottotitolo":"il mio sottotitolo","BodyPart.Text":"<b>il mio body</b>","media":[158] } /// </summary> /// <param name="eObj"></param> /// <returns></returns> public Response Post(sasa eObjs) { dynamic eObj = new ExpandoObject(); // var eObj = new ExpandoObject() as IDictionary<string, Object>; //eObj.Add("Language", eObjs.Language); //eObj.Add("ContentType", eObjs.ContentType); //eObj.Add("Valorenumerico", eObjs.Valorenumerico); //eObj.Add("TitlePart.Title", "titolo"); eObj.Language = eObjs.Language; eObj.ContentType = eObjs.ContentType; eObj.Valorenumerico = eObjs.Valorenumerico; // try { var currentUser = _orchardServices.WorkContext.CurrentUser; if (currentUser == null) { return(StoreNewContentItem(eObj, null)); //return (_utilsServices.GetResponse(ResponseType.InvalidUser)); } else if (_csrfTokenHelper.DoesCsrfTokenMatchAuthToken()) { return(StoreNewContentItem(eObj, currentUser.ContentItem)); } else { //if (!_orchardServices.Authorizer.Authorize(OrchardCore.Settings.Permissions.ManageSettings, T("You don't have permission \"Manage settings\" to define and manage User Groups!"))) { //} //else { // return new HttpUnauthorizedResult(); //} return(_utilsServices.GetResponse(ResponseType.InvalidXSRF)); // { Message = "Invalid Token/csrfToken", Success = false, ErrorCode=ErrorCode.InvalidXSRF,ResolutionAction=ResolutionAction.Login }); } }
public ActionResult Display(string alias, int page = 1, int pageSize = 10, int maxLevel = 10) { try { JObject json; if (alias == null) { var result = new ContentResult { ContentType = "application/json" }; result.Content = Newtonsoft.Json.JsonConvert.SerializeObject(_utilsServices.GetResponse(ResponseType.MissingParameters)); return(result); } IContent content; if (alias.ToLower() == "user+info" || alias.ToLower() == "user info") { #region [ Richiesta dati di uno user ] var currentUser = _authenticationService.GetAuthenticatedUser(); if (currentUser == null) { // return Content((Json(_utilsServices.GetResponse(ResponseType.InvalidUser))).ToString(), "application/json");// { Message = "Error: No current User", Success = false,ErrorCode=ErrorCode.InvalidUser,ResolutionAction=ResolutionAction.Login }); var result = new ContentResult { ContentType = "application/json" }; result.Content = Newtonsoft.Json.JsonConvert.SerializeObject(_utilsServices.GetResponse(ResponseType.InvalidUser)); return(result); } else if (!_csrfTokenHelper.DoesCsrfTokenMatchAuthToken()) { var result = new ContentResult { ContentType = "application/json" }; result.Content = Newtonsoft.Json.JsonConvert.SerializeObject(_utilsServices.GetResponse(ResponseType.InvalidXSRF)); return(result); // Content((Json(_utilsServices.GetResponse(ResponseType.InvalidXSRF))).ToString(), "application/json");// { Message = "Error: No current User", Success = false,ErrorCode=ErrorCode.InvalidUser,ResolutionAction=ResolutionAction.Login }); } else { #region utente validato content = currentUser.ContentItem; #endregion } #endregion } else { content = _commonServices.GetContentByAlias(alias); } if (content == null) { return(new HttpStatusCodeResult(404)); } if (!_orchardServices.Authorizer.Authorize(Permissions.ViewContent, content)) { return(Json(_utilsServices.GetResponse(ResponseType.UnAuthorized), JsonRequestBehavior.AllowGet)); } //_maxLevel = maxLevel; json = _contentSerializationServices.GetJson(content, page, pageSize); //_contentSerializationServices.NormalizeSingleProperty(json); return(Content(json.ToString(Newtonsoft.Json.Formatting.None), "application/json")); //return GetJson(content, page, pageSize); } catch (System.Security.SecurityException) { return(Json(_utilsServices.GetResponse(ResponseType.InvalidUser), JsonRequestBehavior.AllowGet)); } }
public dynamic Get(Int32 id) { ContentItem ContentToView; Response rsp = new Response(); if (id > 0) { List <ContentItem> li = _orchardServices.ContentManager.GetAllVersions(id).ToList(); if (li.Count() == 0) { return(_utilsServices.GetResponse(ResponseType.Validation, T("No content with this Id").ToString())); } else if (li.Count() == 1) { ContentToView = li[0]; } else { ContentToView = _orchardServices.ContentManager.Get(id, VersionOptions.Latest); } if (!_orchardServices.Authorizer.Authorize(OrchardCore.Contents.Permissions.ViewContent, ContentToView)) { if (!_contentExtensionService.HasPermission(ContentToView.ContentType, Methods.Get, ContentToView)) { return(_utilsServices.GetResponse(ResponseType.UnAuthorized)); } } if (((dynamic)ContentToView).AutoroutePart != null) { string tenantname = ""; if (string.IsNullOrWhiteSpace(_shellSettings.RequestUrlPrefix) == false) { tenantname = _shellSettings.RequestUrlPrefix + "/"; } return(Redirect(Url.Content("~/" + tenantname + "WebServices/Alias?displayAlias=" + ((dynamic)ContentToView).AutoroutePart.DisplayAlias))); } else { throw new Exception("Method not implemented, content without AutoroutePart"); } } else { return(_utilsServices.GetResponse(ResponseType.None, T("No content with this Id").ToString())); } }
protected ContentResult ExternalTokenLogOnLogic(string __provider__, string token, string secret = "", bool createPersistentCookie = false) { // TempDataDictionary registeredServicesData = new TempDataDictionary(); var result = new Response(); try { if (String.IsNullOrWhiteSpace(__provider__) || String.IsNullOrWhiteSpace(token)) { result = _utilsServices.GetResponse(ResponseType.None, "One or more of the required parameters was not provided or was an empty string."); return(_utilsServices.ConvertToJsonResult(result)); } // ricava il return URL così come registrato nella configurazione del provider di OAuth (es. Google) var returnUrl = Url.MakeAbsolute(Url.Action("ExternalLogOn", "Account")); AuthenticationResult dummy = new AuthenticationResult(true); AuthenticationResult authResult = _openAuthClientProvider.GetUserData(__provider__, dummy, token, secret, returnUrl); // authResult may be null if the provider name matches no configured provider if (authResult == null || !authResult.IsSuccessful) { result = _utilsServices.GetResponse(ResponseType.InvalidUser, "Token authentication failed."); return(_utilsServices.ConvertToJsonResult(result)); } else { if (_orchardOpenAuthWebSecurity.Login(authResult.Provider, authResult.ProviderUserId, createPersistentCookie)) { // Login also returns false for disabled users (this used to not be the case) if (HttpContext.Response.Cookies.Count == 0) { // For some reason, SignIn failed to add the authentication cookie to the response result = _utilsServices.GetResponse(ResponseType.None, "Unable to send back a cookie."); return(_utilsServices.ConvertToJsonResult(result)); } else { // The LoggedIn event is already raised in the Login method just before returning true, // so we should not be raising it here as well. return(_utilsServices.ConvertToJsonResult(_utilsServices.GetUserResponse("", _identityProviders))); } } // Login returned false: either the user given by Provider+UserId has never been registered (so we have no // matching username to use), or no user exists in Orchard with that username, or SignIn failed somehow, or // the user is disabled. // _openAuthClientProvider.NormalizeData(params) may return null if there is no configuration for a provider // with the given name. If authResult != null, that is not the case, because in that condition GetUserData(params) // would return null, and we would have already exited the method. var userParams = _openAuthClientProvider.NormalizeData(authResult.Provider, new OpenAuthCreateUserParams(authResult.UserName, authResult.Provider, authResult.ProviderUserId, authResult.ExtraData)); var temporaryUser = _openAuthMembershipServices.CreateTemporaryUser(userParams); // This is an attempt to login using an OAuth provider. The call to .Login(params) returned false. In an actual // login there is no reason why GetAuthenticatedUser() should return a user, unless we are in a situation where, // as authenticated users, we are allowed to add information from OAuth providers to our account // The authenticated User or depending from settings the first created user with the same e-mail var masterUser = _authenticationService.GetAuthenticatedUser() ?? _orchardOpenAuthWebSecurity.GetClosestMergeableKnownUser(temporaryUser); var authenticatedUser = _authenticationService.GetAuthenticatedUser(); if (masterUser != null) { // If the current user is logged in or settings ask for a user merge and we found a User with the same email // create or merge accounts _orchardOpenAuthWebSecurity.CreateOrUpdateAccount(authResult.Provider, authResult.ProviderUserId, masterUser, authResult.ExtraData); // Handle LoggedIn Event if (authenticatedUser == null) { _authenticationService.SignIn(masterUser, createPersistentCookie); _userEventHandler.LoggedIn(masterUser); // The LoggedIn event is invoked here, because if authenticateUser != null, then it means the user // had already logged in some other time } return(_utilsServices .ConvertToJsonResult(_utilsServices .GetUserResponse(T("Your {0} account has been attached to your local account.", authResult.Provider).Text, _identityProviders))); } if (_openAuthMembershipServices.CanRegister() && masterUser == null) { // User can register and there is not a user with the same email var createUserParams = new OpenAuthCreateUserParams(authResult.UserName, authResult.Provider, authResult.ProviderUserId, authResult.ExtraData); createUserParams = _openAuthClientProvider.NormalizeData(authResult.Provider, createUserParams); // Creating the user here calls the IMembershipService, that will take care of invoking the user events var newUser = _openAuthMembershipServices.CreateUser(createUserParams); // newUser may be null here, if creation of a new user fails. // TODO: we should elsewhere add an UserEventHandler that in the Creating event handles the case where // here we are trying to create a user with the same Username or Email as an existing one. That would simply // use IUserService.VerifyUnicity(username, email) if (newUser != null) { // CreateOrUpdateAccount causes specific OpenAuth events to fire _orchardOpenAuthWebSecurity.CreateOrUpdateAccount(authResult.Provider, authResult.ProviderUserId, newUser, authResult.ExtraData); // The default implementation of IOpendAuthMembershipService creates an approved user. // The events specific to open auth give points to attach handlers where the UserProviderRecord // is populated correctly. _authenticationService.SignIn(newUser, createPersistentCookie); if (HttpContext.Response.Cookies.Count == 0) { // SignIn adds the authentication cookie to the response, so that is what we are checking here // We should never be here executing this code. result = _utilsServices.GetResponse(ResponseType.None, "Unable to send back a cookie."); return(_utilsServices.ConvertToJsonResult(result)); } else { // Handle LoggedIn Event _userEventHandler.LoggedIn(newUser); return(_utilsServices.ConvertToJsonResult(_utilsServices.GetUserResponse(T("You have been logged in using your {0} account. We have created a local account for you with the name '{1}'", authResult.Provider, newUser.UserName).Text, _identityProviders))); } } // if newUser == null, just go ahead and return the "Login Failed" Response } result = _utilsServices.GetResponse(ResponseType.None, "Login failed."); return(_utilsServices.ConvertToJsonResult(result)); } } catch (Exception e) { result = _utilsServices.GetResponse(ResponseType.None, e.Message); return(_utilsServices.ConvertToJsonResult(result)); } }
public void OnActionExecuting(ActionExecutingContext filterContext) { bool isAdminService = filterContext.ActionDescriptor.GetCustomAttributes(typeof(AdminServiceAttribute), false).Any(); var fullActionName = filterContext.Controller.GetType().FullName + "." + filterContext.ActionDescriptor.ActionName; if (_workContext.GetContext().CurrentUser != null && !allowedControllers.Contains(filterContext.Controller.GetType().FullName) && !allowedControllers.Contains(fullActionName) && !AdminFilter.IsApplied(filterContext.RequestContext) && !isAdminService) { var language = _workContext.GetContext().CurrentCulture; IEnumerable <PolicyTextInfoPart> neededPolicies = _userExtensionServices.GetUserLinkedPolicies(language); if (neededPolicies.Count() > 0) { var missingPolicies = MissingRegistrationPolices(); if (missingPolicies.Count() > 0) { if (filterContext.Controller.GetType().FullName == "Laser.Orchard.WebServices.Controllers.JsonController") { string data = _policyServices.PoliciesLMNVSerialization(neededPolicies.Where(w => missingPolicies.Any(a => a == w.Id))); filterContext.Result = new ContentResult { Content = data, ContentType = "application/json" }; } else if (filterContext.Controller.GetType().FullName == "Laser.Orchard.WebServices.Controllers.WebApiController") { string data = _policyServices.PoliciesPureJsonSerialization(neededPolicies.Where(w => missingPolicies.Any(a => a == w.Id))); filterContext.Result = new ContentResult { Content = data, ContentType = "application/json" }; } else { string outputFormat = _workContext.GetContext().HttpContext.Request.Headers["OutputFormat"]; if (String.Equals(outputFormat, "LMNV", StringComparison.OrdinalIgnoreCase)) { string data = _policyServices.PoliciesLMNVSerialization(neededPolicies.Where(w => missingPolicies.Any(a => a == w.Id))); Response response = _utilsServices.GetResponse(ResponseType.MissingPolicies, "", Newtonsoft.Json.JsonConvert.DeserializeObject(data)); filterContext.Result = new ContentResult { Content = Newtonsoft.Json.JsonConvert.SerializeObject(response), ContentType = "application/json" }; } else if (String.Equals(outputFormat, "PureJson", StringComparison.OrdinalIgnoreCase)) { string data = _policyServices.PoliciesPureJsonSerialization(neededPolicies.Where(w => missingPolicies.Any(a => a == w.Id))); Response response = _utilsServices.GetResponse(ResponseType.MissingPolicies, "", Newtonsoft.Json.JsonConvert.DeserializeObject(data)); filterContext.Result = new ContentResult { Content = Newtonsoft.Json.JsonConvert.SerializeObject(response), ContentType = "application/json" }; } else { var returnType = ((ReflectedActionDescriptor)filterContext.ActionDescriptor).MethodInfo.ReturnType; if (returnType == typeof(JsonResult)) { string data = _policyServices.PoliciesPureJsonSerialization(neededPolicies.Where(w => missingPolicies.Any(a => a == w.Id))); Response response = _utilsServices.GetResponse(ResponseType.MissingPolicies, "", Newtonsoft.Json.JsonConvert.DeserializeObject(data)); filterContext.Result = new ContentResult { Content = Newtonsoft.Json.JsonConvert.SerializeObject(response), ContentType = "application/json" }; } else { var encodedAssociatedPolicies = Convert.ToBase64String(Encoding.UTF8.GetBytes(string.Join(",", missingPolicies))); UrlHelper urlHelper = new UrlHelper(_httpContextAccessor.Current().Request.RequestContext); var url = urlHelper.Action("Index", "Policies", new { area = "Laser.Orchard.Policy", lang = language, policies = encodedAssociatedPolicies, returnUrl = _httpContextAccessor.Current().Request.RawUrl }); filterContext.Result = new RedirectResult(url); } } } } } } return; }
public ActionResult GetObjectById(int contentId = 0, SourceTypes sourceType = SourceTypes.ContentItem, ResultTarget resultTarget = ResultTarget.Contents, string mfilter = "", int page = 1, int pageSize = 1000, bool tinyResponse = true, bool minified = false, bool realformat = false, int deeplevel = 10, decimal version = 0) { if (contentId > 0) { IContent item = _orchardServices.ContentManager.Get(contentId, VersionOptions.Published); if (item == null) { Response rsp = _utilsServices.GetResponse(ResponseType.None, "Valore Id non valido"); // rsp.Message = ; XmlSerializer serializer = new XmlSerializer(typeof(Response)); XmlDocument doc = new XmlDocument(); StringWriter sww = new StringWriter(); XmlWriter writer = XmlWriter.Create(sww); serializer.Serialize(writer, rsp); var xml = sww.ToString(); return(this.Content(xml, "text/xml")); } else { if (item.As <AutoroutePart>() != null) { return(GetObjectByAlias(item.As <AutoroutePart>().DisplayAlias, sourceType, resultTarget, mfilter, page, pageSize, tinyResponse, deeplevel, version)); } else { Response rsp = _utilsServices.GetResponse(ResponseType.None); rsp.Message = "Valore Id non valido"; XmlSerializer serializer = new XmlSerializer(typeof(Response)); XmlDocument doc = new XmlDocument(); StringWriter sww = new StringWriter(); XmlWriter writer = XmlWriter.Create(sww); serializer.Serialize(writer, rsp); var xml = sww.ToString(); return(this.Content(xml, "text/xml")); } } } else { Response rsp = _utilsServices.GetResponse(ResponseType.None); rsp.Message = "Valore Id non valido"; XmlSerializer serializer = new XmlSerializer(typeof(Response)); XmlDocument doc = new XmlDocument(); StringWriter sww = new StringWriter(); XmlWriter writer = XmlWriter.Create(sww); serializer.Serialize(writer, rsp); var xml = sww.ToString(); return(this.Content(xml, "text/xml")); } //if (item == null) { // new HttpException(404, ("Not found")); // Response rsp = _utilsServices.GetResponse(ResponseType.None); // rsp.Message = "Pagina non trovata"; // XmlSerializer serializer = new XmlSerializer(typeof(Response)); // XmlDocument doc = new XmlDocument(); // StringWriter sww = new StringWriter(); // XmlWriter writer = XmlWriter.Create(sww); // serializer.Serialize(writer, rsp); // var xml = sww.ToString(); // return this.Content(xml, "text/xml"); //} //return (ContentResult)GetContent(item, sourceType, resultTarget, mfilter, page, pageSize, tinyResponse, minified, realformat, deeplevel); }
protected ContentResult RegisterLogic(UserRegistration userRegistrationParams) { Response result; // ensure users can request lost password var registrationSettings = _orchardServices.WorkContext.CurrentSite.As <RegistrationSettingsPart>(); if (!registrationSettings.UsersCanRegister) { result = _utilsServices.GetResponse(ResponseType.None, T("Users cannot register due to site settings.").Text); return(_utilsServices.ConvertToJsonResult(result)); } try { _usersExtensionsServices.Register(userRegistrationParams); List <string> roles = new List <string>(); var message = ""; var registeredServicesData = _utilsServices.GetUserIdentityProviders(_identityProviders); if (_orchardServices.WorkContext.CurrentUser == null && registrationSettings.UsersMustValidateEmail) { message = T("Thank you for registering. We sent you an e-mail with instructions to enable your account.").ToString(); } var json = registeredServicesData.ToString(); result = _utilsServices.GetResponse(ResponseType.Success, message, json); } catch (Exception ex) { result = _utilsServices.GetResponse(ResponseType.None, ex.Message); } return(_utilsServices.ConvertToJsonResult(result)); }
public Response RegisterLogic(UserRegistration userRegistrationParams) { Response result; // ensure users can request lost password var registrationSettings = _orchardServices.WorkContext.CurrentSite.As <RegistrationSettingsPart>(); if (!registrationSettings.UsersCanRegister) { result = _utilsServices.GetResponse(ResponseType.None, T("Users cannot register due to site settings.").Text); return(result); } try { _usersExtensionsServices.Register(userRegistrationParams); var registeredServicesData = _utilsServices.GetUserIdentityProviders(_identityProviders); var json = registeredServicesData.ToString(); result = _utilsServices.GetResponse(ResponseType.Success, data: json); } catch (Exception ex) { result = _utilsServices.GetResponse(ResponseType.None, ex.Message); } return(result); }
// METODO GET USATO PER AVVIARE MANUALMENTE IL METODO GENERATO DAL TRIGGER DELL'INVIO EMAIL E WORKFLOW //public void Get() { // bool b = _questionnairesServices.SendTemplatedEmailRanking(); //} /// <summary> /// esempio di chiamata /// http://localhost/Orchard.Community/testgame/api/laser.orchard.questionnaires/GameRanking /// parametri {"Point":12,"Identifier":"io","UsernameGameCenter":"123","Device":"Apple","ContentIdentifier":22} /// Device è un enumeratore Android, Apple, WindowsMobile /// </summary> /// <param name="Risp"></param> /// <returns></returns> public Response Post([FromBody] RankingVM Risp) { //HttpResponseMessage Response = new HttpResponseMessage(); //foreach (string coo in _orchardServices.WorkContext.HttpContext.Request.Cookies) { // var authCookie = _orchardServices.WorkContext.HttpContext.Request.Cookies[coo].Value; // Logger.Error(coo + " " + authCookie); //} bool AccessSecured = false; Int32 User_Id = 0; var currentUser = _orchardServices.WorkContext.CurrentUser; if (currentUser != null) { User_Id = currentUser.Id; // Logger.Error("User logged= " + User_Id.ToString()); if (_csrfTokenHelper.DoesCsrfTokenMatchAuthToken()) { AccessSecured = true; } } Int32 ContentItemToLink = Risp.ContentIdentifier; ContentItem cilinked = _orchardServices.ContentManager.Get(Risp.ContentIdentifier); if (cilinked != null) { if (cilinked.As <GamePart>() == null) { return(_utilsServices.GetResponse(ResponseType.Validation, "ContentItem with no GamePart " + Risp.ContentIdentifier.ToString())); } else if (!cilinked.As <GamePart>().Settings.GetModel <GamePartSettingVM>().Ranking) { return(_utilsServices.GetResponse(ResponseType.Validation, "This Game is not enabled to ranking " + Risp.ContentIdentifier.ToString())); } else { if (cilinked.As <LocalizationPart>() != null) { if (cilinked.As <LocalizationPart>().MasterContentItem != null) { ContentItemToLink = cilinked.As <LocalizationPart>().MasterContentItem.Id; } } } } else { return(_utilsServices.GetResponse(ResponseType.Validation, "No ContentItem with id " + Risp.ContentIdentifier.ToString())); } var RankingCi = _orchardServices.ContentManager.New("Ranking"); RankingPart rankingpart = RankingCi.As <RankingPart>(); rankingpart.Point = Risp.Point; rankingpart.ContentIdentifier = ContentItemToLink; rankingpart.Device = Risp.Device; rankingpart.Identifier = Risp.Identifier; rankingpart.RegistrationDate = DateTime.Now;; rankingpart.UsernameGameCenter = Risp.UsernameGameCenter; rankingpart.AccessSecured = AccessSecured; rankingpart.User_Id = User_Id; _orchardServices.ContentManager.Create(RankingCi); return(_utilsServices.GetResponse(ResponseType.Success)); }
public dynamic Get(string Language = "it-IT") { var eObj = new ExpandoObject() as IDictionary <string, Object>; var currentUser = _authenticationService.GetAuthenticatedUser(); // var currentUser = _orchardServices.WorkContext.CurrentUser; if (currentUser == null) { return(_utilsServices.GetResponse(ResponseType.InvalidUser)); // { Message = "Error: No current User", Success = false,ErrorCode=ErrorCode.InvalidUser,ResolutionAction=ResolutionAction.Login }); } #region Tutti i field var fields = currentUser.ContentItem.Parts.SelectMany(x => x.Fields); string tipofield = ""; foreach (ContentField singleField in fields) { tipofield = singleField.GetType().Name; if (tipofield == typeof(DateTimeField).Name) { eObj.Add(singleField.Name, ((dynamic)singleField).DateTime); } else if (tipofield == typeof(ContentPickerField).Name || tipofield == typeof(MediaLibraryPickerField).Name) { eObj.Add(singleField.Name, ((dynamic)singleField).Ids); } else if (tipofield == typeof(TaxonomyField).Name) { #region Tassonomia in Lingua var taxobase = _taxonomyService.GetTaxonomyByName(singleField.PartFieldDefinition.Settings["TaxonomyFieldSettings.Taxonomy"]); // seleziono la tassonomia in lingua int idmaster = taxobase.Id; if (((dynamic)taxobase.ContentItem).LocalizationPart.MasterContentItem != null) { idmaster = ((dynamic)taxobase.ContentItem).LocalizationPart.MasterContentItem.Id; } if (((dynamic)taxobase.ContentItem).LocalizationPart.Culture.Culture != Language) { taxobase = _taxonomyService.GetTaxonomies().Where(x => (x.Id == idmaster || (((dynamic)x.ContentItem).LocalizationPart.MasterContentItem != null && ((dynamic)x.ContentItem).LocalizationPart.MasterContentItem.Id == idmaster)) && ((dynamic)x.ContentItem).LocalizationPart.Culture.Culture == Language).FirstOrDefault(); } List <TermPart> cata = _taxonomyService.GetTermsForContentItem(currentUser.Id, singleField.Name).ToList(); List <string> ListCategory = new List <string>(); ListCategory = cata.Select(x => x.Id.ToString()).ToList(); List <TaxoVM> elements = new List <TaxoVM>(); foreach (var term in taxobase.Terms) { if (term.FullPath == "/" + term.Id) { elements.Add(new TaxoVM() { Id = term.Id, testo = term.Name, valore = term.Id.ToString(), flag = ListCategory.Contains(term.Id.ToString()) }); } else { Int32 idtermfather = Convert.ToInt32(term.FullPath.Split('/')[term.FullPath.Split('/').Length - 2]); FindTaxoVM(elements, idtermfather).child.Add(new TaxoVM() { Id = term.Id, testo = term.Name, valore = term.Id.ToString(), flag = ListCategory.Contains(term.Id.ToString()) }); } } eObj.Add(singleField.Name, elements); #endregion Tassonomia in Lingua } else if (tipofield == typeof(EnumerationField).Name) { eObj.Add(singleField.Name, ((dynamic)singleField).Value); string[] elencovalori = singleField.PartFieldDefinition.Settings["EnumerationFieldSettings.Options"].Split(new string[] { "\r\n" }, StringSplitOptions.None); // Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US"); List <string> elencoValoriInLingua = new List <string>(); foreach (string val in elencovalori) { elencoValoriInLingua.Add(_localizedStringManager.GetLocalizedString("UserEnumeratore", val, Language)); //T.Target.(elencovalori[0],) } eObj.Add(singleField.Name + "valori", singleField.PartFieldDefinition.Settings["EnumerationFieldSettings.Options"]); eObj.Add(singleField.Name + "valoriLang", String.Join("\r\n", elencoValoriInLingua)); } else { eObj.Add(singleField.Name, ((dynamic)singleField).Value); } } #endregion Tutti i field return(eObj); }
protected ContentResult ExternalTokenLogOnLogic(string __provider__, string token, string secret = "", bool createPersistentCookie = false) { // TempDataDictionary registeredServicesData = new TempDataDictionary(); var result = new Response(); try { if (string.IsNullOrWhiteSpace(__provider__) || string.IsNullOrWhiteSpace(token)) { result = _utilsServices.GetResponse(ResponseType.None, "One or more of the required parameters was not provided or was an empty string."); return(_utilsServices.ConvertToJsonResult(result)); } // ricava il return URL così come registrato nella configurazione del provider di OAuth (es. Google) var returnUrl = Url.MakeAbsolute(Url.Action("ExternalLogOn", "Account")); AuthenticationResult authResult = ResultForProvider(__provider__, token, secret, returnUrl); // authResult may be null if the provider name matches no configured provider if (authResult == null || !authResult.IsSuccessful) { result = _utilsServices.GetResponse(ResponseType.InvalidUser, "Token authentication failed."); return(_utilsServices.ConvertToJsonResult(result)); } else { if (_orchardOpenAuthWebSecurity.Login(authResult.Provider, authResult.ProviderUserId, createPersistentCookie)) { // Login also returns false for disabled users (this used to not be the case) if (HttpContext.Response.Cookies.Count == 0) { // For some reason, SignIn failed to add the authentication cookie to the response result = _utilsServices.GetResponse(ResponseType.None, "Unable to send back a cookie."); return(_utilsServices.ConvertToJsonResult(result)); } else { // The LoggedIn event is already raised in the Login method just before returning true, // so we should not be raising it here as well. return(_utilsServices.ConvertToJsonResult(_utilsServices.GetUserResponse("", _identityProviders))); } } // Login returned false: either the user given by Provider+UserId has never been registered (so we have no // matching username to use), or no user exists in Orchard with that username, or SignIn failed somehow, or // the user is disabled. // This is an attempt to login using an OAuth provider. The call to .Login(params) returned false. In an actual // login there is no reason why GetAuthenticatedUser() should return a user, unless we are in a situation where, // as authenticated users, we are allowed to add information from OAuth providers to our account // The authenticated User or depending from settings the first created user with the same e-mail var masterUser = GetMasterUser(authResult); if (masterUser != null) { return(MobileUserMergeAndSignIn(masterUser, authResult, returnUrl, createPersistentCookie)); } // here masterUser is null if (_openAuthMembershipServices.CanRegister()) { // User can register and there is not a user with the same email return(MobileOAuthRegister(authResult, returnUrl, createPersistentCookie)); } result = _utilsServices.GetResponse(ResponseType.None, "Login failed."); return(_utilsServices.ConvertToJsonResult(result)); } } catch (Exception e) { result = _utilsServices.GetResponse(ResponseType.None, e.Message); return(_utilsServices.ConvertToJsonResult(result)); } }