public ActionResult LogOff()
        {
            logger.Info(Environment.NewLine + "User logged out: " + CookieHandler.GetUserNameFromCookie("LoginCookie") + " " + DateTime.Now);

            CookieHandler.DeleteCookie("LoginCookie");
            return(RedirectToAction("Login", "Login"));
        }
Beispiel #2
0
        public async Task <IActionResult> AddMessage([FromBody] MessageCreate msg, string username)
        {
            //Create a new message from logged in user
            //TODO if user not logged in
            if (!CookieHandler.LoggedIn(Request) &&
                !(Request.Headers.TryGetValue("Authorization", out var header) && header.Equals(AuthorizationConstants.terribleHackAuth)))
            {
                return(Unauthorized());
            }

            switch (Request.Method)
            {
            case "POST":
                _logger.LogInformation($"User: {username} posted msg: {msg.content}");
                _timelineRepository.PostMessage(username, msg.content);
                return(NoContent());

            case "GET":
                _logger.LogInformation($"GET request to msgs/{username} - This end point should not be called... Typically?");
                _timelineRepository.GetUserTimeline(username);
                return(NoContent());
            }


            return(NoContent());
        }
Beispiel #3
0
        public async Task <ActionResult> PerfilUsuario(Usuario modelo)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    HttpResponseMessage respuesta = await ApiHelper.PUT <Usuario>("Usuario/PutUsuarioPerfil", modelo, GetAuthToken);

                    if (respuesta.IsSuccessStatusCode)
                    {
                        Usuario nuevo = await ApiHelper.GET_By_ID <Usuario>("Usuario/GetUsuario", modelo.IdUsuario, GetAuthToken);

                        HttpContext.Response.Cookies.Set(CookieHandler.UpdateTicket(nuevo));
                    }
                    else
                    {
                        ModelState.AddModelError("", "Ha ocurrido un problema");
                    }
                }
                catch (Exception)
                {
                    ModelState.AddModelError("", "Ha ocurrido un problema");
                    throw;
                }
            }

            return(RedirectToAction("PerfilUsuario"));
        }
        private static void StoreUsernameImpl(string userName, bool persistAcrossSessions)
        {
            Verify.ArgumentNotNullOrEmpty(userName, "userName");

            userName = userName.ToLower(CultureInfo.InvariantCulture);

            TimeSpan timeToLive = (persistAcrossSessions ? TimeSpan.FromDays(365) : TempTicketMaxAge);

            var    ticket          = new FormsAuthenticationTicket(userName, persistAcrossSessions, (int)timeToLive.TotalMinutes);
            string encryptedTicket = FormsAuthentication.Encrypt(ticket);

            var cookie = CookieHandler.SetCookieInternal(AuthCookieName, encryptedTicket);

            cookie.HttpOnly = true;

            var context = HttpContext.Current;

            if (context != null && context.Request.IsSecureConnection)
            {
                cookie.Secure = true;
            }

            if (persistAcrossSessions)
            {
                cookie.Expires = DateTime.Now + timeToLive;
            }
        }
Beispiel #5
0
        public ActionResult EmptyCart(string returnUrl)
        {
            var ch = new CookieHandler();
            ch.EmptyCart();

            return RedirectToAction("Cart",new { returnUrl = returnUrl });
        }
Beispiel #6
0
        public ActionResult Update()
        {
            int    merchandiseId, orderAmount;
            string orderComment;

            // прочитать из Cookie идентификатор клиента
            var customerId = CookieHandler.GetCookieValue <String>(this.Request.Cookies, this.Response, CookieNames.CustomerId, Guid.NewGuid().ToString(), DateTime.Now.AddYears(1));

            #region Прочитать параметры POST-запроса

            if (this.Request.Params.Count == 0)
            {
                ViewBag.ResponseMessage = "error: В запросе не переданы обязательные параметры заказа.";
                return(View());
            }

            merchandiseId = RequestParametersHandler.GetRequestParameter <int>(this.Request.Params, WebRequestParamNames.MerchandiseId);
            orderAmount   = RequestParametersHandler.GetRequestParameter <int>(this.Request.Params, WebRequestParamNames.OrderAmount);
            orderComment  = RequestParametersHandler.GetRequestParameter <string>(this.Request.Params, WebRequestParamNames.OrderComment) ?? String.Empty;

            #endregion

            // Обновить заказ в БД
            ViewBag.ResponseMessage = this.service.UpdateMerchandiseInOrder(customerId, merchandiseId, orderAmount, orderComment);

            return(View());
        }
