예제 #1
0
        public static User GetUser()
        {
            var  context    = HttpContext.Current;
            var  session    = context.Session;
            var  useSession = session.Mode != SessionStateMode.Off;
            User ua;

            if (useSession)
            {
                ua = session[UserContextName] as User;
            }
            else
            {
                ua = context.Items[UserContextName] as User;
            }

            if (ua != null)
            {
                return(ua);
            }

            if (!context.Request.IsAuthenticated)
            {
                return(null);
            }
            var idString = context.User.Identity.Name;
            int id;

            if (!int.TryParse(idString, out id))
            {
                // invalid data in the authenticated user!
                FormsAuthentication.SignOut();
                return(null);
            }

            using (var db = new UploadDb())
            {
                var useraAccount = db.Users.AsNoTracking()
                                   .Where(a => a.UserID == id)
                                   .Select(a => a)
                                   .FirstOrDefault();
                if (useraAccount != null)
                {
                    ua = useraAccount;

                    if (useSession)
                    {
                        session[UserContextName] = ua;
                    }
                    else
                    {
                        context.Items[UserContextName] = ua;
                    }
                    return(ua);
                }
            }

            // invalid data in the authenticated user!
            return(null);
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            using (var db = new UploadDb())
            {
                const int itemsNo = 5;
                var       userId  = UserManager.GetUserId() ?? -1;
                var       user    = UserManager.GetUser();
                bool      isAdmin = user != null && user.IsAdmin;

                ucFiles.Files = db.Files.Include("User")
                                .OrderByDescending(a => a.UploadedFileID)
                                .Take(itemsNo)
                                .Where(a => a.IsPublic).ToList();
                if (ucFiles.Files.Count > 0)
                {
                    ucFiles.Files.ForEach(a =>
                    {
                        a.UploaderUsername = (a.User != null) ? a.User.UserName : "";
                        a.VisitorIsOwner   = isAdmin || a.UserId == userId;
                    });
                    ucFiles.DataBind();
                }
                else
                {
                    boxLatestFiles.Visible = false;
                }
            }
        }
예제 #3
0
        public static bool BasicAuthorize(HttpContext context)
        {
            var req = context.Request;
            var res = context.Response;

            string auth = req.Headers["Authorization"];

            if (!String.IsNullOrEmpty(auth))
            {
                byte[] encodedDataAsBytes = Convert.FromBase64String(auth.Replace("Basic ", ""));
                string value    = Encoding.ASCII.GetString(encodedDataAsBytes);
                string username = value.Substring(0, value.IndexOf(':'));
                string password = value.Substring(value.IndexOf(':') + 1);

                using (var db = new UploadDb())
                {
                    var user = db.Users.FirstOrDefault(a => a.UserName == username && a.Password == password);
                    if (user == null)
                    {
                        UnAuthorizationRequest(context);
                        return(false);
                    }
                    else
                    {
                        context.User = new GenericPrincipal(new GenericIdentity(user.UserID.ToString()), null);
                        return(true);
                    }
                }
            }
            else
            {
                UnAuthorizationRequest(context);
                return(false);
            }
        }
예제 #4
0
        protected void btnRegister_Click(object sender, EventArgs e)
        {
            var username = txtUsername.Text.Trim();
            var password = txtPassword.Text;
            var email    = txtEmail.Text.Trim();
            var isValid  = true;

            if (txtPasswordConfirm.Text != password)
            {
                AddError("Password confirm is not correct!");
                isValid = false;
            }

            if (txtEmailConfirm.Text != email)
            {
                AddError("Email confirm is not correct!");
                isValid = false;
            }
            if (username.Length < 2)
            {
                AddError("Username is too short");
                isValid = false;
            }
            if (password.Length < 2)
            {
                AddError("Password is too short");
                isValid = false;
            }

            if (!isValid)
            {
                return;
            }

            using (var db = new UploadDb())
            {
                var hasAdmin = db.Users.Any(a => a.IsAdmin);

                var user = new User()
                {
                    Email    = email,
                    IsAdmin  = !hasAdmin,
                    Password = password,
                    UserName = username
                };

                db.Users.Add(user);
                db.SaveChanges();

                if (!hasAdmin)
                {
                    Application.Remove("HasAdmin");
                }

                FormsAuthentication.SetAuthCookie(user.UserID.ToString(), true);
                Response.Redirect("/account/");
            }
        }
