Beispiel #1
0
        protected override XElement[] Do(WebContext context)
        {
            string currentPassword = context.httprequest.Form["currentPassword"];
            string newPassword = context.httprequest.Form["newPassword"];
            if(newPassword != context.httprequest.Form["newPassword2"]) throw new FLocalException("new passwords mismatch");
            string registrationEmail = context.httprequest.Form["registrationEmail"];
            int postsPerPage = int.Parse(context.httprequest.Form["postsPerPage"]);
            int threadsPerPage = int.Parse(context.httprequest.Form["threadsPerPage"]);
            int usersPerPage = int.Parse(context.httprequest.Form["usersPerPage"]);
            int uploadsPerPage = int.Parse(context.httprequest.Form["uploadsPerPage"]);
            Skin skin = Skin.LoadById(int.Parse(context.httprequest.Form["skinId"]));
            ModernSkin modernSkin = ModernSkin.LoadById(int.Parse(context.httprequest.Form["modernSkinId"]));
            Machichara machichara = Machichara.LoadById(int.Parse(context.httprequest.Form["machicharaId"]));
            int maxUploadImageWidth = int.Parse(context.httprequest.Form["maxUploadImageWidth"]);
            int maxUploadImageHeight = int.Parse(context.httprequest.Form["maxUploadImageHeight"]);

            if((postsPerPage < 1) || (postsPerPage > 200)) throw new FLocalException("wrong number for postsPerPage");
            if((threadsPerPage < 1) || (threadsPerPage > 200)) throw new FLocalException("wrong number for threadsPerPage");
            if((usersPerPage < 1) || (usersPerPage > 200)) throw new FLocalException("wrong number for usersPerPage");
            if((uploadsPerPage < 1) || (uploadsPerPage > 200)) throw new FLocalException("wrong number for uploadsPerPage");

            if(!context.account.checkPassword(currentPassword)) throw new FLocalException("Wrong password. You should enter your current password in order to change settings.");

            AccountSettings.Save(context.session.account, postsPerPage, threadsPerPage, usersPerPage, uploadsPerPage, skin, modernSkin, machichara, maxUploadImageWidth, maxUploadImageHeight);

            if(newPassword != null && newPassword != "") {
                context.account.updatePassword(newPassword);
            }

            if(registrationEmail != null && registrationEmail != "") {
                context.account.updateRegistrationEmail(registrationEmail);
            }

            return new XElement[0];
        }
		/// <summary>
		/// 
		/// </summary>
		/// <param name="server"></param>
		/// <param name="context"></param>
		/// <param name="callbackEndPoint"></param>
		/// <param name="cancel"></param>
		public override void Run(IHostServer server, WebContext context, string callbackEndPoint, CancellationToken cancel) {
			if (context.PreparedParameters == null) {
				context.PreparedParameters = RequestParameters.Create(context);
			}
			var preparedParams = context.PreparedParameters;
			var fingerprint = preparedParams.Get("cert");
			var cms = preparedParams.Get("message");
			var container = server.Container;
			var caConfigProvider = container.Get<ICaConfigProvider>();
			if (caConfigProvider == null) {
				throw new Exception("Cannot get CA config");
			}
			var caConfig = caConfigProvider.GetConfig();
			if (caConfig == null || !caConfig.GetIsValid()) {
				throw new Exception("Not valid CA config");
			}
			var cmsDecryptor = new CmsDecryptor();
			cmsDecryptor.Initialize(caConfig);
			var cmsMessage = new CmsMessage {
				CertificateFingerprint = fingerprint,
				EncryptedMessage = cms
			};
			context.ContentType = MimeHelper.JSON;
			string salt;
			lock (TokenAuthGetSaltHandler.Sync) {
				salt = TokenAuthGetSaltHandler.Salts[fingerprint].Value;
			}
			var message = cmsDecryptor.Descrypt(cmsMessage);
			var result = message != salt ? "false" : "true";
			context.Finish(result);
		}
        public App()
        {
            InitializeComponent();

            // Handle when your app starts
            DomainContext.DomainClientFactory = new WebApiDomainClientFactory()
            {
                HttpClientHandler = new HttpClientHandler()
                {
                    AutomaticDecompression = System.Net.DecompressionMethods.Deflate | System.Net.DecompressionMethods.GZip
                },
                // TODO: REPLACE WITH IP OF YOUR COMPUTER
                // We might needto query this !
                //ServerBaseUri = new Uri("http://localhost:51359/ClientBin/", UriKind.Absolute)
                ServerBaseUri = new Uri("http://169.254.80.80:51359/ClientBin/", UriKind.Absolute)

            };

            // Create a WebContext and add it to the ApplicationLifetimeObjects collection.
            // This will then be available as WebContext.Current.
            WebContext webContext = new WebContext();
            webContext.Authentication = new FormsAuthentication()
            {
                DomainContext = new AuthenticationDomainService1()
            };

            MainPage = new XamarinXamlApp.MainPage();
        }
        /// <summary>
        /// Initializes the singleton application object.  This is the first line of authored code
        /// executed, and as such is the logical equivalent of main() or WinMain().
        /// </summary>
        public App()
        {
            this.InitializeComponent();
            this.Suspending += OnSuspending;

            DomainClientFactory = new WebApiDomainClientFactory()
            {
                HttpClientHandler =  new HttpClientHandler()
                {
                    AutomaticDecompression = System.Net.DecompressionMethods.Deflate | System.Net.DecompressionMethods.GZip
                },
                ServerBaseUri = new Uri("http://localhost:51359/ClientBin/", UriKind.Absolute)
            };

            DomainContext.DomainClientFactory = DomainClientFactory;

            // Create a WebContext and add it to the ApplicationLifetimeObjects collection.
            // This will then be available as WebContext.Current.
            WebContext webContext = new WebContext();
            webContext.Authentication = new FormsAuthentication()
            {
                DomainContext = new AuthenticationDomainService1()
            };
            //webContext.Authentication = new WindowsAuthentication();
        }
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            //当前参数
            object coursePack = null;
            //输入异常
            filterContext.HttpContext.Response.Write(string.Format("<br/> {0} Action start Execute.....", Message));
            //给当前控制器加参数
            if (filterContext.ActionParameters.ContainsKey("currentCoursePack"))
            {
                filterContext.ActionParameters["currentCoursePack"] = null;
            }
            if (filterContext.ActionParameters.ContainsKey("currentCoursePack"))
            {
                filterContext.ActionParameters["currentCoursePack"] = coursePack;
            }
            //设置当前控制器默认具备的viewBag
            filterContext.Controller.ViewBag.currentCoursePack = null;
            UserData ud = new WebContext(filterContext.HttpContext).GetUserData();
            filterContext.Controller.ViewBag.currentUserInfo = ud;

            //返回结果
            filterContext.Result = new HttpStatusCodeResult(404);

            base.OnActionExecuting(filterContext);
        }
