How do I limit an user?

Just starting out? Need help? Post your questions and find answers here.
AMpos
Posts: 42
Joined: Mon Aug 03, 2020 5:15 pm

How do I limit an user?

Post by AMpos »

I am making a program, where users can upload photos to my server:

https://www.photocallevents.com/demo/index.htm

And I want to limit the photos an user can upload (5 photos, per example)

How can I do it?

I dont care if the user delete his cache to upload more photos, it is not a big problem.

But I don't know how to save a file locally in the user browser (I dont want to control it on server side)

Bonus track: how to do it to limit to X photos per hour?
killer128k
Posts: 7
Joined: Sat Apr 03, 2021 10:54 am

Re: How do I limit an user?

Post by killer128k »

[Eng]
Hello,
For each user to whom you give access to your site, you can assign a folder and put the files there. If the size of the folder exceeds a certain size you block the transfer of files.
You can also put the files on the local sql. I share with you an adaptation of my source code that may be of interest to you.

[Fr]
Bonjour,
Pour chaques utilisateur à qui tu donne un accès sur ton site, tu peux attribuer un dossier et mettre les fichiers dedans. Si la taille du dossier dépasse une certaine taille tu bloque le trasfert des fichiers.
Tu peux aussi mettre les fichiers sur la sql local. Je te partage une adaptation de mon code source peux être quelle t'interessera.

Code: Select all

;
; ------------------------------------------------------------
;
;   charger une image en streaming en local puis l'afficher by klr128
;   avec l'image redimentionné ;encodage et decodage base64 pour envoi blob mysql
;   va enregistrer les images dans la DB puis les charger
; ------------------------------------------------------------
;
;EnableExplicit
 Global *DatabaseBuffer
 Global scrollgad
 Global offy=0 
 Global scrollgad2=10
 