Beispiel #7
0
 protected void Page_Load(object sender, EventArgs e)
 {
     CookieHandler.checkLogin();
     Label1.Text = CookieHandler.getUsername();
     Label2.Text = CookieHandler.getPassword();
     Label3.Text = CookieHandler.getID().ToString();
 }
Beispiel #8
0
        public IActionResult FetchMaitenanceRequest()
        {
            try
            {
                int tenantID = CookieHandler.GetCurrentUserID(Request.Cookies["AuthToken"]);

                var activeRequest   = new List <MaintenanceRequest>();
                var inactiveRequest = new List <MaintenanceRequest>();
                var tenant          = Methods.Methods.GetTenant(tenantID);
                var Requests        = Methods.Methods.RetrieveMaitenanceRequests(tenant.PropertyID);

                foreach (var request in Requests)
                {
                    if (request.ActiveRequest)
                    {
                        activeRequest.Add(request);
                    }
                    else
                    {
                        inactiveRequest.Add(request);
                    }
                }
                return(Json(new { active = activeRequest, inactive = inactiveRequest }));
            }
            catch (Exception ex)
            {
                return(Ok(ex));
            }
        }
Beispiel #9
0
        public IActionResult VerifyBankAccount(string first, string second)
        {
            var tenantID = CookieHandler.GetCurrentUserID(Request.Cookies["AuthToken"]);
            var tenant   = Methods.Methods.GetTenant(tenantID);

            var deposits = new List <string>();

            deposits.Add(first);
            deposits.Add(second);
            try
            {
                if (StripeService.VerifyBankAccount(tenant, deposits))
                {
                    return(Json(new { success = true }));
                }
                else
                {
                    return(Json(new { success = false, error = "Could not verify bank." }));
                }
            }
            catch (Exception ex)
            {
                return(Json(new { success = false, error = ex.Message }));
            }
        }
Beispiel #10
0
        public IActionResult GetPaymentInfo()
        {
            var tenantID = CookieHandler.GetCurrentUserID(Request.Cookies["AuthToken"]);
            var tenant   = Methods.Methods.GetTenant(tenantID);

            //New tenants with no previous payment method
            if (tenant.StripeID == "")
            {
                return(Json(new { success = false }));
            }

            //Tenants who has a payment method on file, but needs to verify a bank account
            if (tenant.StripeIsVerified == false)
            {
                BankAccount bank = StripeService.GetBankAccount(tenant);
                return(Json(new { success = true, isVerified = false, paymentInfo = bank }));
            }

            //Tenant who has payment method on file, and ready to make payments.
            if (tenant.StripeIsVerified == true)
            {
                BankAccount bank = StripeService.GetBankAccount(tenant);
                return(Json(new { success = true, isVerified = true, paymentInfo = bank }));
            }
            return(BadRequest());
        }
        public ActionResult SignIn(FormCollection collection)
        {
            try
            {
                var authToken = collection.Get("oauth");
                if (authToken == null)
                {
                    return(RedirectToAction("Index", "Login"));
                }
                //if cookie doesnt exist
                var encodedTokenArray = System.Text.Encoding.UTF8.GetBytes(authToken);

                // make get request to get current user information from SC

                //TODO 'authToken' needs to be encrypted
                CookieHandler.generateCookie(HttpContext.Response.Cookies, "SoundCloudToken", authToken);

                // make get request to get current user information from SC
                /* this could all be in a class file. can make the api urls constants */

                return(RedirectToAction("Index", "User"));
            }
            catch
            {
                return(View());
                //return RedirectToAction("Index");
            }
        }
    /**
     * Notice that automatic compression doesn't work!
     */
    protected void Page_Load(object sender, EventArgs e)
    {
        if (directive == "compile")
        {
            _mode = CompositeScriptMode.COMPILE;
        }
        else if (CookieHandler.Get("mode") == "develop")
        {
            _mode = CompositeScriptMode.DEVELOP;
        }
        else
        {
            _mode = CompositeScriptMode.OPERATE;
        }

        string folderPath = Path.Combine(HttpContext.Current.Request.PhysicalApplicationPath, "Composite");

        switch (type)
        {
        case "top":
            _defaultscripts = ScriptHandler.GetTopScripts(_mode, folderPath);

            break;

        case "sub":
            _defaultscripts = ScriptHandler.GetSubScripts(_mode, folderPath);
            break;
        }
    }