Beispiel #6
0
        protected override XElement[] Do(WebContext context)
        {
            string title = context.httprequest.Form["title"].Trim();
            if(title == "") throw new FLocalException("title is empty");

            string[] rawOptions = context.httprequest.Form.GetValues("option");
            List<string> options = new List<string>();
            foreach(string rawOption in rawOptions) {
                if(rawOption != null && rawOption.Trim() != "") {
                    options.Add(rawOption.Trim());
                }
            }
            if(options.Count < 2) throw new FLocalException("Only " + options.Count + " options is entered");

            bool isDetailed = context.httprequest.Form.AllKeys.Contains("isDetailed");
            bool isMultiOption = context.httprequest.Form.AllKeys.Contains("isMultiOption");

            Poll poll = Poll.Create(
                context.session.account.user,
                isDetailed,
                isMultiOption,
                title,
                options
            );
            return new XElement[] {
                poll.exportToXml(context),
            };
        }
Beispiel #7
0
		/// <summary>
		/// </summary>
		/// <param name="context"></param>
		public void Process(WebContext context) {
            var parameters = RequestParameters.Create(context);
		    var script = parameters.PostData;
		    
		    string lang = parameters.Get("lang");
		    string format = parameters.Get("format");

			Func<string, XElement> executor = null;
			if (lang == "bxl"){
				executor = BxlExecutor;
			}
			else{
				executor = BSharpExecutor;
			}
			Action<XElement, WebContext> render = null;
			if (format == "wiki"){
				render = RenderAsWiki;
			}
			else{
				render = RenderAsNative;
			}
			
			_showroot = script.Contains("##showroot");
			XElement xml = null;
			try{
				xml = executor(script);
			}
			catch (Exception ex){
				xml = new XElement("error", ex.ToString());
			}
			render(xml, context);
		}
        public void Run(IHostServer server, WebContext context, string callbackEndPoint, CancellationToken cancel) {
            var id = context.User.Identity as Identity;
            if(null==id)throw new Exception("invalid identity type");
            if (null == id.ImpersonationSource) {
                if(!id.IsAdmin)throw new Exception("not admin");
            }
            var src = id.ImpersonationSource ?? id;
            var p = RequestParameters.Create(context);
            var to = p.Get("login");
            Identity newid = null;
            if (string.IsNullOrWhiteSpace(to)) {
                newid = (Identity)src;
            }
            else {
                var user = Users.GetUser(to);
                if (null != user) {
                    newid = new Identity(user);

                }
                else {
                    newid =new Identity{Name = to, IsAuthenticated = true};
                }
                newid.ImpersonationSource = src;
            }
            context.User = new GenericPrincipal(newid,null);
            var token = TokenService.Create(context.Request);
            newid.Token = token;
            TokenService.Store(context.Response,context.Request.Uri,token);
            context.Finish(newid.stringify());
        }
