How to require login to view documents on a website? - html

My website has a series of documents stored in a folder on the webserver (Windows 2012 R2).
The documents can be found on a page that can only be accessed by logged in users. These documents are PDF files that can be downloaded through the click of a hyperlink. They also can be viewed in the web browser.
Currently a user can copy the URL, give it to somebody else and they can use it to download the PDFs thereby not having to go through the login process to view the page behind the login page.
Let's say the URL is https://www.mywebsite.com/documents/adocument.pdf
How can I go about securing these documents so that the url can't just be sent around but prompts for a login instead?
Below is the code to get the documents. An These are then pushed into an ASP.NET placeholder.
Public Shared Function GetLoanDocLinks(ByVal iLoanID As Integer) As String
Dim s As String
s = ""
Dim MyConn As FirebirdSql.Data.FirebirdClient.FbConnection
Dim Adaptor As FirebirdSql.Data.FirebirdClient.FbDataAdapter
Dim ds As DataSet
Dim dr As DataRow
Dim iNumRows, i As Integer
Dim MySQL As String
Dim myContext As HttpContext
Dim MySession As HttpSessionState = System.Web.HttpContext.Current.Session
myContext = HttpContext.Current
ds = New DataSet
'StrConn = ConfigurationManager.ConnectionStrings("FBConnectionString").ConnectionString
MySQL = "SQL statement goes here"
MyConn = New FirebirdSql.Data.FirebirdClient.FbConnection(DBNAME.ConnStr)
Adaptor = New FirebirdSql.Data.FirebirdClient.FbDataAdapter(MySQL, MyConn)
Adaptor.SelectCommand.Parameters.Add("#p1", FirebirdSql.Data.FirebirdClient.FbDbType.Integer).Value = iID
Try
Adaptor.Fill(ds)
Catch ex As Exception
GenExternals.LogEntry("Error:" & ex.Message)
End Try
iNumRows = ds.Tables(0).Rows.Count
For i = 0 To iNumRows - 1
dr = ds.Tables(0).Rows(i)
s = s & "<a href='documents/" & Trim(dr("Filename")) & "' target='+new'>" & Trim(dr("description")) & "</a> "
s = s & "<br /> "
Next
s = s & "<br />"
MyConn.Close()
Adaptor = Nothing
MyConn = Nothing
GetLoanDocLinks = s

Related

SSIS Script Task Special Characters

I am trying to get some data from an API, using an SSIS Script Task with Visual Basic code. But I having some problems because I have Portuguese special characters in some fields. I was trying to solve my problems and I read that this could be achieved by enconding the data. I try to do this with any sucess.
Can anyone help me?
Regards
Using c As WebClient = New WebClient()
c.BaseAddress = URL
c.Headers(HttpRequestHeader.Authorization) = "Basic " + Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(key & ":" & pass))
c.Credentials = New NetworkCredential(key, pass)
Dim xml = c.DownloadString(URL & "CRUser?start=0&count=999&language=English")
'Parse para objetos
Dim doc = XDocument.Parse(xml)
Dim reader = doc.CreateReader()
Dim xRoot As XmlRootAttribute = New XmlRootAttribute()
xRoot.ElementName = "array"
xRoot.IsNullable = True
Dim xmls As New XmlSerializer(GetType(List(Of CRUser)), xRoot)
Dim _data As List(Of CRUser) = xmls.Deserialize(reader)
For Each item As CRUser In _data
'Console.WriteLine(item.id)
'Console.WriteLine(item.firstName)
'..... resto campos injetar no pipelino do SSIS os dados
MyOutputBuffer.AddRow()
MyOutputBuffer.id = item.id
MyOutputBuffer.firstName = item.firstName
Next
End Using

How to fix an empty .csv file export from vb.net using MySQL?