Beispiel #13
0
        public async Task <IActionResult> Register([FromBody] RegisterModel model)
        {
            if (!ModelState.IsValid)
            {
                return(Unauthorized());
            }

            if (CookieHandler.LoggedIn(Request) && Guid.TryParse(Request.Cookies["userId"].ToString(), out var UserId))
            {
                return(RedirectToAction("Root", "Timeline"));
            }

            try
            {
                var res     = _userRepository.RegisterUser(model);
                var options = new CookieOptions();
                options.Expires = DateTime.UtcNow.AddSeconds(60);
                HttpContext.Response.Cookies.Append("user", model.username, options);
                HttpContext.Response.Cookies.Append("userId", res.ToString(), options);
                //return RedirectToAction("Root", "Timeline");
            } catch (Exception e)
            {
            }

            return(NoContent());
        }
        public async Task <IActionResult> fllws([FromBody] followModel follow, string username)
        {
            //TODO maybe auth
            //If user not logged in
            if (!CookieHandler.LoggedIn(Request) &&
                !(Request.Headers.TryGetValue("Authorization", out var header) && header.Equals(AuthorizationConstants.terribleHackAuth)))
            {
                return(Unauthorized());
            }

            // TODO: Figure out this mess :)
            if (string.IsNullOrEmpty(follow.follow))
            {
                _logger.LogInformation($"User {username} Unfollow user {follow.unfollow}");
                if (!_userRepository.UnfollowUser(username, follow.unfollow))
                {
                    return(NoContent());
                }
            }
            else if (string.IsNullOrEmpty(follow.unfollow))
            {
                _logger.LogInformation($"User {username} follow user {follow.follow}");
                if (!_userRepository.FollowUser(username, follow.follow))
                {
                    return(NotFound());
                }
            }
            return(NoContent());
        }
        protected override void Render(HtmlTextWriter writer)
        {
            string root = UrlUtils.AdminRootPath;

            if (Directive == "compile")
            {
                StyleCompiler.Compile(HostingEnvironment.MapPath(root + "/styles/styles.css"),
                                      HostingEnvironment.MapPath(root + "/styles/styles_compiled.css"));

                StyleCompiler.Compile(HostingEnvironment.MapPath(root + "/skins/skin.css"),
                                      HostingEnvironment.MapPath(root + "/skins/skin_compiled.css"));

                return;
            }

            bool isInDevelopMode = CookieHandler.Get("mode") == "develop";

            if (isInDevelopMode)
            {
                writer.WriteLine(stylesheet(root + "/styles/styles.css.aspx"));
                writer.WriteLine(stylesheet(root + "/skins/skin.css.aspx"));
            }
            else
            {
                writer.WriteLine(stylesheet(root + "/styles/styles_compiled.css.aspx"));
                writer.WriteLine(stylesheet(root + "/skins/skin_compiled.css.aspx"));
            }

            writer.WriteLine(stylesheet(root + "/skins/dynamicskin.css.aspx"));
        }