Beispiel #9
0
 protected override IEnumerable<XElement> getSpecificData(WebContext context)
 {
     if(!context.httprequest.Path.StartsWith("/static/") && !context.httprequest.Path.StartsWith("/favicon")) context.LogError(new WrongUrlException());
     return new XElement[] {
         new XElement("path", context.httprequest.Path)
     };
 }
Beispiel #10
0
        protected override XElement[] Do(WebContext context)
        {
            Post post = Post.LoadById(int.Parse(context.httprequest.Form["postId"]));
            XElement postXml = post.exportToXml(context);
            post.Punish(
                context.session.account,
                PunishmentType.LoadById(int.Parse(context.httprequest.Form["punishmentTypeId"])),
                context.httprequest.Form["comment"].Trim(),
                (context.httprequest.Form["transfer"] == "transfer")
                    ?
                    (PunishmentTransfer.NewTransferInfo?)new PunishmentTransfer.NewTransferInfo(Board.LoadById(int.Parse(context.httprequest.Form["transfer_boardId"])), context.httprequest.Form["transfer_subThread"] == "transfer_subThread")
                    :
                    null,
                (context.httprequest.Form["layerChange"] == "layerChange")
                    ?
                    (PunishmentLayerChange.NewLayerChangeInfo?)new PunishmentLayerChange.NewLayerChangeInfo(PostLayer.LoadById(int.Parse(context.httprequest.Form["layerChange_layerId"])), context.httprequest.Form["layerChange_subThread"] == "layerChange_subThread")
                    :
                    null
            );

            return new XElement[] {
                post.thread.board.exportToXml(context, Board.SubboardsOptions.None),
                postXml
            };
        }
		/// <summary>
		/// 
		/// </summary>
		/// <param name="server"></param>
		/// <param name="context"></param>
		/// <param name="callbackEndPoint"></param>
		/// <param name="cancel"></param>
		public override void Run(IHostServer server, WebContext context, string callbackEndPoint, CancellationToken cancel) {
			var container = server.Container;
			if (container == null) {
				throw new Exception("Cannot access container");
			}
			var caProxy = container.Get<ICaWrapper>();
			if (caProxy == null) {
				throw new Exception("Cannot access CA proxy");
			}
			if (context.PreparedParameters == null) {
				context.PreparedParameters = RequestParameters.Create(context);
			}
			var certId = context.PreparedParameters.Get("cert");
			var message = context.PreparedParameters.Get("message");
			if (string.IsNullOrWhiteSpace(certId)) {
				throw new ArgumentException("Empty certificate fingerprint");
			}
			if (string.IsNullOrWhiteSpace(message)) {
				throw new ArgumentException("Empty encrypted message");
			}
			var user = caProxy.ProcessAuth(certId, message);
			if (user != null) {
				var result = ProcessUserLogin(user, server, context);
				var strResult = result.Result.stringify();
				context.Finish(strResult);
				return;
			}
			context.Finish("false");
		}
