the ring programming language version 1.2 book - part 32 of 84

10
Ring Documentation, Release 1.2 41.21 Users registration and Login We have the users classes (Model, View & Controller) to deal with the users data like username & email. The next code is stored in ex25_users.ring Class UsersModel from ModelBase cSearchColumn = "username" Class UsersController From ControllerBase 41.21. Users registration and Login 290

Upload: mahmoud-samir-fayed

Post on 21-Feb-2017

3 views

Category:

Software


0 download

TRANSCRIPT

Page 1: The Ring programming language version 1.2 book - Part 32 of 84

Ring Documentation, Release 1.2

41.21 Users registration and Login

We have the users classes (Model, View & Controller) to deal with the users data like username & email.

The next code is stored in ex25_users.ring

Class UsersModel from ModelBasecSearchColumn = "username"

Class UsersController From ControllerBase

41.21. Users registration and Login 290

Page 2: The Ring programming language version 1.2 book - Part 32 of 84

Ring Documentation, Release 1.2

aColumnsNames = ["id","username","email"]

Func UpdateRecordoModel.id = aPageVars[cRecID]oModel.updatecolumn("username", aPageVars[:username] )oModel.updatecolumn("email", aPageVars[:email] )oView.UpdateView(self)

Class UsersView from ViewBase

oLanguage = new UsersLanguageEnglish

Func AddFuncScript oPage,oControllerreturn oPage.scriptfunc("myadd",oPage.scriptredirection("ex26.ring"))

Func FormViewContent oController,oTranslation,oPagereturn [

[oTranslation.aColumnsTitles[2],"textbox","username",oController.oModel.UserName,oPage.stylewidth("100%")],[oTranslation.aColumnsTitles[3],"textbox","email",oController.oModel.Email,oPage.stylewidth("50%")]

]

Class UsersLanguageEnglishcTitle = "Users Table"cBack = "back"aColumnsTitles = ["ID","User Name","Email"]cOptions = "Options"cSearch = "Search"comboitems = ["Select Option...","Edit","Delete"]cAddRecord = "Add Record"cEditRecord = "Edit Record"cRecordDeleted = "Record Deleted!"aMovePages = ["First","Prev","Next","Last"]cPage = "Page"cOf = "of"cRecordsCount = "Records Count"cSave = "Save"temp = new pagecTextAlign = temp.StyleTextRight()cNoRecords = "No records!"

In the file ex25.ring we load ex25_users.ring then create an object from UsersController class.

Using the created object, we call the routing method.

#!c:\ring\bin\ring.exe -cgiLoad "weblib.ring"Load "datalib.ring"Load "ex25_users.ring"

Import System.Webwebsite = "ex25.ring"New UsersController { Routing() }

Screen Shot:

41.21. Users registration and Login 291

Page 3: The Ring programming language version 1.2 book - Part 32 of 84

Ring Documentation, Release 1.2

See the next code for the registration page

#!c:\ring\bin\ring.exe -cgiLoad "weblib.ring"Load "datalib.ring"Import System.Web

website = "ex26.ring"

new page {boxstart()

text( "Register")newline()

boxend()divstart([:style = stylegradient(6) + stylesize("100%","95%") ])link([ :url = website, :title = "back" , :style = stylecolor("white")])newline()divstart([ :style= styledivcenter("500","160") + stylegradient(52) ])formpost("ex27.ring")

tablestart([ :Style = stylemarginleft("2%") + stylemargintop("2%") +stylewidth("90%") ])

rowstart([])cellstart([:style = stylewidth("20%") + styleheight(30)])text("User Name")

cellend()cellstart([ :style = stylewidth("80%") ])textbox([:name = "username", :style = stylewidth("100%")])

cellend()rowend()rowstart([])

cellstart([ :Style = styleheight(30)])text("Password")

cellend()cellstart([])textbox([:name = "password" , :type = "password"])

41.21. Users registration and Login 292

Page 4: The Ring programming language version 1.2 book - Part 32 of 84

Ring Documentation, Release 1.2

cellend()rowend()rowstart([])

cellstart([ :style = styleheight(30)])text("Email")

cellend()cellstart([])textbox([:name = "email" , :style = stylewidth("100%")])

cellend()rowend()rowstart([])

cellstart([ :style = styleheight(30)])cellend()cellstart([ :style = styleheight(30)])submit([:value = "Register" ])

cellend()rowend()

tableend()formend()divend()divend()

}