Beispiel #16
0
        public IActionResult GetInvoices()
        {
            try
            {
                var            tenantID       = CookieHandler.GetCurrentUserID(Request.Cookies["AuthToken"]);
                List <Invoice> paidInvoices   = new List <Invoice>();
                List <Invoice> unPaidInvoices = new List <Invoice>();
                var            tenant         = Methods.Methods.GetTenant(tenantID);
                var            invoices       = Methods.Methods.GetInvoices(tenant.PropertyID);

                foreach (var invoice in invoices)
                {
                    if (invoice.PaidInFull)
                    {
                        paidInvoices.Add(invoice);
                    }
                    else
                    {
                        unPaidInvoices.Add(invoice);
                    }
                }

                return(Json(new { success = true, paidInvoices = paidInvoices, unPaidInvoices = unPaidInvoices }));
            }
            catch (Exception ex)
            {
                return(Json(new { success = false, error = ex.Message }));
            }
        }
 public HomeController(ApiService apiService, IDataProtectionProvider provider, IConfiguration config, EncryptionService mock)
 {
     _provider     = provider;
     cookieHandler = new CookieHandler(new HttpContextAccessor(), _provider, config);
     _apiService   = apiService;
     _config       = config;
     _mock         = mock;
 }
Beispiel #18
0
        public IActionResult GetEmploymentInfo()
        {
            var tenantID = CookieHandler.GetCurrentUserID(Request.Cookies["AuthToken"]);

            var details = SQLStatements.GetEmploymentDetails(tenantID);

            return(Json(new { success = true, data = details }));
        }
Beispiel #19
0
 protected void Page_Load(object sender, EventArgs e)
 {
     CookieHandler.checkLogin();
     labelName.Text        = CookieHandler.getUserFullName();
     labelJet.Text         = CookieHandler.getCookieValue("jet");
     labelDate.Text        = CookieHandler.getCookieValue("date");
     labelDestination.Text = CookieHandler.getCookieValue("dest");
 }
 public void Init(HttpApplication application)
 {
     _corsHandler    = new CORSHandler();
     _requestHandler = new RequestHandler();
     _cookieHandler  = new CookieHandler();
     _headerHandler  = new HeaderHandler();
     application.PostAuthenticateRequest += OnPostAuthenticateRequest;
     application.BeginRequest            += application_BeginRequest;
 }
Beispiel #21
0
        /// <summary>
        /// Transform the received HTTP cookie to a stored request state instance.
        /// </summary>
        /// <param name="requestBase">Http Request to get the request state from.</param>
        public static StoredRequestState GetStoredRequestState(this HttpRequestBase requestBase)
        {
            if (requestBase == null)
            {
                throw new ArgumentNullException("requestBase");
            }

            return(Deserialize(Decrypt(CookieHandler.Read())));
        }
Beispiel #22
0
 public AuthController(IDataProtectionProvider provider, ApiService apiService, JwtHelper jwtHelper, LogInHandler logInHandler, IConfiguration config, EncryptionService encryptionService, NotificationService notify)
 {
     _apiService          = apiService;
     dataProtectionHelper = new DataProtectionHelper(provider);
     cookieHandler        = new CookieHandler(new HttpContextAccessor(), provider, config);
     _jwtHelper           = jwtHelper;
     _logInHandler        = logInHandler;
     _encryptionService   = encryptionService;
     _notify = notify;
 }
        private static async Task CookieMiddleware(HttpContext context, Func <Task> next)
        {
            if (context.Request.IsInteresting())
            {
                CookieHandler.Handle(context);
                HeaderHandler.Handle(context);
            }

            await next();
        }
        public static string retriveMe(HttpRequestBase request)
        {
            /* check if logged in*/

            /* need to pass in oauth ID */
            string command    = SoundCloudAPIConstants.SoundCloudCommands["Me"];
            string parameters = "?oauth_token=" + CookieHandler.getCookie(request, "SoundCloudToken").Value;

            return(HttpUtil.HttpGet(command, parameters));
        }