예제 #5
0
 void SetNoAdminFlag()
 {
     using (var db = new UploadDb())
     {
         var hasAdmin = db.Users.Any(a => a.IsAdmin);
         if (!hasAdmin)
         {
             Application["HasAdmin"] = false;
         }
     }
 }
예제 #6
0
        void Application_Start(object sender, EventArgs e)
        {
            // Code that runs on application startup
            AuthConfig.RegisterOpenAuth();
            RouteConfig.RegisterRoutes(RouteTable.Routes);

            BundleConfig.RegisterRoutes(BundleTable.Bundles);

            UploadDb.CreateIfNotExists();
            SetNoAdminFlag();
        }
예제 #7
0
 protected void Page_Load(object sender, EventArgs e)
 {
     if (!IsPostBack)
     {
         using (var db = new UploadDb())
         {
             var isAdminRegister = !db.Users.Any(a => a.IsAdmin);
             lblRegisterAdminHead.Visible = isAdminRegister;
             lblRegisterHead.Visible      = !isAdminRegister;
         }
     }
 }
예제 #8
0
 protected void Page_Load(object sender, EventArgs e)
 {
     if (!UserManager.UserIsAdmin())
     {
         Response.Redirect("Login.aspx");
         return;
     }
     using (var db = new UploadDb())
     {
         var users = db.Users.ToList();
         grdUsers.DataSource = users;
         grdUsers.DataBind();
     }
 }
예제 #9
0
        protected void Page_Load(object sender, EventArgs e)
        {
            var idStr = Request.QueryString["id"];
            int id;

            if (!int.TryParse(idStr, out id))
            {
                Response.Redirect("/");
                return;
            }
            using (var db = new UploadDb())
            {
                var file = db.Files.Include("User").FirstOrDefault(a => a.UploadedFileID == id);
                if (file == null)
                {
                    Response.Write("File not found!");
                    Response.StatusCode = 404;
                    Response.End();
                    return;
                }
                var user = UserManager.GetUser();
                if (!file.IsPublic)
                {
                    if (user == null || file.UserId != user.UserID)
                    {
                        Response.Redirect("/", true);
                        return;
                    }
                }

                bool visitorIsOwner = user != null && user.UserID == file.UserId;

                var uploaderUsername = "";
                if (file.User != null)
                {
                    uploaderUsername = file.User.UserName;
                }
                UploadedFile = file;


                file.VisitorIsOwner   = visitorIsOwner;
                file.UploaderUsername = uploaderUsername;
                ucFiles.Files         = new List <UploadedFile>()
                {
                    file
                };
                ucFiles.DataBind();
            }
        }
예제 #10
0
        protected void Page_Load(object sender, EventArgs e)
        {
            var query = (Request.QueryString["q"] ?? "").Trim();

            if (query.Length == 0)
            {
                Response.Redirect("/", true);
                return;
            }
            query = query.ToLower();

            using (var db = new UploadDb())
            {
                const int itemsNo = 5;
                var       user    = UserManager.GetUser();
                var       userId  = UserManager.GetUserId() ?? -1;
                bool      isAdmin = user != null && user.IsAdmin;

                ucFiles.Files = db.Files.Include("User")
                                .OrderByDescending(a => a.UploadedFileID)
                                .Where(a => a.Filename.ToLower().Contains(query))
                                .Where(a => a.IsPublic || a.UserId == userId)
                                .ToList();

                if (ucFiles.Files.Count > 0)
                {
                    ucFiles.Files.ForEach(a =>
                    {
                        a.UploaderUsername = (a.User != null) ? a.User.UserName : "";
                        a.VisitorIsOwner   = isAdmin || a.UserId == userId;
                    });
                    ucFiles.DataBind();
                }
                else
                {
                    AddError("Nothing found!");
                }
            }
        }