Beispiel #12
0
 public void CleanUp()
 {
     if (this._webContext != null)
     {
         this._webContext.Dispose();
         this._webContext = null;
     }
 }
		public override void Run(IHostServer server, WebContext context, string callbackEndPoint, CancellationToken cancel) {
			var container = server.Container;
			if (container == null) {
				throw new Exception("Cannot access container");
			}
			if (context.PreparedParameters == null) {
				context.PreparedParameters = RequestParameters.Create(context);
			}
			var certId = context.PreparedParameters.Get("cert");
			if (string.IsNullOrWhiteSpace(certId)) {
				throw new ArgumentException("Empty certificate fingerprint");
			}
			var hostConfigProvider = container.Get<IHostConfigProvider>();
			if (hostConfigProvider == null) {
				throw new Exception("Cannot resolve server role");
			}
			var hostConfig = hostConfigProvider.GetConfig();
			if (hostConfig == null) {
				throw new Exception("Cannot resolve server role");
			}
			var definition = hostConfig.Definition;
			if (definition == null) {
				throw new Exception("Cannot resolve server role");
			}
			var caAttr = definition.Attr("ca");
			if (!string.IsNullOrWhiteSpace(caAttr) && caAttr.To<bool>()) {
				lock (Sync) {
					Salt saltObj;
					if (Salts.ContainsKey(certId)) {
						saltObj = Salts[certId];
						if (saltObj.Expire <= DateTime.UtcNow) {
							saltObj = new Salt {
								Value = Guid.NewGuid().ToString(),
								Expire = DateTime.UtcNow.AddHours(1)
							};
							Salts[certId] = saltObj;
						}
					} else {
						saltObj = new Salt {
							Value = Guid.NewGuid().ToString(),
							Expire = DateTime.UtcNow.AddHours(1)
						};
						Salts[certId] = saltObj;
					}
					context.Finish("\"" + saltObj.Value + "\"");
					CleanUpExpiredSaltsInternal();
					return;
				}
			}
			var caProxy = container.Get<ICaWrapper>();
			if (caProxy == null) {
				throw new Exception("Cannot access CA proxy");
			}
			context.ContentType = MimeHelper.JSON;
			var salt = caProxy.GetSalt(certId);
			context.Finish(salt);
		}
Beispiel #14
0
        /// <summary>
        /// Creates a new <see cref="App"/> instance.
        /// </summary>
        public App() {
            InitializeComponent();

            // Create a WebContext and add it to the ApplicationLifetimeObjects
            // collection.  This will then be available as WebContext.Current.
            WebContext webContext = new WebContext();
            webContext.Authentication = new FormsAuthentication();
            //webContext.Authentication = new WindowsAuthentication();
            this.ApplicationLifetimeObjects.Add(webContext);
        }
Beispiel #15
0
        protected override XElement[] Do(WebContext context)
        {
            Upload upload = Upload.LoadById(int.Parse(context.httprequest.Form["uploadId"]));

            AvatarsSettings.RemoveAvatar(context.account, upload);

            return new XElement[] {
                new XElement("uploadedId", upload.id)
            };
        }