Beispiel #25
0
        // GET: /Order/Cancel
        public ActionResult Cancel()
        {
            // Проверка наличия в Cookie требуемых параметров - Идентификатор клиента
            var customerId = CookieHandler.GetCookieValue(this.Request.Cookies, this.Response, CookieNames.CustomerId, Guid.NewGuid().ToString(), DateTime.Now.AddYears(1));

            this.service.CancelActiveOrder(customerId);

            CookieHandler.SetCookieValue <bool>(this.Response, CookieNames.IsOrderNotEmpty, false, DateTime.Now.AddDays(1));

            return(View("Main", PrepareOrderDetails()));
        }
        public void FlushUsername()
        {
            CookieHandler.Set(AuthCookieName, "", DateTime.Now.AddYears(-10));

            string key = typeof(HttpContextBasedLoginSessionStore) + "StoredUsername";

            if (RequestLifetimeCache.HasKey(key))
            {
                RequestLifetimeCache.Remove(key);
            }
        }
Beispiel #27
0
        public void Handle(LogInCommand command)
        {
            using (var dbContext = new UserAccountDataContext())
            {
                User user = dbContext.Users.SingleOrDefault(u => u.Login == command.Login);
                ValidateLoginData(user, command);

                var appUser = CreateAppUserEntity(user);
                CookieHandler.Create(appUser, command.RememberMe);
            }
        }
        public static string retriveOAuthToken(HttpRequestBase request)
        {
            var parameters = "?client_id=" + _clientID
                             + "&client_secret=" + _secretKey
                             + "&redirect_uri=" + _redirectUrl
                             + "grant_type=authorization_code"
                             + "&code=" + CookieHandler.getCookie(request, "SoundCloudToken").Value;

            // decrypt token string

            return(HttpUtil.HttpPost("https://api.soundcloud.com/oauth2/token", parameters));
        }
        public IActionResult AdminLogin()
        {
            var cookie = Request.Cookies["AuthToken"];

            //Is Admin already authenticated?
            if (cookie != null && CookieHandler.GetTokenRole(cookie) == "admin")
            {
                return(Redirect("~/admin/"));
            }

            return(View("~/Views/Admin/login.cshtml"));
        }
        public IActionResult Login()
        {
            var cookie = Request.Cookies["AuthToken"];

            //Is Tenant already authenticated?
            if (cookie != null && CookieHandler.GetTokenRole(cookie) == "member")
            {
                return(Redirect("~/"));
            }

            return(View("~/Views/Home/login.cshtml"));
        }
Beispiel #31
0
        public async Task <JsonResult> ActualizarImagenPerfil()
        {
            try
            {
                HttpPostedFileBase file;
                string             fName = string.Empty;
                string             path  = string.Empty;
                string             fileName;

                if (Request.Files.AllKeys.Length != 0)
                {
                    fileName = Request.Files.AllKeys[0];
                    file     = Request.Files[fileName];
                    fName    = file.FileName;
                    if (file != null && file.ContentLength > 0)
                    {
                        string pic = System.IO.Path.GetFileName(fName);

                        path = System.IO.Path.Combine(Server.MapPath("~/ProfileImages"), pic);
                        file.SaveAs(path);
                        path = "/ProfileImages/" + pic;
                    }

                    HttpResponseMessage respuesta = await ApiHelper.PUT <Usuario>("Usuario/PutImagenPerfil", new Usuario()
                    {
                        IdUsuario = GetUserDecrypted.IdUsuario, Imagen = path
                    }, GetAuthToken);

                    if (respuesta.IsSuccessStatusCode)
                    {
                        Usuario nuevo = await ApiHelper.GET_By_ID <Usuario>("Usuario/GetUsuario", GetUserDecrypted.IdUsuario, GetAuthToken);

                        HttpContext.Response.Cookies.Set(CookieHandler.UpdateTicket(nuevo));

                        return(Json("Su imagen ha sido actualizada satisfactoriamente", JsonRequestBehavior.AllowGet));
                    }
                    else
                    {
                        Response.StatusCode = (int)HttpStatusCode.BadRequest;
                        return(Json("Ha ocurrido un error al guardar. Si el problema persiste contacte su administrador."));
                    }
                }
                else
                {
                    return(Json("Por favor, seleccione una nueva imagen"));
                }
            }
            catch (Exception)
            {
                Response.StatusCode = (int)HttpStatusCode.BadRequest;
                return(Json("Ha ocurrido un error al guardar. Si el problema persiste contacte su administrador."));
            }
        }
        public List<CartItem> GetCartList()
        {
            var ch = new CookieHandler();
            var productIdList = ch.GetCartProductIds();
            var productModelList = Services.Products.GetAll(productIdList);

            var cartItemList = productModelList.Select(p => new CartItem()
            {
                ProductId = p.Id,
                Name = p.Name,
                Count = ch.GetCount(p.Id),
                Price = p.Price
            }).ToList();

            return cartItemList;
        }
