transmet/user/user.go

64 lines
1.4 KiB
Go
Raw Normal View History

2015-04-30 04:32:39 +00:00
package user
import (
"database/sql"
"fmt"
_ "github.com/lib/pq"
)
type User struct {
Username string
db *sql.DB
}
func UsernameExists(db *sql.DB, username string) (bool, error) {
rows, err := db.Query("SELECT count(username) FROM users where username=$1", username)
if err != nil {
fmt.Println("User DB Error: ", err)
return false, err
}
var count int
rows.Next()
rows.Scan(&count)
return count > 0, nil
}
func NewUserFromAuth(db *sql.DB, username, password string) *User {
fmt.Println("NewUserFromAuth:", username, ":", password)
2015-05-02 19:28:11 +00:00
rows, err := db.Query("SELECT username FROM users WHERE username = $1 AND password IS NOT NULL AND password = crypt($2 , password);", username, password)
2015-04-30 04:32:39 +00:00
if err != nil {
2015-05-02 17:13:33 +00:00
fmt.Println("Username or auth fail: ", err)
2015-04-30 04:32:39 +00:00
return nil
}
user := User{db: db}
if rows.Next() {
2015-05-02 17:13:33 +00:00
err := rows.Scan(&user.Username)
2015-04-30 04:32:39 +00:00
if err != nil {
fmt.Println("scan err: ", err)
}
} else {
2015-05-02 19:28:11 +00:00
fmt.Println("no match")
2015-04-30 04:32:39 +00:00
return nil
}
2015-05-02 17:13:33 +00:00
return &user
2015-04-30 04:32:39 +00:00
}
func NewUserFromUsername(db *sql.DB, username string) *User {
rows, err := db.Query("SELECT username FROM users WHERE username=$1", username)
if err != nil {
fmt.Println("User DB Error: ", err)
return nil
}
user := User{db: db}
if rows.Next() {
err = rows.Scan(&user.Username)
if err != nil {
fmt.Println("Scan err: ", err)
}
} else {
fmt.Println("User DB Error: No user found with username ", username)
return nil
}
return &user
}