Esempio n. 1
0
        public override void OnAuthorization(HttpActionContext actionContext)
        {
            var authHeader = actionContext.Request.Headers.Authorization;

            if (authHeader != null)
            {
                var authenticationToken        = actionContext.Request.Headers.Authorization.Parameter;
                var decodedAuthenticationToken = Encoding.UTF8.GetString(Convert.FromBase64String(authenticationToken));
                var usernamePasswordArray      = decodedAuthenticationToken.Split(':');
                var userName = usernamePasswordArray[0];
                var password = usernamePasswordArray[1];

                var isValid = CheckMethods.CheckIsUserExist(userName, password);

                if (isValid)
                {
                    var principal = new GenericPrincipal(new GenericIdentity(userName), null);
                    Thread.CurrentPrincipal = principal;


                    return;
                }
            }

            HandleUnathorized(actionContext);
        }
Esempio n. 2
0
        public ActionResult CreateUser(string name, string surname, string email, string password, string username,
                                       int roleId)
        {
            var isAdmin = CheckMethods.IsCurrentUserAdmin(User.Identity.Name);

            if (User.Identity.IsAuthenticated && isAdmin)
            {
                using (var db = new BlogDbContext())
                {
                    var user = new User();
                    user.Name     = name;
                    user.Surname  = surname;
                    user.Email    = email;
                    user.Username = username;
                    user.Password = GetMethods.GetHash(password);
                    user.RoleId   = roleId;
                    db.Users.Add(user);
                    db.SaveChanges();

                    return(View("~/Views/Admin/AdminMain.cshtml"));
                }
            }

            return(new HttpStatusCodeResult(HttpStatusCode.Forbidden));
        }
Esempio n. 3
0
        /**<summary>Assigns a value (string + Expression()) into variables (dictionary). Outputs "Invalid Assignment!"
         * if assignment is invalid and exits/returns the function</summary>
         *
         * <remarks>The assignment is invalid if fails to meet any one of the following criteria:
         * <list type="bullet">
         * <item><term>If the expression contains more than one "=" characters</term></item>
         * <item><term>If the variables name contains no spaces and no numbers</term></item>
         * <item><term>If the expression is valid, see <see cref="Expression.IsExpressionValid()"/></term></item>
         * </list>
         * </remarks>
         */
        public static void Assign(string assignmentExpression)
        {
            #region CHECK_IF_THE_ASSIGNMENT_IS_CORRECT

            var variableAndExpression = assignmentExpression.Split("=");

            //the assignment expression can only have one equal
            if (variableAndExpression.Length != 2)
            {
                AnsiConsole.MarkupLine("[red]Invalid Assignment![/]");
                return;
            }

            var variable   = variableAndExpression[0].Trim();
            var expression = new Expression(variableAndExpression[1].Trim());

            //checks if the variable's name is valid (no spaces, no numbers)
            variable = new Regex(" +").Replace(variable, " ");
            if (Regex.IsMatch(variable, "\\d+") || variable.Contains(" "))
            {
                AnsiConsole.MarkupLine("[red]Invalid Assignment![/]");
                return;
            }

            //checks if the expression is valid
            if (!expression.IsValid)
            {
                AnsiConsole.MarkupLine("[red]Invalid Assignment![/]");
                return;
            }

            //checks if the variable is already defined as a constant
            if (constants.ContainsKey(variable.Trim().ToLower()))
            {
                AnsiConsole.MarkupLine($"[red]\"{variable}\" is already defined as a constant![/]");
                return;
            }

            //prevents the (re)assigning of a function. ex "sin = 20"
            if (CheckMethods.IsAFunction(variable))
            {
                AnsiConsole.MarkupLine($"[red]You can't (re)assign a function![/]");
                return;
            }

            #endregion

            if (variable.Equals("ans"))
            {
                AnsiConsole.MarkupLine($"[red]You can't re-assign \"{variable}\", it stores the value of the previous " +
                                       "expression.[/]");
                return;
            }


            variables[variable] = expression;
            AnsiConsole.MarkupLine("[blue]Assigned![/]");
        }
Esempio n. 4
0
 public AdminController()
 {
     _rehberView = new RehberViewMethods();
     _departman  = new GenericCrudMethod <Departman>();
     _personel   = new GenericCrudMethod <Personel>();
     _check      = new CheckMethods();
     _login      = new LoginController();
     _adminLogin = new GenericCrudMethod <Login>();
 }
Esempio n. 5
0
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            var isAdmin = CheckMethods.IsCurrentUserAdmin(httpContext.User.Identity.Name);

            if (httpContext.Request.IsAuthenticated && isAdmin)
            {
                return(true);
            }

            return(false);
        }
Esempio n. 6
0
        public ActionResult UserDeleteComment(int postId, int commentId)
        {
            string username = User.Identity.Name;
            var    userId   = GetMethods.GetUserId(username);

            if (CheckMethods.IsUsersComment(userId, commentId))
            {
                DeleteComment(commentId);
                return(RedirectToAction("ShowPost", "MainPage", new { postId = postId }));
            }
            return(RedirectToAction("AccessDenied", "Error"));
        }