Procedure CatchImageExCallback(Image)
  OpenGadgetList(scrollgad2)  
    ImageGadget(#PB_Any, 0, offy, ImageWidth(Image), ImageHeight(Image), ImageID(Image))
  CloseGadgetList()
  offy=offy + ImageHeight(Image)+10
EndProcedure

Procedure CatchImageEx(Image, Base64String.s, Callback) 
  Protected W, H, IID
  i=0
  ! var v_i = new Image();
  ! v_i.onload = function(){
  !   v_w = v_i.width;
  !   v_h = v_i.height;
  If Image = #PB_Any
    Image = CreateImage(#PB_Any, W, H)
  Else
    CreateImage(Image, W, H)
  EndIf
  IID = ImageID(Image)  
  !   v_iid.getContext("2d").drawImage(v_i, 0, 0);
  !   v_callback(v_image);
  ! };
  ! console.log("hahassss "+v_base64string);
  ! v_i.src = v_base64string;
EndProcedure

Procedure CreateFileCallback(Status, Filename$, File, SizeRead)
  Select Status
    Case #PB_Status_Saved
      Debug "Database file saved: " + Filename$
      Debug "Please relaunch the program to test the persitency."
    Case #PB_Status_Error
      Debug "Can't save the database: " + Filename$
  EndSelect
EndProcedure

Procedure OnaffDB() ;va suprimer les images présente dans le gadget scrollgad2
  ;  ReadFile(0, "dbsqlitev3.sqlite", @ReadFileCallback(), #PB_LocalStorage)
  nbb=0
  ! var GadgetElement = spider_GadgetID(v_scrollgad2).div;
  ! var tt =GadgetElement.childNodes;
  ! spider.debug.Print(GadgetElement);
  ! var tt2 =tt[0].childNodes;
  ! v_nbb = tt2.length;
  ! spider.debug.Print(v_nbb);
  For sd=0 To nbb-1
    ! tt2[v_nbb-1-v_sd].remove();
  Next
  Debug "delet fin"
  offy=0
EndProcedure

Procedure Loaded(Type, Filename$, ObjectId)
  If ImageWidth(ObjectId)>=ImageHeight(ObjectId)
    vv.f= (300-40)*100/ImageWidth(ObjectId)
    bob=ResizeImage(ObjectId, (300-40), ImageHeight(ObjectId)*vv/100);,#PB_Image_Raw)
  Else
    vv.f= (300 -40)*100/ImageHeight(ObjectId) ;380 -90    
    bob= ResizeImage(ObjectId, ImageWidth(ObjectId)*vv/100, (300-40))
  EndIf
  IDD = ImageID(bob) ;ObjectId) ;
  base64encodeimg.s = "";
  ! v_base64encodeimg = v_idd.toDataURL();
  
  *Buffer = AllocateMemory( Len(base64encodeimg) )
  PokeS(*Buffer, 0, base64encodeimg)
  If OpenDatabase(0, *DatabaseBuffer)       ; Now check if it's really in the db 
    SetDatabaseString(0, 0, "blob test")
    SetDatabaseBlob(0, 1, *Buffer, MemorySize(*Buffer)) ; Assign it to the 2nd paramater    
    DatabaseUpdate(0, "INSERT INTO food (name, image) VALUES (?, ?);")
    OnaffDB() ;pour sup image précédente av rafrechissement
    
   *DatabaseBuffer = ExportDatabaseMemory(DB)
   If CreateFile(0, "dbsqlitev3.sqlite", @CreateFileCallback(), #PB_LocalStorage)
     WriteData(0, *DatabaseBuffer, 0, MemorySize(*DatabaseBuffer))
     CloseFile(0)
   EndIf
    If DatabaseQuery(0, "SELECT * FROM food")
      While NextDatabaseRow(0)
        Debug "name: '" + GetDatabaseString(0, 0) + "', blob size: " + MemorySize(GetDatabaseBlob(0, 1))
        *Buffertmp =GetDatabaseBlob(0, 1)
        ooo.s="";
        sizebuff = MemorySize(GetDatabaseBlob(0, 1))
        For o=0 To sizebuff
          ooo = ooo+ Chr( PeekB( *Buffertmp ,o) )
        Next
        Debug ooo
        CatchImageEx(0, ooo, @CatchImageExCallback())
      Wend
    EndIf
    FinishDatabaseQuery(0)        
  Else
    Debug "OpenDatabase() failed"
  EndIf
  FreeImage(bob)  
EndProcedure

Procedure LoadingError(Type, Filename$, ObjectId)
  Debug Filename$ + ": loading error"
EndProcedure

Enumeration
  #SelectFileGadget
  #ProgressGadget
EndEnumeration

#ChunkSize = 1024 * 1024 ; 1 MB chunk
Global *Buffer = AllocateMemory(#ChunkSize) ; Allocate a global memory buffer to avoid realloc

Procedure ReadCallback(Status, Filename$, File, Size)
  If Status = #PB_Status_Loaded
    ReadData(1, *Buffer, 0, Size)    ; Read all data into the memory buffer
;    AddFingerprintBuffer(1, *Buffer, 0, Size)    ; Continue the fingerprint calculation    
    SetGadgetState(#ProgressGadget, (Loc(1) * 100) / Lof(1))    ; Update the progressbar  
    If Not Eof(1)
      FetchData(1, #ChunkSize) ; Continue the reading if the end of file hasn't be reach yet
    Else
      LoadImage(1, Filename$,#PB_LocalFile);"Data/SpiderBasicLogo.png")
    EndIf
;    ElseIf Status = #PB_Status_Progress
;      Debug "Loading file: " + Filename$ + " (" + FileProgress(0) + "%)"
  ElseIf Status = #PB_Status_Error
    Debug "Error when loading the file: " + Filename$
  EndIf
EndProcedure

Procedure OpenFileRequesterCallback()  ; Start the read the file, in stream mode
  If NextSelectedFile()
    If ReadFile(1, SelectedFileID(), @ReadCallback(), #PB_LocalFile | #PB_File_Streaming)
;      StartFingerprint(1, #PB_Cipher_MD5)      ; Initialize fingerprint calc
      FetchData(1, #ChunkSize)                 ; Read the first chunk from the file
      SetGadgetState(#ProgressGadget, 0)
    EndIf 
  EndIf
EndProcedure

Procedure ChooseFileEvent()
  OpenFileRequester("*.txt", @OpenFileRequesterCallback())
EndProcedure

Procedure ReadFileCallback(Status, Filename$, File, SizeRead)
  Select Status
    Case #PB_Status_Loaded
      ;Debug "bob Database file found and loaded: " + Filename$      ; Get all the file as a memory buffer
      
      *DatabaseBuffer = ExportFileMemory(File)  
      If OpenDatabase(0, *DatabaseBuffer)
        Debug "OpenDatabase() created with previous database data. Performing a query..."
        
        If DatabaseQuery(0, "SELECT * FROM food")
          ;Debug "erreur?: "+DatabaseError()
          id=0
          While NextDatabaseRow(0)
            Debug Str(id)+" name: '" + GetDatabaseString(0, 0) + "', blob size: " + MemorySize(GetDatabaseBlob(0, 1))
            id=id+1
            *Buffertmp =GetDatabaseBlob(0, 1)
            ooo.s="";
            sizebuff = MemorySize(GetDatabaseBlob(0, 1))
            For o=0 To sizebuff
              ooo = ooo+ Chr( PeekB( *Buffertmp ,o) )
            Next
            ;Debug ooo
            CatchImageEx(0, ooo, @CatchImageExCallback())
          Wend
          FinishDatabaseQuery(0)        
        Else
          Debug "DatabaseQuery() failed: " + DatabaseError()
        EndIf 
        ;CloseDatabase(0)
      Else
        Debug "OpenDatabase() failed"
      EndIf
     
    Case #PB_Status_Error
      Debug "Database not found in localstorage: " + Filename$
      Debug "Creating a new database..."
      If OpenDatabase(0)  
        DatabaseUpdate(0, "CREATE TABLE food (name CHAR(50), image BLOB)")       
        ;DatabaseUpdate(0, "INSERT INTO superheroes (firstname, name, weight) Values ('Peter', 'Parker', '80.8')")
        ;DatabaseUpdate(0, "INSERT INTO superheroes (firstname, name, weight) Values ('Bruce', 'Wayne', '70.5')")
        ;DatabaseUpdate(0, "INSERT INTO superheroes (firstname, name, weight) Values ('Clark', 'Kent', '75.1')")
  
        *DatabaseBuffer = ExportDatabaseMemory(DB)          ; Now save the database to a persistent file
        If CreateFile(0, "dbsqlitev3.sqlite", @CreateFileCallback(), #PB_LocalStorage)
          WriteData(0, *DatabaseBuffer, 0, MemorySize(*DatabaseBuffer))
          CloseFile(0)
        EndIf
        
        CloseDatabase(0)
      Else
        Debug "OpenDatabase() failed"
      EndIf
  EndSelect
EndProcedure

  
If OpenWindow(0, 0, 0, 300, 480, "charger une image par morceaux", #PB_Window_ScreenCentered)
  scrollgad =ScrollAreaGadget(#PB_Any, 0, 5, WindowWidth(0), WindowHeight(0)-10, WindowWidth(0), 2000,#PB_ScrollArea_Single) ;#PB_Any
  ! var GadgetElement = spider_GadgetID(v_scrollgad).div;
  ! GadgetElement.style.scrollbarWidth = 'none';
  
  ;  PanelGadget(pannel, 5, 5, WindowWidth(0)-10, WindowHeight(0)-10)
  ;  AddGadgetItem(pannel, -1, "charger") ;-- pannel compte

  ButtonGadget(#SelectFileGadget, 10, 10, 280, 25, "charger une image")

  TextGadget(#PB_Any, 10, 45, 60, 25, "Progression: ")
  ProgressBarGadget(#ProgressGadget, 70, 45, 220, 25, 0, 100)    
  BindGadgetEvent(0, @ChooseFileEvent())
    
  btn_aff = ButtonGadget(#PB_Any, 10, 90, 150, 25, "clear images")
  BindGadgetEvent(btn_aff, @OnaffDB())
    
  ScrollAreaGadget(scrollgad2, 0, 120, WindowWidth(0), WindowHeight(0)-120-20+9, WindowWidth(0)-20, 2000,#PB_ScrollArea_Single) ;#PB_Any
  CloseGadgetList()

  ;AddGadgetItem(pannel, -1, "afficher") ;-- pannel compte    
  ;CloseGadgetList()
  ReadFile(0, "dbsqlitev3.sqlite", @ReadFileCallback(), #PB_LocalStorage)
EndIf

; Register the loading event before calling any resource load command
BindEvent(#PB_Event_Loading, @Loaded())
BindEvent(#PB_Event_LoadingError, @LoadingError())
AMpos
Posts: 42
Joined: Mon Aug 03, 2020 5:15 pm

Re: How do I limit an user?

Post by AMpos »

Thx, I will take a look at it
Post Reply