Beispiel #16
0
 protected override XElement[] Do(WebContext context)
 {
     HttpPostedFile file = context.httprequest.Files["file"];
     if(file == null) throw new FLocalException("file not uploaded");
     if(file.ContentLength != file.InputStream.Length) throw new FLocalException("file is not uploaded completely");
     Upload upload = UploadManager.SafeUploadFile(file.InputStream, System.IO.Path.GetFileName(file.FileName), context.session.account.user);
     return new XElement[] {
         new XElement("uploadedId", upload.id)
     };
 }
 protected string getTitle(WebContext context)
 {
     string title = context.httprequest.Form["title"].Trim();
     if(title == "") {
         throw new FLocalException("Title is empty");
     }
     if(title.Length > 100) {
         throw new FLocalException("Title is too long");
     }
     return title;
 }
Beispiel #18
0
 protected override IEnumerable<XElement> getSpecificData(WebContext context)
 {
     Uri url = context.httprequest.Url;
     return new XElement[] {
         new XElement(
             "url",
             new XElement("host", url.Host),
             new XElement("port", url.Port)
         ),
     };
 }
 protected string getBody(WebContext context)
 {
     string body = context.httprequest.Form["Body"].Trim();
     if(body == "") {
         throw new FLocalException("Body is empty");
     }
     if(body.Length > 30000) {
         throw new FLocalException("Body is too long");
     }
     return body;
 }
        protected override void _Do(WebContext context)
        {
            string[] requestParts = context.httprequest.Path.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries);

            Account account = context.session.account;
            Thread thread = Thread.LoadById(int.Parse(requestParts[2]));
            if(!requestParts[3].StartsWith("p")) throw new WrongUrlException(); //throw new CriticalException("wrong url");
            Post post = Post.LoadById(int.Parse(requestParts[3].PHPSubstring(1)));

            //if(post.thread.id != thread.id) throw new CriticalException("id mismatch");

            thread.forceMarkAsRead(account, post);
        }
Beispiel #21
0
 private XDocument getData(WebContext context)
 {
     var st = Stopwatch.StartNew();
     var specificData = this.getSpecificData(context);
     var commonData = this.getCommonData(context);
     return new XDocument(
         new XElement("root",
             specificData,
             commonData,
             new XElement("processingTime", st.ElapsedMilliseconds)
         )
     );
 }
		/// <summary>
		///		Произведение авторизации и всех сопутствующих процедур
		/// </summary>
		/// <param name="user">Пользователь</param>
		/// <param name="server">Сервер</param>
		/// <param name="context">Контекст</param>
		/// <returns>HandlerResult</returns>
		private HandlerResult ProcessUserLogin(IUser user, IHostServer server, WebContext context) {
			var identity = new Identity(user) {AuthenticationType = "secure"};
			context.User = new GenericPrincipal(identity, null);
			var logondata = new LogonInfo {
				Identity = identity,
				RemoteEndPoint = context.Request.RemoteEndPoint,
				LocalEndPoint = context.Request.LocalEndPoint,
				UserAgent = context.Request.UserAgent
			};
			var token = TokenService.Create(context.Request);
			TokenService.Store(context.Response, context.Request.Uri, token);
			return new HandlerResult { Result = true, Data = logondata };
		}
Beispiel #23
0
        protected override XElement[] Do(WebContext context)
        {
            User.UserData newData = new User.UserData {
                location = context.httprequest.Form["location"].Trim(),
                title = context.httprequest.Form["title"].Trim(),
                signatureUbb = context.httprequest.Form["signature"].Trim(),
                biographyUbb = context.httprequest.Form["biography"].Trim(),
            };

            context.account.user.UpdateData(newData);

            return new XElement[0];
        }
Beispiel #24
0
 protected IEnumerable<XElement> getCommonData(WebContext context)
 {
     return new XElement[] {
         new XElement("handlerName", this.GetType().FullName),
         new XElement("title", Config.instance.AppInfo),
         new XElement("timestamp", DateTime.Now.Ticks.ToString()),
         context.userSettings.skin.exportToXml(),
         context.userSettings.modernSkin.exportToXml(),
         context.userSettings.machichara.exportToXml(),
         context.exportSession(),
         context.exportRequestParameters(),
     };
 }