im trying to export a data table to a .csv file in vb.net Ive written code that opens a save file dialogue and successfully saves the .csv file but the file is 0 bytes and contains no data. I'm using MySQL database, the database name is "tickedoff" and the table that i want to export is "pet".
If anyone can see a mistake in my code and help me it would be greatly appreciated.. I am totally stumped at the moment.
This code is in Form1 (button click event):
Private Sub btnPetInfoExport_Click(sender As Object, e As EventArgs) Handles btnPetInfoExport.Click
Dim saveFileDialog1 = New SaveFileDialog()
Dim statement As String = "SELECT pet.petID, pet.petName, pet.species, pet.breed, " _
& "pet.DOB, pet.gender, pet.weight," _
& "CONCAT(customer.lastName, ', ', customer.firstName) AS Customer " _
& "FROM pet INNER JOIN customer ON pet.customerID = customer.customerID " _
& "ORDER BY pet.petID"
Dim petDataTable As DataTable =
DataAccessLayer.GetPetDataTableForExport(statement)
Dim saveFile As StreamWriter
Dim fileName As String = String.Empty
Dim csvBuilder As New StringBuilder()
For i = 0 To petDataTable.Columns.Count - 1
csvBuilder.Append(petDataTable.Columns(i).ColumnName + ","c)
Next
csvBuilder.Append(vbCr & vbLf)
For i = 0 To petDataTable.Rows.Count - 1
For o = 0 To petDataTable.Columns.Count - 1
csvBuilder.Append(petDataTable.Rows(i)(o).ToString().Replace(",", ";") + ","c)
Next
csvBuilder.Append(vbCr & vbLf)
Next
saveFileDialog1.Filter = "CSV files ( .csv)|.csv|ALL files (.)|. "
If saveFileDialog1.ShowDialog = System.Windows.Forms.DialogResult.OK Then
fileName = saveFileDialog1.FileName
Try
saveFile = File.CreateText(fileName)
Catch ex As Exception
Throw ex
End Try
End If
End Sub
This function is called from the above sub and is in a separate class called "data access layer":
Public Shared Function GetPetDataTableForExport(statement As String) As
DataTable
Dim petDataTableCommand As New MySqlCommand(statement)
Dim petDataTable As New DataTable()
Dim connection As New MySqlConnection("server=localhost; Port=3306; database=tickedoff; username=root;")
Dim petDataTableAdapter As MySqlDataAdapter = New MySqlDataAdapter
petDataTableCommand.CommandType = CommandType.Text
petDataTableCommand.Connection = connection
Try
connection.Open()
petDataTableAdapter.SelectCommand = petDataTableCommand
'fill the table with the pet data from the database
petDataTableAdapter.Fill(petDataTable)
Catch ex As Exception
Throw ex
Finally
connection.Close()
petDataTableAdapter.Dispose()
connection.Dispose()
End Try
Return petDataTable
End Function

restrict access to a .net page without a valid session vb.net

I currently have a login page login.aspx that copies "affID" into a session and uses it on another page dashboard.aspx
login.aspx file looks like this :
Dim Query As String
Query = "select * from mdxmain.taffiliate where affID = '" & username.Text & "' and affPassword = '" & password.Text & "'"
COMMAND = New MySqlCommand(Query, MysqlConn)
Session("affID") = username.Text
READER = COMMAND.ExecuteReader
Dim count As Integer
count = 0
While READER.Read
count = count + 1
End While
If count = 1 Then
Response.Redirect("dashboard.aspx")
Else
Literal1.Text = "Invalid credentials"
End If
MysqlConn.Close()
Finally
End Try
MysqlConn.Dispose()
dashboard.aspx session load file looks like this :
Dim userid As String = HttpContext.Current.Session("affID")
I need help with not allowing access to the dashboard.aspx file without having a valid session. Also how to timeout the session after 2minutes
In your dashboard page_load event, check if the session variable is nothing, if it is, then redirect to your login page.
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
Dim userid As String = HttpContext.Current.Session("affID")
if ( userid is Nothing) then
Response.Redirect("login.aspx")
end if
End Sub
Update
For the timeout there is some good information here

Crystal Report 13 prompts Database Login in VS 2010

I am currently having problem displaying the Crystal Report in my VB.Net(VS2010) application. I Googled this issue, found similar problem, but their solution didn't fixed mine.
Everytime I call the CR report from my VB application, it always prompts for a Database Login. I've entered my DB credentials but it fails. I am connecting to a MySQL5.1 via ODBC connector.
In my Crystal Report, I have created a custom Command which accept 2 parameters from my application, e.i, dateFrom and dateTo, which I used to query between the date range.
I've noticed that when I took off my code where it sets the Crystal Report parameter value, the Database Login doesn't appear.
Here's my code snippet:
Dim appPath As String = Path.GetDirectoryName(Application.ExecutablePath)
Dim cryRpt As New ReportDocument
Dim CRTable As CrystalDecisions.CrystalReports.Engine.Table
Dim CRTLI As CrystalDecisions.Shared.TableLogOnInfo
cryRpt.Load(appPath & "\Reports\crDtrLogs.rpt")
frmReportViewer.crReportViewer.Refresh()
For Each CRTable In cryRpt.Database.Tables
CRTLI = CRTable.LogOnInfo
With CRTLI.ConnectionInfo
.ServerName = "dtrsql"
.UserID = "root"
.Password = "root"
.DatabaseName = "dtrsql"
End With
CRTable.ApplyLogOnInfo(CRTLI)
Next CRTable
When I took this out, everything works fine even without adding the table connection info
cryRpt.SetParameterValue("dtpFrom", dtpFrom.Value.Date.ToString("yyyy-MM-dd"))
cryRpt.SetParameterValue("dtpTo", dtpTo.Value.Date.ToString("yyyy-MM-dd"))
cryRpt.SetParameterValue("strDateRange", dtpFrom.Value.Date.ToString("MMMM dd, yyyy") & " - " & dtpTo.Value.Date.ToString("MMMM dd, yyyy"))
frmReportViewer.crReportViewer.ReportSource = cryRpt
frmReportViewer.Show()
As always, any help is greatly appreciated.
eassy and simple solution for all ....
open field explorer---> database field --->Right Click -->current Data source --->reports connection----->report ----->property ----> set Property as---
Data Source: .\Databasename.accdb
and code on viewer form load as
Dim cryRpt As New ReportDocument
Dim Report1 As New rptItemWise
Dim strServerName As String
strServerName = Application.StartupPath
rptItemWise.SetDatabaseLogon("admin", "", strServerName, "dastabasename.accdb", True)
cryRpt.Load(Application.StartupPath + "\rptItemWise.rpt")
also change the report connection same as data source i think that code work for you ..
Check this code. I guess you should access to the database like this:
Dim appPath As String = Path.GetDirectoryName(Application.ExecutablePath)
Dim cryRpt As New ReportDocument
Dim crtableLogoninfos As New TableLogOnInfos
Dim crtableLogoninfo As New TableLogOnInfo
Dim crConnectionInfo As New ConnectionInfo
Dim CrTables As Tables
cryRpt.Load(appPath & "\Reports\crDtrLogs.rpt")
crConnectionInfo.ServerName = "YOUR SERVER NAME"
crConnectionInfo.DatabaseName = "YOUR DATABASE NAME"
crConnectionInfo.UserID = "YOUR DATABASE USERNAME"
crConnectionInfo.Password = "YOUR DATABASE PASSWORD"
CrTables = cryRpt.Database.Tables
For Each CrTable In CrTables
crtableLogoninfo = CrTable.LogOnInfo
crtableLogoninfo.ConnectionInfo = crConnectionInfo
CrTable.ApplyLogOnInfo(crtableLogoninfo)
Next CrTable