Screen Shot:

The Registration response

#!c:\ring\bin\ring.exe -cgiLoad "weblib.ring"Load "datalib.ring"Load "ex25_users.ring"

41.21. Users registration and Login 293

Page 5: The Ring programming language version 1.2 book - Part 32 of 84

Ring Documentation, Release 1.2

Import System.Web

oUser = new UsersModeloUser.Connect()if oUser.findwith("username",aPageVars["username"])

new page {text("The user name is already registered")

}return

okif oUser.findwith("email",aPageVars["email"])

new page {text("This email is already registered")

}return

ok

aPageVars["salt"] = str2hex(RandBytes(32))aPageVars["pwhash"] = sha256(aPagevars["password"]+aPageVars["salt"])aPageVars["sessionid"] = str2hex(randbytes(32))oUser.Insert()new page {

cookie("sessionid",aPageVars["sessionid"])text("New User Created!")newline()text("User Name : " + aPageVars["username"])newline()

}oUser.Disconnect()

See the next code for the Login page

#!c:\ring\bin\ring.exe -cgiLoad "weblib.ring"Load "datalib.ring"

Import System.Web

website = "ex28.ring"

new page {boxstart()

text( "Login")newline()

boxend()divstart([:style = stylegradient(6) + stylesize("100%","95%") ])link([ :url = website, :title = "back" , :style = stylecolor("white")])newline()divstart([ :style= styledivcenter("500","130") + stylegradient(52) ])formpost("ex29.ring")

tablestart([ :Style = stylemarginleft("2%") + stylemargintop("2%") +stylewidth("90%") ])

rowstart([])cellstart([:style = stylewidth("20%") + styleheight(30)])text("User Name")

cellend()cellstart([ :style = stylewidth("80%") ])textbox([:name = "username", :style = stylewidth("100%")])

cellend()

41.21. Users registration and Login 294

Page 6: The Ring programming language version 1.2 book - Part 32 of 84

Ring Documentation, Release 1.2

rowend()rowstart([])

cellstart([ :style = styleheight(30)])text("Password")

cellend()cellstart([])textbox([:name = "password" , :type = "password"])

cellend()rowend()rowstart([])

cellstart([ :style = styleheight(30) ])cellend()cellstart([])submit([:value = "Login" ])

cellend()rowend()

tableend()formend()divend()divend()

}

Screen Shot:

The response page

#!c:\ring\bin\ring.exe -cgiLoad "weblib.ring"Load "datalib.ring"Load "ex25_users.ring"

Import System.Web

41.21. Users registration and Login 295

Page 7: The Ring programming language version 1.2 book - Part 32 of 84

Ring Documentation, Release 1.2

oUser = new UsersModeloUser.Connect()lResult = oUser.FindWith("username",aPageVars["username"])new page {

if lResultif sha256(aPagevars["password"]+oUser.Salt) = oUser.pwhash

text ("Correct Password!")aPageVars["sessionid"] = str2hex(randbytes(32))oUser.UpdateColumn("sessionid",aPageVars["sessionid"])cookie("sessionid",aPageVars["sessionid"])

elsetext ("Bad password!")

okelse

text("Bad User Name!")ok

}oUser.Disconnect()

The next code for checking if the user needs to login or not

#!c:\ring\bin\ring.exe -cgiLoad "weblib.ring"Load "datalib.ring"Load "ex25_users.ring"

Import System.Web

oUser = new UsersModeloUser.Connect()lResult = oUser.FindWith("sessionid",aPageVars["sessionid"])new page {

if lResulttext("User Name : " + oUser.username )

elsetext("Please Login First!")

ok}oUser.Disconnect()

41.22 Database, ModelBase & ControllerBase classes

In this section we will see some code from datalib.ring

The next code presents the Database, ModelBase & ControllerBase classes

Import System.Web

Class Database

cServer = "localhost"cUserName = "root"cPassword = "root"cDatabase = "mahdb"

Func Connect

41.22. Database, ModelBase & ControllerBase classes 296

Page 8: The Ring programming language version 1.2 book - Part 32 of 84

Ring Documentation, Release 1.2

con = mysql_init()mysql_connect(con, cServer, cUserName, cPassWord,cDatabase)