예제 #11
0
        protected void Page_Load(object sender, EventArgs e)
        {
            var user = UserManager.GetUser();

            if (user == null)
            {
                Response.Redirect("Login.aspx", true);
                return;
            }
            using (var db = new UploadDb())
            {
                var files = db.Files
                            .OrderByDescending(a => a.UploadedFileID)
                            .Where(a => a.UserId == user.UserID)
                            .ToList();
                ucFiles.Files = files;
                ucFiles.Files.ForEach(a =>
                {
                    a.UploaderUsername = user.UserName;
                    a.VisitorIsOwner   = true;
                });
                ucFiles.DataBind();



                if (files.Count == 0)
                {
                    boxMessage.Visible = true;
                    boxCount.Visible   = false;
                }
                else
                {
                    var totalSize = files.Sum(a => a.FileSize);
                    lblFilesCount.Text = UploadedFileManager.GetFileSizeString(totalSize) + " for " + files.Count + " file(s).";
                }
            }
        }
예제 #12
0
        protected void btnLogin_Click(object sender, EventArgs e)
        {
            var username = txtUsername.Text.Trim();
            var password = txtPassword.Text;
            var isValid  = true;

            if (username.Length == 0)
            {
                AddError("Username is too short");
                isValid = false;
            }
            if (password.Length == 0)
            {
                AddError("Password is too short");
                isValid = false;
            }

            if (!isValid)
            {
                return;
            }


            using (var db = new UploadDb())
            {
                var user = db.Users.FirstOrDefault(a => a.UserName == username && a.Password == password);

                if (user == null)
                {
                    AddError("Username or password is invalid.");
                    return;
                }

                FormsAuthentication.SetAuthCookie(user.UserID.ToString(), true);
                Response.Redirect("/account/");
            }
        }
예제 #13
0
        protected void btnFromPcUpload_Click(object sender, EventArgs e)
        {
            try
            {
                if (!filePcUpload.HasFile)
                {
                    AddError("No file is selected!");
                    return;
                }
                using (var db = new UploadDb())
                {
                    var fileName    = Path.GetFileName(filePcUpload.PostedFile.FileName);
                    var extension   = Path.GetExtension(fileName);
                    var sizeInBytes = filePcUpload.PostedFile.ContentLength;
                    var user        = UserManager.GetUser();
                    var isPublic    = txtVisibility.Value == "1";

                    var newName = txtNewName.Text.Trim();
                    if (newName.Length > 0)
                    {
                        fileName = newName;
                    }

                    var newFile = new UploadedFile
                    {
                        Comment        = txtRemoteComment.Text,
                        Extension      = extension,
                        Filename       = fileName,
                        Downloaded     = 0,
                        FileSize       = sizeInBytes,
                        LastDownload   = null,
                        UploadDate     = DateTime.Now.ToUniversalTime(),
                        UserId         = (user != null) ? user.UserID : (int?)null,
                        UploadedFileID = 0,
                        IsPublic       = isPublic
                    };

                    try
                    {
                        db.Files.Add(newFile);
                        db.SaveChanges();

                        var filePath = UploadedFileManager.MapToPhysicalPath(newFile);
                        filePcUpload.PostedFile.SaveAs(filePath);

                        Response.Redirect("file.aspx?id=" + newFile.UploadedFileID);
                    }
                    catch (ThreadAbortException ex)
                    {
                    }
                    catch (Exception ex)
                    {
                        if (newFile.UploadedFileID > 0)
                        {
                            db.Files.Remove(newFile);

                            db.SaveChanges();
                        }

                        AddError("An unhandled error occured.");
                        AddError(ex.Message);
                    }
                }
            }
            catch (Exception ex)
            {
                AddError(ex.Message);
            }
        }