String from Database set as public string

Ok from the answer from the previous question the reasoning still applies here but this time A different issue. There is a login system (Loginvb.vb) that I got for the launcher I was creating and was wondering 2 things:
Is there a better way to do the Login check with the database (as in
more secure) (the login style will have a web based registration
setting via PHP script)?
Is there a way to take a certain column (labled as access) in the database and put it
as a public string so I can check if it will equal 1 2 or 3 in a
different form labeled as Main.vb
Here is the current login check:
Public Sub login_Click(sender As Object, e As EventArgs) Handles login.Click
If txtuserName.Text = "" Or txtpassWord.Text = "" Then
MsgBox("You cannot progress until you login....(moron =p)")
Else
'Connects To the Database
Dim connect As MySqlConnection
connect = New MySqlConnection()
connect.ConnectionString = "server=127.0.0.1;user id=sc;Password=derp;database=sclaunch" 'not the actual login ;)
Try
connect.Open()
Catch myerror As MySqlException
MsgBox("Error Connecting to Database. Please Try again !")
End Try
'SQL Query To Get The Details
Dim myAdapter As New MySqlDataAdapter
Dim sqlquerry = "Select * From login where username = '" + txtuserName.Text + "' And password= '" + txtpassWord.Text + "'"
Dim myCommand As New MySqlCommand()
'My fail attempt at what I am trying to do :(
Dim sql22 As MySqlConnection
sql22 = New MySqlConnection()
sql22.ConnectionString = "Select * From login where access ="
'End of fail attempt
myCommand.Connection = connect
myCommand.CommandText = sqlquerry
'Starting The Query
myAdapter.SelectCommand = myCommand
Dim mydata As MySqlDataReader
mydata = myCommand.ExecuteReader
'To check the Username and password and to validate the login
If mydata.HasRows = 0 Then
MsgBox("Invalid Login")
Else
'fail testing xD
Label3.Text = sql22
MsgBox("You are now Loged In!")
End If
End If
End Sub
Still basically learning more and more as I am coding all this got to love trial and error and the moments where you get stuck =/ (Sorry to the admins or whatever for fixing tag issues still new to the site xD)
Assuming that the same table login that contains the credentials contains also the access column that you want to retrieve, then I have changed a lot of your code
Dim sqlquerry = "Select * From login where username = #name AND password=#pwd"
Dim myCommand As New MySqlCommand(sqlquery, connect)
myCommand.Parameters.AddWithValue("#name", txtuserName.Text)
myCommand.Parameters.AddWithValue("#pwd", txtpassWord.Text)
Dim mydata = myCommand.ExecuteReader
If mydata.HasRows = False Then
MsgBox("Invalid Login")
Else
' the same record that contains the credentials contains the access field'
mydata.Read()
Label3.Text = mydata("access").ToString()
MsgBox("You are now Loged In!")
End If
What I have changed:
Removed the string concatenation and added the appropriate parameters
Removed myAdapter and every references to it (not needed, you don't
fill DataTable/DataSet)
Removed sql22 and every references to it. It's a Connection and you
try to use like a Command
Fixed the check on HasRows (Returns a boolean not an integer. Are you
using Option Strict Off?)