Ready for first test?

This commit is contained in:
scs 2018-12-27 21:49:59 +00:00
parent 7432a08a46
commit 6747d68177
3 changed files with 168 additions and 3 deletions

BIN
example/example Executable file

Binary file not shown.

54
example/example.go Normal file
View File

@ -0,0 +1,54 @@
package main
import (
"gitto.work/shortcut/scsusers"
"github.com/jmoiron/sqlx"
"flag"
"os"
"fmt"
_ "github.com/mattn/go-sqlite3"
)
func main() {
var email string
flag.StringVar(&email, "email", "", "Email address to use for registration test")
flag.Parse()
db, err:=sqlx.Open("sqlite3", ":memory")
if err!=nil {
fmt.Println("Couldn't open sqlite3 in-memory db:" + err.Error())
os.Exit(1)
}
err=db.Ping()
if err!=nil {
fmt.Println("Couldn't ping sqlite3 in-memory db:" + err.Error())
os.Exit(1)
}
schema:=`CREATE TABLE test_auth (
username text NOT NULL unique key ,
crypt text NOT NULL,
email text NOT NULL unique key,
recovery text NOT NULL DEFAULT '',
recoverytime timestamp null,
lastseen timestamp );`
_ ,err=db.Exec(schema)
if err != nil {
fmt.Println("Schema creation failed: " + err.Error())
os.Exit(1)
}
scsusers.Init(db, "test", "Example Test", "nobody@nowhere.com")
a:=scsusers.UsernameAvailable("testuser")
fmt.Printf("Initial test of username available: %v\n", a)
a=scsusers.Register("testuser", email, "127.0.0.1")
fmt.Printf("Register returned %v\n",a)
fmt.Printf("Enter code from email:")
var code string
fmt.Scan(&code)
a=scsusers.Login("testuser", code)
fmt.Printf("Login returned %v\n",a)
}

117
main.go
View File

@ -13,6 +13,7 @@ import (
"strings" "strings"
) )
type templates struct { type templates struct {
Registration *template.Template Registration *template.Template
Alert *template.Template Alert *template.Template
@ -38,7 +39,6 @@ func Init(dbin *sqlx.DB, tp, sitename, fromaddr string) {
SetRegistrationTemplate("") SetRegistrationTemplate("")
SetAlertTemplate("") SetAlertTemplate("")
SetRecoveryTemplate("") SetRecoveryTemplate("")
} }
func UsernameAvailable(username string) bool { func UsernameAvailable(username string) bool {
@ -72,8 +72,62 @@ func Register(username, email, ip string) bool {
return true return true
} }
func Login(username, password string) bool {
q:=fmt.Sprintf("select password from %s_auth where username=$1",c.TablePrefix)
var crypt string
err:=c.db.Get(&crypt, q, username)
if err != nil {
log.Println("Failed login attempt for unknown username: " + username)
return false
}
if bcrypt.CompareHashAndPassword([]byte(crypt), []byte(password)) == nil {
log.Println("Failed password for " + username)
return false
}
bump(username)
return true
}
func bump(username string) {
q:=fmt.Sprintf("update %s_auth set lastseen=NOW() where username=$1", c.TablePrefix)
_, err :=c.db.Exec(q, username)
if err != nil {
log.Println("Error on user bump: " + err.Error())
}
}
func RecoverByUsername(u string) {
var username, email string
q:=fmt.Sprintf("select username, email from %s_auth where username=$1", c.TablePrefix)
row:=c.db.QueryRow(q, u)
err:=row.Scan(&username, &email)
if err!=sql.ErrNoRows {
recoverycode:=randBytes(10)
qq:=fmt.Sprintf("update %s_auth set recoverycode=$1, recoverytime=NOW() where username=$2", c.TablePrefix)
_,err:=c.db.Exec(qq, recoverycode, username)
if err==nil {
sendRecoveryEmail(email, username, string(recoverycode))
}
}
}
func RecoverByEmail(e string) {
var username, email string
q:=fmt.Sprintf("select username, email from %s_auth where email=$1", c.TablePrefix)
row:=c.db.QueryRow(q, e)
err:=row.Scan(&username, &email)
if err!=sql.ErrNoRows {
recoverycode:=randBytes(10)
qq:=fmt.Sprintf("update %s_auth set recoverycode=$1, recoverytime=NOW() where username=$2", c.TablePrefix)
_,err:=c.db.Exec(qq, recoverycode, username)
if err==nil {
sendRecoveryEmail(email, username, string(recoverycode))
}
}
}
func randBytes(n int) []byte { func randBytes(n int) []byte {
const letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" const letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"
b := make([]byte, n) b := make([]byte, n)
for i := range b { for i := range b {
b[i] = letterBytes[rand.Intn(len(letterBytes))] b[i] = letterBytes[rand.Intn(len(letterBytes))]
@ -108,6 +162,63 @@ func sendRegistrationEmail(recipient, username, password string) bool {
return true return true
} }
func sendAlertEmail(username, recipient, message string) bool {
data := struct {
SiteName string
FromEmail string
UserName string
Activity string
}{
SiteName: c.SiteName,
FromEmail: c.FromEmail,
UserName: username,
Activity: message,
}
var body bytes.Buffer
err := c.Templates.Registration.Execute(&body, data)
if err != nil {
log.Printf("Alert template failed to execute: %v returned %s\n", data, err.Error())
return false
}
subject := fmt.Sprintf("New activity on %s", c.SiteName)
err = SendMail("localhost:25", c.FromEmail, subject, body.String(), recipient)
if err != nil {
log.Printf("Error sending mail to %s: %s\n", recipient, err.Error())
return false
}
return true
}
func sendRecoveryEmail(recipient, username, code string) bool {
data := struct {
SiteName string
FromEmail string
UserName string
RecoveryCode string
}{
SiteName: c.SiteName,
FromEmail: c.FromEmail,
UserName: username,
RecoveryCode: code,
}
var body bytes.Buffer
err := c.Templates.Registration.Execute(&body, data)
if err != nil {
log.Printf("Registration template failed to execute: %v returned %s\n", data, err.Error())
return false
}
subject := fmt.Sprintf("Welcome to %s", c.SiteName)
err = SendMail("localhost:25", c.FromEmail, subject, body.String(), recipient)
if err != nil {
log.Printf("Error sending mail to %s: %s\n", recipient, err.Error())
return false
}
return true
}
func SetRegistrationTemplate(t string) bool { func SetRegistrationTemplate(t string) bool {
if len(t) != 0 { if len(t) != 0 {
r, err := template.New("reg").Parse(t) r, err := template.New("reg").Parse(t)
@ -135,7 +246,7 @@ func SetAlertTemplate(t string) bool {
return true return true
} }
} }
df := `<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html></head><body><p> Hello {{.UserName}}! Just letting you know that {{.Activity}}.<br> You can disable future notifications in your user settings.</p></body></html>` df := `<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html></head><body><p> Hey {{.UserName}}! Just letting you know that {{.Activity}}.<br> You can disable future notifications in your user settings.</p></body></html>`
r, err := template.New("alert").Parse(df) r, err := template.New("alert").Parse(df)
if err != nil { if err != nil {
log.Fatal("Default alert template MUST compile. Error: " + err.Error()) log.Fatal("Default alert template MUST compile. Error: " + err.Error())