Esempio n. 7
0
 public ActionResult UserDeletePost(int postId)
 {
     using (BlogDbContext db = new BlogDbContext())
     {
         var username = User.Identity.Name;
         if (CheckMethods.IsUsersPost(postId, username))
         {
             DeletePost(postId);
             return(RedirectToAction("Profile", "Account"));
         }
     }
     return(RedirectToAction("AccessDenied", "Error"));
 }
Esempio n. 8
0
        public ActionResult UserUpdatePost(int postId, string title, string content)
        {
            using (BlogDbContext db = new BlogDbContext())
            {
                var username = User.Identity.Name;
                if (CheckMethods.IsUsersPost(postId, username))
                {
                    InsertMethods.UpdatePost(postId, title, content);
                    return(RedirectToAction("ShowPost", "MainPage", new { postId }));
                }
            }

            return(RedirectToAction("AccessDenied", "Error"));
        }
Esempio n. 9
0
 public ActionResult Register(RegisterModel model)
 {
     if (ModelState.IsValid)
     {
         var status = InsertMethods.RegisterNewUser(model);
         if (status == (int)Registration.Success && CheckMethods.IsUserExists(model.Login))
         {
             FormsAuthentication.SetAuthCookie(model.Login, true);
             return(RedirectToAction("Index", "Account"));
         }
     }
     ViewBag.Error = "Already exists";
     return(View("~/Views/Register/Registration.cshtml", model));
 }
Esempio n. 10
0
        public ActionResult OpenUserUpdatePost(int postid)
        {
            using (BlogDbContext db = new BlogDbContext())
            {
                var username = User.Identity.Name;
                if (CheckMethods.IsUsersPost(postid, username))
                {
                    ViewData["Layout"] = GetMethods.GetLayout(User.Identity.Name);
                    var post = db.Posts.FirstOrDefault(p => p.PostId == postid);
                    return(View("~/Views/User/UserUpdatePost.cshtml", post));
                }

                return(RedirectToAction("AccessDenied", "Error"));
            }
        }
Esempio n. 11
0
        public ActionResult OpenUpdateUser(int userId)
        {
            using (var db = new BlogDbContext())
            {
                var isAdmin = CheckMethods.IsCurrentUserAdmin(User.Identity.Name);
                if (User.Identity.IsAuthenticated && isAdmin)
                {
                    var user = db.Users.FirstOrDefault(u => u.UserId == userId);
                    ViewBag.User = user;
                    return(View("~/Views/Admin/CreateUser.cshtml"));
                }
            }

            return(new HttpStatusCodeResult(HttpStatusCode.Forbidden));
        }
Esempio n. 12
0
        public ActionResult Login(LoginModel model, object returnurl)
        {
            if (ModelState.IsValid)
            {
                if (CheckMethods.Authenticate(model.Login, model.Password))
                {
                    FormsAuthentication.SetAuthCookie(model.Login, true);
                    return(RedirectToAction("Index", "MainPage"));
                }
                else
                {
                    ViewBag.Error = "Пользователя с таким логином и паролем не существует";
                }
            }

            return(View("~/Views/Login/Login.cshtml", model));
        }