Func Disconnect

mysql_close(con)

Func Query cQuery

mysql_query(con,cQuery)

Func QueryResult

return mysql_result(con)

Func QueryResultWithColumns# return columns names + query resultreturn mysql_result2(con)

Func QueryValueaResult = mysql_result(con)if islist(aResult) and len(aResult) >= 1aResult = aResult[1]if len(aResult) >= 1

return aResult[1]ok

okreturn 0

Func EscapeString xif isstring(x)return MySQL_Escape_String(con,x)

elsereturn MySQL_Escape_String(con,string(x))

ok

Privatecon = NULL

Class ModelBase from Database

cTableName = ""cSearchColumn = "name"aColumns = []aQueryResult = []ID = 0

# set table name from class nameclassname = lower(classname(self))if right(classname,5) = :model

cTablename = left(classname,len(classname)-5)ok

Func Insert

cValues = ""for x in aColumnscValues += "'" + EscapeString(aPageVars[x]) + "',"

41.22. Database, ModelBase & ControllerBase classes 297

Page 9: The Ring programming language version 1.2 book - Part 32 of 84

Ring Documentation, Release 1.2

NextcValues = left(cValues,len(cValues)-1) # remove last commacColumns = ""for x in aColumnscColumns += x + ","

nextcColumns = left(cColumns,len(cColumns)-1)query("insert into " + cTableName + "("+cColumns+") values (" +

cValues + ")" )

Func Update nID

cStr = ""for x in aColumnscStr += x + " = '" + EscapeString(aPageVars[x]) + "' , "

# the space after comma is necessaryNextcStr = left(cStr,len(cStr)-2)query("update " + cTableName + " set " + cStr + " where id = " + nID )

Func UpdateColumn cColumn,cValuequery("update " + cTableName + " set " + cColumn + " = '" +EscapeString(cValue) + "' where id = " + self.ID )

Func Count cValue

query("SELECT count(*) FROM " + cTableName +" where "+cSearchColumn+" like '" + EscapeString(cValue) + "%'")

return queryValue()

Func Read nStart,nRecordsPerPage

query("SELECT * FROM "+ cTableName+" limit " + EscapeString(nStart) + "," +EscapeString(nRecordsPerPage) )aQueryResult = queryResult()

Func Search cValue,nStart,nRecordsPerPage

query("SELECT * FROM "+ cTableName+" where "+cSearchColumn+" like '" +EscapeString(cValue) + "%'" +" limit " + EscapeString(nStart) + "," + EscapeString(nRecordsPerPage) )

aQueryResult = queryResult()

Func Find nID

query("select * from " + cTableName + " where id = " + EscapeString(nID) )aResult = queryResult()[1]# move the result from the array to the object attributesID = nIDcCode = ""for x = 2 to len(aResult)cCode += aColumns[x-1] + " = hex2str('" + str2hex(aResult[x]) + "')" + nl

nexteval(cCode)

Func FindWith cColumn,cValue

41.22. Database, ModelBase & ControllerBase classes 298

Page 10: The Ring programming language version 1.2 book - Part 32 of 84

Ring Documentation, Release 1.2

query("select * from " + cTableName + " where "+cColumn+" = '" +EscapeString(cValue) + "'" )aResult = queryResult()if len(aResult) > 0aResult = aResult[1]

elsereturn 0

ok# move the result from the array to the object attributesID = aResult[1]cCode = ""for x = 2 to len(aResult)cCode += aColumns[x-1] + " = hex2str('" + str2hex(aResult[x]) + "')" + nl

nexteval(cCode)return 1

Func Delete ID

query("delete from " + cTableName + " where id = " + EscapeString(ID) )

Func Clear

cCode = ""for x in aColumnscCode += x + ' = ""' + nl

nexteval(cCode)

Func LoadModel

# create the columns arrayquery("SELECT * FROM "+ cTableName + " limit 0,1")aQueryResult = QueryResultWithColumns()[1]for x = 2 to len(aQueryResult)aColumns + lower(trim(aQueryResult[x]))

next

# create attribute for each columnfor x in aColumnsaddattribute(self,x)

next

Func Connect

Super.Connect()if nLoadModel = 0nLoadModel = 1LoadModel()

ok

private

nLoadModel = 0

Class ControllerBase

41.22. Database, ModelBase & ControllerBase classes 299