Beispiel #33
0
        public ActionResult Checkout()
        {
            if (Session["LoggedIn"] != null)
            {
                if ((bool)Session["LoggedIn"])
                {
                    var productBLL = new ProductBLL();
                    var ch = new CookieHandler();

                    var Email = (string)Session["Email"];
                    var pidList = ch.GetCartProductIds();
                    var productModelList = productBLL.GetProducts(pidList);

                    var cart = productModelList.Select(p => new CartItem()
                    {
                        ProductId = p.ProductId,
                        Name = p.ProductName,
                        Count = ch.GetCount(p.ProductId),
                        Price = p.Price
                    }).ToList();

                    var customerModel = new AccountBLL().GetCustomer(Email);
                    var customer = new CustomerView()
                    {
                        Firstname = customerModel.Firstname,
                        Lastname = customerModel.Lastname,
                        Address = customerModel.Address,
                        Zipcode = customerModel.Zipcode,
                        City = customerModel.City,
                        CustomerId = customerModel.CustomerId,
                        Email = customerModel.Email

                    };

                    ViewBag.Cart = cart;
                    ViewBag.Customer = customer;
                    ViewBag.LoggedIn = LoginStatus();
                    TempData["Message"] = "";
                    return View();
                }
            }
            TempData["Message"] = "Logg inn for å betale";
            return RedirectToAction("Index", "Home");
        }
 public int UpdateCartProductCount(int ProductId, int Count)
 {
     var ch = new CookieHandler();
     return ch.UpdateCartProductCount(ProductId, Count);
 }
 public BaseController()
 {
     Services = new ServiceManager();
     CookieHandler = new CookieHandler();
 }
Beispiel #36
0
        public ActionResult PlaceOrder(string returnUrl)
        {
            if (Session["LoggedIn"] != null)
            {
                if ((bool)Session["LoggedIn"])

                {
                    var productBLL = new ProductBLL();
                    var ch = new CookieHandler();

                    var productIdList = ch.GetCartProductIds();
                    var productModelList = productBLL.GetProducts(productIdList);

                    var cart = productModelList.Select(p => new CartItem()
                    {
                        ProductId = p.ProductId,
                        Name = p.ProductName,
                        Count = ch.GetCount(p.ProductId),
                        Price = p.Price
                    }).ToList();

                    var order = new OrderModel();
                    var orderlines = new List<OrderlineModel>();

                    foreach (var item in cart)
                    {
                        orderlines.Add(new OrderlineModel()
                        {
                            Count = item.Count,
                            ProductId = item.ProductId
                        });
                    }
                    order.Orderlines = orderlines;
                    order.CustomerId = new AccountBLL().GetCustomer((String)Session["Email"]).CustomerId;
                    order.Date = DateTime.Now;
                    var OrderId = _orderBLL.PlaceOrder(order);

                    if (OrderId > 0)
                    {
                        ch.EmptyCart();

                        ViewBag.LoggedIn = (bool)Session["LoggedIn"];
                        ViewBag.Reciept = GetReciept(OrderId);

                        return View("GetReciept");
                    }
                }
            }
            return RedirectToAction("Index", "Home");
        }
 public int RemoveFromCart(int ProductId)
 {
     var ch = new CookieHandler();
     return ch.RemoveFromCart(ProductId);
 }
 public int NumItemsInCart()
 {
     var ch = new CookieHandler();
     return ch.NumItemsInCart();
 }
 public void EmptyCart()
 {
     var ch = new CookieHandler();
     ch.EmptyCart();
 }
 public int AddToCart(int ProductId)
 {
     var ch = new CookieHandler();
     return ch.AddToCart(ProductId);
 }