Esempio n. 13
0
        /** <summary>Returns true/false depending on whether the expession is valid or not (Respectively)</summary>
         *
         * <remarks>The region "SPECIFIC_CASES" detect whether an expression is a lone variable or a lone number.
         * <example>"someVariable" for a lone variable, and "-10" for a lone number</example>
         * Furthermore, the function also checks the following:
         * <list type="bullet">
         * <item><term>If the last character of the expression is an operator</term></item>
         * <item><term>If the all the values in the expression list are numbers separated by spaces</term></item>
         * <item><term>If the parenthesis are in the right order and properly formatted</term></item>
         * </list></remarks>
         */
        // ReSharper disable once CognitiveComplexity
        private bool IsExpressionValid()
        {
            #region SPECIFIC_CASES

            //Lone number case
            if (CheckMethods.IsANumber(InputExpression))
            {
                return(true);
            }

            //Lone variable case
            if (CheckMethods.IsAVariable(InputExpression) && ExpressionList.Count == 1)
            {
                return(true);
            }

            #endregion

            //checks if the last character is an operator
            if (CheckMethods.IsAValidOperator(InputExpression[^ 1].ToString()) ||
Esempio n. 14
0
        public ActionResult UserUpdateComment(int postId, int commentId)
        {
            using (BlogDbContext db = new BlogDbContext())
            {
                string username = User.Identity.Name;
                var    userId   = GetMethods.GetUserId(username);
                if (!CheckMethods.IsUsersComment(userId, commentId))
                {
                    return(RedirectToAction("AccessDenied", "Error"));
                }
                string commentToUpdate = db.Comments.Where(c => c.CommentId == commentId).Select(c => c.Content).FirstOrDefault();
                ViewBag.CommentToUpdate = commentToUpdate;
                var post     = db.Posts.FirstOrDefault(p => p.PostId == postId);
                var user     = db.Users.FirstOrDefault(u => u.UserId == post.UserId);
                var comments = db.Comments.Where(c => c.PostId == postId).ToList();
                comments     = GetMethods.GetInitializedUserList(comments);
                ViewBag.User = user;

                ViewBag.Comments   = comments;
                ViewData["Layout"] = GetMethods.GetLayout(User.Identity.Name);
                return(View("~/Views/Main/ShowPost.cshtml", post));
            }
        }
Esempio n. 15
0
        public JsonResult PostRegisterUser(string username, string name, string surname, string password, string email)
        {
            InsertMethods.RegisterNewUser(username, name, surname, password, email);
            if (CheckMethods.IsUserExists(username))
            {
                JsonResult res = new JsonResult()
                {
                    Data = new { status = "succesful" }
                };
                return(res);
            }

            var err = new Error()
            {
                ErrorCode = HttpStatusCode.InternalServerError, Message = "Server error"
            };

            JsonConvert.SerializeObject(err);
            return(new JsonResult()
            {
                Data = err
            });
        }
Esempio n. 16
0
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            ComplexEvRunner evr1 = new ComplexEvRunner(new List <Event>()
            {
                new Event(1, 2), new Event(1, 3), new Event(1, 3), new Event("NamedDice", 1, 2)
            });
            CheckMethods cm = new CheckMethods(evr1.checkSMIN);

            cm += new CheckMethods(evr1.checkFMIN);
            evr1.setChecks(cm, new List <int> {
                2, 1
            });
            evr1.Name = "Bollocks!";

            SimpleEvRunner evr2 = new SimpleEvRunner(new Event(1, 5), 0, 2);

            Application.Run(new ComplexEvForm(new ComplexEvRunner(new List <EventRunner>()
            {
                evr1, evr2
            })));
        }
 public void init()
 {
     checkMethods = new CheckMethods();
 }
Esempio n. 18
0
        /** <summary>If the expression is valid, the method solves the expression. Otherwise, it will return null
         * if the method is called and the validity of the expression is false, it will return null </summary>
         *
         * <remarks>The method turns the expression (which is in infix notation) into its postfix expression using the
         * <see cref="ExpressionManipulation.InfixToPostfix(string[])"/> function, then solves the expression using
         * a postfix expression solving algorithm described
         * <a href="https://runestone.academy/runestone/books/published/pythonds/BasicDS/InfixPrefixandPostfixExpressions.html">here</a>.
         * </remarks>.
         */
        // ReSharper disable once CognitiveComplexity
        public double?Solve()
        {
            if (!IsValid)
            {
                AnsiConsole.MarkupLine("[red]Cannot solve expression as it is invalid![/]");
                return(null);
            }

            //If the expression is a lone number, output it back
            if (CheckMethods.IsANumber(InputExpression))
            {
                var value = double.Parse(InputExpression);
                Variables.SetAns(value.ToString());
                return(value);
            }

            //If the expression is a lone variable, output its value back
            if (CheckMethods.IsAVariable(InputExpression) && ExpressionList.Count == 1)
            {
                var value = Variables.GetValue(InputExpression);
                if (value is not null)
                {
                    Variables.SetAns(value.ToString());
                    return(value);
                }
                AnsiConsole.MarkupLine($"[red]The variable \"{InputExpression}\" is not initialized![/]");
                return(null);
            }

            //Creates a copy of the list int o a string array
            var tempExpressionList = new string[ExpressionList.Count];

            for (var i = 0; i < ExpressionList.Count; i++)
            {
                tempExpressionList[i] = ExpressionList[i];
            }

            //substitutes the values of the variables in the expression. At this point, ALL variables are defined (checked).
            //A copy is used so the expression can mamintain its variables, so the value of a variable can change if the
            //vaues in its variables (if it has any) change.
            for (var i = 0; i < tempExpressionList.Length; i++)
            {
                if (CheckMethods.IsAFunction(tempExpressionList[i]))
                {
                    continue;
                }
                if (!CheckMethods.IsAVariable(tempExpressionList[i]))
                {
                    continue;
                }
                tempExpressionList[i] = Variables.GetValue(tempExpressionList[i]).ToString();
            }

            var            postfixExpression = ExpressionManipulation.InfixToPostfix(tempExpressionList);
            Stack <double> operandStack      = new Stack <double>();

            foreach (var token in postfixExpression)
            {
                if (CheckMethods.IsANumber(token))
                {
                    operandStack.Push(double.Parse(token));
                    continue;
                }

                //if it is a trigonometric function, it only needs the top of the stack. So it pops, calculates, then
                //pushes again.
                if (CheckMethods.IsAFunction(token))
                {
                    operandStack.Push(Computation.Compute(operandStack.Pop(), token));
                    continue;
                }

                //if its not a number, it is an operator
                var number2 = operandStack.Pop();
                var number1 = operandStack.Pop();
                operandStack.Push(Computation.Compute(number1, number2, token));
            }

            if (operandStack.Count == 1)
            {
                var value = operandStack.Pop();
                Variables.SetAns(value.ToString());     //sets the "ans" variable to this value
                return(value);
            }

            AnsiConsole.MarkupLine("[red]Invalid Expression (at Solve)[/]");
            return(null);
        }