Beispiel #25
0
 public void Handle(WebContext context)
 {
     try {
         context.WriteTransformResult(this.templateName, this.getData(context));
     } catch(response.SkipXsltTransformException) {
     } catch(RedirectException) {
         throw;
     } catch(WrongUrlException) {
         throw;
     } catch(Exception e) {
         context.LogError(e);
         context.WriteTransformResult("Exception.xslt", new XDocument(new XElement("root", this.getCommonData(context), e.ToXml())));
     }
 }
 protected override Account DoCreateAccount(WebContext context)
 {
     Account account = Account.LoadById(int.Parse(context.httprequest.Form["accountId"]));
     if(!account.needsMigration) throw new FLocalException("Account '" + account.name + "' is already migrated");
     string userInfo = ShallerGateway.getUserInfoAsString(account.user.name);
     Regex regex = new Regex("\\(fhn\\:([a-z0-9]+)\\)", RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.Singleline);
     Match match = regex.Match(userInfo);
     if(!match.Success) throw new FLocalException("key (fhn:***) not found on user info page ( http://forumlocal.ru/showprofile.php?User="******"&What=login&showlite=l )");
     string check = Util.md5(match.Groups[1].Value +  " " + Config.instance.SaltMigration + " " + account.id);
     if(check != context.httprequest["check"]) throw new FLocalException("Wrong key (fhn:" + match.Groups[1].Value + ")");
     if(context.httprequest.Form["password"] != context.httprequest.Form["password2"]) throw new FLocalException("Passwords mismatch");
     account.migrate(context.httprequest.Form["password"], context.httprequest.UserHostAddress, context.httprequest.Form["registrationEmail"]);
     return account;
 }
        public App()
        {
            this.Startup += this.Application_Startup;
            this.Exit += this.Application_Exit;
            this.UnhandledException += this.Application_UnhandledException;

            InitializeComponent();
            WebContext webcontext = new WebContext();
            FormsAuthentication formsAuthentication = new System.ServiceModel.DomainServices.Client.ApplicationServices.FormsAuthentication();
            formsAuthentication.DomainContext = new AuthenticationContext();
            webcontext.Authentication = formsAuthentication;

            this.ApplicationLifetimeObjects.Add(webcontext);
        }
Beispiel #28
0
        protected override XElement[] Do(WebContext context)
        {
            Upload upload = null;

            if(!string.IsNullOrEmpty(context.httprequest.Form["uploadId"])) {
                upload = Upload.LoadById(int.Parse(context.httprequest.Form["uploadId"]));
            }

            context.account.user.SetAvatar(upload);

            return new XElement[] {
                (upload != null) ? new XElement("uploadedId", upload.id) : null
            };
        }
        protected override sealed XElement[] Do(WebContext context)
        {
            if(context.httprequest.Form["constitution"] != "constitution") {
                throw new FLocalException("constitution not accepted");
            }
            if(context.httprequest.Form["showPostsToAll"] != "showPostsToAll") {
                throw new FLocalException("publicity not accepted");
            }
            if(context.httprequest.Form["law"] != "law") {
                throw new FLocalException("laws not accepted");
            }

            this.DoCreateAccount(context);
            return new XElement[0];
        }
Beispiel #30
0
        private SystemManageDomainContext SystemManageDomainContext; //= new SystemManageDomainContext();

        #endregion Fields

        #region Constructors

        //public ILogonPersionCallBack LogonPersionCallBack;
        public App()
        {
            SystemManageDomainContext = new SystemManageDomainContext();

            this.Startup += this.Application_Startup;
            this.Exit += this.Application_Exit;
            this.UnhandledException += this.Application_UnhandledException;

            InitializeComponent();
            CompositionInitializer.SatisfyImports(this);
            WebContext webContext = new WebContext();
            webContext.Authentication = new FormsAuthentication();
            this.ApplicationLifetimeObjects.Add(webContext);

            //LogonPersionCallBack = new OnLinePersionCallBack();
        }