예제 #14
0
        protected void rptRepeat_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            if (e.CommandName == "Delete")
            {
                var idString = e.CommandArgument.ToString();
                int id;
                if (!int.TryParse(idString, out id))
                {
                    return;
                }

                using (var db = new UploadDb())
                {
                    var file = db.Files.FirstOrDefault(a => a.UploadedFileID == id);
                    if (file == null)
                    {
                        Response.Write("File not found!");
                        Response.StatusCode = 404;
                        return;
                    }
                    var user = UserManager.GetUser();
                    if (user == null || (user.UserID != file.UserId && !user.IsAdmin))
                    {
                        Response.Write("You do not have the permission to delete!");
                        Response.StatusCode = 500;
                        return;
                    }
                    if (file.UserId == null && !user.IsAdmin)
                    {
                        Response.Write("You do not have the permission to delete!");
                        Response.StatusCode = 500;
                        return;
                    }

                    var fileAddress = UploadedFileManager.MapToPhysicalPath(file);
                    try
                    {
                        System.IO.File.Delete(fileAddress);

                        db.Files.Remove(file);
                        db.SaveChanges();
                        if (RedirectAfterDelete)
                        {
                            Response.Redirect(RedirectAfterDeleteLocation);
                        }
                        else
                        {
                            var notDisplayFile = Files.FirstOrDefault(a => a.UploadedFileID == file.UploadedFileID);
                            if (notDisplayFile != null)
                            {
                                Files.Remove(notDisplayFile);
                            }

                            ReloadFilesList();
                        }
                    }
                    catch (Exception ex)
                    {
                        AddError(ex.Message);
                    }
                }
            }
        }
        public void ProcessRequest(HttpContext context)
        {
            var request  = context.Request;
            var response = context.Response;

            // Accepting user request
            var idStr = request.QueryString["id"];

            try
            {
                int id;
                if (!int.TryParse(idStr, out id))
                {
                    InvalidRequest(context, "Invalid request!");
                    return;
                }
                UploadedFile uploadedFile;
                using (var db = new UploadDb())
                {
                    db.Configuration.AutoDetectChangesEnabled = false;
                    db.Configuration.ProxyCreationEnabled     = false;

                    var file = db.Files.FirstOrDefault(a => a.UploadedFileID == id);
                    if (file == null)
                    {
                        InvalidRequest(context, "File does not exists!");
                        response.StatusCode = 404;
                        return;
                    }
                    uploadedFile = file;
                }

                //SiteException.LogException(new Exception(
                //	string.Format("UploadedFileID:{0}, IsPublic:{1}, UploadDate:{2}, Filename:{3}",
                //		uploadedFile.UploadedFileID,
                //		uploadedFile.IsPublic,
                //		uploadedFile.UploadDate,
                //		uploadedFile.Filename)));

                if (uploadedFile.IsPublic == false)
                {
                    // check the owner
                    var user = UserManager.GetUser();
                    if (user == null)
                    {
                        var succeed = UserManager.BasicAuthorize(context);
                        if (!succeed)
                        {
                            return;
                        }
                        user = UserManager.GetUser();
                    }

                    // not the file owner!
                    if (user == null || user.UserID != uploadedFile.UserId)
                    {
                        context.Response.Clear();
                        context.Response.Write("You do not have access to download this file!");
                        context.Response.StatusCode = (int)HttpStatusCode.Forbidden;
                        context.Response.Flush();
                        context.Response.End();
                        return;
                    }
                }

                // file path
                var fileName = UploadedFileManager.MapToPhysicalPath(uploadedFile);

                // reading file info
                var fileInfo   = new FileInfo(fileName);
                var fileLength = fileInfo.Length;

                // Download information class
                using (var downloadInfo = new DownloadDataInfo(fileName))
                {
                    downloadInfo.DisplayFileName = UploadedFileManager.GetUrlFileName(uploadedFile);

                    // Reading request download range
                    var requestedRanges = HeadersParser.ParseHttpRequestHeaderMultipleRange(context.Request, fileLength);

                    // apply the ranges to the download info
                    downloadInfo.InitializeRanges(requestedRanges);

                    string etagMatched;
                    int    outcomeStausCode = 200;

                    // validating the ranges specified
                    if (!HeadersParser.ValidatePartialRequest(context.Request, downloadInfo, out etagMatched, ref outcomeStausCode))
                    {
                        // the request is invalid, this is the invalid code
                        context.Response.StatusCode = outcomeStausCode;

                        // show to the client what is the real ETag
                        if (!string.IsNullOrEmpty(etagMatched))
                        {
                            context.Response.AppendHeader("ETag", etagMatched);
                        }

                        // stop the preoccess
                        // but don't hassle with error messages
                        return;
                    }

                    // user ID, or IP or anything you use to identify the user
                    //var userIP = context.Request.UserHostAddress;

                    // Option 1: limiting the download speed for this file for this user!
                    //UserSpeedLimitManager.StartNewDownload(downloadInfo, userIP, DownloadLimit);

                    // Option 2: Limiting only this connection
                    downloadInfo.LimitTransferSpeed(DownloadLimit);

                    // It is very important to destory the DownloadProcess object
                    // Here the using block does it for us.
                    using (var process = new DownloadProcess(downloadInfo))
                    {
                        var state = DownloadProcess.DownloadProcessState.None;
                        try
                        {
                            // start the download
                            state = process.ProcessDownload(context.Response);
                        }
                        catch (HttpException)
                        {
                            // preventing:
                            // System.Web.HttpException (0x800703E3): The remote host closed the connection. The error code is 0x800703E3.
                        }

                        // checking the state of the download
                        if (state == DownloadProcess.DownloadProcessState.LastPartfinished)
                        {
                            // all parts of download are finish, do something here!
                            using (var db = new UploadDb())
                            {
                                var dbFile = db.Files.FirstOrDefault(a => a.UploadedFileID == uploadedFile.UploadedFileID);
                                if (dbFile != null)
                                {
                                    dbFile.Downloaded++;
                                    dbFile.LastDownload = DateTime.Now.ToUniversalTime();
                                    db.SaveChanges();
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                SiteException.LogException(ex, "ID: " + idStr);
                throw;
            }
        }
예제 #16
0
        protected void btnRemoteUpload_Click(object sender, EventArgs e)
        {
            try
            {
                var url = txtRemoteUrl.Text.Trim();
                Uri uri;
                if (string.IsNullOrWhiteSpace(url) || !Uri.TryCreate(url, UriKind.Absolute, out uri))
                {
                    AddError("Please enter a valid Url!");
                    return;
                }

                var fileName = Path.GetFileName(url);
                var newName  = txtNewName.Text.Trim();
                if (newName.Length > 0)
                {
                    fileName = newName;
                }

                var referer = txtReferrer.Text.Trim();

                // temporary file name
                var  fileTempAddress = UploadedFileManager.MapToPhysicalPath(fileName + Guid.NewGuid().ToString());
                long sizeInBytes     = 0;

                var cookies = Deserialize(txtCookies.Value);
                try
                {
                    using (var file = new FileStream(fileTempAddress, FileMode.Create))
                    {
                        Download(uri, referer, cookies, file);
                        sizeInBytes = file.Length;
                    }
                }
                catch (Exception)
                {
                    System.IO.File.Delete(fileTempAddress);
                    throw;
                }

                // done!
                using (var db = new UploadDb())
                {
                    var extension = Path.GetExtension(fileName);
                    var user      = UserManager.GetUser();
                    var isPublic  = txtVisibility.Value == "1";

                    var newFile = new UploadedFile
                    {
                        Comment        = txtRemoteComment.Text,
                        Extension      = extension,
                        Filename       = fileName,
                        Downloaded     = 0,
                        FileSize       = sizeInBytes,
                        LastDownload   = null,
                        UploadDate     = DateTime.Now.ToUniversalTime(),
                        UserId         = (user != null) ? user.UserID : (int?)null,
                        UploadedFileID = 0,
                        IsPublic       = isPublic
                    };

                    try
                    {
                        db.Files.Add(newFile);
                        db.SaveChanges();

                        var filePath = UploadedFileManager.MapToPhysicalPath(newFile);
                        System.IO.File.Move(fileTempAddress, filePath);

                        Response.Redirect("file.aspx?id=" + newFile.UploadedFileID);
                    }
                    catch (ThreadAbortException ex)
                    {
                    }
                    catch (Exception ex)
                    {
                        if (newFile.UploadedFileID > 0)
                        {
                            db.Files.Remove(newFile);

                            db.SaveChanges();
                        }
                        try
                        {
                            System.IO.File.Delete(fileTempAddress);
                        }
                        catch { }

                        AddError("An unhandled error occured.");
                        AddError(ex.Message);
                    }
                }
            }
            catch (Exception ex)
            {
                AddError(ex.Message);
            }
        }